branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep># Created By <NAME>
# Created On Mar 2018
# Lets User choose a number and see if their number == random number
import random
randomNumber = random.randint(1,6)
print(randomNumber)
numberGuessed = int(input('Guess a number between 1 and 6:'))
if numberGuessed == randomNumber:
print( 'You Win!' )
else:
print( 'You Lose!' )
input("end") | e45500e4f49667d669242a4374be7e4d212213ce | [
"Python"
] | 1 | Python | AminZeina/unit601Python | 020ee78cb7f937f475fd68b56458fb7e391e4aea | 039633727e9e5c3a76aebbd5e85184dda7548131 | |
refs/heads/master | <repo_name>nikhilnassa20/AssessmentAngular<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Assessment Result';
gradeA="A";
gradeB="B";
gradeC="C";
gradeO="O";
items = [
{ firstName: 'Nikhil', lastName: 'Nassa', age: '22', Grade: 'A' },
{ firstName: 'Rishabh', lastName: 'Khurana', age: '24', Grade: 'O' },
{ firstName: 'Saket', lastName: 'Saroha', age: '22', Grade: 'B' },
{ firstName: 'Arpit', lastName: 'Bhardwaj', age: '22', Grade: 'C' },
{ firstName: 'Priyanshu', lastName: 'Nassa', age: '16', Grade: 'O' },
{ firstName: 'Aman', lastName: 'Sharma', age: '23', Grade: 'B' },
{ firstName: 'Dikshant', lastName: 'Rana', age: '24', Grade: 'A' },
{ firstName: 'Ritik', lastName: 'Raheja', age: '21', Grade: 'C' },
];
}
| 81d6bb26c5c6fd1c8775baf4b85cc7d37b4136df | [
"TypeScript"
] | 1 | TypeScript | nikhilnassa20/AssessmentAngular | 945532efa24fbd79a3c7241cab819ab49f6b5827 | 4f07474f0142cf65e20e3d72d67192c59fa55e39 | |
refs/heads/master | <repo_name>haji4ref/Future<file_sep>/FutureProj/src/classes/Tashvigh.java
package classes;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Reza on 1/22/2016.
*/
public class Tashvigh extends JLabel {
public Tashvigh(boolean correctness) {
this.correctness = correctness;
x = 0;
y = 0;
xSpeed = 5;
ySpeed = 2;
icon_temp = new ImageIcon(getClass().getClassLoader().getResource("icons/star.png"));
image_true = icon_temp.getImage();
icon_temp = new ImageIcon(getClass().getClassLoader().getResource("icons/error.png"));
image_false = icon_temp.getImage();
al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
x += xSpeed;
// y += ySpeed;
repaint();
}
};
}
public ActionListener getActionListener() {
return al;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (correctness == true) {
g.drawImage(image_true, x, y, 500, 400, null);
} else g.drawImage(image_false, x, y, 500, 400, null);
}
private boolean correctness;
private int x;
private int y;
private double xSpeed;
private double ySpeed;
private ImageIcon icon_temp;
private Image image_true;
private Image image_false;
private ActionListener al;
}
<file_sep>/README.md
# Future
this is a start ... a start for future !
<file_sep>/FutureProj/src/classes/LearningUI.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package classes;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javafx.embed.swing.JFXPanel;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javax.swing.*;
/**
* @author Reza
*/
public class LearningUI extends StepUI {
public LearningUI(int stepNumber, int subjectNumber, Dimension screenSize, Font font, boolean isSoundDisable, boolean isTextDisable, int picNumber) {
this.setLayout(null);
this.screenSize = screenSize;
this.subjectNumber = subjectNumber;
this.stepNumber = stepNumber;
this.setBackground(Color.white);
this.setSize(screenSize.width * 3 / 4, screenSize.height);
this.setLocation(0, 0);
this.pictureNumber = picNumber;
stepText = new ArrayList<>();
loadText();
fxpanel = new JFXPanel();
checkBox_sound = new JCheckBox("صدا پخش نشود");
checkBox_sound.setSize(300, 40);
checkBox_sound.setLocation(1200, 20);
checkBox_sound.setFont(font.deriveFont(Font.PLAIN, 30));
checkBox_text = new JCheckBox("متن نشان داده نشود");
checkBox_text.setSize(300, 40);
checkBox_text.setLocation(1200, 70);
checkBox_text.setFont(font.deriveFont(Font.PLAIN, 30));
checkBox_sound.setSelected(isSoundDisable);
checkBox_text.setSelected(isTextDisable);
this.add(checkBox_sound);
this.add(checkBox_text);
icon_next = new ImageIcon(getClass().getClassLoader().getResource("icons/next.png"));
Image image = icon_next.getImage();
Image newimg = image.getScaledInstance(icon_next.getIconWidth() * screenSize.height / 1080, icon_next.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_next = new ImageIcon(newimg);
icon_next_Rollover = new ImageIcon(getClass().getClassLoader().getResource("icons/nextro.png"));
image = icon_next_Rollover.getImage();
newimg = image.getScaledInstance(icon_next_Rollover.getIconWidth() * screenSize.height / 1080, icon_next_Rollover.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_next_Rollover = new ImageIcon(newimg);
icon_next_Pressed = new ImageIcon(getClass().getClassLoader().getResource("icons/nextp.png"));
image = icon_next_Pressed.getImage();
newimg = image.getScaledInstance(icon_next_Pressed.getIconWidth() * screenSize.height / 1080, icon_next_Pressed.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_next_Pressed = new ImageIcon(newimg);
icon_previous = new ImageIcon(getClass().getClassLoader().getResource("icons/prev.png"));
image = icon_previous.getImage();
newimg = image.getScaledInstance(icon_previous.getIconWidth() * screenSize.height / 1080, icon_previous.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_previous = new ImageIcon(newimg);
icon_prevoius_Rollover = new ImageIcon(getClass().getClassLoader().getResource("icons/prevro.png"));
image = icon_prevoius_Rollover.getImage();
newimg = image.getScaledInstance(icon_prevoius_Rollover.getIconWidth() * screenSize.height / 1080, icon_prevoius_Rollover.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_prevoius_Rollover = new ImageIcon(newimg);
icon_previous_Pressed = new ImageIcon(getClass().getClassLoader().getResource("icons/prevp.png"));
image = icon_previous_Pressed.getImage();
newimg = image.getScaledInstance(icon_previous_Pressed.getIconWidth() * screenSize.height / 1080, icon_previous_Pressed.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_previous_Pressed = new ImageIcon(newimg);
icon_repeat = new ImageIcon(getClass().getClassLoader().getResource("icons/hint.png"));
image = icon_repeat.getImage();
newimg = image.getScaledInstance(icon_repeat.getIconWidth() * screenSize.height / 1080, icon_repeat.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_repeat = new ImageIcon(newimg);
icon_repeat_Rollover = new ImageIcon(getClass().getClassLoader().getResource("icons/hintro.png"));
image = icon_repeat_Rollover.getImage();
newimg = image.getScaledInstance(icon_repeat_Rollover.getIconWidth() * screenSize.height / 1080, icon_repeat_Rollover.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_repeat_Rollover = new ImageIcon(newimg);
icon_repeat_Pressed = new ImageIcon(getClass().getClassLoader().getResource("icons/hintp.png"));
image = icon_repeat_Pressed.getImage();
newimg = image.getScaledInstance(icon_repeat_Pressed.getIconWidth() * screenSize.height / 1080, icon_repeat_Pressed.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_repeat_Pressed = new ImageIcon(newimg);
label_text = new JLabel();
if (!checkBox_text.isSelected()) label_text.setText(stepText.get(pictureNumber));
label_text.setSize(this.getWidth(), 150);
label_text.setLocation(this.getWidth() * 5 / 10 - this.getWidth() / 2, screenSize.height * 82 / 100);
label_text.setHorizontalAlignment(SwingConstants.CENTER);
label_text.setVerticalAlignment(SwingConstants.CENTER);
label_text.setFont(font.deriveFont(Font.PLAIN, 80));
btn_next = new JButton(icon_next);
btn_previous = new JButton(icon_previous);
btn_repeat = new JButton(icon_repeat);
btn_next.setRolloverIcon(icon_next_Rollover);
btn_next.setPressedIcon(icon_next_Pressed);
btn_previous.setRolloverIcon(icon_prevoius_Rollover);
btn_previous.setPressedIcon(icon_previous_Pressed);
btn_repeat.setRolloverIcon(icon_repeat_Rollover);
btn_repeat.setPressedIcon(icon_repeat_Pressed);
btn_next.setSize(icon_next.getIconWidth(), icon_next.getIconHeight());
btn_previous.setSize(icon_previous.getIconWidth(), icon_previous.getIconHeight());
btn_repeat.setSize(icon_repeat.getIconWidth(), icon_repeat.getIconHeight());
btn_next.setLocation(this.getWidth() * 9 / 10, screenSize.height * 4 / 10);
btn_previous.setLocation(this.getWidth() * 5 / 100, screenSize.height * 4 / 10);
btn_repeat.setLocation(this.getWidth() * 80 / 100, screenSize.height * 82 / 100);
btn_next.addActionListener((ActionEvent e) -> {
btn_previous.setEnabled(true);
if (pictureNumber < stepElementsNumber) {
pictureNumber++;
icon_picture = new ImageIcon(getClass().getClassLoader().getResource("stepdata/step" + stepNumber + "/pictures/" + subjectNumber + "/" + pictureNumber + ".jpg"));
Image image2 = icon_picture.getImage();
Image newimg2 = image2.getScaledInstance(icon_picture.getIconWidth() * screenSize.height / 1080, icon_picture.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_picture = new ImageIcon(newimg2);
media = new Media(getClass().getClassLoader().getResource("stepdata/step" + stepNumber + "/sounds/" + subjectNumber + "/" + pictureNumber + ".mp3").toString());
if (isMediaPlaying) {
mediaplayer.stop();
}
mediaplayer = new MediaPlayer(media);
if (!checkBox_sound.isSelected()) mediaplayer.play();
isMediaPlaying = true;
label_picture.setIcon(icon_picture);
if (!checkBox_text.isSelected()) label_text.setText(stepText.get(pictureNumber));
else label_text.setText("");
if (pictureNumber == stepElementsNumber) {
btn_next.setEnabled(false);
}
}
});
btn_previous.addActionListener((ActionEvent e) -> {
btn_next.setEnabled(true);
if (pictureNumber > 1) {
pictureNumber--;
icon_picture = new ImageIcon(getClass().getClassLoader().getResource("stepdata/step" + stepNumber + "/pictures/" + subjectNumber + "/" + pictureNumber + ".jpg"));
Image image2 = icon_picture.getImage();
Image newimg2 = image2.getScaledInstance(icon_picture.getIconWidth() * screenSize.height / 1080, icon_picture.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_picture = new ImageIcon(newimg2);
media = new Media(getClass().getClassLoader().getResource("stepdata/step" + stepNumber + "/sounds/" + subjectNumber + "/" + pictureNumber + ".mp3").toString());
if (isMediaPlaying) {
mediaplayer.stop();
}
mediaplayer = new MediaPlayer(media);
if (!checkBox_sound.isSelected()) mediaplayer.play();
isMediaPlaying = true;
label_picture.setIcon(icon_picture);
if (!checkBox_text.isSelected()) label_text.setText(stepText.get(pictureNumber));
else label_text.setText("");
if (pictureNumber == 1) {
btn_previous.setEnabled(false);
}
}
});
btn_repeat.addActionListener((ActionEvent e) -> {
if (isMediaPlaying) {
mediaplayer.stop();
}
mediaplayer = new MediaPlayer(media);
mediaplayer.play();
isMediaPlaying = true;
});
btn_next.setBorderPainted(false);
btn_next.setFocusPainted(false);
btn_next.setContentAreaFilled(false);
btn_previous.setBorderPainted(false);
btn_previous.setFocusPainted(false);
btn_previous.setContentAreaFilled(false);
btn_repeat.setBorderPainted(false);
btn_repeat.setFocusPainted(false);
btn_repeat.setContentAreaFilled(false);
icon_picture = new ImageIcon(getClass().getClassLoader().getResource("stepdata/step" + stepNumber + "/pictures/" + subjectNumber + "/" + pictureNumber + ".jpg"));
image = icon_picture.getImage();
newimg = image.getScaledInstance(icon_picture.getIconWidth() * screenSize.height / 1080, icon_picture.getIconHeight() * screenSize.height / 1080, java.awt.Image.SCALE_SMOOTH);
icon_picture = new ImageIcon(newimg);
label_picture = new JLabel(icon_picture);
label_picture.setSize(icon_picture.getIconWidth(), icon_picture.getIconHeight());
label_picture.setLocation((this.getWidth() - icon_picture.getIconWidth()) / 2 + 10, (this.getHeight() - icon_picture.getIconHeight()) / 2 - 50);
icon_frame = new ImageIcon(getClass().getClassLoader().getResource("icons/mainBack.png"));
// image = icon_frame.getImage();
// newimg = image.getScaledInstance(550, 500, java.awt.Image.SCALE_SMOOTH);
// icon_frame = new ImageIcon(newimg);
label_frame = new JLabel(icon_frame);
label_frame.setSize(icon_frame.getIconWidth(), icon_frame.getIconHeight());
label_frame.setLocation(this.getWidth() * 3 / 20, this.getHeight() / 9);
media = new Media(getClass().getClassLoader().getResource("stepdata/step" + stepNumber + "/sounds/" + subjectNumber + "/" + pictureNumber + ".mp3").toString());
mediaplayer = new MediaPlayer(media);
if (!checkBox_sound.isSelected()) mediaplayer.play();
isMediaPlaying = true;
this.add(btn_next);
this.add(btn_previous);
this.add(btn_repeat);
this.add(label_picture);
this.add(label_text);
this.add(label_frame);
}
public boolean isSoundDisable() {
return checkBox_sound.isSelected();
}
public boolean isTextDisable() {
return checkBox_text.isSelected();
}
public void deleteComponentsForHintFrame() {
this.remove(checkBox_sound);
this.remove(checkBox_text);
this.remove(btn_next);
this.remove(btn_previous);
}
public void resetComponentsLocationForHintFrame() {
btn_repeat.setLocation(this.getWidth() * 80 / 100 - 200, screenSize.height * 82 / 100 - 200);
label_frame.setLocation(this.getWidth() * 3 / 20 - 100, this.getHeight() / 9 - 100);
label_picture.setLocation((this.getWidth() - icon_picture.getIconWidth()) / 2 + 10 - 100, (this.getHeight() - icon_picture.getIconHeight()) / 2 - 50 - 100);
label_text.setLocation(this.getWidth() * 5 / 10 - this.getWidth() / 2 - 200, screenSize.height * 82 / 100 - 200);
}
private boolean isMediaPlaying;
private int pictureNumber;
private JLabel label_picture;
private JLabel label_text;
private JLabel label_frame;
private JCheckBox checkBox_sound;
private JCheckBox checkBox_text;
private JButton btn_next;
private JButton btn_previous;
private JButton btn_repeat;
private ImageIcon icon_frame;
private ImageIcon icon_picture;
private ImageIcon icon_next;
private ImageIcon icon_next_Rollover;
private ImageIcon icon_next_Pressed;
private ImageIcon icon_previous;
private ImageIcon icon_prevoius_Rollover;
private ImageIcon icon_previous_Pressed;
private ImageIcon icon_repeat;
private ImageIcon icon_repeat_Rollover;
private ImageIcon icon_repeat_Pressed;
private final JFXPanel fxpanel;
private Media media;
private MediaPlayer mediaplayer;
}
/*
lpPicture.add(lblPicture);
lpPicture.add(lblFrame);
mainPanel.add(lpPicture);
mainPanel.add(lblText);
*/
<file_sep>/FutureProj/src/classes/Step.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package classes;
import classes.KalameApp.StepType;
/**
*
* @author Reza
*/
public class Step {
public Step(int numberOfLearnings, int numberOfExams, String[] stepNames, StepType[] examTypes) {
this.numberOfLearnings = numberOfLearnings;
this.numberOfExams = numberOfExams;
this.stepNames = stepNames;
this.examTypes = examTypes;
}
public int getNumberOfLearnings() {
return numberOfLearnings;
}
public int getNumberOfExams() {
return numberOfExams;
}
public String[] getStepNames() {
return stepNames;
}
public StepType[] getExamTypes() {
return examTypes;
}
private final int numberOfLearnings;
private final int numberOfExams;
private final String[] stepNames;
private final StepType[] examTypes;
}
| ad51b40ae15ea3c8a89ef6b4e2d9fc12c831f005 | [
"Markdown",
"Java"
] | 4 | Java | haji4ref/Future | 8721be75b2a570993d4bce5194bde37030534761 | adfc8874abc3eef5abb8a2761199f2911e07cbbc | |
refs/heads/master | <file_sep>/*
Copyright (c) 2012, Broadcom Europe Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder 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 HOLDER 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.
*/
/*=============================================================================
VCOS - packet-like messages, based loosely on those found in TRIPOS.
=============================================================================*/
#ifndef VCOS_MSGQUEUE_H
#define VCOS_MSGQUEUE_H
#ifdef __cplusplus
extern "C" {
#endif
#include "vcos_types.h"
#include "vcos_platform.h"
/**
* \file
*
* Packet-like messages, based loosely on those found in TRIPOS and
* derivatives thereof.
*
* A task can send a message *pointer* to another task, where it is
* queued on a linked list and the task woken up. The receiving task
* consumes all of the messages on its input queue, and optionally
* sends back replies using the original message memory.
*
* A caller can wait for the reply to a specific message - any other
* messages that arrive in the meantime are queued separately.
*
*
* All messages have a standard common layout, but the payload area can
* be used freely to extend this.
*/
/** Map the payload portion of a message to a structure pointer.
*/
#define VCOS_MSG_DATA(_msg) (void*)((_msg)->data)
/** Standard message ids - FIXME - these need to be done properly! */
#define VCOS_MSG_N_QUIT 1
#define VCOS_MSG_N_OPEN 2
#define VCOS_MSG_N_CLOSE 3
#define VCOS_MSG_N_PRIVATE (1<<20)
#define VCOS_MSG_REPLY_BIT (1<<31)
/** Make gnuc compiler be happy about pointer punning */
#ifdef __GNUC__
#define __VCOS_MAY_ALIAS __attribute__((__may_alias__))
#else
#define __VCOS_MAY_ALIAS
#endif
/** A single message queue.
*/
typedef struct VCOS_MSGQUEUE_T
{
struct VCOS_MSG_T *head; /**< head of linked list of messages waiting on this queue */
struct VCOS_MSG_T *tail; /**< tail of message queue */
VCOS_SEMAPHORE_T sem; /**< thread waits on this for new messages */
VCOS_MUTEX_T lock; /**< locks the messages list */
} VCOS_MSGQUEUE_T;
/** A single message
*/
typedef struct VCOS_MSG_T
{
uint32_t code; /**< message code */
int error; /**< error status signalled back to caller */
VCOS_MSGQUEUE_T *dst; /**< destination queue */
VCOS_MSGQUEUE_T *src; /**< source; replies go back to here */
struct VCOS_MSG_T *next; /**< next in queue */
VCOS_THREAD_T *src_thread; /**< for debug */
uint32_t data[25]; /**< payload area */
} VCOS_MSG_T;
/** An endpoint
*/
typedef struct VCOS_MSG_ENDPOINT_T
{
VCOS_MSGQUEUE_T primary; /**< incoming messages */
VCOS_MSGQUEUE_T secondary; /**< this is used for waitspecific */
char name[32]; /**< name of this endpoint, for find() */
struct VCOS_MSG_ENDPOINT_T *next; /**< next in global list of endpoints */
} VCOS_MSG_ENDPOINT_T;
#define MSG_REPLY_BIT (1<<31)
/** Initalise the library. Normally called from vcos_init().
*/
VCOSPRE_ VCOS_STATUS_T VCOSPOST_ vcos_msgq_init(void);
/** De-initialise the library. Normally called from vcos_deinit().
*/
VCOSPRE_ void VCOSPOST_ vcos_msgq_deinit(void);
/** Find a message queue by name and get a handle to it.
*
* @param name the name of the queue to find
*
* @return The message queue, or NULL if not found.
*/
VCOSPRE_ VCOS_MSGQUEUE_T VCOSPOST_ *vcos_msgq_find(const char *name);
/** Wait for a message queue to come into existence. If it already exists,
* return immediately, otherwise block.
*
* On the whole, if you find yourself using this, it is probably a sign
* of poor design, since you should create all the server threads first,
* and then the client threads. But it is sometimes useful.
*
* @param name the name of the queue to find
* @return The message queue
*/
VCOSPRE_ VCOS_MSGQUEUE_T VCOSPOST_ *vcos_msgq_wait(const char *name);
/** Send a message.
*/
VCOSPRE_ void VCOSPOST_ vcos_msg_send(VCOS_MSGQUEUE_T *dest, uint32_t code, VCOS_MSG_T *msg);
/** Send a message and wait for a reply.
*/
VCOSPRE_ void VCOSPOST_ vcos_msg_sendwait(VCOS_MSGQUEUE_T *queue, uint32_t code, VCOS_MSG_T *msg);
/** Wait for a message on this thread's endpoint.
*/
VCOSPRE_ VCOS_MSG_T * VCOSPOST_ vcos_msg_wait(void);
/** Wait for a specific message.
*/
VCOS_MSG_T * vcos_msg_wait_specific(VCOS_MSGQUEUE_T *queue, VCOS_MSG_T *msg);
/** Peek for a message on this thread's endpoint, if a message is not available, NULL is
returned. If a message is available it will be removed from the endpoint and returned.
*/
VCOSPRE_ VCOS_MSG_T * VCOSPOST_ vcos_msg_peek(void);
/** Send a reply to a message
*/
VCOSPRE_ void VCOSPOST_ vcos_msg_reply(VCOS_MSG_T *msg);
/** Create an endpoint. Each thread should need no more than one of these - if you
* find yourself needing a second one, you've done something wrong.
*/
VCOSPRE_ VCOS_STATUS_T VCOSPOST_ vcos_msgq_endpoint_create(VCOS_MSG_ENDPOINT_T *ep, const char *name);
/** Destroy an endpoint.
*/
VCOSPRE_ void VCOSPOST_ vcos_msgq_endpoint_delete(VCOS_MSG_ENDPOINT_T *ep);
#ifdef __cplusplus
}
#endif
#endif
<file_sep>#!/bin/bash
mkdir -p build/arm-android/release/
pushd build/arm-android/release/
echo "Before running this, set ANDROID_ROOT to your root-Android-dir, and ANDROID_TOOLCHAIN to your toolchain's /bin dir."
cmake -DCMAKE_TOOLCHAIN_FILE=../../../makefiles/cmake/toolchains/arm-android.cmake -DCMAKE_BUILD_TYPE=Release ../../..
make
popd
<file_sep>#
# CMake defines to cross-compile to ARM/Linux on BCM2708 using glibc.
#
# Note that the compilers should be in $ANDROID_TOOLCHAIN
SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_C_COMPILER $ENV{ANDROID_TOOLCHAIN}/arm-linux-androideabi-gcc)
SET(CMAKE_CXX_COMPILER $ENV{ANDROID_TOOLCHAIN}/arm-linux-androideabi-g++)
SET(CMAKE_ASM_COMPILER $ENV{ANDROID_TOOLCHAIN}/arm-linux-androideabi-as)
SET(CMAKE_SYSTEM_PROCESSOR arm)
SET(ANDROID TRUE)
#ADD_DEFINITIONS("-march=armv6")
add_definitions("-mcpu=arm1176jzf-s")
# rdynamic means the backtrace should work
IF (CMAKE_BUILD_TYPE MATCHES "Debug")
add_definitions(-rdynamic)
ENDIF()
# avoids annoying and pointless warnings from gcc
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -U_FORTIFY_SOURCE")
<file_sep>#ifndef _GRLC_H
#define _GRLC_H
#include "include/ui/android_native_buffer.h"
typedef struct gralloc_private_handle_t{
int res_type;
int w;
int h;
int stride;
uint32_t vcHandle;
int gl_format;
android_native_buffer_t * buffer;
} gralloc_private_handle_t;
/*
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
*/
const int GRALLOC_PRIV_TYPE_MM_RESOURCE = 0;
const int GRALLOC_PRIV_TYPE_GL_RESOURCE = 1;
const int GRALLOC_MAGICS_HAL_PIXEL_FORMAT_OPAQUE = 0;
const int GRALLOC_MAGICS_HAL_PIXEL_FORMAT_TRANSLUCENT = 1;
gralloc_private_handle_t* gralloc_private_handle_from_client_buffer(EGLClientBuffer buffer);
uint32_t gralloc_private_handle_get_vc_handle(gralloc_private_handle_t *b);
uint32_t gralloc_private_handle_get_egl_image(gralloc_private_handle_t *b);
int gralloc_get_pf(gralloc_private_handle_t *b);
#endif
<file_sep>This repository contains the source code for the ARM side libraries used on Raspberry Pi.
These typically are installed in /opt/vc/lib and includes source for the ARM side code to interface to:
EGL, mmal, GLESv2, vcos, openmaxil, vchiq_arm, bcm_host, WFC, OpenVG.
This is an effort to create an Android-compatible version of the libraries. It <em>should</em> be usable as of commit '168441d31c'. However, as there's no working gralloc module for Android on the Raspberry Pi, there's no real way of knowing if it is. If you happen to discover any issue with the libs, post an issue and it'll be looked into, or better yet, fork me and fix it yourself, then gimme a pull request.
Use buildme.android to build. It requires cmake to be installed and an arm cross compiler.
Before running buildme.android, set the environment variables 'ANDROID_ROOT' to your root-Android-dir (as in, your CyanogenMod source tree with proper RPi-patches etc), and 'ANDROID_TOOLCHAIN' to your toolchain's /bin dir.</p>
Contact: #razdroid @ irc.freenode.net -- My nick is Warg.
<file_sep>/*
Copyright (c) 2012, Broadcom Europe Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "mmal_clock.h"
#include "mmal_logging.h"
#include "core/mmal_clock_private.h"
#include "core/mmal_port_private.h"
#include "util/mmal_util.h"
#ifdef __VIDEOCORE__
# include "vcfw/rtos/common/rtos_common_mem.h"
#endif
/** Minimum number of buffers required on a clock port */
#define MMAL_PORT_CLOCK_BUFFERS_MIN 8
/** Private clock port context */
typedef struct MMAL_PORT_MODULE_T
{
MMAL_PORT_CLOCK_EVENT_CB event_cb; /**< callback for notifying the component of clock events */
MMAL_QUEUE_T *queue; /**< queue for empty buffers sent to the port */
MMAL_CLOCK_T *clock; /**< clock module for scheduling requests */
MMAL_BOOL_T is_reference; /**< TRUE -> clock port is a reference, therefore
will forward time updates */
} MMAL_PORT_MODULE_T;
/*****************************************************************************
* Private functions
*****************************************************************************/
#ifdef __VIDEOCORE__
/* FIXME: mmal_buffer_header_mem_lock() assumes that payload memory is on the
* relocatable heap when on VC. However that is not always the case. The MMAL
* framework will allocate memory from the normal heap when ports are connected.
* To work around this, override the default behaviour by providing a payload
* allocator for clock ports which always allocates from the relocatable heap. */
static uint8_t* mmal_port_clock_payload_alloc(MMAL_PORT_T *port, uint32_t payload_size)
{
int alignment = port->buffer_alignment_min;
uint8_t *mem;
if (!alignment)
alignment = 32;
vcos_assert((alignment & (alignment-1)) == 0);
mem = (uint8_t*)mem_alloc(payload_size, alignment, MEM_FLAG_DIRECT, port->name);
if (!mem)
{
LOG_ERROR("could not allocate %u bytes", payload_size);
return NULL;
}
return mem;
}
static void mmal_port_clock_payload_free(MMAL_PORT_T *port, uint8_t *payload)
{
MMAL_PARAM_UNUSED(port);
mem_release((MEM_HANDLE_T)payload);
}
#endif
/* Callback invoked by the clock module in response to a client request */
static void mmal_port_clock_request_cb(MMAL_CLOCK_T* clock, int64_t media_time, void *cb_data, MMAL_CLOCK_VOID_FP cb)
{
MMAL_PORT_CLOCK_REQUEST_CB cb_client = (MMAL_PORT_CLOCK_REQUEST_CB)cb;
/* Forward to the client */
cb_client((MMAL_PORT_T*)clock->user_data, media_time, cb_data);
}
/* Process buffers received from other clock ports */
static MMAL_STATUS_T mmal_port_clock_process_buffer(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
{
MMAL_STATUS_T status = MMAL_SUCCESS;
MMAL_CLOCK_PAYLOAD_T payload;
if (buffer->length != sizeof(MMAL_CLOCK_PAYLOAD_T))
{
LOG_ERROR("invalid buffer length %d", buffer->length);
return MMAL_EINVAL;
}
mmal_buffer_header_mem_lock(buffer);
memcpy(&payload, buffer->data, sizeof(MMAL_CLOCK_PAYLOAD_T));
mmal_buffer_header_mem_unlock(buffer);
if (payload.magic != MMAL_CLOCK_PAYLOAD_MAGIC)
{
LOG_ERROR("buffer corrupt (magic %4.4s)", (char*)&payload.magic);
return MMAL_EINVAL;
}
LOG_TRACE("port %s length %d id %4.4s time %"PRIi64,
port->name, buffer->length, (char*)&payload.id, payload.time);
switch (payload.id)
{
case MMAL_CLOCK_PAYLOAD_TIME:
mmal_clock_media_time_set(port->priv->module->clock, payload.time);
break;
case MMAL_CLOCK_PAYLOAD_SCALE:
mmal_clock_scale_set(port->priv->module->clock, payload.data.scale);
break;
default:
LOG_ERROR("invalid id %4.4s", (char*)&payload.id);
status = MMAL_EINVAL;
break;
}
/* Finished with the buffer, so return it */
buffer->length = 0;
mmal_port_buffer_header_callback(port, buffer);
return status;
}
static MMAL_STATUS_T mmal_port_clock_send(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
{
MMAL_PORT_MODULE_T *module = port->priv->module;
if (buffer->length)
return mmal_port_clock_process_buffer(port, buffer);
/* Queue empty buffers to be used later when forwarding clock updates */
mmal_queue_put(module->queue, buffer);
return MMAL_SUCCESS;
}
static MMAL_STATUS_T mmal_port_clock_flush(MMAL_PORT_T *port)
{
MMAL_BUFFER_HEADER_T *buffer;
/* Flush empty buffers */
buffer = mmal_queue_get(port->priv->module->queue);
while (buffer)
{
mmal_port_buffer_header_callback(port, buffer);
buffer = mmal_queue_get(port->priv->module->queue);
}
return MMAL_SUCCESS;
}
static MMAL_STATUS_T mmal_port_clock_parameter_set(MMAL_PORT_T *port, const MMAL_PARAMETER_HEADER_T *param)
{
MMAL_STATUS_T status = MMAL_SUCCESS;
MMAL_PORT_MODULE_T *module = port->priv->module;
MMAL_CLOCK_PAYLOAD_T event;
switch (param->id)
{
case MMAL_PARAMETER_CLOCK_REFERENCE:
{
const MMAL_PARAMETER_BOOLEAN_T *p = (const MMAL_PARAMETER_BOOLEAN_T*)param;
module->is_reference = p->enable;
event.id = MMAL_CLOCK_PAYLOAD_REFERENCE;
event.time = mmal_clock_media_time_get(module->clock);
event.data.enable = p->enable;
}
break;
case MMAL_PARAMETER_CLOCK_ACTIVE:
{
const MMAL_PARAMETER_BOOLEAN_T *p = (const MMAL_PARAMETER_BOOLEAN_T*)param;
status = mmal_clock_active_set(module->clock, p->enable);
event.id = MMAL_CLOCK_PAYLOAD_ACTIVE;
event.time = mmal_clock_media_time_get(module->clock);
event.data.enable = p->enable;
}
break;
case MMAL_PARAMETER_CLOCK_SCALE:
{
const MMAL_PARAMETER_RATIONAL_T *p = (const MMAL_PARAMETER_RATIONAL_T*)param;
status = mmal_port_clock_scale_set(port, p->value);
event.id = MMAL_CLOCK_PAYLOAD_SCALE;
event.time = mmal_clock_media_time_get(module->clock);
event.data.scale = p->value;
}
break;
case MMAL_PARAMETER_CLOCK_TIME:
{
const MMAL_PARAMETER_INT64_T *p = (const MMAL_PARAMETER_INT64_T*)param;
status = mmal_port_clock_media_time_set(port, p->value);
event.id = MMAL_CLOCK_PAYLOAD_INVALID;
}
break;
case MMAL_PARAMETER_CLOCK_TIME_OFFSET:
{
const MMAL_PARAMETER_INT64_T *p = (const MMAL_PARAMETER_INT64_T*)param;
status = mmal_port_clock_media_time_offset_set(port, p->value);
event.id = MMAL_CLOCK_PAYLOAD_INVALID;
}
break;
case MMAL_PARAMETER_CLOCK_UPDATE_THRESHOLD:
{
const MMAL_PARAMETER_CLOCK_UPDATE_THRESHOLD_T *p = (MMAL_PARAMETER_CLOCK_UPDATE_THRESHOLD_T *)param;
status = mmal_clock_update_threshold_set(module->clock, p);
event.id = MMAL_CLOCK_PAYLOAD_INVALID;
}
break;
case MMAL_PARAMETER_CLOCK_DISCONT_THRESHOLD:
{
const MMAL_PARAMETER_CLOCK_DISCONT_THRESHOLD_T *p = (MMAL_PARAMETER_CLOCK_DISCONT_THRESHOLD_T *)param;
status = mmal_clock_discont_threshold_set(module->clock, p);
event.id = MMAL_CLOCK_PAYLOAD_INVALID;
}
break;
default:
return MMAL_ENOSYS;
}
/* Notify the component */
if (module->event_cb && status == MMAL_SUCCESS && event.id != MMAL_CLOCK_PAYLOAD_INVALID)
module->event_cb(port, &event);
return status;
}
static MMAL_STATUS_T mmal_port_clock_parameter_get(MMAL_PORT_T *port, MMAL_PARAMETER_HEADER_T *param)
{
MMAL_PORT_MODULE_T *module = port->priv->module;
switch (param->id)
{
case MMAL_PARAMETER_CLOCK_REFERENCE:
{
MMAL_PARAMETER_BOOLEAN_T *p = (MMAL_PARAMETER_BOOLEAN_T*)param;
p->enable = module->is_reference;
}
break;
case MMAL_PARAMETER_CLOCK_ACTIVE:
{
MMAL_PARAMETER_BOOLEAN_T *p = (MMAL_PARAMETER_BOOLEAN_T*)param;
p->enable = mmal_clock_is_active(module->clock);
}
break;
case MMAL_PARAMETER_CLOCK_SCALE:
{
MMAL_PARAMETER_RATIONAL_T *p = (MMAL_PARAMETER_RATIONAL_T*)param;
p->value = mmal_clock_scale_get(module->clock);
}
break;
case MMAL_PARAMETER_CLOCK_TIME:
{
MMAL_PARAMETER_INT64_T *p = (MMAL_PARAMETER_INT64_T*)param;
p->value = mmal_clock_media_time_get(module->clock);
}
break;
case MMAL_PARAMETER_CLOCK_TIME_OFFSET:
{
MMAL_PARAMETER_INT64_T *p = (MMAL_PARAMETER_INT64_T*)param;
p->value = mmal_clock_media_time_offset_get(module->clock);
}
break;
case MMAL_PARAMETER_CLOCK_UPDATE_THRESHOLD:
{
MMAL_PARAMETER_CLOCK_UPDATE_THRESHOLD_T *p = (MMAL_PARAMETER_CLOCK_UPDATE_THRESHOLD_T *)param;
mmal_clock_update_threshold_get(module->clock, p);
}
break;
case MMAL_PARAMETER_CLOCK_DISCONT_THRESHOLD:
{
MMAL_PARAMETER_CLOCK_DISCONT_THRESHOLD_T *p = (MMAL_PARAMETER_CLOCK_DISCONT_THRESHOLD_T *)param;
mmal_clock_discont_threshold_get(module->clock, p);
}
break;
default:
return MMAL_ENOSYS;
}
return MMAL_SUCCESS;
}
static MMAL_STATUS_T mmal_port_clock_enable(MMAL_PORT_T *port, MMAL_PORT_BH_CB_T cb)
{
MMAL_PARAM_UNUSED(port);
MMAL_PARAM_UNUSED(cb);
return MMAL_SUCCESS;
}
static MMAL_STATUS_T mmal_port_clock_disable(MMAL_PORT_T *port)
{
MMAL_PORT_MODULE_T *module = port->priv->module;
if (mmal_clock_is_active(module->clock))
mmal_clock_active_set(module->clock, MMAL_FALSE);
mmal_port_clock_flush(port);
return MMAL_SUCCESS;
}
static MMAL_STATUS_T mmal_port_clock_set_format(MMAL_PORT_T *port)
{
MMAL_PARAM_UNUSED(port);
return MMAL_SUCCESS;
}
static MMAL_STATUS_T mmal_port_clock_connect(MMAL_PORT_T *port, MMAL_PORT_T *other_port)
{
MMAL_PARAM_UNUSED(port);
MMAL_PARAM_UNUSED(other_port);
return MMAL_ENOSYS;
}
/* Send a payload buffer to a connected port/client */
static MMAL_STATUS_T mmal_port_clock_forward_payload(MMAL_PORT_T *port, const MMAL_CLOCK_PAYLOAD_T *payload)
{
MMAL_STATUS_T status;
MMAL_BUFFER_HEADER_T *buffer;
buffer = mmal_queue_get(port->priv->module->queue);
if (!buffer)
{
LOG_ERROR("no free buffers available");
return MMAL_ENOSPC;
}
status = mmal_buffer_header_mem_lock(buffer);
if (status != MMAL_SUCCESS)
{
LOG_ERROR("failed to lock buffer %s", mmal_status_to_string(status));
mmal_queue_put_back(port->priv->module->queue, buffer);
goto end;
}
buffer->length = sizeof(MMAL_CLOCK_PAYLOAD_T);
memcpy(buffer->data, payload, buffer->length);
mmal_buffer_header_mem_unlock(buffer);
mmal_port_buffer_header_callback(port, buffer);
end:
return status;
}
/* Send a clock time update to a connected port/client */
static MMAL_STATUS_T mmal_port_clock_forward_media_time(MMAL_PORT_T *port, int64_t media_time)
{
MMAL_CLOCK_PAYLOAD_T payload;
payload.id = MMAL_CLOCK_PAYLOAD_TIME;
payload.magic = MMAL_CLOCK_PAYLOAD_MAGIC;
payload.time = media_time;
return mmal_port_clock_forward_payload(port, &payload);
}
/* Send a clock scale update to a connected port/client */
static MMAL_STATUS_T mmal_port_clock_forward_scale(MMAL_PORT_T *port, MMAL_RATIONAL_T scale)
{
MMAL_CLOCK_PAYLOAD_T payload;
payload.id = MMAL_CLOCK_PAYLOAD_SCALE;
payload.magic = MMAL_CLOCK_PAYLOAD_MAGIC;
payload.time = mmal_clock_media_time_get(port->priv->module->clock);
payload.data.scale = scale;
return mmal_port_clock_forward_payload(port, &payload);
}
/* Initialise all callbacks and setup internal resources */
static MMAL_STATUS_T mmal_port_clock_setup(MMAL_PORT_T *port, MMAL_PORT_CLOCK_EVENT_CB event_cb)
{
MMAL_STATUS_T status;
status = mmal_clock_create(&port->priv->module->clock);
if (status != MMAL_SUCCESS)
{
LOG_ERROR("failed to create clock module on port %s (%s)", port->name, mmal_status_to_string(status));
return status;
}
port->priv->module->clock->user_data = port;
port->buffer_size = sizeof(MMAL_CLOCK_PAYLOAD_T);
port->buffer_size_min = sizeof(MMAL_CLOCK_PAYLOAD_T);
port->buffer_num_min = MMAL_PORT_CLOCK_BUFFERS_MIN;
port->buffer_num_recommended = MMAL_PORT_CLOCK_BUFFERS_MIN;
port->priv->module->event_cb = event_cb;
port->priv->module->queue = mmal_queue_create();
if (!port->priv->module->queue)
{
mmal_clock_destroy(port->priv->module->clock);
return MMAL_ENOMEM;
}
port->priv->pf_set_format = mmal_port_clock_set_format;
port->priv->pf_enable = mmal_port_clock_enable;
port->priv->pf_disable = mmal_port_clock_disable;
port->priv->pf_send = mmal_port_clock_send;
port->priv->pf_flush = mmal_port_clock_flush;
port->priv->pf_parameter_set = mmal_port_clock_parameter_set;
port->priv->pf_parameter_get = mmal_port_clock_parameter_get;
port->priv->pf_connect = mmal_port_clock_connect;
#ifdef __VIDEOCORE__
port->priv->pf_payload_alloc = mmal_port_clock_payload_alloc;
port->priv->pf_payload_free = mmal_port_clock_payload_free;
port->capabilities = MMAL_PORT_CAPABILITY_ALLOCATION;
#endif
return status;
}
/* Release all internal resources */
static void mmal_port_clock_teardown(MMAL_PORT_T *port)
{
if (!port)
return;
mmal_queue_destroy(port->priv->module->queue);
mmal_clock_destroy(port->priv->module->clock);
}
/*****************************************************************************
* Public functions
*****************************************************************************/
/* Allocate a clock port */
MMAL_PORT_T* mmal_port_clock_alloc(MMAL_COMPONENT_T *component, MMAL_PORT_CLOCK_EVENT_CB event_cb)
{
MMAL_PORT_T *port;
port = mmal_port_alloc(component, MMAL_PORT_TYPE_CLOCK, sizeof(MMAL_PORT_MODULE_T));
if (!port)
return NULL;
if (mmal_port_clock_setup(port, event_cb) != MMAL_SUCCESS)
{
mmal_port_free(port);
return NULL;
}
return port;
}
/* Free a clock port */
void mmal_port_clock_free(MMAL_PORT_T *port)
{
mmal_port_clock_teardown(port);
mmal_port_free(port);
}
/* Allocate an array of clock ports */
MMAL_PORT_T **mmal_ports_clock_alloc(MMAL_COMPONENT_T *component, unsigned int ports_num, MMAL_PORT_CLOCK_EVENT_CB event_cb)
{
unsigned int i;
MMAL_PORT_T **ports;
ports = mmal_ports_alloc(component, ports_num, MMAL_PORT_TYPE_CLOCK, sizeof(MMAL_PORT_MODULE_T));
if (!ports)
return NULL;
for (i = 0; i < ports_num; i++)
{
if (mmal_port_clock_setup(ports[i], event_cb) != MMAL_SUCCESS)
break;
}
if (i != ports_num)
{
for (ports_num = i, i = 0; i < ports_num; i++)
mmal_port_clock_free(ports[i]);
vcos_free(ports);
return NULL;
}
return ports;
}
/* Free an array of clock ports */
void mmal_ports_clock_free(MMAL_PORT_T **ports, unsigned int ports_num)
{
unsigned int i;
for (i = 0; i < ports_num; i++)
mmal_port_clock_free(ports[i]);
vcos_free(ports);
}
/* Register a callback request */
MMAL_STATUS_T mmal_port_clock_request_add(MMAL_PORT_T *port, int64_t media_time, int64_t offset,
MMAL_PORT_CLOCK_REQUEST_CB cb, void *cb_data)
{
return mmal_clock_request_add(port->priv->module->clock, media_time, offset,
mmal_port_clock_request_cb, cb_data, (MMAL_CLOCK_VOID_FP)cb);
}
/* Flush all pending clock requests */
MMAL_STATUS_T mmal_port_clock_request_flush(MMAL_PORT_T *port)
{
return mmal_clock_request_flush(port->priv->module->clock);
}
/* Set the media-time on the clock port */
MMAL_STATUS_T mmal_port_clock_media_time_set(MMAL_PORT_T *port, int64_t media_time)
{
MMAL_STATUS_T status;
status = mmal_clock_media_time_set(port->priv->module->clock, media_time);
if (status != MMAL_SUCCESS)
{
LOG_DEBUG("clock update ignored");
return status;
}
/* Only forward time updates if this port is set as a reference clock port */
if (port->priv->module->is_reference)
mmal_port_clock_forward_media_time(port, mmal_clock_media_time_get(port->priv->module->clock));
return status;
}
/* Set the media-time offset on the clock port */
MMAL_STATUS_T mmal_port_clock_media_time_offset_set(MMAL_PORT_T *port, int64_t offset)
{
MMAL_STATUS_T status;
status = mmal_clock_media_time_offset_set(port->priv->module->clock, offset);
/* The media-time has effectively changed, so need to inform connected clock ports */
if (port->priv->module->is_reference)
mmal_port_clock_forward_media_time(port, mmal_clock_media_time_get(port->priv->module->clock));
return status;
}
/* Return the current media-time */
int64_t mmal_port_clock_media_time_get(MMAL_PORT_T *port)
{
return mmal_clock_media_time_get(port->priv->module->clock);
}
/* Return the media-time offset */
int64_t mmal_port_clock_media_time_offset_get(MMAL_PORT_T *port)
{
return mmal_clock_media_time_offset_get(port->priv->module->clock);
}
/* Set the clock scale factor */
MMAL_STATUS_T mmal_port_clock_scale_set(MMAL_PORT_T *port, MMAL_RATIONAL_T scale)
{
MMAL_STATUS_T status;
status = mmal_clock_scale_set(port->priv->module->clock, scale);
if (port->priv->module->is_reference)
mmal_port_clock_forward_scale(port, scale);
return status;
}
/* Return the clock scale factor */
MMAL_RATIONAL_T mmal_port_clock_scale_get(MMAL_PORT_T *port)
{
return mmal_clock_scale_get(port->priv->module->clock);
}
/* Return TRUE if clock is running (media-time is advancing) */
MMAL_BOOL_T mmal_port_clock_is_active(MMAL_PORT_T *port)
{
return mmal_clock_is_active(port->priv->module->clock);
}
<file_sep>#ifndef __LOGGY__
#define NO_OPENVG 1
#include "include/android/log.h"
#define LOG_TAG "LOGGY_WARG"
# define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
# define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define __LOGGY__ 1
#endif
<file_sep># setup environment for cross compile to arm-linux
if (DEFINED CMAKE_TOOLCHAIN_FILE)
else()
message(FATAL_ERROR
" *********************************************************\n"
" * CMAKE_TOOLCHAIN_FILE not defined *\n"
" * Please DELETE the build directory and re-run with: *\n"
" * -DCMAKE_TOOLCHAIN_FILE=toolchain_file.cmake *\n"
" * *\n"
" * Toolchain files are in makefiles/cmake/toolchains. *\n"
" *********************************************************"
)
endif()
# pull in headers for android
if(ANDROID)
# build shared libs
OPTION (BUILD_SHARED_LIBS ON)
#
# work out where android headers and library are
#
set(ANDROID_PRODUCT "rpi" CACHE INTERNAL "" FORCE)
set(ANDROID_ROOT $ENV{ANDROID_ROOT} CACHE INTERNAL "" FORCE)
set(ANDROID_NDK_ROOT $ENV{ANDROID_NDK_ROOT} CACHE INTERNAL "" FORCE)
set(ANDROID_LIBS $ENV{ANDROID_LIBS} CACHE INTERNAL "" FORCE)
set(ANDROID_BIONIC $ENV{ANDROID_BIONIC} CACHE INTERNAL "" FORCE)
set(ANDROID_LDSCRIPTS $ENV{ANDROID_LDSCRIPTS} CACHE INTERNAL "" FORCE)
if("${ANDROID_NDK_ROOT}" STREQUAL "")
find_program(ANDROID_COMPILER arm-eabi-gcc)
get_filename_component(ANDROID_BIN ${ANDROID_COMPILER} PATH)
find_path(_ANDROID_ROOT Makefile PATHS ${ANDROID_BIN}
PATH_SUFFIXES ../../../../..
NO_DEFAULT_PATH)
if("${_ANDROID_ROOT}" STREQUAL "_ANDROID_ROOT-NOTFOUND")
set(_ANDROID_ROOT "$ENV{ANDROID_ROOT}" CACHE INTERNAL "" FORCE)
endif()
if("${_ANDROID_ROOT}" STREQUAL "")
# message(FATAL_ERROR "Cannot find android root directory")
SET(ANDROID_ROOT ".")
endif()
get_filename_component(ANDROID_ROOT ${_ANDROID_ROOT} ABSOLUTE CACHE)
#
# top level of cross-compiler target include and lib directory structure
#
set(ANDROID_NDK_ROOT
"${ANDROID_ROOT}/prebuilt/ndk" CACHE INTERNAL "" FORCE)
set(ANDROID_BIONIC
"${ANDROID_ROOT}/bionic" CACHE INTERNAL "" FORCE)
set(ANDROID_LDSCRIPTS
"${ANDROID_ROOT}/build/core" CACHE INTERNAL "" FORCE)
set(ANDROID_LIBS
"${ANDROID_ROOT}/out/target/product/${ANDROID_PRODUCT}/obj/lib"
CACHE INTERNAL "" FORCE)
endif()
if("${ANDROID_NDK_ROOT}" STREQUAL "")
message(FATAL_ERROR "Cannot find Android NDK root directory")
endif()
if("${ANDROID_BIONIC}" STREQUAL "")
message(FATAL_ERROR "Cannot find Android BIONIC directory")
endif()
if("${ANDROID_LDSCRIPTS}" STREQUAL "")
message(FATAL_ERROR "Cannot find Android LD scripts directory")
endif()
set(CMAKE_SYSTEM_PREFIX_PATH "${ANDROID_NDK_ROOT}/android-ndk-r${ANDROID_NDK_RELEASE}/platforms/android-${ANDROID_NDK_PLATFORM}/arch-${CMAKE_SYSTEM_PROCESSOR}/usr")
if("${ANDROID_LIBS}" STREQUAL "")
set(ANDROID_LIBS "${CMAKE_SYSTEM_PREFIX_PATH}/lib"
CACHE INTERNAL "" FORCE)
# message(FATAL_ERROR "Cannot find android libraries")
endif()
#
# add include directories for pthreads
#
include_directories("${CMAKE_SYSTEM_PREFIX_PATH}/include" BEFORE SYSTEM)
include_directories("${ANDROID_BIONIC}/libc/include/arch-arm/include" BEFORE SYSTEM)
include_directories("${ANDROID_BIONIC}/libc/include" BEFORE SYSTEM)
include_directories("${ANDROID_BIONIC}/libc/kernel/arch-arm" BEFORE SYSTEM)
include_directories("${ANDROID_BIONIC}/libc/kernel/common" BEFORE SYSTEM)
include_directories("${ANDROID_BIONIC}/libm/include" BEFORE SYSTEM)
include_directories("${ANDROID_BIONIC}/libm/include/arch/arm" BEFORE SYSTEM)
include_directories("${ANDROID_BIONIC}/libstdc++/include" BEFORE SYSTEM)
#
# Pull in Android link options manually
#
set(ANDROID_SHARED_CRTBEGIN "${ANDROID_TOOLCHAIN}/../lib/gcc/arm-linux-androideabi/4.6.3/crtbeginS.o")
set(ANDROID_SHARED_CRTEND "${ANDROID_TOOLCHAIN}/../lib/gcc/arm-linux-androideabi/4.6.3/crtendS.o")
set(CMAKE_SHARED_LINKER_FLAGS "-nostdlib ${ANDROID_SHARED_CRTBEGIN} -Wl,-Bdynamic -Wl,-T${ANDROID_LDSCRIPTS}/armelf.x")
# set(ANDROID_CRTBEGIN "/home/viktor/arm-linux-androideabi-4.6.3/lib/gcc/arm-linux-androideabi/4.6.3/crtbegin.o")
# set(ANDROID_CRTEND "/home/viktor/arm-linux-androideabi-4.6.3/lib/gcc/arm-linux-androideabi/4.6.3/crtend.o")
link_directories(${ANDROID_LIBS})
set(CMAKE_EXE_LINKER_FLAGS "-nostdlib ${ANDROID_SHARED_CRTBEGIN} -nostdlib -Wl,-z,noexecstack")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-dynamic-linker,/system/bin/linker -Wl,-rpath,${CMAKE_INSTALL_PREFIX}/lib")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-T${ANDROID_LDSCRIPTS}/armelf.x -Wl,--gc-sections")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,nocopyreloc -Wl,-z,noexecstack -Wl,--fix-cortex-a8 -Wl,--no-undefined")
set(CMAKE_C_STANDARD_LIBRARIES "-llog -lc -lgcc ${ANDROID_SHARED_CRTEND}" CACHE INTERNAL "" FORCE)
set(SHARED "SHARED")
else()
set(SHARED "SHARED")
endif()
# All linux systems have sbrk()
add_definitions(-D_HAVE_SBRK)
# pull in declarations of lseek64 and friends
add_definitions(-D_LARGEFILE64_SOURCE)
# test for glibc malloc debugging extensions
try_compile(HAVE_MTRACE
${CMAKE_BINARY_DIR}
${CMAKE_SOURCE_DIR}/makefiles/cmake/srcs/test-mtrace.c
OUTPUT_VARIABLE foo)
add_definitions(-DHAVE_CMAKE_CONFIG)
configure_file (
"makefiles/cmake/cmake_config.h.in"
"${PROJECT_BINARY_DIR}/cmake_config.h"
)
<file_sep>#!/bin/bash
sudo apt-get install g++-4.6-arm-linux-gnueabi gcc-4.6-arm-linux-gnueabi binutils-arm-linux-gnueabi unzip
wget -O libs.zip https://www.dropbox.com/s/wovdzzxplqjze1o/req_libs.zip?dl=1
unzip libs.zip
rm -rf build
mkdir -p build/arm-android/release/
pushd build/arm-android/release/
cmake -DCMAKE_TOOLCHAIN_FILE=../../../makefiles/cmake/toolchains/drone-linux.cmake -DCMAKE_BUILD_TYPE=Release ../../..
make -j8
popd
<file_sep>add_library (mmal_core
mmal_format.c
mmal_port.c
mmal_port_clock.c
mmal_component.c
mmal_buffer.c
mmal_queue.c
mmal_pool.c
mmal_events.c
mmal_logging.c
mmal_clock.c
)
target_link_libraries (mmal_core vcos)
<file_sep>/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_ANDROID_NATIVES_PRIV_H
#define ANDROID_ANDROID_NATIVES_PRIV_H
#include "include/ui/egl/android_natives.h"
#ifdef __cplusplus
extern "C" {
#endif
/*****************************************************************************/
typedef struct android_native_buffer_t
{
#ifdef __cplusplus
android_native_buffer_t() {
common.magic = ANDROID_NATIVE_BUFFER_MAGIC;
common.version = sizeof(android_native_buffer_t);
memset(common.reserved, 0, sizeof(common.reserved));
}
// Implement the methods that sp<android_native_buffer_t> expects so that it
// can be used to automatically refcount android_native_buffer_t's.
void incStrong(const void* id) const {
common.incRef(const_cast<android_native_base_t*>(&common));
}
void decStrong(const void* id) const {
common.decRef(const_cast<android_native_base_t*>(&common));
}
#endif
struct android_native_base_t common;
int width;
int height;
int stride;
int format;
int usage;
/* transformation as defined in hardware.h */
uint8_t transform;
uint8_t reserved_bytes[3];
void* reserved[1];
buffer_handle_t handle;
void* reserved_proc[8];
} android_native_buffer_t;
/*****************************************************************************/
#ifdef __cplusplus
}
#endif
/*****************************************************************************/
#endif /* ANDROID_ANDROID_NATIVES_PRIV_H */
<file_sep>cmake_minimum_required(VERSION 2.8)
project(vmcs_host_apps)
set(BUILD_MMAL TRUE)
set(ANDROID TRUE)
set(BUILD_MMAL_APPS FALSE)
set(vmcs_root ${PROJECT_SOURCE_DIR})
get_filename_component(VIDEOCORE_ROOT . ABSOLUTE)
set(VCOS_PTHREADS_BUILD_SHARED TRUE)
include(makefiles/cmake/global_settings.cmake)
if(DRONE)
include(makefiles/cmake/arm-drone.cmake)
endif()
if(NOT DRONE)
include(makefiles/cmake/arm-linux.cmake)
endif()
include(makefiles/cmake/vmcs.cmake)
# Global include paths
include_directories(host_applications/framework)
include_directories(${PROJECT_SOURCE_DIR})
include_directories(interface/vcos/pthreads)
include_directories(interface/vmcs_host/linux)
include_directories(interface/vmcs_host)
include_directories(interface/vmcs_host/khronos)
include_directories(interface/khronos/include)
include_directories(${PROJECT_BINARY_DIR})
include_directories(interface/vchiq_arm)
#include_directories(tools/inet_transport)
include_directories(host_support/include)
# Global compiler flags
if(CMAKE_COMPILER_IS_GNUCC)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-multichar -Wall -Wno-unused-but-set-variable")
endif()
add_definitions(-D_REENTRANT)
add_definitions(-DUSE_VCHIQ_ARM -DVCHI_BULK_ALIGN=1 -DVCHI_BULK_GRANULARITY=1)
add_definitions(-DOMX_SKIP64BIT)
add_definitions(-DEGL_SERVER_DISPMANX)
add_definitions(-D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE)
# do we actually need this?
add_definitions(-D__VIDEOCORE4__)
# add_definitions(-DKHRONOS_CLIENT_LOGGING)
# Check for OpenWF-C value set via command line
if(KHRONOS_EGL_PLATFORM MATCHES "openwfc")
add_definitions(-DKHRONOS_EGL_PLATFORM_OPENWFC)
endif()
# "gralloc"
# add_subdirectory(gralloc)
# List of subsidiary CMakeLists
add_subdirectory(interface/vcos)
add_subdirectory(interface/vmcs_host)
add_subdirectory(interface/vchiq_arm)
add_subdirectory(interface/khronos)
#add_subdirectory(opensrc/tools/lua)
if(BUILD_MMAL)
include_directories(interface/mmal)
add_subdirectory(interface/mmal)
endif()
#add_subdirectory(containers)
add_subdirectory(middleware/openmaxil)
# 3d demo code
#if(NOT ANDROID)
# add_subdirectory(thirdparty/applications/demos)
# add_subdirectory(opensrc/applications/demos)
#endif()
#if(ENABLE_3D_TESTS)
# add_subdirectory(thirdparty/applications/test)
#endif()
# FIXME: this directory needs a more sensible name and better
# platform factoring
add_subdirectory(interface/usbdk)
# FIXME: we should use a pre-packaged version of freetype
# rather than the one included in the repo.
#add_subdirectory(opensrc/helpers/freetype)
#add_subdirectory(${PROJECT_SOURCE_DIR}/opensrc/helpers/fonts/ttf-bitstream-vera)
# VMCS Host Applications
#add_subdirectory(host_applications/framework)
#add_subdirectory(host_applications/vmcs)
# add_subdirectory(interface/vchiq/test/win32)
# Apps and libraries supporting Camera Tuning Tool
#add_subdirectory(tools/inet_transport/linux)
#add_subdirectory(host_support/vcstandalone)
# add linux apps
add_subdirectory(host_applications/linux)
set(vmcs_host_apps_VERSION_MAJOR 1)
set(vmcs_host_apps_VERSION_MINOR 0)
include_directories("${PROJECT_BINARY_DIR}")
# Remove cache entry, if one added by command line
unset(KHRONOS_EGL_PLATFORM CACHE)
<file_sep>if (WIN32)
set(VCOS_PLATFORM win32)
else ()
set(VCOS_PLATFORM pthreads)
add_definitions(-Wall -Werror)
endif ()
include_directories( ../ )
add_library(grlc ${SHARED} gralloc.c)
target_link_libraries(grlc vcos)
install(TARGETS grlc DESTINATION lib)
<file_sep>add_library (mmal_util
mmal_il.c
mmal_util.c
mmal_connection.c
mmal_graph.c
mmal_list.c
mmal_param_convert.c
mmal_util_params.c
mmal_component_wrapper.c
mmal_util_rational.c
)
target_link_libraries (mmal_util vcos)
<file_sep>#
# CMake defines to cross-compile to ARM/Linux on BCM2708 using glibc.
#
# Note that the compilers should be in $ANDROID_TOOLCHAIN
SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_C_COMPILER arm-linux-gnueabi-gcc-4.6)
SET(CMAKE_CXX_COMPILER arm-linux-gnueabi-g++-4.6)
SET(CMAKE_ASM_COMPILER arm-linux-gnueabi-as)
SET(CMAKE_SYSTEM_PROCESSOR arm)
SET(ANDROID_ROOT lib)
SET(ANDROID TRUE)
SET(DRONE TRUE)
#ADD_DEFINITIONS("-march=armv6")
add_definitions("-mcpu=arm1176jzf-s")
# rdynamic means the backtrace should work
IF (CMAKE_BUILD_TYPE MATCHES "Debug")
add_definitions(-rdynamic)
ENDIF()
# avoids annoying and pointless warnings from gcc
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -U_FORTIFY_SOURCE")
<file_sep>/*
* Copyright (C) 2005 The Android Open Source Project
*
* 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.
*/
//
// Pixel formats used across the system.
// These formats might not all be supported by all renderers, for instance
// skia or SurfaceFlinger are not required to support all of these formats
// (either as source or destination)
// XXX: we should consolidate these formats and skia's
#ifndef UI_PIXELFORMAT_H
#define UI_PIXELFORMAT_H
#include <stdint.h>
#include <sys/types.h>
//#include <utils/Errors.h>
#include "include/pixelflinger/format.h"
#include "include/hardware/hardware.h"
//namespace android {
enum {
//
// these constants need to match those
// in graphics/PixelFormat.java & pixelflinger/format.h
//
PIXEL_FORMAT_UNKNOWN = 0,
PIXEL_FORMAT_NONE = 0,
// logical pixel formats used by the SurfaceFlinger -----------------------
PIXEL_FORMAT_CUSTOM = -4,
// Custom pixel-format described by a PixelFormatInfo structure
PIXEL_FORMAT_TRANSLUCENT = -3,
// System chooses a format that supports translucency (many alpha bits)
PIXEL_FORMAT_TRANSPARENT = -2,
// System chooses a format that supports transparency
// (at least 1 alpha bit)
PIXEL_FORMAT_OPAQUE = -1,
// System chooses an opaque format (no alpha bits required)
// real pixel formats supported for rendering -----------------------------
PIXEL_FORMAT_RGBA_8888 = HAL_PIXEL_FORMAT_RGBA_8888, // 4x8-bit RGBA
PIXEL_FORMAT_RGBX_8888 = HAL_PIXEL_FORMAT_RGBX_8888, // 4x8-bit RGB0
PIXEL_FORMAT_RGB_888 = HAL_PIXEL_FORMAT_RGB_888, // 3x8-bit RGB
PIXEL_FORMAT_RGB_565 = HAL_PIXEL_FORMAT_RGB_565, // 16-bit RGB
PIXEL_FORMAT_BGRA_8888 = HAL_PIXEL_FORMAT_BGRA_8888, // 4x8-bit BGRA
PIXEL_FORMAT_RGBA_5551 = HAL_PIXEL_FORMAT_RGBA_5551, // 16-bit ARGB
PIXEL_FORMAT_RGBA_4444 = HAL_PIXEL_FORMAT_RGBA_4444, // 16-bit ARGB
PIXEL_FORMAT_A_8 = GGL_PIXEL_FORMAT_A_8, // 8-bit A
PIXEL_FORMAT_L_8 = GGL_PIXEL_FORMAT_L_8, // 8-bit L (R=G=B=L)
PIXEL_FORMAT_LA_88 = GGL_PIXEL_FORMAT_LA_88, // 16-bit LA
PIXEL_FORMAT_RGB_332 = GGL_PIXEL_FORMAT_RGB_332, // 8-bit RGB
// New formats can be added if they're also defined in
// pixelflinger/format.h
};
typedef int32_t PixelFormat;
/*struct PixelFormatInfo
{
enum {
INDEX_ALPHA = 0,
INDEX_RED = 1,
INDEX_GREEN = 2,
INDEX_BLUE = 3
};
enum { // components
ALPHA = 1,
RGB = 2,
RGBA = 3,
LUMINANCE = 4,
LUMINANCE_ALPHA = 5,
OTHER = 0xFF
};
struct szinfo {
uint8_t h;
uint8_t l;
};
inline PixelFormatInfo() : version(sizeof(PixelFormatInfo)) { }
size_t getScanlineSize(unsigned int width) const;
size_t getSize(size_t ci) const {
return (ci <= 3) ? (cinfo[ci].h - cinfo[ci].l) : 0;
}
size_t version;
PixelFormat format;
size_t bytesPerPixel;
size_t bitsPerPixel;
union {
szinfo cinfo[4];
struct {
uint8_t h_alpha;
uint8_t l_alpha;
uint8_t h_red;
uint8_t l_red;
uint8_t h_green;
uint8_t l_green;
uint8_t h_blue;
uint8_t l_blue;
};
};
uint8_t components;
uint8_t reserved0[3];
uint32_t reserved1;
};
// Consider caching the results of these functions are they're not
// guaranteed to be fast.
ssize_t bytesPerPixel(PixelFormat format);
ssize_t bitsPerPixel(PixelFormat format);
status_t getPixelFormatInfo(PixelFormat format, PixelFormatInfo* info);
}; // namespace android
*/
#endif // UI_PIXELFORMAT_H
| 5ee9558c9e3cc21f56d4b45e79c2b08e8e161e2a | [
"Markdown",
"C",
"CMake",
"Shell"
] | 16 | C | degs01/userland | 28d1efce2fed4f40288bb42a4ce23bfa4b961bee | 4db2936e5b40f0b67a6060c72c2f504b09a3907d | |
refs/heads/master | <repo_name>acheuqueman/atajos_0.2-MASTER<file_sep>/src/app/app.component.ts
import { Component, ViewChild } from '@angular/core';
import { Platform, Nav } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { ROGallegosPage } from '../pages/r-ogallegos/r-ogallegos';
import { MunicipiosPage } from '../pages/municipios/municipios';
import { ComisionesDeFomentosPage } from '../pages/comisiones-de-fomentos/comisiones-de-fomentos';
import { ParajesPage } from '../pages/parajes/parajes';
import { UrgenciasPage } from '../pages/urgencias/urgencias';
import { HomePage } from '../pages/home/home';
import { TabsControllerPage } from '../pages/tabs-controller/tabs-controller';
import { AndroidPermissions } from '@ionic-native/android-permissions';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import {TasksServiceProvider } from '../providers/tasks-service/tasks-service';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
@ViewChild(Nav) navCtrl: Nav;
rootPage:any = TabsControllerPage;
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
androidPermissions: AndroidPermissions,
public sqlite: SQLite,
public tasksService: TasksServiceProvider) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
androidPermissions.requestPermissions(
[
//androidPermissions.PERMISSION.CAMERA,
androidPermissions.PERMISSION.CALL_PHONE,
//androidPermissions.PERMISSION.GET_ACCOUNTS,
//androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE,
//androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE
]
);
this.createDatabase();
//this.createDatabase_numeros()
//this.tasksService.insert_prueba();
}); //Fin platform ready
}
goToROGallegos(params){
if (!params) params = {};
this.navCtrl.setRoot(ROGallegosPage);
}goToMunicipios(params){
if (!params) params = {};
this.navCtrl.setRoot(MunicipiosPage);
}goToComisionesDeFomentos(params){
if (!params) params = {};
this.navCtrl.setRoot(ComisionesDeFomentosPage);
}goToParajes(params){
if (!params) params = {};
this.navCtrl.setRoot(ParajesPage);
}goToUrgencias(params){
if (!params) params = {};
this.navCtrl.setRoot(UrgenciasPage);
}
//Crea la base de datos en SQLite
private createDatabase(){
this.sqlite.create({
name: 'contactos_local.db',
location: 'default' // the location field is required
})
.then((db : SQLiteObject) => {
console.log("Base de datos: "+db);
this.tasksService.setDatabase(db);
//this.tasksService.prueba_borrartabla(); //// Borra contenido de tabla contactos_local
this.tasksService.createTable_contactos();
return this.tasksService.createTable_numeros();
})
.catch(error =>{
console.error(error);
});
}
/*
private createDatabase_numeros(){
this.sqlite.create({
name: 'numeros.db',
location: 'default' // the location field is required
})
.then((db) => {
console.log(db);
this.tasksService.setDatabase(db);
return this.tasksService.createTable();
})
.catch(error =>{
console.error(error);
});
}
*/
} //Fin Clase
<file_sep>/src/pages/mostrar-telefonos/mostrar-telefonos.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {AbstractItemsProvider} from '../../providers/abstract-items/abstract-items';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { DetallesPage } from '../detalles/detalles';
/**
* Generated class for the MostrarTelefonosPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-mostrar-telefonos',
templateUrl: 'mostrar-telefonos.html',
})
export class MostrarTelefonosPage {
items: any[];
busqueda: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public http: HttpClient, private provider:AbstractItemsProvider) {
console.log("Pagina: Mostrar-telefonos");
//Para que ande el post
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': ''
})
};
this.busqueda = navParams.get('busqueda');
//console.log("Busqueda: " + this.busqueda);
if (this.busqueda != true)
{
this.cargar_telefonos();
} else if (this.busqueda == true) {
this.items = this.provider.items;
//this.provider.Categoria_id = this.items
}
}
/*
ocultar_spiner(){
console.log(document.getElementById("espiner2"));
document.getElementById("espiner2").style.visibility = "hidden";
document.getElementById("espiner2").style.position = "absolute";
}
*/
ionViewDidLoad() {
if (this.busqueda == true){
//console.log("Busqueda true");
//this.ocultar_spiner();
this.provider.loading.dismiss();
this.busqueda = false;
}
}
//++ Hacer esto funcion de provider para que usen lo mismo mostrar-telefonos.ts y el buscador
cargar_telefonos(){
//console.log("Cargar Telefonos:");
var longitud : any;
this.items = [];
///+++ Convierte a JSON los datos que se le quiere enviar al php
var datos_consulta = JSON.stringify({
"localidad": this.provider.Localidad_id,
"categoria": this.provider.Categoria_id,
"tipo_localidad": this.provider.Tipo_localidad,
"busqueda":"false",
"buscando": "false"
});
console.log("Datos Consulta: " +datos_consulta);
var ip_gettelefonos = this.provider.ip_carpeta+"get_telefonos.php"; //Direccion del php
///+++ post subscribe que manda y recibe del php,
console.log(ip_gettelefonos);
this.provider.ShowLoader();
this.http.post<string>(ip_gettelefonos,datos_consulta) // (direccion php,JSON)
.subscribe((data : any) => //data: informacion de recibe del php
{
this.provider.loading.dismiss();
longitud = data['lenght'];
//console.log("lengh consulta: "+longitud);
//console.log("Input del php"+data['json']);
for(let i = 0; i < longitud; i++){ //Recibe cada uno de los telefonos y sus datos
this.items.push({
nombre: data[i]['nombre'],
direccion: data[i]['direccion'],
telefono: data[i]['telefono'],
pagina: data[i]['pagina'],
categoria: data[i]['categoria'],
nombre_localidad: data[i]['nombre_localidad'],
id: data[i]['id']
});
} //Fin For
},
(error : any) =>
{
this.provider.error_conexion();
});
} //Fin
ver_detalles(item){
//console.log(item);
this.navCtrl.push(DetallesPage, { //Cambia a la pagina "detalles" enviando variable
item:item
});
}
}
<file_sep>/src/pages/cloud-tab-default-page/cloud-tab-default-page.ts
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, Searchbar } from 'ionic-angular';
import {AbstractItemsProvider} from '../../providers/abstract-items/abstract-items';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { MostrarTelefonosPage } from '../mostrar-telefonos/mostrar-telefonos';
@Component({
selector: 'page-cloud-tab-default-page',
templateUrl: 'cloud-tab-default-page.html'
})
/*
@ViewChild('searchbox')({
searchbox_html: ElementRef
})
*/
export class CloudTabDefaultPagePage {
items: any[];
constructor(public navCtrl: NavController, public http: HttpClient, private provider:AbstractItemsProvider) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': ''
})
};
}
//++ Hacer esto funcion de provider para que usen lo mismo mostrar-telefonos.ts y el buscador
buscar_contacto(busqueda_text){
//console.log(this.searchbox_html.nativeElement.innerText);
var longitud : any;
this.items = [];
///+++ Convierte a JSON los datos que se le quiere enviar al php
var datos_consulta = JSON.stringify({
"localidad": "false",
"categoria": "false",
"tipo_localidad": "false",
"busqueda": busqueda_text,
"buscando": "true"
});
console.log(datos_consulta);
var ip_gettelefonos = this.provider.ip_carpeta+"get_telefonos.php"; //Direccion del
console.log(ip_gettelefonos);
///+++ post subscribe que manda y recibe del php,
this.provider.ShowLoader();
this.http
.post<string>(ip_gettelefonos,datos_consulta) // (direccion php,JSON)
.subscribe((data : any) => //data: informacion de recibe de los echos del php
{
longitud = data['lenght'];
console.log("lengh consulta: "+longitud);
for(let i = 0; i < longitud; i++){ ///+++ Recibe cada uno de los telefonos y sus datos
//console.log(data[i]);
this.items.push({
nombre: data[i]['nombre'],
direccion: data[i]['direccion'],
telefono: data[i]['telefono'],
pagina: data[i]['pagina'],
categoria: data[i]['categoria'],
nombre_localidad: data[i]['nombre_localidad'],
id: i
});
} //Fin For
console.log(this.items);
this.provider.items = this.items;
this.navCtrl.push(MostrarTelefonosPage, { //Que vaya a pagina detalles
busqueda : true
});
},
(error : any) =>
{
});
}
}
<file_sep>/src/pages/home/home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ROGallegosPage } from '../r-ogallegos/r-ogallegos';
import { MunicipiosPage } from '../municipios/municipios';
import { ComisionesDeFomentosPage } from '../comisiones-de-fomentos/comisiones-de-fomentos';
import { ParajesPage } from '../parajes/parajes';
import { UrgenciasPage } from '../urgencias/urgencias';
import {ContactoPage} from '../contacto/contacto';
import {AbstractItemsProvider} from '../../providers/abstract-items/abstract-items';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
//prueba : string;
//AbstractItemsProvider:AbstractItemsProvider;
localidad : number;
ip_wamp = 'http://localhost/Atajos/get_telefonos.php';
constructor(public navCtrl: NavController, private provider:AbstractItemsProvider, public http: HttpClient) {
console.log("Pagina: Home");
//this.prueba = AbstractItemsProvider.getUserName();
//console.log(this.prueba);
this.provider.Tipo_localidad = 0;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': ''
})
};
//this.provider.probar_conexion();
}// Fin constructor
goToROGallegos(params){
//this.localidad = this.AbstractItemsProvider.setLocalidad();
//this.provider.setLocalidad(29);
this.provider.Localidad_id = 29;
this.provider.Tipo_localidad = 1;
this.provider.Localidad_Nombre = "<NAME>";
if (!params) params = {};
this.navCtrl.push(ROGallegosPage);
}
goToMunicipios(params){
this.provider.Tipo_localidad = 2;
if (!params) params = {};
this.navCtrl.push(MunicipiosPage);
}
goToComisionesDeFomentos(params){
this.provider.Tipo_localidad = 3;
if (!params) params = {};
this.navCtrl.push(MunicipiosPage);
}
goToParajes(params){
this.provider.Tipo_localidad = 4;
if (!params) params = {};
this.navCtrl.push(MunicipiosPage);
}
goToOtros(params){
this.provider.Tipo_localidad = 5;
if (!params) params = {};
this.navCtrl.push(MunicipiosPage);
}
goToUrgencias(params){
if (!params) params = {};
this.navCtrl.push(UrgenciasPage);
}
goToContacto(params){
if (!params) params = {};
this.navCtrl.push(ContactoPage);
}
}
<file_sep>/src/pages/r-ogallegos/r-ogallegos.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
//import { ROGallegosPage } from '../r-ogallegos/r-ogallegos';
import { MostrarTelefonosPage } from '../mostrar-telefonos/mostrar-telefonos';
import {AbstractItemsProvider} from '../../providers/abstract-items/abstract-items';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
@Component({
selector: 'page-r-ogallegos',
templateUrl: 'r-ogallegos.html'
})
export class ROGallegosPage {
nombre : string;
array_cantidad2 : any[];
cat1 : any;
cat2 : any;
cat3 : any;
cat4 : any;
cat5 : any;
cat6 : any;
constructor(public navCtrl: NavController, private provider:AbstractItemsProvider,public http: HttpClient) {
console.log("ROGallegosPage");
this.nombre = provider.Localidad_Nombre;
//Para que ande el post
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': ''
})
};
this.ver_categorias();
}// Fin constructor
asign_cat(id_cat){
/*
this.provider.setCategoria(id_cat);
console.log(this.provider.getCategoria())
*/
this.provider.Categoria_id = id_cat;
console.log(this.provider.Categoria_id);
this.navCtrl.push(MostrarTelefonosPage);
}
/*
goToROGallegos(params){
if (!params) params = {};
this.navCtrl.push(ROGallegosPage);
}
*/
ver_categorias(){
var datos_consulta_cat = JSON.stringify({
"localidad": this.provider.Localidad_id,
}); //"tipo_localidad": this.provider.Tipo_localidad,
var ip_categoria = this.provider.ip_carpeta+"consulta_categoria.php";
console.log(ip_categoria);
var array_cantidad = [];
this.provider.ShowLoader();
this.http
.post<string>(ip_categoria,datos_consulta_cat) // (direccion php,JSON)
.subscribe((data : any) => //data: informacion de recibe de los echos del php
{
console.log("Cantidad: "+data);
this.provider.loading.dismiss();
for(let i = 0; i < 7; i++){ ///+++ Recibe cada uno de los telefonos y sus datos
//console.log(data[i]);
array_cantidad.push({
cant: data[i],
});
//console.log(array_cantidad[i]['cant']);
if (array_cantidad[i]['cant'] >= 1)
{
var id_cat: string | null | undefined;
id_cat = "cat_"+i;
//console.log(id_cat);
document.getElementById(id_cat).style.visibility = "visible";
}
}
/*
document.getElementById("espiner").style.visibility = "hidden";
document.getElementById("espiner").style.position = "absolute";
*/
//console.log(array_cantidad);
this.array_cantidad2 = array_cantidad;
this.array_cantidad2["uno"] = array_cantidad[1];
//console.log(this.array_cantidad2);
this.cat1 = array_cantidad[1]['cant'];
this.cat2 = array_cantidad[2]['cant'];
this.cat3 = array_cantidad[3]['cant'];
this.cat4 = array_cantidad[4]['cant'];
this.cat5 = array_cantidad[5]['cant'];
this.cat6 = array_cantidad[6]['cant'];
},
(error : any) =>
{
this.provider.error_conexion();
});
}
}
<file_sep>/src/app/app.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { CameraTabDefaultPagePage } from '../pages/camera-tab-default-page/camera-tab-default-page';
import { CartTabDefaultPagePage } from '../pages/cart-tab-default-page/cart-tab-default-page';
import { CloudTabDefaultPagePage } from '../pages/cloud-tab-default-page/cloud-tab-default-page';
import { TabsControllerPage } from '../pages/tabs-controller/tabs-controller';
import { HomePage } from '../pages/home/home';
import { ROGallegosPage } from '../pages/r-ogallegos/r-ogallegos';
import { MunicipiosPage } from '../pages/municipios/municipios';
import { ComisionesDeFomentosPage } from '../pages/comisiones-de-fomentos/comisiones-de-fomentos';
import { ParajesPage } from '../pages/parajes/parajes';
import { UrgenciasPage } from '../pages/urgencias/urgencias';
import { MostrarTelefonosPage } from '../pages/mostrar-telefonos/mostrar-telefonos';
import { DetallesPage } from '../pages/detalles/detalles';
import { ContactoPage } from '../pages/contacto/contacto';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { AbstractItemsProvider } from '../providers/abstract-items/abstract-items';
//Imports Ionic
import { AndroidPermissions } from '@ionic-native/android-permissions';
import {CallNumber} from '@ionic-native/call-number';
//Imports Angular
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { SQLite } from '@ionic-native/sqlite';
import { TasksServiceProvider } from '../providers/tasks-service/tasks-service';
@NgModule({
declarations: [
MyApp,
CameraTabDefaultPagePage,
CartTabDefaultPagePage,
CloudTabDefaultPagePage,
TabsControllerPage,
HomePage,
ROGallegosPage,
MunicipiosPage,
ComisionesDeFomentosPage,
ParajesPage,
UrgenciasPage,
MostrarTelefonosPage,
DetallesPage,
ContactoPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpClientModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
CameraTabDefaultPagePage,
CartTabDefaultPagePage,
CloudTabDefaultPagePage,
TabsControllerPage,
HomePage,
ROGallegosPage,
MunicipiosPage,
ComisionesDeFomentosPage,
ParajesPage,
UrgenciasPage,
MostrarTelefonosPage,
DetallesPage,
ContactoPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
AbstractItemsProvider, //Provider agregado automaticamente
AndroidPermissions,
HttpClientModule,
CallNumber,
HttpClient,
SQLite,
TasksServiceProvider
]
})
export class AppModule {}<file_sep>/src/pages/detalles/detalles.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {CallNumber} from '@ionic-native/call-number';
import {AbstractItemsProvider} from '../../providers/abstract-items/abstract-items';
import {TasksServiceProvider } from '../../providers/tasks-service/tasks-service';
import {
GoogleMaps,
GoogleMap,
//GoogleMapsEvent,
Marker,
//GoogleMapsAnimation,
//MyLocation,
//Environment,
Geocoder,
GeocoderResult,
} from '@ionic-native/google-maps';
/**
* Generated class for the DetallesPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-detalles',
templateUrl: 'detalles.html',
})
export class DetallesPage {
item: any;
imagen: any;
constructor(
public navCtrl: NavController,
private provider:AbstractItemsProvider,
public navParams: NavParams,
private CallNumber:CallNumber,
public tasksService: TasksServiceProvider) {
this.item = navParams.get('item');
//console.log(this.item);
this.set_imagen();
this.loadMap1();
//console.log("Pagina web: " + this.item.pagina);
}
ionViewDidLoad() {
//console.log('ionViewDidLoad DetallesPage');
if (this.item.pagina == ""){
document.getElementById("pagina_boton").style.visibility = "hidden";
document.getElementById("pagina_boton").style.position = "absolute";
//angular.element( document.querySelector( '#some-id' ) );
}
}
InsertarFavorito(){
this.tasksService.InsertFavorito(this.item);
}
Llamar(numero){
/*
this.CallNumber.callNumber(numero,true)
.then(res => console.log("Funco",res))
.catch(err => console.log("No Funco",err))
*/
this.provider.Llamar(numero);
}
set_imagen(){
//console.log(this.provider.Categoria_id);
//console.log("Categoria: "+this.item['categoria']);
var categoria = this.item['categoria'];
if(categoria == 1 ){
this.imagen = '../../assets/imgs/categ1.png';
}
else if(categoria ==2){
this.imagen = '../../assets/imgs/categ2.png';
}
else if(categoria ==3){
this.imagen = '../../assets/imgs/categ3.png';
}
else if(categoria ==4){
this.imagen = '../../assets/imgs/categ4.png';
}
else if(categoria ==5){
this.imagen = '../../assets/imgs/categ5.png';
}
}
map1: GoogleMap;
search_address: any;
isRunning: boolean = false;
loadMap1() { //Funcion para crear el mapa
//this.search_address = this.item['nombre'] + " , " + this.item['direccion'] + " , " + this.item['nombre_localidad'] + ", Santa Cruz";
this.search_address = this.item['nombre'] + " " + this.item['direccion'] + " " + this.item['nombre_localidad'] + " Santa Cruz";
//this.search_address = "<NAME>";
//console.log("Search adress: "+this.search_address);
this.map1 = GoogleMaps.create('map_canvas1');
// Address -> latitude,longitude
Geocoder.geocode({
"address": this.search_address //Direccion ingresada
}).then((results: GeocoderResult[]) => {
//console.log(results);
if (!results.length) {
this.isRunning = false;
return null;
}
// Add a marker
let marker: Marker = this.map1.addMarkerSync({
'position': results[0].position,
'title': this.item['nombre']
});
// Move to the position
this.map1.animateCamera({
'target': marker.getPosition(),
'zoom': 16
}).then(() => {
marker.showInfoWindow();
this.isRunning = false;
});
});
}
}
<file_sep>/php/Atajos/get_municipios.php
<?php
include "conexion.php";
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$tipo_localidad = $request->tipo_localidad;
$municipios = mysql_query("SELECT * FROM localidades WHERE tipo_localidad = '$tipo_localidad' ");
$array_municipios_php = array();
$i = 0;
while ( $municipios_array = mysql_fetch_array($municipios))
{
$array_municipios_php[$i]['nombre_municipio'] = $municipios_array['localidad']; //Nombre
$array_municipios_php[$i]['id_municipio'] = $municipios_array['id_localidad']; //id
$i++;
//echo($municipios_array[2]);
}
$array_municipios_php['lenght'] = count($array_municipios_php);
echo json_encode($array_municipios_php);
?><file_sep>/src/pages/tabs-controller/tabs-controller.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HomePage } from '../home/home';
import { ROGallegosPage } from '../r-ogallegos/r-ogallegos';
import { MunicipiosPage } from '../municipios/municipios';
import { ComisionesDeFomentosPage } from '../comisiones-de-fomentos/comisiones-de-fomentos';
import { ParajesPage } from '../parajes/parajes';
import { UrgenciasPage } from '../urgencias/urgencias';
import { CloudTabDefaultPagePage } from '../cloud-tab-default-page/cloud-tab-default-page';
import {CartTabDefaultPagePage} from '../cart-tab-default-page/cart-tab-default-page';
@Component({
selector: 'page-tabs-controller',
templateUrl: 'tabs-controller.html'
})
export class TabsControllerPage {
tab1Root: any = HomePage;
tab2Root: any = CloudTabDefaultPagePage;
tab3Root: any = CartTabDefaultPagePage;
constructor(public navCtrl: NavController) {
console.log("Pagina: tab-controller");
}
goToHome(params){
if (!params) params = {};
this.navCtrl.push(HomePage);
}goToROGallegos(params){
if (!params) params = {};
this.navCtrl.push(ROGallegosPage);
}goToMunicipios(params){
if (!params) params = {};
this.navCtrl.push(MunicipiosPage);
}goToComisionesDeFomentos(params){
if (!params) params = {};
this.navCtrl.push(ComisionesDeFomentosPage);
}goToParajes(params){
if (!params) params = {};
this.navCtrl.push(ParajesPage);
}goToUrgencias(params){
if (!params) params = {};
this.navCtrl.push(UrgenciasPage);
}
}
<file_sep>/php/Atajos/conexion.php
<?php
$link = mysql_connect('localhost','root');
mysql_select_db('base_telefonos',$link);
mysql_set_charset('utf8');
header('Access-Control-Allow-Headers:*'); ///// Para que acepte el POST
?><file_sep>/base_telefonos OP.sql
-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1:3306
-- Tiempo de generación: 21-11-2018 a las 15:11:27
-- Versión del servidor: 5.7.23
-- Versión de PHP: 5.6.38
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `base_telefonos`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `departamentos`
--
DROP TABLE IF EXISTS `departamentos`;
CREATE TABLE IF NOT EXISTS `departamentos` (
`id_dep` int(5) NOT NULL,
`nombre_dep` varchar(60) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `departamentos`
--
INSERT INTO `departamentos` (`id_dep`, `nombre_dep`) VALUES
(1, '<NAME>'),
(2, 'Desado'),
(3, '<NAME>'),
(4, 'Lago Argentino'),
(5, 'Lago Buenos Aires'),
(6, 'Magallanes '),
(7, 'Rio Chico');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `localidades`
--
DROP TABLE IF EXISTS `localidades`;
CREATE TABLE IF NOT EXISTS `localidades` (
`id_localidad` int(6) NOT NULL AUTO_INCREMENT,
`localidad` varchar(60) NOT NULL,
`tipo_localidad` int(6) NOT NULL,
`dep_localidad` int(6) NOT NULL,
PRIMARY KEY (`id_localidad`)
) ENGINE=MyISAM AUTO_INCREMENT=35 DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `localidades`
--
INSERT INTO `localidades` (`id_localidad`, `localidad`, `tipo_localidad`, `dep_localidad`) VALUES
(1, '28 de noviembre ', 2, 3),
(2, '<NAME>', 5, 7),
(3, 'B<NAME>', 5, 6),
(4, '<NAME>', 2, 2),
(5, '<NAME>', 3, 2),
(6, '<NAME>', 2, 4),
(7, '<NAME>', 2, 4),
(8, '<NAME>', 5, 3),
(9, '<NAME>', 5, 3),
(10, '<NAME>', 5, 3),
(11, 'Estancia Las Vegas ', 5, 3),
(12, '<NAME>', 3, 2),
(13, '<NAME>', 5, 1),
(14, '<NAME>', 2, 7),
(15, '<NAME> ', 3, 7),
(16, 'Jaramillo', 3, 2),
(17, '<NAME>', 4, 3),
(18, '<NAME>', 3, 2),
(19, '<NAME>', 5, 7),
(20, '<NAME>', 2, 2),
(21, 'Los Antiguos ', 2, 5),
(22, '<NAME>', 2, 5),
(23, '<NAME>', 2, 2),
(24, 'Piedrabuena ', 2, 1),
(25, '<NAME>', 2, 2),
(26, '<NAME>', 2, 6),
(27, '<NAME>', 2, 1),
(28, '<NAME>', 5, 2),
(29, '<NAME>', 1, 3),
(30, '<NAME>', 2, 3),
(31, 'Rospentek', 5, 3),
(32, '<NAME> ', 5, 1),
(33, 'Tellier', 5, 2),
(34, '<NAME>', 3, 4);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `numeros`
--
DROP TABLE IF EXISTS `numeros`;
CREATE TABLE IF NOT EXISTS `numeros` (
`id_numero` int(12) NOT NULL AUTO_INCREMENT,
`lugar_numero` int(30) NOT NULL,
`numero_numero` bigint(30) NOT NULL,
PRIMARY KEY (`id_numero`)
) ENGINE=MyISAM AUTO_INCREMENT=1859 DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `numeros`
--
INSERT INTO `numeros` (`id_numero`, `lugar_numero`, `numero_numero`) VALUES
(1248, 1, 2902482075),
(1249, 2, 2902482121),
(1250, 3, 2902482103),
(1251, 3, 2902482049),
(1252, 3, 2902482166),
(1253, 4, 2902482055),
(1254, 4, 2902482744),
(1255, 5, 2902482078),
(1256, 6, 2902482400),
(1257, 7, 2902482210),
(1258, 8, 2902482073),
(1259, 9, 2902482078),
(1260, 10, 2902482022),
(1261, 12, 2966422291),
(1262, 13, 0),
(1263, 14, 2974851230),
(1264, 15, 2974851285),
(1265, 16, 2974851389),
(1266, 16, 2974853417),
(1267, 16, 2974853417),
(1268, 17, 2974852889),
(1269, 17, 2974852107),
(1270, 17, 2974852200),
(1271, 18, 2974856320),
(1272, 18, 2974835922),
(1273, 19, 2974856988),
(1274, 20, 2974851200),
(1275, 20, 2974856087),
(1276, 20, 2974856534),
(1277, 21, 2974857241),
(1278, 21, 2974853364),
(1279, 21, 2974852100),
(1280, 22, 2974859340),
(1281, 22, 2974856136),
(1282, 23, 2974859410),
(1283, 23, 2974856296),
(1284, 24, 2974837165),
(1285, 25, 2974831551),
(1286, 26, 2974851666),
(1287, 26, 2974851395),
(1288, 27, 2974830521),
(1289, 27, 2974858994),
(1290, 28, 2974850300),
(1291, 28, 2974850457),
(1292, 29, 2974851852),
(1293, 30, 2974854477),
(1294, 31, 2974851868),
(1295, 32, 0),
(1296, 33, 2974852944),
(1297, 34, 2974851602),
(1298, 35, 2974856403),
(1299, 36, 2974851467),
(1300, 37, 2974851957),
(1301, 38, 2974851603),
(1302, 41, 2974851224),
(1303, 42, 2974851646),
(1304, 43, 2974851618),
(1305, 44, 2974854614),
(1306, 45, 2974858811),
(1307, 46, 2974851890),
(1308, 47, 2974856740),
(1309, 48, 2974857944),
(1310, 49, 2974837294),
(1311, 50, 2974837553),
(1312, 51, 2971562460),
(1313, 52, 2974857949),
(1314, 53, 2974851614),
(1315, 54, 2974851798),
(1316, 55, 2974851152),
(1317, 56, 2974851347),
(1318, 57, 2974851643),
(1319, 58, 2974837294),
(1320, 59, 2974856862),
(1321, 60, 2974851868),
(1322, 61, 2974854443),
(1323, 62, 2974856648),
(1324, 63, 2974857447),
(1325, 64, 2974837295),
(1326, 65, 2974837552),
(1327, 66, 2974859330),
(1328, 67, 2974851157),
(1329, 68, 2974851818),
(1330, 69, 2974851224),
(1331, 71, 2974851674),
(1332, 73, 2974854477),
(1333, 74, 2974854068),
(1334, 75, 0),
(1335, 76, 0),
(1336, 77, 2974859330),
(1337, 78, 2974851224),
(1338, 79, 2974851937),
(1339, 81, 2974856780),
(1340, 82, 2974850101),
(1341, 82, 2974850100),
(1342, 83, 2974850144),
(1343, 84, 2974850103),
(1344, 85, 2974850454),
(1345, 86, 2902491020),
(1346, 86, 2902491082),
(1347, 87, 491020),
(1348, 88, 491090),
(1349, 89, 491020),
(1350, 90, 497103),
(1351, 91, 2902491173),
(1352, 92, 2902490701),
(1353, 93, 2902491825),
(1354, 93, 2902491077),
(1355, 94, 2902491819),
(1356, 94, 2902496871),
(1357, 94, 2902490077),
(1358, 94, 2902497026),
(1359, 95, 2902491824),
(1360, 95, 2902497694),
(1361, 96, 2902491070),
(1362, 96, 2902492317),
(1363, 97, 2902490770),
(1364, 98, 2902491205),
(1365, 99, 2902491560),
(1366, 100, 2902491022),
(1367, 101, 2902495857),
(1368, 102, 2902491438),
(1369, 103, 2902491914),
(1370, 104, 2902490060),
(1371, 105, 2902490980),
(1372, 106, 2902493720),
(1373, 107, 2902491086),
(1374, 108, 2902493088),
(1375, 110, 2902497305),
(1376, 111, 2902496490),
(1377, 112, 2902491587),
(1378, 114, 2902489222),
(1379, 115, 2902495857),
(1380, 116, 2902491209),
(1381, 117, 2962493004),
(1382, 118, 2962493370),
(1383, 119, 2962493011),
(1384, 120, 2962493105),
(1385, 121, 2962493058),
(1386, 122, 2962493270),
(1387, 123, 2962493003),
(1388, 123, 2962433135),
(1389, 124, 2962493240),
(1390, 124, 2962493142),
(1391, 124, 2962493013),
(1392, 125, 2962493048),
(1393, 126, 2962493048),
(1394, 127, 2962493125),
(1395, 128, 2962493104),
(1396, 129, 2962493048),
(1397, 130, 0),
(1398, 131, 2966421214),
(1399, 132, 0),
(1400, 133, 0),
(1401, 134, 0),
(1402, 135, 0),
(1403, 136, 0),
(1404, 137, 0),
(1405, 138, 0),
(1406, 139, 491055),
(1407, 140, 2962491001),
(1408, 141, 2962491088),
(1409, 141, 2962491055),
(1410, 141, 2962491459),
(1411, 142, 2962491099),
(1412, 143, 2962491281),
(1413, 144, 2962491281),
(1414, 145, 2962491032),
(1415, 146, 0),
(1416, 147, 2962491031),
(1417, 148, 2962491250),
(1418, 149, 2962491119),
(1419, 150, 2963490258),
(1420, 151, 2963490204),
(1421, 152, 2963490204),
(1422, 153, 2974806018),
(1423, 154, 0),
(1424, 155, 2974806038),
(1425, 156, 2974806038),
(1426, 157, 2902482916),
(1427, 158, 2902482915),
(1428, 159, 2974993881),
(1429, 160, 2974993883),
(1430, 161, 2974993834),
(1431, 162, 2974993821),
(1432, 163, 2974993821),
(1433, 164, 2963490228),
(1434, 164, 2963490295),
(1435, 164, 2963490220),
(1436, 165, 4974071077),
(1437, 166, 2974851007),
(1438, 167, 4974078),
(1439, 168, 4975558),
(1440, 169, 2974974666),
(1441, 170, 2974974030),
(1442, 170, 2974975912),
(1443, 171, 2974975830),
(1444, 171, 2974974550),
(1445, 172, 2974974444),
(1446, 173, 2974975477),
(1447, 174, 2974975116),
(1448, 175, 2974974811),
(1449, 177, 2974974002),
(1450, 178, 2974975486),
(1451, 179, 2974974803),
(1452, 180, 2974974053),
(1453, 181, 2974974850),
(1454, 182, 2974974809),
(1455, 183, 2974974808),
(1456, 184, 2974975244),
(1457, 185, 2974975699),
(1458, 186, 2974976272),
(1459, 188, 0),
(1460, 189, 2974976085),
(1461, 190, 2974975158),
(1462, 191, 2963491261),
(1463, 192, 2963491262),
(1464, 193, 2963491303),
(1465, 194, 2963491312),
(1466, 194, 2963491269),
(1467, 195, 2963491151),
(1468, 195, 2963491268),
(1469, 196, 2963491381),
(1470, 197, 2963491381),
(1471, 198, 2963491039),
(1472, 199, 2963491344),
(1473, 200, 2963491309),
(1474, 202, 2963432072),
(1475, 202, 2963210276),
(1476, 202, 2963422226),
(1477, 202, 2963562157),
(1478, 203, 296343063),
(1479, 204, 2963432011),
(1480, 205, 2963432014),
(1481, 205, 2963432012),
(1482, 206, 2963432299),
(1483, 207, 2963432697),
(1484, 208, 2963432054),
(1485, 209, 2963432073),
(1486, 211, 2963432054),
(1487, 212, 2974293993),
(1488, 213, 2963432574),
(1489, 214, 2963432001),
(1490, 215, 2963432726),
(1491, 217, 2974992160),
(1492, 218, 2974992202),
(1493, 219, 2974992156),
(1494, 220, 2974992192),
(1495, 221, 2974999616),
(1496, 221, 2974999211),
(1497, 221, 2971499286),
(1498, 222, 2974993111),
(1499, 222, 2974994111),
(1500, 223, 2974992790),
(1501, 224, 2974993303),
(1502, 224, 2974990703),
(1503, 224, 2974992000),
(1504, 224, 2974992333),
(1505, 225, 2974992079),
(1506, 226, 2974992860),
(1507, 227, 2974990800),
(1508, 229, 2974999974),
(1509, 230, 2974992612),
(1510, 231, 2974991200),
(1511, 232, 2974990700),
(1512, 233, 2974992959),
(1513, 234, 2974993181),
(1514, 235, 2974994203),
(1515, 236, 2974992612),
(1516, 237, 2974996058),
(1517, 238, 2974992134),
(1518, 239, 2974992132),
(1519, 240, 2974992146),
(1520, 241, 2974992234),
(1521, 242, 2974992860),
(1522, 243, 2974991766),
(1523, 244, 2974992612),
(1524, 246, 0),
(1525, 247, 2974990669),
(1526, 248, 2962497125),
(1527, 249, 2962497117),
(1528, 249, 2962497063),
(1529, 250, 2966463785),
(1530, 251, 2962497192),
(1531, 252, 2962497577),
(1532, 252, 2962497818),
(1533, 253, 2962497346),
(1534, 254, 2962497338),
(1535, 256, 2962497500),
(1536, 257, 2962492035),
(1537, 258, 2962497261),
(1538, 259, 2962497338),
(1539, 260, 2962497758),
(1540, 261, 2962497732),
(1541, 262, 4872248),
(1542, 263, 4870362),
(1543, 264, 2974872364),
(1544, 266, 2974870914),
(1545, 267, 2974870066),
(1546, 267, 2974872625),
(1547, 267, 2974872557),
(1548, 267, 2974872625),
(1549, 268, 2974871346),
(1550, 269, 2974872579),
(1551, 270, 2974870259),
(1552, 271, 2974871069),
(1553, 273, 2974870586),
(1554, 274, 2974871194),
(1555, 275, 2974872342),
(1556, 276, 2974870246),
(1557, 277, 2974870239),
(1558, 278, 2974872623),
(1559, 279, 2974871326),
(1560, 281, 2974870147),
(1561, 282, 2974870259),
(1562, 283, 2974870147),
(1563, 284, 2974872741),
(1564, 285, 2962452076),
(1565, 285, 2962415523),
(1566, 286, 0),
(1567, 287, 296245141),
(1568, 288, 2962452188),
(1569, 289, 2962452170),
(1570, 290, 2962452202),
(1571, 290, 2962452122),
(1572, 291, 2962452254),
(1573, 291, 2962452355),
(1574, 291, 2962452446),
(1575, 292, 2962452170),
(1576, 293, 2966538629),
(1577, 294, 2962452065),
(1578, 295, 2962452400),
(1579, 296, 2962452311),
(1580, 297, 2962454468),
(1581, 298, 2962454188),
(1582, 299, 2962452127),
(1583, 300, 0),
(1584, 301, 2962452101),
(1585, 302, 2962454231),
(1586, 304, 2962452061),
(1587, 305, 2962414536),
(1588, 306, 0),
(1589, 307, 2962498153),
(1590, 308, 2962498111),
(1591, 308, 2962498166),
(1592, 309, 2962498300),
(1593, 310, 2962498751),
(1594, 311, 2962498127),
(1595, 313, 2962498224),
(1596, 314, 2962498318),
(1597, 316, 2962498127),
(1598, 317, 2966549055),
(1599, 318, 2966423000),
(1600, 319, 2966420555),
(1601, 320, 2966421200),
(1602, 321, 2966420214),
(1603, 322, 2966420042),
(1604, 323, 2966436811),
(1605, 323, 2966661546),
(1606, 323, 2966412202),
(1607, 323, 2966966156),
(1608, 324, 2966422365),
(1609, 325, 2966422322),
(1610, 325, 2966080022),
(1611, 326, 2966442367),
(1612, 327, 2966420999),
(1613, 328, 2966427582),
(1614, 328, 2966081055),
(1615, 329, 2966422651),
(1616, 330, 457804),
(1617, 331, 442571),
(1618, 332, 2966442169),
(1619, 333, 2966420193),
(1620, 334, 2966422631),
(1621, 335, 2966428862),
(1622, 336, 2966426745),
(1623, 336, 2966426759),
(1624, 337, 2966420505),
(1625, 337, 2966437804),
(1626, 337, 2966429002),
(1627, 337, 2966420979),
(1628, 338, 2966420993),
(1629, 338, 2966420016),
(1630, 338, 2966449976),
(1631, 338, 2966424134),
(1632, 339, 2966420031),
(1633, 339, 2966436612),
(1634, 339, 2966423200),
(1635, 340, 2966420100),
(1636, 340, 2966420313),
(1637, 341, 2966423222),
(1638, 341, 2966428376),
(1639, 342, 2966432714),
(1640, 342, 2966431794),
(1641, 343, 2966423257),
(1642, 343, 2966423616),
(1643, 344, 2966669638),
(1644, 344, 2966296646),
(1645, 344, 2966359229),
(1646, 344, 2966664635),
(1647, 345, 2966428685),
(1648, 346, 2966648535),
(1649, 347, 2966637221),
(1650, 348, 2966422291),
(1651, 349, 2966420861),
(1652, 349, 2966422260),
(1653, 350, 2966420232),
(1654, 350, 2966431247),
(1655, 351, 2966420600),
(1656, 352, 2966444463),
(1657, 353, 2966639019),
(1658, 354, 2966428968),
(1659, 355, 2966422874),
(1660, 356, 2966428970),
(1661, 357, 2966428975),
(1662, 358, 2966428979),
(1663, 359, 2966442296),
(1664, 360, 2966422759),
(1665, 361, 0),
(1666, 362, 2966420641),
(1667, 362, 2966426221),
(1668, 362, 2966421448),
(1669, 363, 0),
(1670, 364, 2966431988),
(1671, 365, 2966420511),
(1672, 366, 2966431270),
(1673, 367, 2966429069),
(1674, 368, 2966436646),
(1675, 369, 2966438090),
(1676, 370, 2966437288),
(1677, 371, 2966430419),
(1678, 372, 0),
(1679, 373, 2966420257),
(1680, 374, 2966435623),
(1681, 375, 2966426593),
(1682, 376, 2966426836),
(1683, 377, 2966426184),
(1684, 378, 2966444857),
(1685, 380, 2966420394),
(1686, 381, 2966420071),
(1687, 382, 2966432943),
(1688, 383, 2966420138),
(1689, 384, 2966420219),
(1690, 385, 2966437528),
(1691, 386, 2966422019),
(1692, 387, 2966421999),
(1693, 388, 2966424004),
(1694, 389, 2966436041),
(1695, 390, 2966421406),
(1696, 391, 2966435158),
(1697, 392, 2966426396),
(1698, 393, 2966436768),
(1699, 11, 2902482400),
(1700, 39, 2974830962),
(1701, 40, 2974831344),
(1702, 70, 2974851215),
(1703, 72, 2974854056),
(1704, 80, 2974854058),
(1705, 109, 2902492637),
(1706, 113, 2902491412),
(1707, 176, 0),
(1708, 187, 2974974678),
(1709, 201, 2963491381),
(1710, 210, 0),
(1711, 216, 2963432290),
(1712, 228, 0),
(1713, 245, 2974992206),
(1714, 255, 0),
(1715, 265, 2974870946),
(1716, 265, 2974872777),
(1717, 265, 2974871321),
(1718, 265, 2974871208),
(1719, 272, 0),
(1720, 280, 2974870252),
(1721, 303, 2962452063),
(1722, 312, 2962498318),
(1723, 315, 2962498290),
(1724, 379, 2966433949),
(1725, 394, 2966436130),
(1726, 395, 2966420885),
(1727, 396, 2966436206),
(1728, 397, 2966422628),
(1729, 398, 0),
(1730, 399, 0),
(1731, 400, 2966426252),
(1732, 401, 2966420394),
(1733, 402, 2966426769),
(1734, 403, 2966420806),
(1735, 404, 2966420149),
(1736, 405, 2966420703),
(1737, 406, 2966420511),
(1738, 407, 2966422178),
(1739, 408, 2966422012),
(1740, 409, 2966424085),
(1741, 410, 2966438185),
(1742, 411, 2966422263),
(1743, 412, 2966436646),
(1744, 413, 2966426605),
(1745, 414, 2966427497),
(1746, 415, 2966429069),
(1747, 416, 2966436205),
(1748, 417, 2966442832),
(1749, 418, 2966437850),
(1750, 419, 2966434159),
(1751, 420, 2966420258),
(1752, 421, 2966437288),
(1753, 422, 2966429025),
(1754, 423, 2966426960),
(1755, 424, 2966442832),
(1756, 425, 2966422737),
(1757, 426, 2966433710),
(1758, 427, 2966420229),
(1759, 428, 2966444726),
(1760, 429, 2966423727),
(1761, 430, 2966424939),
(1762, 431, 2966426198),
(1763, 432, 2966426859),
(1764, 433, 2966430560),
(1765, 434, 2966438518),
(1766, 435, 2966426787),
(1767, 436, 2966436205),
(1768, 437, 2966431500),
(1769, 438, 2966420258),
(1770, 439, 2966427467),
(1771, 440, 2966422914),
(1772, 441, 0),
(1773, 442, 2966426198),
(1774, 443, 2966426859),
(1775, 444, 2966426787),
(1776, 445, 2966431500),
(1777, 446, 0),
(1778, 447, 2966422737),
(1779, 448, 2966420394),
(1780, 449, 2966420229),
(1781, 450, 2966433710),
(1782, 451, 2966423727),
(1783, 452, 2966425703),
(1784, 453, 2966436463),
(1785, 454, 2966429173),
(1786, 455, 2966436189),
(1787, 456, 2966420394),
(1788, 457, 2966430624),
(1789, 458, 2966420085),
(1790, 459, 2966427707),
(1791, 460, 2966156390),
(1792, 461, 2902421496),
(1793, 461, 2902422779),
(1794, 462, 2902422363),
(1795, 462, 2902421256),
(1796, 463, 2902421160),
(1797, 464, 2902421335),
(1798, 465, 2902421171),
(1799, 465, 2902421172),
(1800, 465, 2902421196),
(1801, 465, 2902410569),
(1802, 466, 2902421171),
(1803, 466, 2902421172),
(1804, 466, 2902421196),
(1805, 467, 2902482920),
(1806, 467, 2902482644),
(1807, 468, 2902421233),
(1808, 469, 2902421111),
(1809, 470, 2902421258),
(1810, 471, 2902421646),
(1811, 472, 2902421185),
(1812, 473, 2902421177),
(1813, 474, 2902421084),
(1814, 475, 2902422251),
(1815, 476, 2902421177),
(1816, 477, 2902421722),
(1817, 478, 2902422312),
(1818, 479, 2902421657),
(1819, 480, 2902421258),
(1820, 481, 2902421835),
(1821, 482, 2902421177),
(1822, 483, 2902421185),
(1823, 484, 2902482827),
(1824, 485, 2902482831),
(1825, 486, 2902482827),
(1826, 487, 2902482827),
(1827, 488, 2962497207),
(1828, 489, 297490100),
(1829, 490, 2962495050),
(1830, 490, 2962495073),
(1831, 491, 2962495070),
(1832, 491, 2962495035),
(1833, 491, 2962495064),
(1834, 492, 2962495055),
(1835, 493, 2962495002),
(1836, 494, 2962495002),
(1837, 495, 2962497967),
(1838, 496, 1045),
(1839, 497, 5429664240),
(1840, 498, 2966422651),
(1841, 499, 2966429462),
(1842, 499, 2966427446),
(1843, 500, 2966420543),
(1844, 500, 2966437224),
(1845, 501, 2966427446),
(1846, 501, 2966429462),
(1847, 502, 2966438725),
(1848, 502, 2966437412),
(1849, 503, 2966420189),
(1850, 503, 2966438728),
(1851, 504, 2966427446),
(1852, 504, 2966429462),
(1853, 505, 2966424650),
(1854, 505, 2966426175),
(1855, 506, 2966429344),
(1856, 507, 2966436653),
(1857, 508, 2966426744),
(1858, 508, 2966437658);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `telefonos`
--
DROP TABLE IF EXISTS `telefonos`;
CREATE TABLE IF NOT EXISTS `telefonos` (
`id_telefono` int(7) NOT NULL AUTO_INCREMENT,
`id_localidad` int(4) NOT NULL,
`nombre_telefono` varchar(60) NOT NULL,
`direccion_telefono` varchar(60) NOT NULL,
`telefono_telefono` varchar(60) NOT NULL,
`paginaweb_telefono` varchar(60) NOT NULL,
`id_categoria` int(4) NOT NULL,
PRIMARY KEY (`id_telefono`)
) ENGINE=MyISAM AUTO_INCREMENT=509 DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `telefonos`
--
INSERT INTO `telefonos` (`id_telefono`, `id_localidad`, `nombre_telefono`, `direccion_telefono`, `telefono_telefono`, `paginaweb_telefono`, `id_categoria`) VALUES
(1, 1, 'Municipalidad', '?????', '02902 48-2075', 'plus.google.com/111033911046825921420/posts', 1),
(2, 1, 'HOSPITAL SAN LUCAS', 'Rio Negro esq. 9 DE Julio', '(02902) 482121/ 4821', '', 3),
(3, 1, 'DIVISIÓN COMISARIA 28 DE NOVIEMBRE', 'Antártida Argentina 510', '2902-482103 (fax)/482049/482166 (Destacamento)', '', 2),
(4, 1, 'DIVISIÓN CUARTEL 14 BOMBEROS', 'Av. <NAME> 467', '2902-482055/482744 (100)', '', 2),
(5, 1, 'E.P.J.A. PRIMARIA Nº 07 SOBERANIA NACIONAL', 'ANTARTIDA ARGENTINA 537', '02902-482078', '', 4),
(6, 1, 'E.P.J.A. SECUNDARIA Nº 02 MARIA BEN<NAME>', 'ANTARTIDA ARGENTINA 1164', '02902-482400', '', 4),
(7, 1, 'JARDIN DE INFANTES Nº 21 ALUEN', 'SARMIENTO1445', '02902-482210', '', 4),
(8, 1, 'JARDIN DE INFANTES Nº 48 ARCO IRIS', 'LIBERTAD 139', '02902-482073', '', 4),
(9, 1, 'ESC. PRIMARIA PROV. Nº 32 PROVINCIA DE FORMOSA', 'ANTARTIDA ARGENTINA 537', '02902-482078', '', 4),
(10, 1, 'ESC. PRIMARIA PROV. Nº 67 JORGE AMERICO BLACHERE', 'HIPOLITO IRIGOYEN 1497', '02902-482022', '', 4),
(12, 2, 'ESC. PRIMARIA PROV. RURAL Nº 48 POLICIA DE SANTA CRUZ', '<NAME>', '02966-422291', '', 4),
(13, 3, 'ESC. PRIMARIA PROV. RURAL Nº 37 PADRE DE LA PATRIA', 'RUTA NACIONAL 40', '-', '', 4),
(14, 4, 'Municipalidad de Caleta Olivia', '25 de May 0443', '0297-4851230', 'http://www.caletaolivia.gov.ar/', 1),
(15, 4, 'Terminal Omnibus Caleta Olivia', 'Av. Independencia y San Martin', '0297-4851285/6', '', 5),
(16, 4, 'HOSPITAL ZONAL PADRE <NAME>', 'Av. Peron esq. Gob. Gregores', '(297) 4851389 - 4853417 - 4853417', '', 3),
(17, 4, 'DIRECCIÓN GENERAL DE REGIONAL NORTE', 'Capitán Gutero 480', '297-4852889/4852107/4852200', '', 2),
(18, 4, 'DIVISIÓN COMANDO RADIOELÉCTRICO', 'Capitán Gutero 436', '297-4856320/4835922', '', 5),
(19, 4, 'RE.P.<NAME>', 'H<NAME> 2375', '297-4856988', '', 6),
(20, 4, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', 'E<NAME> 590', '297-4851200/4856087/4856534', '', 2),
(21, 4, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', '<NAME> 1269', '297-4857241(fax)/4853364/4852100', '', 2),
(22, 4, 'DIVISIÓN COMISARIA SECCIONAL TERCERA', 'Av. E. Perón s/n', '297-4859340/4856136 (fax)', '', 2),
(23, 4, 'DIVISIÓN COMISARIA SECCIONAL CUARTA', 'Islas Bahamas 500-598', '297-4859410/4856296', '', 2),
(24, 4, 'DIVISIÓN COMISARIA SECCIONAL QUINTA', 'B. Rotary 23 San Luis s/n', '297-4837165', '', 2),
(25, 4, 'DIVISIÓN COMISARIA DE LA MUJER Y LA FAMILIA', 'Av. <NAME> s/n (pegado galpón lapeidade)', '297-4831551', '', 2),
(26, 4, 'DIVISIÓN CUARTEL 5', 'Dirección: Almirante Brown y Capitán Guttero', '297-4851666 (100)/4851395 (fax)', '', 2),
(27, 4, 'DIVISIÓN CUARTEL 16', 'B° Unión José Hernández 1228', '297-4830521 (fax)/4858994', '', 2),
(28, 4, 'DIVISIÓN CUARTEL 18', '<NAME> s/n', '297-4850300 (108)/4850457 (fax)', '', 2),
(29, 4, 'E.P.J.A. PRIMARIA Nº 02', 'JU<NAME> 263', '0297-4851852', '', 4),
(30, 4, 'E.P.J.A. PRIMARIA Nº 16', '<NAME> 2545', '0297-4854477', '', 4),
(31, 4, 'E.P.J.A. SECUNDARIA Nº 13 J.J. DE URQUIZA', 'EVA PERON 73', '0297-4851868', '', 4),
(32, 4, 'E.P.J.A. SECUNDARIA Nº 21', '<NAME> 263', '', '', 4),
(33, 4, 'CENTRO MUNICIPAL DE EDUCACION POR EL ARTE', 'BARBARA SERRANO E INDEPENDENCIA', '0297-4852944', '', 4),
(34, 4, 'ESCUELA ESPECIAL Nº 02 CECILIA GRIERSON', '<NAME> 119', '0297-4851602', '', 4),
(35, 4, 'ESCUELA ESPECIAL Nº 08 VENTANA A LA VIDA', 'RIVADAVIA 420', '0297-4856403', '', 4),
(36, 4, 'ESCUELA ESPECIAL Nº 13 SALVADOR GAVIOTA', 'VELEZ SARSFIELD 300', '0297-4851467', '', 4),
(37, 4, 'ESCUELA ESPECIAL Nº 15', 'MAIPU 37', '0297-4851957', '', 4),
(38, 4, 'CENTRO DE CAPACITACION LABORAL N° 1 SAN JOSE OBRERO', 'SAN JOSE OBRERO 1620', '0297-4851603', '', 4),
(41, 4, 'JARDIN DE INFANTES INSTITUTO M<NAME>', '<NAME> 193', '0297-4851224', '', 4),
(42, 4, 'JARDIN DE INFANTES Nº 11 RUCANTUN', 'VELES SARFIELD 385', '0297-4851646', '', 4),
(43, 4, 'JARDIN DE INFANTES Nº 18 ISLAS MALVINAS ARG.', 'MADROÑAL 530', '0297-4851618', '', 4),
(44, 4, 'JARDIN DE INFANTES Nº 20 AIKEN', 'AV. REPUBLICA 930', '0297-4854614', '', 4),
(45, 4, 'JARDIN DE INFANTES Nº 28 ANTUKELEN', 'SAN MARTIN 558', '0297-4858811', '', 4),
(46, 4, 'JARDIN DE INFANTES Nº 42 PILMAYKEN', '<NAME> 1340', '0297-4851890', '', 4),
(47, 4, 'JARDIN DE INFANTES Nº 51 MAILEN', 'EJERCITO ARGENTINO Y LAS LILAS', '0297-4856740', '', 4),
(48, 4, 'JARDIN DE INFANTES Nº 52 CUMELEN', 'TOMILLO 730', '0297-4857944', '', 4),
(49, 4, 'JARDIN DE INFANTES Nº 57 OMILEN ANTU', 'TIERRA DEL FUEGO 1984', '0297-4837294', '', 4),
(50, 4, 'JARDIN DE INFANTES Nº 58 AYEN HUE', 'ENTRE RIOS 2784', '0297-4837553', '', 4),
(51, 4, 'COLEGIO DE ENSEÑANZA DIGITAL CALETA OLIVIA', 'RUTA PROV N° 3 - ACC SUR', '0297-156246033', '', 4),
(52, 4, 'ESC. PRIMARIA PROV. Nº 13 ROBERTO J.PAIRO', 'CHACABUCO Y <NAME>', '0297-4857949', '', 4),
(53, 4, 'ESC. PRIMARIA PROV. Nº 14 20 DE NOVIEMBRE', 'JU<NAME>VAREZ 263', '0297-4851614', '', 4),
(54, 4, 'ESC. PRIMARIA PROV. Nº 28 GUARDIA NACIONAL', 'CEFERINO NAMUNCURA 2657', '0297-4851798', '', 4),
(55, 4, 'ESC. PRIMARIA PROV. Nº 29 <NAME>', 'BEAUVOIR 833', '0297-4851152', '', 4),
(56, 4, 'ESC. PRIMARIA PROV. Nº 36 ANTARTIDA ARGENTINA', 'AZCUENAGA 307', '0297-4851347', '', 4),
(57, 4, 'ESC. PRIMARIA PROV. Nº 43 PEDRO B. <NAME>', '<NAME> 423', '0297-4851643', '', 4),
(58, 4, 'ESC. PRIMARIA PROV. Nº 57 JOSE INGENIEROS', '<NAME> 1372', '0297-4837294', '', 4),
(59, 4, 'ESC. PRIMARIA PROV. Nº 65 MAR ARGENTINO', '<NAME> 930', '0297-4856862', '', 4),
(60, 4, 'ESC. PRIMARIA PROV. Nº 69 HIELOS CONTINENTALES', 'EVA PERON 73', '0297-4851868', '', 4),
(61, 4, 'ESC. PRIMARIA PROV. Nº 74 VIENTOS SUREÑOS', 'BRASIL 521', '0297-4854443', '', 4),
(62, 4, 'ESC. PRIMARIA PROV. Nº 76 KIMEHUEN', 'LAS MARGARITAS 2145', '0297-4856648', '', 4),
(63, 4, 'ESC. PRIMARIA PROV. Nº 79', '<NAME> 575', '0297-4857447', '', 4),
(64, 4, 'ESC. PRIMARIA PROV. Nº 82', 'TIERRA DEL FUEGO 2062', '0297-4837295', '', 4),
(65, 4, 'ESC. PRIMARIA PROV. Nº 88', 'ENTRE RIOS 2730', '0297-4837552', '', 4),
(66, 4, 'ESC. PRIMARIA <NAME>', '<NAME> 1850', '0297-4859330', '', 4),
(67, 4, 'ESCUELA PRIVADA ADVENTISTA PERITO MORENO', '<NAME> 111', '0297-4851157', '', 4),
(68, 4, '<NAME>', '<NAME> 1469', '0297-4851818', '', 4),
(69, 4, 'INSTITUTO <NAME> (PRIMARIA)', '<NAME> 193', '0297-4851224', '', 4),
(71, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 13 LEOPOLDO LUGONES', '<NAME> 121', '0297-4851674', '', 4),
(73, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 22', '<NAME> 2545', '0297-4854477', '', 4),
(74, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 27', 'GOB. PARADELO 939', '0297-4854068', '', 4),
(75, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 42', 'ENTRE RIOS 2784', '-', '', 4),
(76, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 43', '<NAME> 575', '-', '', 4),
(77, 4, 'COLEGIO SECUNDARIO <NAME>', '<NAME> 1850', '0297-4859330', '', 4),
(78, 4, 'INSTITUTO SECUNDARIO <NAME>', '<NAME> 193', '0297-4851224', '', 4),
(79, 4, 'INSTITUTO PROVINCIAL DE EDUCACION SUPERIOR (CO)', '<NAME> 1370', '0297-4851937', '', 4),
(81, 4, 'ESCUELA INDUSTRIAL Nº 01 GRAL. ENRIQUE MOSCONI', 'ESTRADA 435', '0297-4856780', '', 4),
(82, 5, 'DIVISIÓN COMISARIA Ca<NAME>', 'San Martin y Medanito s/n', '297-4850101 (fax)/4850100', '', 2),
(83, 5, 'JARDIN DE INFANTES Nº 12 TIEMPO DE CRECER', 'BARRANCAS S/N', '0297-4850144', '', 4),
(84, 5, 'ESC. PRIMARIA PROV. Nº 23 26 DE JUNIO', 'CAIMANCITO 6095', '0297-4850103', '', 4),
(85, 5, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 33', 'CAIMANCITO 6095', '0297-4850454', '', 4),
(86, 6, 'Municipalidad', 'Piloto Civil Norberto Fernandez Nº 16', '(02902) – 491020 – 491082', '', 1),
(87, 6, 'Dirección de comercio', '', '491020', '', 1),
(88, 6, 'Secretaría. De Turismo', '', '491090', '', 1),
(89, 6, 'Dpto de Medicina del Trabajo', '', '491020', '', 1),
(90, 6, 'Dirección de Defensa Civil', '', '497103', '', 2),
(91, 6, 'HOSPITAL DISTR. <NAME>', 'Av. Rocca N° 1487', '(02902) 491173', '', 3),
(92, 6, 'DIRECCIÓN GENERAL REGIONAL SUDOESTE', 'Av. Libertador N° 819', '2902-490701 (fax)', '', 2),
(93, 6, 'DIVISIÓN COMISARIA 1RA LAGO ARGENTINO', 'Av. Libertador San Martin N° 819', '2902-491825/491077', '', 2),
(94, 6, 'DIVISIÓN COMISARIA 2DA LAGO ARGENTINO', 'Av. 349 y 17 de Octubre', '2902-491819 (fax)/496871/490077/497026', '', 2),
(95, 6, 'DIVISIÓN COMANDO RADIOELÉCTRICO EL CALAFATE', 'Av. Libertador N° 835 (fondo)', '2902-491824/497694', '', 2),
(96, 6, 'DIVISIÓN CUARTEL 8 BOMBEROS', 'Formenti 17', '2902-491070/492317(100)', '', 2),
(97, 6, 'DIVISIÓN CUARTEL 21 (2249) BOMBEROS', '<NAME> y <NAME>', '2902-490770', '', 2),
(98, 6, 'E.P.J.A. PRIMARIA Nº 11 <NAME>', '<NAME> 41', '02902-491205', '', 4),
(99, 6, 'E.P.J.A. SECUNDARIA Nº 04', '<NAME> 1325', '02902-491560', '', 4),
(100, 6, 'ESCUELA ESPECIAL Nº 05 TENINK AIKEN', 'VALENTIN FEILBERG 169', '02902-491022', '', 4),
(101, 6, 'CENTRO EDUCATIVO JOVEN LABRADOR', 'MONSEÑOR FAGNANO 1457', '02902-495857', '', 4),
(102, 6, 'JARDIN DE INFANTES Nº 10 GRAL. MARTIN MIGUEL DE GUEMES', 'CAMPAÑA DEL DESIERTO 1438', '02902-491438', '', 4),
(103, 6, 'JARDIN DE INFANTES Nº 54 KAU TALENK', 'MA. EVA DUARTE DE PERON 2038', '02902-491914', '', 4),
(104, 6, 'JARDIN DE INFANTES Nº 60', 'PROF. NORMA ROTONDO 191', '02902-490060', '', 4),
(105, 6, 'JARDIN DE INFANTES Nº 63', 'CAMPAÑA DEL DESIERTO 1130', '02902-490980', '', 4),
(106, 6, '<NAME>.', '<NAME> 366', '02902-493720', '', 4),
(107, 6, 'ESC. PRIMARIA PROV. Nº 09 CONTRALMIRANTE VALENTIN FEILBERG', '<NAME> 893', '02902-491086', '', 4),
(108, 6, 'ESC. PRIMARIA PROV. Nº 73 LAGO ARGENTINO', 'CAMPAÑA DEL DESIERTO 1850', '02902-493088', '', 4),
(110, 6, 'ESC. PRIMARIA PROV. Nº 89', '<NAME> 41', '02902-497305', '', 4),
(111, 6, 'ESCUELA NUESTRA SEÑORA DE LA PATAGONIA', 'CALLE SIN NOMBRE 51', '02902-496490', '', 4),
(112, 6, '<NAME>', 'MONSEÑOR FAGNANO 1457', '02902-491587', '', 4),
(114, 6, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 46', 'PROF. NORMA ROTONDO 53', '02902-489222', '', 4),
(115, 6, 'CENTRO DE ESTUDIOS SUPERIORES PADRE ALBERTO DE AGOSTINI', 'MONSEÑOR FAGNANO 1457', '02902-495857', '', 4),
(116, 6, 'ESCUELA INDUSTRIAL Nº 09', '<NAME> 41', '02902-491209', '', 4),
(117, 7, 'Zona Norte - Parque Nacional Los Glaciares', 'Ruta 3 s/n', '02962 493004', '', 6),
(118, 7, 'Dirección de Turismo, Medio Ambiente y Pesca', 'Ubicación: Terminal de Ómnibus', 'Teléfono: 02962 493370', '', 1),
(119, 7, 'Municipalidad de El Chaltén', 'Av. M. M. de Güemes 21', '02962 493011/262', '', 1),
(120, 7, 'Registro Civil El Chaltén Oficina Seccional 2756', 'Av. Lago del Desierto 341', '02962 493105', '', 1),
(121, 7, 'J<NAME> El Chaltén', 'Av. Lago del Desierto 335', '02962 493058', '', 1),
(122, 7, 'Dirección de Cultura Ceremonial y Protocolo', 'Av. M. M. de Güemes 21', '02962 493270/011', '', 1),
(123, 7, 'DIVISIÓN COMISARIA', 'Av. San Martin N° 318', '2962-493003/433135', '', 2),
(124, 7, 'DIVISIÓN CUARTEL 17 (3239) BOMBEROS', 'Pasaje Founroge s/n', '2962-493240 (fax)/493142 (fax)/493013', '', 2),
(125, 7, 'E.P.J.A. PRIMARIA Nº 20', 'AVDA. MIGUEL DE GUEMES Y LAS ALDEAS', '02962-493048', '', 4),
(126, 7, 'E.P.J.A. SECUNDARIA Nº 19', 'AVDA. MIGUEL DE GUEMES Y LAS ALDEAS', '02962-493048', '', 4),
(127, 7, 'JARDIN DE INFANTES Nº 46 LOS HUEMULES', 'LAS ADELAS S/N', '02962-493125', '', 4),
(128, 7, 'ESC. PRIMARIA PROV. RURAL Nº 59 LOS NOTROS', 'LAS ADELAS S/N', '02962-493104', '', 4),
(129, 7, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 28', 'AVDA. MIGUEL DE GUEMES Y LAS ALDEAS', '02962-493048', '', 4),
(130, 8, 'ESC. PRIMARIA PROV. RURAL Nº 24 CACIQUE CILCACHO', 'RESERVA INDIGENA CAM<NAME>', '-', '', 4),
(131, 9, 'ESC. PRIMARIA PROV. RURAL Nº 31 GENDARME ARGENTINO', 'ESTANCIA EL CONDOR', '02966-421214', '', 4),
(132, 10, 'ESC. PRIMARIA PROV. RURAL Nº 25 CACIQUE C<NAME>', '<NAME>', '-', '', 4),
(133, 11, 'ESC. PRIMARIA PROV. RURAL Nº 26 GENDARMERIA NACIONAL', 'PARAJE LAS VEGAS', '-', '', 4),
(134, 12, 'DIVISIÓN SUBCOMISARIA <NAME>', '<NAME>', 'No poseen', '', 2),
(135, 12, 'JARDIN DE INFANTES Nº 29 TRENCITO DEL SUR', '<NAME>/N', '-', '', 4),
(136, 12, 'ESC. PRIMARIA PROV. Nº 20 MALVINAS ARGENTINAS', '<NAME>/N', '-', '', 4),
(137, 13, 'ESC. PRIMARIA PROV. RURAL Nº 34 FCO. <NAME>', 'ESTANCIA FUENTES DEL COYLE', '-', '', 4),
(138, 13, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 35', 'ESTANCIA FUENTES DEL COYLE', '-', '', 4),
(139, 14, 'Municipalidad de Gobernador Gregores', 'San Martin 514', '491055', '', 1),
(140, 14, 'HOSPITAL DR. <NAME>', 'M. Castulo Paradelo N° 1025', '(02962) 491001', '', 3),
(141, 14, 'DIVISIÓN COMISARIA', 'San Martin 1087', '2962-491088/491055/491459', '', 2),
(142, 14, 'DIVISIÓN CUARTEL 10', 'Av. San Martin 1087', '2962-491099', '', 2),
(143, 14, 'E.P.J.A. PRIMARIA Nº 10 <NAME>', '<NAME>IC 667', '02962-491281', '', 4),
(144, 14, 'E.P.J.A. SECUNDARIA Nº 16 <NAME>', '<NAME> 667', '02962-491281', '', 4),
(145, 14, 'JARDIN DE INFANTES Nº 07 MARIA MONTESSORI', 'COLON 583', '02962-491032', '', 4),
(146, 14, 'ESC. HOGAR PRIMARIA PROV. RURAL Nº 2 HEROES DE MALVINAS', 'RUTA PROVINCIAL 27', '-', '', 4),
(147, 14, 'ESC. PRIMARIA PROV. Nº 18 <NAME>', '<NAME> 573', '02962-491031', '', 4),
(148, 14, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 21 JOSE FONT', 'ROCA 1154', '02962-491250', '', 4),
(149, 14, 'ESCUELA AGROPECUARIA PROV. Nº 1', 'RUTA PROVINCIAL 27', '02962-491119', '', 4),
(150, 15, '<NAME> Nº 40 VALLE DE AMANCAY', 'LAS CALANDRIAS 136', '02963-490258', '', 4),
(151, 15, 'ESC. PRIMARIA PROV. RURAL Nº 42 <NAME>', '<NAME> S/N', '02963-490204', '', 4),
(152, 15, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 29', '<NAME> S/N', '02963-490204', '', 4),
(153, 16, '<NAME>', 'Av. <NAME> s/n', '297-4806018', '', 2),
(154, 16, '<NAME> Nº 32 MACACHIN', '<NAME> S/N', '-', '', 4),
(155, 16, 'ESC. PRIMARIA PROV. Nº 07', '<NAME> S/N', '0297-4806038', '', 4),
(156, 16, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 31', '<NAME> S/N', '0297-4806038', '', 4),
(157, 17, 'JARDIN DE INFANTES Nº 23 YE<NAME>', 'Bº MEDIO', '02902-482916', '', 4),
(158, 17, 'ESC. PRIMARIA PROV. Nº 30 JULIA DUFOUR', 'Bº MEDIO', '02902-482915', '', 4),
(159, 18, 'DIVISIÓN SUBCOMISARIA', '<NAME> s/n', '297-4993881', '', 2),
(160, 18, 'DIVISIÓN CUARTEL 23', '<NAME> s/n', '297-4993883', '', 2),
(161, 18, '<NAME> Nº 30 RINCON DE LUZ', 'SARMIENTO S/N', '0297-4993834', '', 4),
(162, 18, 'ESC. PRIMARIA PROV. Nº 21 PROVINCIA DEL CHUBUT', '<NAME>', '0297-4993821', '', 4),
(163, 18, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 32', '<NAME>', '0297-4993821', '', 4),
(164, 19, 'SUBCOMISARIA Lago Posadas', 'Av. San Martin esq. Las Lengas', '2963-490228 (fax)/490295/490220', '', 2),
(165, 20, 'Municipalidad de las Heras', 'Antiguos Pobladores y San Martin', '4974-071/077/110/232', '', 1),
(166, 20, 'Servicios Publicos', 'Hip<NAME>, 2456', '0297-4851007 ', '', 5),
(167, 20, 'Defensa Civil', '', '4974078', '', 1),
(168, 20, 'Registro Civil las Heras', '', '4975558', '', 1),
(169, 20, 'HOSPITAL SECCIONAL LAS HERAS', '28 de Noviembre esq. El Calafate', '(0297) 4974666', '', 4),
(170, 20, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', '<NAME> y <NAME>', '297-4974030/4975912', '', 2),
(171, 20, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', '28 de Noviembre y 25 de Mayo', '297-4975830/4974550', '', 2),
(172, 20, 'DIVISION CUARTEL 11', '<NAME> s/n', '297-4974444', '', 2),
(173, 20, 'E.P.J.A. PRIMARIA Nº 14', '<NAME> 854', '0297-4975477', '', 4),
(174, 20, 'E.P.J.A. SECUNDARIA Nº 14', 'SARMIENTO 494', '0297-4975116', '', 4),
(175, 20, 'ESCUELA ESPECIAL Nº 07', 'ESTRADA 850', '0297-4974811', '', 4),
(177, 20, 'ESCUELA DE CAPACITACION LABORAL PADRE DUPUY', 'RIVADAVIA 240', '0297-4974002', '', 4),
(178, 20, 'JARDIN DE INFANTES Nº 08 RUCAYLIN', '1º DE MAYO 675', '0297-4975486', '', 4),
(179, 20, 'JARDIN DE INFANTES Nº 47 KOONEK', 'MINISTRO CALDERON 563', '0297-4974803', '', 4),
(180, 20, 'JARDIN DE INFANTES Nº 55 TALENKE-JOSHEN', '28 DE NOVIEMBRE S/N', '0297-4974053', '', 4),
(181, 20, 'JARDIN DE INFANTES Nº 59', 'PUERTO DESEADO 60', '0297-4974850', '', 4),
(182, 20, 'ESC. PRIMARIA PROV. Nº 03 <NAME>', 'GOBERNADOR GREGORES 854', '0297-4974809', '', 4),
(183, 20, 'ESC. PRIMARIA PROV. Nº 53 <NAME>', 'PUERTO DESEADO 47', '0297-4974808', '', 4),
(184, 20, 'ESC. PRIMARIA PROV. Nº 64', '13 DE December 1050', '0297-4975244', '', 4),
(185, 20, 'ESC. PRIMARIA PROV. Nº 77', 'CALAFATE S/N', '0297-4975699', '', 4),
(186, 20, 'ESC. PRIMARIA PROV. Nº 84', 'SARMIENTO 494', '0297-4976272', '', 4),
(188, 20, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 44', '13 DE December 1050', '-', '', 4),
(189, 20, 'INSTITUTO SUPERIOR DE HIDROCARBUROS', 'HIPOLITO YRIGOYEN 150', '0297-4976085', '', 4),
(190, 20, 'ESCUELA INDUSTRIAL Nº 07', '<NAME> S/N', '0297-4975158', '', 4),
(191, 21, 'OFICINA DE TURISMO DE LOS ANTIGUOS', 'Avenida 11 de Julio 446', '02963) 491261', 'http://www.losantiguos.tur.ar/', 6),
(192, 21, 'Municipalidad de los Antiguos', 'Avenida 11 de Julio 432 Cp (9041)', '0296 349 1262', 'https://www.losantiguos.gob.ar/', 1),
(193, 21, 'HOSPITAL SECCIONAL LOS ANTIGUOS', 'Patagonia Argentina N° 68', '(02963) 491303', '', 3),
(194, 21, 'DIVISIÓN COMISARIA CABO E. GRIPPO', 'Gobernador Gregores 12', '2963-491312/491269', '', 2),
(195, 21, 'DIVISIÓN CUARTEL 13', 'Bulgarini y Picadero', '2963-491151/491268 (100)', '', 2),
(196, 21, 'E.P.J.A. PRIMARIA Nº 15', 'PERITO MORENO 253', '02963-491381', '', 4),
(197, 21, 'E.P.J.A. SECUNDARIA Nº 08', 'PERITO MORENO 253', '02963-491381', '', 4),
(198, 21, 'JARDIN DE INFANTES Nº 25', 'FITZ ROY 460', '02963-491039', '', 4),
(199, 21, 'ESC. HOGAR PRIMARIA PROV. RURAL Nº 1 FRANCISCO P. MORENO', 'AVENIDA TEHUELCHES 79', '02963-491344', '', 4),
(200, 21, 'ESC. PRIMARIA PROV. Nº 17 POLICIA FEDERAL ARGENTINA', 'CRUZ DEL SUR 29', '02963-491309', '', 4),
(202, 22, 'Municipalidad Perito Moreno', 'Av.San Martin 1776', '02963-432072/210/2764/222/2656/2157/23/86', '', 1),
(203, 22, 'Terminal Omnibus', 'Acceso Ruta 43', '296343063', '', 5),
(204, 22, 'HOSPITAL SECCIONAL DR. <NAME>', 'Colon N° 1237', '(02963) 432011', '', 3),
(205, 22, 'DIVISIÓ<NAME>', '25 de May 1394', '2963-432014 (fax)/432012 (fax)', '', 2),
(206, 22, 'DIVISIÓN CUARTEL 12', '25 de Mayo s/n', '2963-432299', '', 2),
(207, 22, 'E.P.J.A. PRIMARIA Nº 13 <NAME>', '<NAME> 1295', '02963-432697', '', 4),
(208, 22, 'ESCUELA PARA ADULTOS SAN MARTIN DE TOURS', '<NAME>IN 1662', '02963-432054', '', 4),
(209, 22, 'E.P.J.A. SECUNDARIA Nº 01 <NAME>', 'COLON 1973', '02963-432073', '', 4),
(211, 22, 'INSTITUTO SAN MARTIN DE TOURS', 'SAN MARTIN 1662', '02963-432054', '', 4),
(212, 22, '<NAME> \"MIS ANGELITOS\"', 'SAAVEDRA 751', '0297-4293993', '', 4),
(213, 22, 'J<NAME> Nº 06 ARISKAIKEN', 'ALMIRANTE BROWN 1966', '02963-432574', '', 4),
(214, 22, 'ESC. PRIMARIA PROV. Nº 12 REMEDIOS ESCALADA DE SAN MARTIN', 'ESTRADA 980', '02963-432001', '', 4),
(215, 22, 'ESC. PRIMARIA PROV. Nº 72 PIONEROS DEL SUR', 'COLON 1973', '02963-432726', '', 4),
(217, 23, 'Municipalidad de Pico Truncado', 'Calle 9 de Julio 450, Pico Truncado, Santa Cruz', '0297 499-2160', '', 1),
(218, 23, 'Oficina de Turismo de Pico Truncado', 'Gob. Gregores y Urquiza', '0297-4992202', '', 6),
(219, 23, 'Correo Argentino', 'Rivadavia 455', '297-4992156', '', 5),
(220, 23, 'HOSPITAL SECCIONAL PICO TRUNCADO', 'Velez Sarfield N° 305', '(0297) 4992192', '', 3),
(221, 23, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', 'B. Rivadavia 495', '297-4999616 (fax)/ 49992111/4992862', '', 2),
(222, 23, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', 'Ramón Lista 400', 'Teléfonos: 297-4993111/4994111', '', 2),
(223, 23, 'DIVISIÓN COMISARIA DE LA MUJER Y FAMILIA', 'Viamonte 836', '297-4992790 (fax)', '', 2),
(224, 23, 'DIVISIÓN CUARTEL 6', 'Roca 638', '297-4993303 (fax)/4990703/4992000 (100)/ 4992333 (100)', '', 2),
(225, 23, 'E.P.J.A. PRIMARIA Nº 05 BEATRIZ <NAME>ARRO', 'BELGRANO 172', '0297-4992079', '', 4),
(226, 23, 'E.P.J.A. SECUNDARIA Nº 03', 'ESPAÑA 461', '0297-4992860', '', 4),
(227, 23, 'ESCUELA ESPECIAL Nº 03', '<NAME> 1164', '0297-4990800', '', 4),
(229, 23, 'ESCUELA DE CAPACITACION LABORAL Nº 2 NAZARETH', 'RAMON LISTA 832', '0297-4999974', '', 4),
(230, 23, 'CO<NAME> (INICIAL)', '<NAME> 455', '0297-4992612', '', 4),
(231, 23, 'JARDIN DE INFANTES Nº 14 LIHUEN', '9 DE July 0372', '0297-4991200', '', 4),
(232, 23, 'JARDIN DE INFANTES Nº 26 KIKEN', 'TUCUMAN 412', '0297-4990700', '', 4),
(233, 23, 'JARDIN DE INFANTES Nº 49 TR<NAME>', 'PELLEGRINI 1189', '0297-4992959', '', 4),
(234, 23, 'JARDIN DE INFANTES Nº 62', 'URDIN 140', '0297-4993181', '', 4),
(235, 23, '<NAME>', 'HIPOLITO YRIGOYEN 950', '0297-4994203', '', 4),
(236, 23, '<NAME> (PRIMARIO)', '<NAME> 455', '0297-4992612', '', 4),
(237, 23, 'COLEGIO DE ENSEÑANZA DIGITAL PICO TRUNCADO', 'AVDA GREGORES Y 20 DE NOVIEMBRE', '0297-4996058', '', 4),
(238, 23, 'ESC. PRIMARIA PROV. Nº 08 CAPITAN DE LOS ANDES', 'SARMIENTO 688', '0297-4992134', '', 4),
(239, 23, 'ESC. PRIMARIA PROV. Nº 35 FELIX GREGORIO FRIAS', '<NAME> 716', '0297-4992132', '', 4),
(240, 23, 'ESC. PRIMARIA PROV. Nº 40 <NAME>', 'PELLEGRINI 1047', '0297-4992146', '', 4),
(241, 23, 'ESC. PRIMARIA PROV. Nº 45 PATAGONIA ARGENTINA', 'SAAVEDRA 322', '0297-4992234', '', 4),
(242, 23, 'ESC. PRIMARIA PROV. Nº 52 <NAME>', 'ESPAÑA 461', '0297-4992860', '', 4),
(243, 23, 'ESC. PRIMARIA PROV. Nº 85', 'BELGRANO 172', '0297-4991766', '', 4),
(244, 23, '<NAME> (SECUNDARIO)', 'MARIANO MORENO 455', '0297-4992612', '', 4),
(246, 23, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 45', 'SARMIENTO 688', '-', '', 4),
(247, 23, 'ESCUELA INDUSTRIAL Nº 02', 'ESPAÑA 1075', '0297-4990669', '', 4),
(248, 24, 'HOSPITAL SECCIONAL DR. <NAME>', '<NAME> s/n', '(02962) 497125', '', 4),
(249, 24, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', 'Lavalle Este 70', '2962-497117/497063 (fax)', '', 2),
(250, 24, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', 'Ruta Nacional N° 3 Km 2373 Mz.205 B', '2966-463785', '', 2),
(251, 24, 'DIVISIÓN COMISARIA DE LA M<NAME>', 'San Martin 242', '2962-497192 (fax)', '', 2),
(252, 24, 'DIVISIÓN CUARTEL 15 BOMBEROS', '<NAME> s/n', '2962-497577/497818(fax)', '', 2),
(253, 24, 'E.P.J.A. PRIMARIA Nº 12', 'MITRE 478', '02962-497346', '', 4),
(254, 24, 'E.P.J.A. SECUNDARIA Nº 07 PROF <NAME>', 'MITRE 478', '02962-497338', '', 4),
(256, 24, 'JARDIN DE INFANTES Nº 05 RASTREADOR GUARANI', '<NAME> 315', '02962-497500', '', 4),
(257, 24, 'JARDIN DE INFANTES Nº 61', 'BARRIO MILITAR - CASA 151', '02962-492035', '', 4),
(258, 24, 'ESC. PRIMARIA PROV. Nº 06 IS<NAME>', '<NAME> 178', '02962-497261', '', 4),
(259, 24, 'ESC. PRIMARIA PROV. Nº 86', 'MITRE 478', '02962-497338', '', 4),
(260, 24, 'ESCUE<NAME>', 'BARRIO 118 VIV. IDUV', '02962-497758', '', 4),
(261, 24, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 01 <NAME>', '<NAME> 421', '02962-497732', '', 4),
(262, 25, 'Municipalidad de Puerto Deseado', 'Alte. Brown nº 415 ', '4872248', '', 1),
(263, 25, 'Correo Argentino - Sucursal Puerto Deseado', 'San Martin nº 1075 ', '4870362', '', 5),
(264, 25, 'HOSPITAL DISTR. PTO. DESEADO', 'España N° 991 - (0297) 4872364', '(0297) 4872364', '', 3),
(266, 25, 'DIVISIÓN COMISARIA DEL A MUJER Y LA FAMILIA', 'Belgrano 420', '297-4870914', '', 2),
(267, 25, 'DIVISIÓN CUARTEL 22', '12 de Octubre y Perito Moreno', '297-4870066/4872625/4872557/4872625 (Planta Verif)', '', 2),
(268, 25, 'DIVISIÓN CUARTEL 4', '<NAME>. 1068', '297-4871346', '', 2),
(269, 25, 'E.P.J.A. PRIMARIA Nº 06 MARIO CACCIA', '12 DE October 1608', '0297-4872579', '', 4),
(270, 25, 'E.P.J.A. SECUNDARIA Nº 18', '<NAME> 230', '0297-4870259', '', 4),
(271, 25, 'ESCUELA ESPECIAL Nº 11 CANTO A LA VIDA', 'SARMIENTO 255', '0297-4871069', '', 4),
(273, 25, 'JARDIN DE INFANTES Nº 09 CHALTEN', 'VENEZUELA 1364', '0297-4870586', '', 4),
(274, 25, 'JARDIN DE INFANTES Nº 39 AONIKENKE', 'GOB. GREGORES 1254', '0297-4871194', '', 4),
(275, 25, 'JARDIN DE INFANTES Nº 56 A<NAME>', 'BATALLA PUERTO ARGENTINO 1386', '0297-4872342', '', 4),
(276, 25, 'ESC. PRIMARIA PROV. Nº 05 CAP<NAME>', 'ESTRADA 1163', '0297-4870246', '', 4),
(277, 25, 'ESC. PRIMARIA PROV. Nº 56 KREWEN KAU', 'VENEZUELA Y PATAGONIA', '0297-4870239', '', 4),
(278, 25, 'ESC. PRIMARIA PROV. Nº 66 FUERTE SAN CARLOS', 'CAPITAN ONETO 1355', '0297-4872623', '', 4),
(279, 25, 'ESC. PRIMARIA PROV. Nº 87', 'ING. PORTELLA 1549', '0297-4871326', '', 4),
(281, 25, 'INSTIT<NAME> (PRIMARIO)', '12 DE October 0577', '0297-4870147', '', 4),
(282, 25, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 24 17 DE AGOSTO', '<NAME> 230', '0297-4870259', '', 4),
(283, 25, 'INSTITUTO <NAME> (SECUNDARIO)', '12 DE October 0577', '0297-4870147', '', 4),
(284, 25, 'ESCUELA INDUSTRIAL Nº 03 OSCAR SMITH', 'AV. MAYOR LOTUFO 91', '0297-4872741', '', 4),
(285, 26, 'Municipalidad de Puerto San Julian', 'Av. San Martin y Rivadavia', '02962-452076/4155/2353', '', 1),
(286, 26, 'Terminal de Omnibus', 'Av. San Martin 1570', '', '', 5),
(287, 26, '<NAME>', 'Av. San Martin 335', '02962-45141', '', 5),
(288, 26, 'HOSPITAL DISTR. PTO. SAN JULIAN', 'Av. Costanera esq. El Cano', '(02962) 452188', '', 4),
(289, 26, 'DIRECCIÓN GENERAL DE REGIONAL CENTRO', 'Roca 980', '2962-452170', '', 2),
(290, 26, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', 'Av. San Martin 864', '2962-452202/452122 (fax)', '', 2),
(291, 26, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', '<NAME> 2115', '2962-452254/452355 (fax)/452446', '', 2),
(292, 26, 'DIVISIÓN COMANDO RADIOELECTRICO', 'Av. San Martin 882', '2962-452170', '', 2),
(293, 26, 'DIVISIÓN UNIDAD OPERATIVA TRES CERROS', 'Tres Cerros', '2966-538629', '', 2),
(294, 26, 'DIVISIÓN CUARTEL 3 BOMBEROS', 'Roca 970', '2962-452065', '', 2),
(295, 26, 'E.P.J.A. PRIMARIA Nº 09 PREFECTURA NAVAL ARGENTINA', 'AV SAN MARTIN 145', '02962-452400', '', 4),
(296, 26, 'E.P.J.A. SECUNDARIA Nº 15', 'AVDA. SAN MART<NAME>', '02962-452311', '', 4),
(297, 26, 'ESCUELA ESPECIAL Nº 12', 'VELEZ SARSFIELD 886', '02962-454468', '', 4),
(298, 26, '<NAME>', 'COLON 251', '02962-454188', '', 4),
(299, 26, 'JARDIN DE INFANTES Nº 04 GRANADEROS DE SAN MARTIN', 'DARWIN 1760', '02962-452127', '', 4),
(300, 26, 'JARDIN DE INFANTES Nº 64', 'PERIODICO EL ECO 1616', '-', '', 4),
(301, 26, 'ESC. PRIMARIA PROV. Nº 04 FLORENTINO AMEGHINO', 'VIEYTES 775', '02962-452101', '', 4),
(302, 26, 'ESC. PRIMARIA PROV. Nº 75 SANTO GIULIANO DE CESAREA', 'DARWIN 1651', '02962-454231', '', 4),
(304, 26, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 02 FLORIDA BLANCA', 'ALBERDI 1759', '02962-452061', '', 4),
(305, 26, 'ESCUELA INDUSTRIAL Nº 08', 'ALBERDI 1759', '02962-414536', '', 4),
(306, 27, 'Municipio de Puerto Santa Cruz', 'Dirección Belgrano Nº 527', '', 'https://www.puertosantacruz.gob.ar/?q=contacto', 1),
(307, 27, 'HOSPITAL SECCIONAL EDUARDO CANOSA', 'Juan William N° 448', '(02962) 498153', '', 3),
(308, 27, 'DIVISIÓN COMISARIA', '<NAME> y <NAME>', '2962-498111/498166', '', 2),
(309, 27, 'UNIDAD DE BOMBEROS 7 BOMBEROS', 'San Juan Bosco 470', '2962-498300', '', 2),
(310, 27, 'E.<NAME>IMARIA Nº 17 \"GUARDACOSTAS RIO IGUAZU\"', '9 DE July 0610', '02962-498751', '', 4),
(311, 27, 'E.P.J.A. SECUNDARIA Nº 05', 'ALFEREZ BALESTRA 556', '02962-498127', '', 4),
(313, 27, 'J<NAME> Nº 03 TAMBORCITO DE TACUARI', '<NAME> 248', '02962-498224', '', 4),
(314, 27, 'ESC. PRIMARIA PROV. Nº 02 DOMINGO F.SARMIENTO', '25 DE May 0460', '02962-498318', '', 4),
(316, 27, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 08 NACIONES UNIDAS', 'ALFERES BALESTRA 556', '02962-498127', '', 4),
(317, 28, 'DIVISIÓN UNIDAD OPERATIVA RAMÓN SANTOS', 'Ruta Nacional N° 3 Limite con Pcia. de Chubut', '2966-549055', '', 2),
(318, 29, 'Medisur SA', 'Maipú 55', '2966 423000', 'medisur-rgl.com.ar', 3),
(319, 29, '<NAME>', 'San Martín 350', '2966 420555', 'medisur-rgl.com.ar', 3),
(320, 29, '<NAME>', 'Santiago del estero 236', '2966 421200', 'medisur-rgl.com.ar', 3),
(321, 29, 'San Jose', 'Corrientes 253', '02966 42-0214', '', 3),
(322, 29, 'Defensa Civil', 'Gdor. <NAME> 327', '02966-420042', '', 5),
(323, 29, 'Subsecretaria de la Mujer', 'Moreno Nº 175', '02966 – 436811 / GUARDIA: (02966) 15464122 02966 – 15644943', '', 2),
(324, 29, 'Municipalidad de Rio Gallegos', 'Avda. San Martin 791', '2966-422365/6', 'https://www.riogallegos.gov.ar/', 1),
(325, 29, 'Servicios Publicos', 'Av. Pte. <NAME>, 669', '(02966)-422322 - 0800-222-7773', 'http://www.spse.com.ar/ ', 5),
(326, 29, 'Vialidad Provincial', 'Av. Lisandro de la Torre 952', '02966 44-2367', 'http://www.agvp.gov.ar/', 5),
(327, 29, 'ANSES ', '<NAME> 399', '02966 42-0999', 'https://www.anses.gob.ar/', 1),
(328, 29, 'Camuzzi - Gas del Sur', 'C Pellegrini 241 PB', '2966-427582 - 0810-555-3698', 'http://www.camuzzigas.com/', 5),
(329, 29, 'Registro Civil Provincia de Santa Cruz', 'Moreno 123', '2966-422651', '', 5),
(330, 29, 'Servicios Generales', '', '457804', '', 5),
(331, 29, 'Control Animal', 'Paseo de los Arrieros y Ruta N° 3', '442571', '', 5),
(332, 29, 'Terminal Omnibus Rio Gallegos', 'Eva Perón 1451-1499', '02966 44-2169', '', 5),
(333, 29, 'Correo Argentino - Sucursal Rio Gallegos', 'Av.Pte.Nestor Kirchner 893', '02966-420193', '', 5),
(334, 29, 'L.O.A.S', '<NAME> 116 esq. Zapiola', '(02966) 422631', '', 6),
(335, 29, 'Canal 9', '<NAME> 250', '2966 428862', 'http://canalnuevesantacruz.tv/web/', 5),
(336, 29, 'DIRECCIÓN GENERAL REGIONAL SUR', 'Prospero Palazzo 820', '2966-426745 / 426759', '', 2),
(337, 29, 'DIVISIÓN COMANDO RADIOELÉCTRICO', 'J<NAME> 451', '2966-420505/437804/429002/420979', '', 2),
(338, 29, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', 'Av. Pdte. <NAME> 534', '2966-420993/420016/449976/424134 (fax)', '', 2),
(339, 29, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', 'Ameghino 85', '2966-420031/436612/423200(fax)', '', 2),
(340, 29, 'DIVISIÓN COMISARIA SECCIONAL TERCERA', 'Av. Paradelo s/n', '2966-420100 (fax)/420313', '', 2),
(341, 29, 'DIVISIÓN COMISARIA SECCIONAL CUARTA', '<NAME> 301 y <NAME>', '2966-423222/428376 (fax)', '', 2),
(342, 29, 'DIVISIÓN COMISARIA SECCIONAL QUINTA', '<NAME>. 2330', '2966-432714/431794', '', 2),
(343, 29, 'DIVISIÓN COMISARIA SECCIONAL SEXTA', 'Lola Mora 441', '2966-423257/423616 (fax)', '', 2),
(344, 29, 'DIVISIÓN COMISARIA SECCIONAL SÉPTIMA', 'B° San Benito – Calle 13 y 32', '2966-669638 (claro) / 2966-463592 / 2966-463593', '', 2),
(345, 29, 'DIVISIÓN COMISARIA DE LA MUJER Y LA FAMILIA', 'Mitre 170', '2966-428685', '', 2),
(346, 29, 'DIVISIÓN UNIDAD OPERATIVA COMISARIA GUER AIKE', 'Ruta Nacional N° 3', '2966-648535', '', 2),
(347, 29, 'DIVISIÓN UNIDAD OPERATIVA COMISARIA CHIMEN AIKE', 'Ruta Nacional N° 3', '2966-637221', '', 2),
(348, 29, 'DIVISIÓN UNIDAD OPERATIVA LA ESPERANZA', 'Ruta 40 – Paraje La Esperanza', '2966-422291', '', 2),
(349, 29, 'DIVISIÓN CUARTEL CENTRAL DE BOMBEROS', 'Av. <NAME> (s/n) y <NAME> (1084)', '2966-420861/422260', '', 2),
(350, 29, 'DIVISIÓN CUARTEL 1o BOMBEROS', 'Gobernador Lista 385', '2966-420232/431247', '', 2),
(351, 29, 'DIVISIÓN CUARTEL 2o BOMBEROS', 'Posadas Gervacio s/n', '2966-420600', '', 2),
(352, 29, 'DIVISIÓN CUARTEL 19o BOMBEROS', 'Avenida Paradelo 120', '2966-444463', '', 2),
(353, 29, 'DIVISIÓN CUARTEL 24o BOMBEROS', 'Calle 32 esquina calle 17', '2966-639019', '', 2),
(354, 29, 'CENTRO DE SALUD Nº 1', 'Pasteur esquina Perito Moreno', '(2966) - 428968', '', 3),
(355, 29, 'CENTRO DE SALUD N° 2', 'Psje. Zucarino S/N entre calles corrientes y Amegnino', '(2966) - 422874', '', 3),
(356, 29, 'CENTRO DE SALUD N° 3', 'Alvear esq. Los Pozos', '(2966) - 42-8970', '', 3),
(357, 29, 'CENTRO DE SALUD N° 4', '<NAME>', '(2966) 42-8975', '', 3),
(358, 29, 'CENTRO DE SALUD N° 5', '<NAME> S/N', '(2966) 42-8979', '', 3),
(359, 29, 'CENTRO DE SALUD N° 6', 'Av. Perito moreno S/N', '(2966) 44-2296', '', 3),
(360, 29, 'CENTRO DE SALUD N° 7', '13 de Julio esq. <NAME>', '(2966) 422759', '', 3),
(361, 29, 'CENTRO DE SALUD N° 8', 'B° San Benito', '?????????????', '', 3),
(362, 29, 'HOSPITAL REGIONAL RIO GALLEGOS', 'Jose Ingenieros Nº 98', '(2966) 420641 - 426221 - 421448', '', 3),
(363, 29, 'HOSPITAL MILITAR', 'Av. J<NAME> 2270', '?????????????', '', 3),
(364, 29, 'CENTRO DE CAPACITACION LABORAL DOMINGO SAVIO', 'DEFENSA 633', '02966-431988', '', 4),
(365, 29, 'E.P.J.A. PRIMARIA Nº 01 <NAME>', 'AV.KIRCHNER 1432', '02966-420511', '', 4),
(366, 29, 'E.P.J.A. PRIMARIA Nº 04 FRAGATA LIBERTAD', 'AMEGHINO 1218', '02966-431270', '', 4),
(367, 29, 'E.P.J.A. PRIMARIA Nº 08', 'BELGRANO 1386', '02966-429069', '', 4),
(368, 29, 'E.P.J.A. SECUNDARIA Nº 09', 'JARAMILLO 620', '02966-436646', '', 4),
(369, 29, 'E.P.J.A. SECUNDARIA Nº 10', 'BELGRANO 390', '02966-438090', '', 4),
(370, 29, 'E.P.J.A. SECUNDARIA Nº 12 MANUEL BELGRANO', 'COMODORO PY 361', '02966-437288', '', 4),
(371, 29, 'E.P.J.A. SECUNDARIA Nº 17 CENTENARIO DE RIO GALLEGOS', 'PERITO MORENO 630', '02966-430419', '', 4),
(372, 29, 'E.P.J.A. SECUNDARIA Nº 20', 'ALVEAR 1427', '', '', 4),
(373, 29, 'ESCUELA ESPECIAL Nº 01 TALENGH-KAU', '<NAME> 413', '02966-420257', '', 4),
(374, 29, 'ESCUELA ESPECIAL Nº 04', 'VELEZ SARSFIELD 1087', '02966-435623', '', 4),
(375, 29, 'ESCUELA ESPECIAL Nº 06', 'LAS PIEDRAS 345', '02966-426593', '', 4),
(376, 29, 'ESCUELA ESPECIAL Nº 10', 'COMODORO PY 315', '02966-426836', '', 4),
(377, 29, 'ESCUELA ESPECIAL Nº 14 USH NASH', 'POSADAS 753', '02966-426184', '', 4),
(378, 29, 'INSTITUTO PARA TRASTORNOS DEL ESPECTRO AUTISTA', 'MURATORE 444', '02966-444857', '', 4),
(380, 29, '<NAME> <NAME>', 'FAGNANO 142', '02966 -420394', '', 4),
(381, 29, '<NAME> <NAME>', 'CHACABUCO 107', '02966-420071', '', 4),
(382, 29, '<NAME> <NAME>', 'HIPOLITO YRIGOYEN 454', '02966-432943', '', 4),
(383, 29, 'JARDIN DE INFANTES Nº 01 <NAME>', 'ALVEAR 67', '02966-420138', '', 4),
(384, 29, 'JARDIN DE INFANTES Nº 13 <NAME>', 'PETREL 1125', '02966-420219', '', 4),
(385, 29, 'JARDIN DE INFANTES Nº 15 EJERCITO ARGENTINO', 'PERITO MORENO 590', '02966-437528', '', 4),
(386, 29, 'JARDIN DE INFANTES Nº 16 MERCEDITAS DE SAN MARTIN', '<NAME> 305', '02966-422019', '', 4),
(387, 29, 'JARDIN DE INFANTES Nº 17 FEDERICO FROEBEL', 'PELLEGRINI 367', '02966-421999', '', 4),
(388, 29, 'JARDIN DE INFANTES Nº 19 SAN VICENTE DE PAUL', 'COLON 560', '02966-424004', '', 4),
(389, 29, 'JARDIN DE INFANTES Nº 22 KOSPI', 'DEFENSA 660', '02966-436041', '', 4),
(390, 29, 'JARDIN DE INFANTES Nº 24 LOS CHARITOS', 'FITZ ROY 124', '02966-421406', '', 4),
(391, 29, 'JARDIN DE INFANTES Nº 35 TALENKE AMEL', '<NAME> 1325', '02966-435158', '', 4),
(392, 29, 'JARDIN DE INFANTES Nº 37 EVITA', 'POSADAS 616', '02966-426396', '', 4),
(393, 29, 'JARDIN DE INFANTES Nº 41 CHEELKENEU', '<NAME>TI 614', '02966-436768', '', 4),
(11, 1, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 12 DR. M. CASTULO P', 'ANTARTIDA ARGENTINA 1164', '02902-482400', '', 4),
(39, 4, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'PJE. DURAZNILLO S/N', '0297-4830962', '', 4),
(40, 4, 'INSTITUTO PRIVADO DE ENSEÑANZA BILINGUE \"<NAME>', 'PRESIDENTE PERON 358', '0297-4831344', '', 4),
(70, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 06 NICOLAS AVELLANE', '<NAME> 1390', '0297-4851215', '', 4),
(72, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 20 GRAL. <NAME>', 'JO<NAME> 1370', '0297-4854056', '', 4),
(80, 4, 'ESCUELA DE BIOLOGIA MARINA Y LABORATORISTA Nº 1 ATLANTICO SU', '<NAME> 73', '0297-4854058', '', 4),
(109, 6, 'ESC. PRIMARIA PROV. Nº 80 M. <NAME>', 'PROF. NORMA ROTONDO 53', '02902-492637', '', 4),
(113, 6, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 09 POLICIA DE PCIA ', 'J<NAME> 1325', '02902-491412', '', 4),
(176, 20, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'INACTIVO A LA FECHA', '', '', 4),
(187, 20, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 03 JOSE MANUEL ESTR', 'HIPOLITO YRIGOYEN 970', '0297-4974678', '', 4),
(201, 21, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 15 <NAME>', 'PERITO MORENO 253', '02963-491381', '', 4),
(210, 22, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'AV<NAME>ON 1733', '-', '', 4),
(216, 22, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 05 MART<NAME>UEL DE', 'COLON 1577', '02963-432290', '', 4),
(228, 23, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'SIN DIRECCION ASIGNADA', '', '', 4),
(245, 23, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 14 CENT. DE LA CONQ', '<NAME> 1222', '0297-4992206', '', 4),
(255, 24, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'INACTIVO A LA FECHA', '-', '', 4),
(265, 25, 'DIVISIÓN COMISARIA PTO.DESEADO', 'Ameghino F. 1080', '297-4870946 (fax)/4872777/4871321/4871208/4872556(101)/48711', '', 2),
(272, 25, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'AV. MAYOR LOTUFO 91', '-', '', 4),
(280, 25, 'INSTITUTO MARIA AUXILIADORA (PD) (INICIAL - PRIMARIA - SECUN', '<NAME> 411', '0297-4870252', '', 4),
(303, 26, 'INSTITUTO MARIA AUXILIADORA (PSJ) (INICIAL - PRIMARIA - SECU', 'ZEBALLOS 1191', '02962-452063', '', 4),
(312, 27, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', '25 DE May 0460', '02962-498318', '', 4),
(315, 27, 'INSTITUTO MARIA AUXILIADORA (PSC) (INICIAL - PRIMARIA - SECU', '25 DE May 0540', '02962-498290', '', 4),
(379, 29, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'MITRE 291', '02966-433949', '', 4),
(394, 29, 'JARDIN DE INFANTES Nº 43 BARRILETE VIAJERO', 'JARAMILLO 666', '02966-436130', '', 4),
(395, 29, 'JARDIN DE INFANTES Nº 44 MARIA TERESA POMI', 'BELGRANO S/N', '02966-420885', '', 4),
(396, 29, 'JARDIN DE INFANTES Nº 50 KAU SI AIKE', 'ALCORTA 805', '02966-436206', '', 4),
(397, 29, 'JARDIN DE INFANTES Nº 53 KETENK AIKE', 'SAN LORENZO entre FERRADÁ y GARCÍA', '02966-422628', '', 4),
(398, 29, 'JARDIN DE INFANTES Nº 65', 'CALLE 19 ESQ. CALLE 14 (Bº SAN BENITO)', '', '', 4),
(399, 29, 'J<NAME> INFANTES Nº 66', 'EINSTEIN ESQ. ENTRAIGA (Bº EVITA)', '', '', 4),
(400, 29, '<NAME>', 'MARIANO MORENO 986', '02966-426252', '', 4),
(401, 29, 'ESC. PRIMARIA NUESTRA SEÑORA DE LUJAN', 'FAGNANO 142', '02966-420394', '', 4),
(402, 29, 'ESC. PRIMARIA PROV. Nº 01 HERNAN<NAME>', 'MAIPU 53', '02966-426769', '', 4),
(403, 29, 'ESC. PRIMARIA PROV. Nº 10 HIPOLITO IRIGOYEN', 'AV. DE LOS INMIGRANTES 700', '02966-420806', '', 4),
(404, 29, 'ESC. PRIMARIA PROV. Nº 11 SESQUICENTENARIO DE LA REVOL.DE MA', 'PERITO MORENO 590', '02966-420149', '', 4),
(405, 29, 'ESC. PRIMARIA PROV. Nº 15 PCIA. DE SANTIAGO DEL ESTERO', 'PELLEGRINI 357', '02966-420703', '', 4),
(406, 29, 'ESC. PRIMARIA PROV. Nº 19 CTE. LUIS PIEDRA BUENA', 'AV.KIRCHNER 1432', '02966-420511', '', 4),
(407, 29, 'ESC. PRIMARIA PROV. Nº 33 COM. INSP. VICTORIANO <NAME>', 'LIBERTAD 1390', '02966-422178', '', 4),
(408, 29, 'ESC. PRIMARIA PROV. Nº 38 GRAL.SAN MARTIN', 'CAÑADON SECO 400', '02966-422012', '', 4),
(409, 29, 'ESC. PRIMARIA PROV. Nº 39 PABLO VI', 'COLON 520', '02966-424085', '', 4),
(410, 29, 'ESC. PRIMARIA PROV. Nº 41 REP.DE VENEZUELA', 'LAS PIEDRAS 1158', '02966-438185', '', 4),
(411, 29, 'ESC. PRIMARIA PROV. Nº 44 19 DE DICIEMBRE', 'SAN JOSE OBRERO 654', '02966-422263', '', 4),
(412, 29, 'ESC. PRIMARIA PROV. Nº 46 INTEGRACION LATINOAMERICANA', 'JARAMILLO 620', '02966-436646', '', 4),
(413, 29, 'ESC. PRIMARIA PROV. Nº 47 NTRA. SRA. DE LORETO', 'AVDA. EVA PERON 1351', '02966-426605', '', 4),
(414, 29, 'ESC. PRIMARIA PROV. Nº 55 VAPOR TRANSP. VILLARINO', 'PRESIDENTE PERON 454', '02966-427497', '', 4),
(415, 29, 'ESC. PRIMARIA PROV. Nº 58 CRUCERO AR<NAME>', 'BELGRANO 1386', '02966-429069', '', 4),
(416, 29, 'ESC. PRIMARIA PROV. Nº 61 CELIA SUAREZ DE SUSACASA', '<NAME> 2150', '02966-436205', '', 4),
(417, 29, 'ESC. PRIMARIA PROV. Nº 62 \"RE<NAME>O\"', '<NAME> 577', '02966-442832', '', 4),
(418, 29, 'ESC. PRIMARIA PROV. Nº 63 PIL<NAME> <NAME>', '<NAME> 1850', '02966-437850', '', 4),
(419, 29, 'ESC. PRIMARIA PROV. Nº 70 DR. <NAME>', 'ERRAZURIZ 145', '02966-434159', '', 4),
(420, 29, 'ESC. PRIMARIA PROV. Nº 71 PIONEROS DE SANT<NAME>', '<NAME> 183', '02966-420258', '', 4),
(421, 29, 'ESC. PRIMARIA PROV. Nº 78 <NAME>', 'COMODORO PY 361', '02966-437288', '', 4),
(422, 29, 'ESC. PRIMARIA PROV. Nº 81 \"<NAME>\"', 'AMEGHINO 1218', '02966-429025', '', 4),
(423, 29, 'ESC. PRIMARIA PROV. Nº 83', 'ITUZAINGO 689', '02966-426960', '', 4),
(424, 29, 'ESC. PRIMARIA PROV. Nº 90 \"<NAME>\"', '<NAME> 577', '02966-442832', '', 4),
(425, 29, 'ESCUELA NUESTRA SEÑORA DE FATIMA', 'ESTRADA 751', '02966-422737', '', 4),
(426, 29, 'INSTITUTO CRISTIANO DE ENSEÑANZA PATAGONICO', 'MAIPU 2470', '02966-433710', '', 4),
(427, 29, 'INSTITUTO MARIA AUXILIADORA (RGL) (INICIAL - PRIMARIO)', 'AV. KIRCHNER 529', '02966-420229', '', 4),
(428, 29, 'INSTITUTO PRIVADO AUSTRO', 'HIPOLITO YRIGOYEN 450', '02966-444726', '', 4),
(429, 29, 'INSTITUTO PRIVADO DE EDUCACION INTEGRAL', 'ZAPIOLA 155', '02966-423727', '', 4),
(430, 29, 'CENTRO POLIVALENTE DE ARTE N° 1', 'COMODORO PY 312', '02966-424939', '', 4),
(431, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 07 DR. <NAME>', 'DON BOSCO 105', '02966-426198', '', 4),
(432, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 10 GOB. <NAME>', 'PERITO MORENO 630', '02966-426859', '', 4),
(433, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 11 GRAL. <NAME>', 'BELLA VISTA 660', '02966-430560', '', 4),
(434, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 16 <NAME>', 'AMEGHINO 1218', '02966-438518', '', 4),
(435, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 17 <NAME>', '<NAME>', '02966-426787', '', 4),
(436, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 18 TOPOGRAFO <NAME>', '<NAME> 2150', '02966-436205', '', 4),
(437, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 19 CINCUENTENARIO L', 'ALVEAR 1427', '02966-431500', '', 4),
(438, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 23 REP. DE GUATEMAL', '<NAME> 183', '02966-420258', '', 4),
(439, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 25 LAGO DEL DESIERT', 'ALBERDI 518', '02966-427467', '', 4),
(440, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 26 PA<NAME>', 'BELGRANO 390', '02966-422914', '', 4),
(441, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 36', 'DR. BORIS GOS 1111', '', '', 4),
(442, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 37', '<NAME> 105', '02966-426198', '', 4),
(443, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 38', 'PERITO MORENO 630', '02966-426859', '', 4),
(444, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 39', '<NAME> 1147', '02966-426787', '', 4),
(445, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 40', 'ALVEAR 1427', '02966-431500', '', 4),
(446, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 41', '', '-', '', 4),
(447, 29, 'COLEGIO SECUNDARIO NUESTRA SEÑORA DE FATIMA', 'ESTRADA 751', '02966-422737', '', 4),
(448, 29, 'COLEGIO SECUNDARIO NUESTRA SEÑORA DE LUJAN', 'FAGNANO 142', '02966-420394', '', 4),
(449, 29, 'INSTITUTO MARIA AUXILIADORA (RGL) (SECUNDARIO)', '<NAME> 529', '02966-420229', '', 4),
(450, 29, 'INSTITUTO CRISTIANO DE ENSEÑANZA PATAGONICO', 'MAIPU 2470', '02966-433710', '', 4),
(451, 29, 'INSTITUTO PRIVADO DE EDUCACIÓN INTEGRAL', 'ZAPIOLA 155', '02966-423727', '', 4),
(452, 29, 'POPLARS JUNIOR SCHOOL', 'ESTRADA 355', '02966-425703', '', 4),
(453, 29, 'CONSERVATORIO PROV. DE MUSICA PADRE EUGENIO ROSSO', 'ALVEAR 315', '02966-436463', '', 4),
(454, 29, 'ESCUELA TECNICA DE VIALIDAD Nº 5', '<NAME> 1147', '02966-429173', '', 4),
(455, 29, 'INSTITUTO PROVINCIAL DE EDUCACION SUPERIOR (RGL)', '<NAME> 183', '02966-436189', '', 4),
(456, 29, 'INSTITUTO SALESIANO DE ESTUDIOS SUPERIORES', 'FAGNANO 142', '02966-420394', '', 4),
(457, 29, 'INSTITUTO SUPERIOR DE ENSEÑANZA TECNICA', 'ALCORTA 250', '02966-430624', '', 4),
(458, 29, 'INSTITUTO SUPERIOR DE FORMACION POLICIAL \"CRIO. INSP. (R) VI', 'RUTA Nº 3 - KM. 2579', '02966-420085', '', 4),
(459, 29, 'ESCUELA INDUSTRIAL Nº 04 <NAME>', 'MITRE 291', '02966-427707', '', 4),
(460, 29, 'ESCUELA INDUSTRIAL Nº 06 Xº BRIGADA AEREA', 'RUTA NACIONAL Nº 3', '02966-15639012', '', 4),
(461, 30, 'Caja De Servicios Sociales', '', '(2902) 42 - 1496 / 42 - 2779', '', 1),
(462, 30, 'Servicos Publicos ', '', '(2902) 42 - 2363 /42 - 1256', '', 5),
(463, 30, 'Municipalidad de Rio Turbio', '<NAME> y <NAME>, Z9407 Río Turbio, Santa Cruz, A', '02902 42-1160', 'https://www.municipalidad.com.ar/Home/Menu', 1),
(464, 30, 'HOSPITAL DE LA CUENCA CARBONIFERA', 'Gendarmeria nacional N° 126', '(02902) 421335', '', 3),
(465, 30, 'DIVISIÓN COMISARIA RIO TURBIO', 'Av. <NAME> s/n', '2902-421171/421172/421196 (fax)/ 410569 (Destacamento Turbio', '', 2),
(466, 30, 'DIVISIÓN COMANDO RADIOELECTRICO RIO TURBIO', 'Av. <NAME> s/n', '2902-421171/421172/421196 (fax)', '', 2),
(467, 30, 'DIVISIÓN UNIDAD OPERATIVA JULIA DUFOUR', '<NAME> – Ruta 40', '2902-482920 (fax) / 482644 (Destacamento Krashh)', '', 2),
(468, 30, 'DIVISIÓN CUARTEL 9 BOMBEROS', 'Teniente del Castillo s/n', '2902-421233', '', 2),
(469, 30, 'E.P.J.A. PRIMARIA Nº 03 CAMPAMENTO DE MARINA', 'GLACIAR BOLADOS 221', '02902-421111', '', 4),
(470, 30, 'E.P.J.A. SECUNDARIA Nº 06', '<NAME> 221', '02902-421258', '', 4),
(471, 30, 'ESCUELA ESPECIAL Nº 09 KEOKEN', 'CTE. LUIS PIEDRA BUENA 268', '02902-421646', '', 4),
(472, 30, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'AVDA. Y.C.F. 50', '02902-421185', '', 4),
(473, 30, '<NAME>', '<NAME> 661', '02902-421177', '', 4),
(474, 30, 'JARDIN DE INFANTES Nº 02 FUERZA AEREA ARGENTINA', 'HIPOLITO YRIGOYEN 96', '02902-421084', '', 4),
(475, 30, 'JARDIN DE INFANTES Nº 45 UAMEN TALENKE', 'GLACIAR UPSALA 60', '02902-422251', '', 4),
(476, 30, '<NAME>', 'AV SAN MARTIN 661', '02902-421177', '', 4),
(477, 30, 'ESC. PRIMARIA PROV. Nº 54 WOLF SCHCOLNIK', 'SAN MARTIN 17', '02902-421722', '', 4),
(478, 30, 'ESC. PRIMARIA PROV. Nº 60 ING. NEO ZULIANI', 'GLACIAR BOLADOS 221', '02902-422312', '', 4),
(479, 30, 'ESC. PRIMARIA PROV. Nº 68', 'JULIO ARGENTINO ROCA 259', '02902-421657', '', 4),
(480, 30, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 04 PERITO F. PASCAC', '<NAME> 221', '02902-421258', '', 4),
(481, 30, '<NAME>', '<NAME> 247', '02902-421835', '', 4),
(482, 30, '<NAME>', 'AV. <NAME> 661', '02902-421177', '', 4),
(483, 30, 'ESCUELA INDUSTRIAL Nº 05 TTE A. <NAME>', 'AVDA.Y.C.F. 50', '02902-421185', '', 4),
(484, 31, 'E.P.J.A. SECUNDARIA Nº 11', 'BARRIO MILITAR Nº 2', '02902-482827', '', 4),
(485, 31, 'JARDIN DE INFANTES Nº 33 NTRA SRA.DE LA NIEVES', 'BARRIO MILITAR Nº 2', '02902-482831', '', 4),
(486, 31, 'ESC. PRIMARIA PROV. Nº 50 MONSEÑOR J<NAME>', 'BARRIO MILITAR Nº 2', '02902-482827', '', 4),
(487, 31, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 34', 'BARRIO MILITAR Nº 2', '02902-482827', '', 4),
(488, 32, 'ESCUELA PRIMARIA RURAL \"<NAME>ON\"', 'EST. S<NAME>ON', '02962-497207', '', 4),
(489, 33, 'ESC. PRIMARIA PROV. RURAL Nº 51', 'RUTA Nº 281 KM 20', '0297-490100', '', 4),
(490, 34, 'SUBCOMISARIA', 'San Martin 18', '2962-495050 (fax) /495073 (101)', '', 2),
(491, 34, 'UNIDAD DE BOMBEROS 20', '<NAME> s/n', '2962-495070 (fax)/495035/495064 (100)', '', 2),
(492, 34, 'JARDIN DE INFANTES Nº 27 SOBERANIA NACIONAL', 'AV. SAN MARTIN S/N', '02962-495055', '', 4),
(493, 34, 'ESC. PRIMARIA PROV. RURAL Nº 16 RVDO. PADRE FEDERICO TORRES', 'AVDA. SAN MARTIN S/N', '02962-495002', '', 4),
(494, 34, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 30', 'AVDA. SAN MARTIN S/N', '02962-495002', '', 4),
(495, 24, 'Municipalidad Piedrabuena', '', '(2962) 49-7967', '', 1),
(496, 29, 'Asip', '02966-420454', 'Av. Pres. Dr. <NAME> 1045', 'https://www.asip.gob.ar/', 1),
(497, 29, 'Caja de previsión Social', 'Avenida San Martín N° 1058', '54 2966 424074', 'https://cps.gov.ar/', 1),
(498, 29, 'Registro Civil Santa Cruz', 'Moreno 123', '2966-422651', '', 1),
(499, 29, 'Ministerio de la Producción, Comercio e Industria', 'Avellaneda Nº 801', '(02966) – 429462-427446', 'http://minpro.gob.ar/', 1),
(500, 29, 'Secretaria de Estado de Mineria', 'Av. Presidente <NAME> Nº 1551', '(02966) 420543 - 437224', '', 1),
(501, 29, 'Secretaria de Estado de Comercio e Industria', 'Avellaneda Nº 801', '(02966) 427446 - 429462', '', 1),
(502, 29, 'Secretaria de Estado de Pesca y Agricultura', 'Avellaneda 801', ' (02966) - 438725 / 437412', '<EMAIL>', 1),
(503, 29, 'Secretaria de Transporte', 'Alvear Nº 625 ', '(02966) - 420189 - 438728', '', 1),
(504, 29, 'Subsecretaria de Coordinacion Administrativa', 'Avellaneda Nº 801', '(02966) 427446 - 429462', '', 1),
(505, 29, '<NAME>', 'Alberdi Nº 643', '(02966) 424650 - 426175', 'www.fomicruz.com', 1),
(506, 29, 'Unidad Ejecutora Portuaria Santa Cruz', 'Gobernador Lista Nº 395 ', '(02966) 429344', '', 1),
(507, 29, 'Instituto de Energia Santa Cruz', 'Ricardo Alfonsín Nº 146/148 -', '(02966) - 436653', '', 1),
(508, 29, 'Consejo Provincial de Educacion\r\n', 'Mariano Moreno Nº 576', '(02966) 426744 – 437658', '', 1);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `tiposervicio`
--
DROP TABLE IF EXISTS `tiposervicio`;
CREATE TABLE IF NOT EXISTS `tiposervicio` (
`id_servicio` int(5) NOT NULL,
`tipo_servicio` varchar(60) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `tiposervicio`
--
INSERT INTO `tiposervicio` (`id_servicio`, `tipo_servicio`) VALUES
(1, 'Ente de gobierno'),
(2, 'Seguridad'),
(3, 'Salud'),
(4, 'Educacion '),
(5, 'Servicios'),
(6, 'Otro');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/src/providers/tasks-service/tasks-service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { SQLiteObject } from '@ionic-native/sqlite';
import { AlertController } from 'ionic-angular';
//PUTO EL QUE LEE
/*
Generated class for the TasksServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class TasksServiceProvider {
db: SQLiteObject = null;
constructor(
public http: HttpClient,
public AlertController: AlertController) {
//console.log('Hello TasksServiceProvider Provider');
}
//Elige Database creada
setDatabase(db: SQLiteObject){
if(this.db === null){
this.db = db;
}
}
prueba_borrartabla(){
let sql2 = 'DROP TABLE numeros_local';
this.db.executeSql(sql2, [])
.then(() => console.log('Executed SQL'))
.catch(e => console.log(e));
let sql = 'DROP TABLE contactos_local';
return this.db.executeSql(sql, [])
.then(() => console.log('Executed SQL'))
.catch(e => console.log(e));
;
}
createTable_contactos(){
//let sql = 'CREATE TABLE IF NOT EXISTS tasks(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, completed INTEGER)';
let sql = 'CREATE TABLE IF NOT EXISTS contactos_local(id INTEGER PRIMARY KEY, nombre_localidad TEXT, nombre TEXT, direccion TEXT, pagina TEXT, categoria INTERGER)';
return this.db.executeSql(sql, [])
.then(() => console.log('Creada tabla contactos_local'))
.catch(e => console.log(e));
}
createTable_numeros(){
//let sql = 'CREATE TABLE IF NOT EXISTS tasks(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, completed INTEGER)';
let sql = 'CREATE TABLE IF NOT EXISTS numeros_local(id_numero INTEGER PRIMARY KEY AUTOINCREMENT, id_contacto INTERGER, numero_numero INTERGER)';
return this.db.executeSql(sql, [])
.then(() => console.log('Creada tabla numeros_local'))
.catch(e => console.log(e));
}
getAll(){
let sql = 'SELECT * FROM contactos_local'; //Consulta obtener todos contactos de favoritos
return this.db.executeSql(sql, []) //Ejecuta consulta
.then(response_contacto => {
//console.log("contactos lenght "+response.rows.length);
let tasks = [];
for (let index = 0; index < response_contacto.rows.length; index++) {
tasks[index] = response_contacto.rows.item(index); //Contacto guardado en array
tasks[index]['telefono'] = [];
//console.log(tasks[index]['id']);
let sql_gettelefonos = 'SELECT * FROM numeros_local WHERE id_contacto=?'; //Obtener telefonos de contacto de index actual
this.db.executeSql(sql_gettelefonos, [tasks[index]['id']])
.then(response_num => {
//console.log("Response lenght: "+response.rows.length);
let numeros = [];
for (let i =0;i<response_num.rows.length;i++){
numeros[i] = response_num.rows.item(i);
console.log("id_contacto: "+numeros[i]['id_contacto']);
console.log("numero_numero: "+numeros[i]['numero_numero']);
tasks[index]['telefono'].push(numeros[i]['numero_numero']);
//console.log("Response rows: "+numeros[i]['numero_numero']);
}
})
.catch(error => Promise.reject(error));
}
return Promise.resolve( tasks );
})
.catch(error => Promise.reject(error));
}
insert(task: any){
let sql = 'INSERT INTO tasks(title, completed) VALUES(?,?)';
return this.db.executeSql(sql, [task.title, task.completed])
.then(() => console.log('Executed SQL'))
.catch(e => console.log(e));
}
InsertFavorito(item){
//console.log("Entro InsertFavorito");
var flag:any;
let sql_select = 'SELECT * FROM contactos_local WHERE id=?';
this.db.executeSql(sql_select,item['id']).then((data) => {
//console.log("Lenght: "+data.rows.length);
//console.log("Exito select"); //Si existe que lo elimine
if (data.rows.length >= 1){
/*
const alert = this.AlertController.create({
title: 'Favorito repetido',
subTitle: '',
buttons: ['OK']
});
alert.present();
let sql_delete = 'DELETE FROM contactos_local WHERE id=?';
return this.db.executeSql(sql_delete, item['id']);
*/
} else {
let sql = 'INSERT INTO contactos_local(id,nombre_localidad,nombre,direccion,pagina,categoria) VALUES(?,?,?,?,?,?)';
/*
console.log(
item['id'] + " - " +
item['nombre_localidad'] + " - " +
item['nombre'] + " - " +
item['direccion'] + " - " +
item['pagina'] + " - " +
item['categoria']
);
*/
return this.db.executeSql(sql, [item['id'],item['nombre_localidad'],item['nombre'],item['direccion'],item['pagina'],item['categoria']])
.then(() => {
console.log('Insertado Favorito');
const alert = this.AlertController.create({
title: 'Favorito guardado',
subTitle: '',
buttons: ['OK']
});
alert.present();
{ //inserta telefonos
//console.log("Lenght telefono: "+item['telefono'].length);
for (let i = 0; i<item['telefono'].length;i++)
{
let sql_telefono = 'INSERT INTO numeros_local(id_contacto,numero_numero) VALUES (?,?)';
this.db.executeSql(sql_telefono,[item['id'],item['telefono'][i]])
.then(() => {
console.log("Telefono insertado " +item['telefono'][i]);
})
.catch(e => {
console.log("Error telefono");
});
}
}
})
.catch(e => {
const alert = this.AlertController.create({
title: 'Ya existe en favoritos',
subTitle: '',
buttons: ['OK']
});
alert.present();
});
}
}) //Fin then
.catch(e => {
console.log("Error select"); //Si no existe que lo agrege
});
}
/*
update(task: any){
let sql = 'UPDATE tasks SET title=?, completed=? WHERE id=?';
return this.db.executeSql(sql, [task.title, task.completed, task.id]);
}
delete(task: any){
let sql = 'DELETE FROM tasks WHERE id=?';
return this.db.executeSql(sql, [task.id]);
}
*/
}
<file_sep>/src/pages/mostrar-telefonos/mostrar-telefonos.module.ts
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { MostrarTelefonosPage } from './mostrar-telefonos';
@NgModule({
declarations: [
MostrarTelefonosPage,
],
imports: [
IonicPageModule.forChild(MostrarTelefonosPage),
],
})
export class MostrarTelefonosPageModule {}
<file_sep>/src/pages/urgencias/urgencias.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {CallNumber} from '@ionic-native/call-number';
import {AbstractItemsProvider} from '../../providers/abstract-items/abstract-items';
@Component({
selector: 'page-urgencias',
templateUrl: 'urgencias.html'
})
export class UrgenciasPage {
constructor(public navCtrl: NavController, private CallNumber:CallNumber, private provider:AbstractItemsProvider) {
}
Llamar(numero){
/*
this.CallNumber.callNumber(numero,true)
.then(res => console.log("Funco",res))
.catch(err => console.log("No Funco",err))
*/
this.provider.Llamar(numero);
}
}
<file_sep>/src/pages/cart-tab-default-page/cart-tab-default-page.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {TasksServiceProvider } from '../../providers/tasks-service/tasks-service';
import {DetallesPage} from '../detalles/detalles';
@Component({
selector: 'page-cart-tab-default-page',
templateUrl: 'cart-tab-default-page.html'
})
export class CartTabDefaultPagePage {
contactos: any[];
constructor(
public navCtrl: NavController,
public tasksService: TasksServiceProvider) {
//console.log("Pagina: cart-tab");
}
//Recibe el contenido de la tabla utilizando funcion de provider
getAllTasks(){
this.tasksService.getAll()
.then(tasks => {
this.contactos = tasks;
})
.catch( error => {
console.error( error );
});
}
/*
ionViewDidLoad(){
//this.tasksService.insert_prueba();
this.getAllTasks();
}
*/
ionViewDidEnter() {
this.getAllTasks();
}
ver_detalles(item){
//console.log(item);
this.navCtrl.push(DetallesPage, {
item:item
});
}
}
<file_sep>/src/pages/comisiones-de-fomentos/comisiones-de-fomentos.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-comisiones-de-fomentos',
templateUrl: 'comisiones-de-fomentos.html'
})
export class ComisionesDeFomentosPage {
constructor(public navCtrl: NavController) {
}
}
<file_sep>/php/Atajos/get_telefonos.php
<?php
include "conexion.php";
////// ++++++ Para recibir el POST del ts
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$Localidad = $request->localidad;
$Categoria = $request->categoria;
$tipo_localidad = $request->tipo_localidad;
$busqueda = $request->busqueda;
$buscando = $request->buscando;
if ($buscando == "true"){
$sql_detalles = "SELECT * FROM telefonos WHERE nombre_telefono LIKE '%$busqueda%'";
} else {
if ($tipo_localidad <= 2){
$sql_detalles = "SELECT * FROM telefonos WHERE id_localidad = '$Localidad' AND id_categoria='$Categoria' ";
} else{
$sql_detalles = "SELECT * FROM telefonos WHERE id_localidad = '$Localidad'";
}
}
$telefono = mysql_query($sql_detalles);
$array_telefono_php = array();
$i = 0;
while ( $telefono_array = mysql_fetch_array($telefono))
{
$sql_numeros = "SELECT numero_numero FROM numeros WHERE lugar_numero = '$telefono_array[0]'";
$numero = mysql_query($sql_numeros);
$array_numero = mysql_fetch_array($numero);
$array_telefono_php[$i]['nombre'] = $telefono_array[2]; //Nombre
$array_telefono_php[$i]['direccion'] = $telefono_array[3]; //Direccion
//$array_telefono_php[$i][2] = $telefono_array[4]; //Telefono
$array_telefono_php[$i]['telefono'] = $array_numero[0]; //Telefono
$array_telefono_php[$i]['pagina'] = $telefono_array[5]; //Pagina Web
$array_telefono_php[$i]['categoria'] = $telefono_array[6]; //Categoria
$sql_localidad = "SELECT localidad FROM localidades WHERE id_localidad = '$telefono_array[id_localidad]'";
$query_localidad = mysql_query($sql_localidad);
$array_localidad = mysql_fetch_array($query_localidad);
$array_telefono_php[$i]['nombre_localidad'] = $array_localidad[0];
//$array_telefono_php[$i][3] = $telefono_array[6]; //Imagen
$i++;
//echo($telefono_array[2]);
}
$array_telefono_php['lenght'] = count($array_telefono_php);
echo json_encode($array_telefono_php);
?><file_sep>/base_telefonos.sql
-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1:3306
-- Tiempo de generación: 17-11-2018 a las 23:37:48
-- Versión del servidor: 5.7.23
-- Versión de PHP: 5.6.38
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES*/;
--
-- Base de datos: `base_telefonos`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `departamentos`
--
DROP TABLE IF EXISTS `departamentos`;
CREATE TABLE IF NOT EXISTS `departamentos` (
`id_dep` int(5) NOT NULL,
`nombre_dep` varchar(60) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `departamentos`
--
INSERT INTO `departamentos` (`id_dep`, `nombre_dep`) VALUES
(1, '<NAME>'),
(2, 'Desado'),
(3, '<NAME>'),
(4, 'Lago Argentino'),
(5, 'Lago Buenos Aires'),
(6, 'Magallanes '),
(7, 'Rio Chico');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `localidades`
--
DROP TABLE IF EXISTS `localidades`;
CREATE TABLE IF NOT EXISTS `localidades` (
`id_localidad` int(6) NOT NULL AUTO_INCREMENT,
`localidad` varchar(60) NOT NULL,
`tipo_localidad` int(6) NOT NULL,
`dep_localidad` int(6) NOT NULL,
PRIMARY KEY (`id_localidad`)
) ENGINE=MyISAM AUTO_INCREMENT=35 DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `localidades`
--
INSERT INTO `localidades` (`id_localidad`, `localidad`, `tipo_localidad`, `dep_localidad`) VALUES
(1, '28 de noviembre ', 2, 3),
(2, '<NAME>', 5, 7),
(3, 'B<NAME>', 5, 6),
(4, '<NAME>', 2, 2),
(5, '<NAME>', 3, 2),
(6, 'El Calafate', 2, 4),
(7, '<NAME>', 2, 4),
(8, '<NAME>', 5, 3),
(9, '<NAME>', 5, 3),
(10, '<NAME>', 5, 3),
(11, 'Estancia Las Vegas ', 5, 3),
(12, '<NAME>', 3, 2),
(13, '<NAME>', 5, 1),
(14, '<NAME>', 2, 7),
(15, '<NAME> ', 3, 7),
(16, 'Jaramillo', 3, 2),
(17, '<NAME>', 4, 3),
(18, '<NAME>', 3, 2),
(19, '<NAME>', 5, 7),
(20, '<NAME>', 2, 2),
(21, 'Los Antiguos ', 2, 5),
(22, '<NAME>', 2, 5),
(23, '<NAME>', 2, 2),
(24, 'Piedrabuena ', 2, 1),
(25, '<NAME>', 2, 2),
(26, '<NAME>', 2, 6),
(27, '<NAME>', 2, 1),
(28, '<NAME>', 5, 2),
(29, '<NAME>', 1, 3),
(30, '<NAME>', 2, 3),
(31, 'Rospentek', 5, 3),
(32, '<NAME> ', 5, 1),
(33, 'Tellier', 5, 2),
(34, '<NAME>', 3, 4);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `numeros`
--
DROP TABLE IF EXISTS `numeros`;
CREATE TABLE IF NOT EXISTS `numeros` (
`id_numero` int(12) NOT NULL AUTO_INCREMENT,
`lugar_numero` int(30) NOT NULL,
`numero_numero` bigint(30) NOT NULL,
PRIMARY KEY (`id_numero`)
) ENGINE=MyISAM AUTO_INCREMENT=1248 DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `numeros`
--
INSERT INTO `numeros` (`id_numero`, `lugar_numero`, `numero_numero`) VALUES
(740, 1, 2902482075),
(741, 2, 2902482121),
(742, 3, 2902482103),
(743, 4, 2902482055),
(744, 5, 2902482078),
(745, 6, 2902482400),
(746, 7, 2902482210),
(747, 8, 2902482073),
(748, 9, 2902482078),
(749, 10, 2902482022),
(750, 12, 2966422291),
(751, 13, 0),
(752, 14, 2974851230),
(753, 15, 2974851285),
(754, 16, 2974851389),
(755, 17, 2974852889),
(756, 18, 2974856320),
(757, 19, 2974856988),
(758, 20, 2974851200),
(759, 21, 2974857241),
(760, 22, 2974859340),
(761, 23, 2974859410),
(762, 24, 2974837165),
(763, 25, 2974831551),
(764, 26, 2974851666),
(765, 27, 2974830521),
(766, 28, 2974850300),
(767, 29, 2974851852),
(768, 30, 2974854477),
(769, 31, 2974851868),
(770, 32, 0),
(771, 33, 2974852944),
(772, 34, 2974851602),
(773, 35, 2974856403),
(774, 36, 2974851467),
(775, 37, 2974851957),
(776, 38, 2974851603),
(777, 41, 2974851224),
(778, 42, 2974851646),
(779, 43, 2974851618),
(780, 44, 2974854614),
(781, 45, 2974858811),
(782, 46, 2974851890),
(783, 47, 2974856740),
(784, 48, 2974857944),
(785, 49, 2974837294),
(786, 50, 2974837553),
(787, 51, 2971562460),
(788, 52, 2974857949),
(789, 53, 2974851614),
(790, 54, 2974851798),
(791, 55, 2974851152),
(792, 56, 2974851347),
(793, 57, 2974851643),
(794, 58, 2974837294),
(795, 59, 2974856862),
(796, 60, 2974851868),
(797, 61, 2974854443),
(798, 62, 2974856648),
(799, 63, 2974857447),
(800, 64, 2974837295),
(801, 65, 2974837552),
(802, 66, 2974859330),
(803, 67, 2974851157),
(804, 68, 2974851818),
(805, 69, 2974851224),
(806, 71, 2974851674),
(807, 73, 2974854477),
(808, 74, 2974854068),
(809, 75, 0),
(810, 76, 0),
(811, 77, 2974859330),
(812, 78, 2974851224),
(813, 79, 2974851937),
(814, 81, 2974856780),
(815, 82, 2974850101),
(816, 83, 2974850144),
(817, 84, 2974850103),
(818, 85, 2974850454),
(819, 86, 2902491020),
(820, 87, 491020),
(821, 88, 491090),
(822, 89, 491020),
(823, 90, 497103),
(824, 91, 2902491173),
(825, 92, 2902490701),
(826, 93, 2902491825),
(827, 94, 2902491819),
(828, 95, 2902491824),
(829, 96, 2902491070),
(830, 97, 2902490770),
(831, 98, 2902491205),
(832, 99, 2902491560),
(833, 100, 2902491022),
(834, 101, 2902495857),
(835, 102, 2902491438),
(836, 103, 2902491914),
(837, 104, 2902490060),
(838, 105, 2902490980),
(839, 106, 2902493720),
(840, 107, 2902491086),
(841, 108, 2902493088),
(842, 110, 2902497305),
(843, 111, 2902496490),
(844, 112, 2902491587),
(845, 114, 2902489222),
(846, 115, 2902495857),
(847, 116, 2902491209),
(848, 117, 2962493004),
(849, 118, 2962493370),
(850, 119, 2962493011),
(851, 120, 2962493105),
(852, 121, 2962493058),
(853, 122, 2962493270),
(854, 123, 2962493003),
(855, 124, 2962493240),
(856, 125, 2962493048),
(857, 126, 2962493048),
(858, 127, 2962493125),
(859, 128, 2962493104),
(860, 129, 2962493048),
(861, 130, 0),
(862, 131, 2966421214),
(863, 132, 0),
(864, 133, 0),
(865, 134, 0),
(866, 135, 0),
(867, 136, 0),
(868, 137, 0),
(869, 138, 0),
(870, 139, 491055),
(871, 140, 2962491001),
(872, 141, 2962491088),
(873, 142, 2962491099),
(874, 143, 2962491281),
(875, 144, 2962491281),
(876, 145, 2962491032),
(877, 146, 0),
(878, 147, 2962491031),
(879, 148, 2962491250),
(880, 149, 2962491119),
(881, 150, 2963490258),
(882, 151, 2963490204),
(883, 152, 2963490204),
(884, 153, 2974806018),
(885, 154, 0),
(886, 155, 2974806038),
(887, 156, 2974806038),
(888, 157, 2902482916),
(889, 158, 2902482915),
(890, 159, 2974993881),
(891, 160, 2974993883),
(892, 161, 2974993834),
(893, 162, 2974993821),
(894, 163, 2974993821),
(895, 164, 2963490228),
(896, 165, 4974071077),
(897, 166, 2974851007),
(898, 167, 4974078),
(899, 168, 4975558),
(900, 169, 2974974666),
(901, 170, 2974974030),
(902, 171, 2974975830),
(903, 172, 2974974444),
(904, 173, 2974975477),
(905, 174, 2974975116),
(906, 175, 2974974811),
(907, 177, 2974974002),
(908, 178, 2974975486),
(909, 179, 2974974803),
(910, 180, 2974974053),
(911, 181, 2974974850),
(912, 182, 2974974809),
(913, 183, 2974974808),
(914, 184, 2974975244),
(915, 185, 2974975699),
(916, 186, 2974976272),
(917, 188, 0),
(918, 189, 2974976085),
(919, 190, 2974975158),
(920, 191, 2963491261),
(921, 192, 2963491262),
(922, 193, 2963491303),
(923, 194, 2963491312),
(924, 195, 2963491151),
(925, 196, 2963491381),
(926, 197, 2963491381),
(927, 198, 2963491039),
(928, 199, 2963491344),
(929, 200, 2963491309),
(930, 202, 2963432072),
(931, 203, 296343063),
(932, 204, 2963432011),
(933, 205, 2963432014),
(934, 206, 2963432299),
(935, 207, 2963432697),
(936, 208, 2963432054),
(937, 209, 2963432073),
(938, 211, 2963432054),
(939, 212, 2974293993),
(940, 213, 2963432574),
(941, 214, 2963432001),
(942, 215, 2963432726),
(943, 217, 2974992160),
(944, 218, 2974992202),
(945, 219, 2974992156),
(946, 220, 2974992192),
(947, 221, 2974999616),
(948, 222, 2974993111),
(949, 223, 2974992790),
(950, 224, 2974993303),
(951, 225, 2974992079),
(952, 226, 2974992860),
(953, 227, 2974990800),
(954, 229, 2974999974),
(955, 230, 2974992612),
(956, 231, 2974991200),
(957, 232, 2974990700),
(958, 233, 2974992959),
(959, 234, 2974993181),
(960, 235, 2974994203),
(961, 236, 2974992612),
(962, 237, 2974996058),
(963, 238, 2974992134),
(964, 239, 2974992132),
(965, 240, 2974992146),
(966, 241, 2974992234),
(967, 242, 2974992860),
(968, 243, 2974991766),
(969, 244, 2974992612),
(970, 246, 0),
(971, 247, 2974990669),
(972, 248, 2962497125),
(973, 249, 2962497117),
(974, 250, 2966463785),
(975, 251, 2962497192),
(976, 252, 2962497577),
(977, 253, 2962497346),
(978, 254, 2962497338),
(979, 256, 2962497500),
(980, 257, 2962492035),
(981, 258, 2962497261),
(982, 259, 2962497338),
(983, 260, 2962497758),
(984, 261, 2962497732),
(985, 262, 4872248),
(986, 263, 4870362),
(987, 264, 2974872364),
(988, 266, 2974870914),
(989, 267, 2974870066),
(990, 268, 2974871346),
(991, 269, 2974872579),
(992, 270, 2974870259),
(993, 271, 2974871069),
(994, 273, 2974870586),
(995, 274, 2974871194),
(996, 275, 2974872342),
(997, 276, 2974870246),
(998, 277, 2974870239),
(999, 278, 2974872623),
(1000, 279, 2974871326),
(1001, 281, 2974870147),
(1002, 282, 2974870259),
(1003, 283, 2974870147),
(1004, 284, 2974872741),
(1005, 285, 2962452076),
(1006, 286, 0),
(1007, 287, 296245141),
(1008, 288, 2962452188),
(1009, 289, 2962452170),
(1010, 290, 2962452202),
(1011, 291, 2962452254),
(1012, 292, 2962452170),
(1013, 293, 2966538629),
(1014, 294, 2962452065),
(1015, 295, 2962452400),
(1016, 296, 2962452311),
(1017, 297, 2962454468),
(1018, 298, 2962454188),
(1019, 299, 2962452127),
(1020, 300, 0),
(1021, 301, 2962452101),
(1022, 302, 2962454231),
(1023, 304, 2962452061),
(1024, 305, 2962414536),
(1025, 306, 0),
(1026, 307, 2962498153),
(1027, 308, 2962498111),
(1028, 309, 2962498300),
(1029, 310, 2962498751),
(1030, 311, 2962498127),
(1031, 313, 2962498224),
(1032, 314, 2962498318),
(1033, 316, 2962498127),
(1034, 317, 2966549055),
(1035, 318, 2966423000),
(1036, 319, 2966420555),
(1037, 320, 2966421200),
(1038, 321, 2966420214),
(1039, 322, 2966420042),
(1040, 323, 2966436811),
(1041, 324, 2966422365),
(1042, 325, 2966422322),
(1043, 326, 2966442367),
(1044, 327, 2966420999),
(1045, 328, 2966427582),
(1046, 329, 2966422651),
(1047, 330, 457804),
(1048, 331, 442571),
(1049, 332, 2966442169),
(1050, 333, 2966420193),
(1051, 334, 2966422631),
(1052, 335, 2966428862),
(1053, 336, 2966426745),
(1054, 337, 2966420505),
(1055, 338, 2966420993),
(1056, 339, 2966420031),
(1057, 340, 2966420100),
(1058, 341, 2966423222),
(1059, 342, 2966432714),
(1060, 343, 2966423257),
(1061, 344, 2966669638),
(1062, 345, 2966428685),
(1063, 346, 2966648535),
(1064, 347, 2966637221),
(1065, 348, 2966422291),
(1066, 349, 2966420861),
(1067, 350, 2966420232),
(1068, 351, 2966420600),
(1069, 352, 2966444463),
(1070, 353, 2966639019),
(1071, 354, 2966428968),
(1072, 355, 2966422874),
(1073, 356, 2966428970),
(1074, 357, 2966428975),
(1075, 358, 2966428979),
(1076, 359, 2966442296),
(1077, 360, 2966422759),
(1078, 361, 0),
(1079, 362, 2966420641),
(1080, 363, 0),
(1081, 364, 2966431988),
(1082, 365, 2966420511),
(1083, 366, 2966431270),
(1084, 367, 2966429069),
(1085, 368, 2966436646),
(1086, 369, 2966438090),
(1087, 370, 2966437288),
(1088, 371, 2966430419),
(1089, 372, 0),
(1090, 373, 2966420257),
(1091, 374, 2966435623),
(1092, 375, 2966426593),
(1093, 376, 2966426836),
(1094, 377, 2966426184),
(1095, 378, 2966444857),
(1096, 380, 2966420394),
(1097, 381, 2966420071),
(1098, 382, 2966432943),
(1099, 383, 2966420138),
(1100, 384, 2966420219),
(1101, 385, 2966437528),
(1102, 386, 2966422019),
(1103, 387, 2966421999),
(1104, 388, 2966424004),
(1105, 389, 2966436041),
(1106, 390, 2966421406),
(1107, 391, 2966435158),
(1108, 392, 2966426396),
(1109, 393, 2966436768),
(1110, 11, 2902482400),
(1111, 39, 2974830962),
(1112, 40, 2974831344),
(1113, 70, 2974851215),
(1114, 72, 2974854056),
(1115, 80, 2974854058),
(1116, 109, 2902492637),
(1117, 113, 2902491412),
(1118, 176, 0),
(1119, 187, 2974974678),
(1120, 201, 2963491381),
(1121, 210, 0),
(1122, 216, 2963432290),
(1123, 228, 0),
(1124, 245, 2974992206),
(1125, 255, 0),
(1126, 265, 2974870946),
(1127, 272, 0),
(1128, 280, 2974870252),
(1129, 303, 2962452063),
(1130, 312, 2962498318),
(1131, 315, 2962498290),
(1132, 379, 2966433949),
(1133, 394, 2966436130),
(1134, 395, 2966420885),
(1135, 396, 2966436206),
(1136, 397, 2966422628),
(1137, 398, 0),
(1138, 399, 0),
(1139, 400, 2966426252),
(1140, 401, 2966420394),
(1141, 402, 2966426769),
(1142, 403, 2966420806),
(1143, 404, 2966420149),
(1144, 405, 2966420703),
(1145, 406, 2966420511),
(1146, 407, 2966422178),
(1147, 408, 2966422012),
(1148, 409, 2966424085),
(1149, 410, 2966438185),
(1150, 411, 2966422263),
(1151, 412, 2966436646),
(1152, 413, 2966426605),
(1153, 414, 2966427497),
(1154, 415, 2966429069),
(1155, 416, 2966436205),
(1156, 417, 2966442832),
(1157, 418, 2966437850),
(1158, 419, 2966434159),
(1159, 420, 2966420258),
(1160, 421, 2966437288),
(1161, 422, 2966429025),
(1162, 423, 2966426960),
(1163, 424, 2966442832),
(1164, 425, 2966422737),
(1165, 426, 2966433710),
(1166, 427, 2966420229),
(1167, 428, 2966444726),
(1168, 429, 2966423727),
(1169, 430, 2966424939),
(1170, 431, 2966426198),
(1171, 432, 2966426859),
(1172, 433, 2966430560),
(1173, 434, 2966438518),
(1174, 435, 2966426787),
(1175, 436, 2966436205),
(1176, 437, 2966431500),
(1177, 438, 2966420258),
(1178, 439, 2966427467),
(1179, 440, 2966422914),
(1180, 441, 0),
(1181, 442, 2966426198),
(1182, 443, 2966426859),
(1183, 444, 2966426787),
(1184, 445, 2966431500),
(1185, 446, 0),
(1186, 447, 2966422737),
(1187, 448, 2966420394),
(1188, 449, 2966420229),
(1189, 450, 2966433710),
(1190, 451, 2966423727),
(1191, 452, 2966425703),
(1192, 453, 2966436463),
(1193, 454, 2966429173),
(1194, 455, 2966436189),
(1195, 456, 2966420394),
(1196, 457, 2966430624),
(1197, 458, 2966420085),
(1198, 459, 2966427707),
(1199, 460, 2966156390),
(1200, 461, 2902421496),
(1201, 462, 2902422363),
(1202, 463, 2902421160),
(1203, 464, 2902421335),
(1204, 465, 2902421171),
(1205, 466, 2902421171),
(1206, 467, 2902482920),
(1207, 468, 2902421233),
(1208, 469, 2902421111),
(1209, 470, 2902421258),
(1210, 471, 2902421646),
(1211, 472, 2902421185),
(1212, 473, 2902421177),
(1213, 474, 2902421084),
(1214, 475, 2902422251),
(1215, 476, 2902421177),
(1216, 477, 2902421722),
(1217, 478, 2902422312),
(1218, 479, 2902421657),
(1219, 480, 2902421258),
(1220, 481, 2902421835),
(1221, 482, 2902421177),
(1222, 483, 2902421185),
(1223, 484, 2902482827),
(1224, 485, 2902482831),
(1225, 486, 2902482827),
(1226, 487, 2902482827),
(1227, 488, 2962497207),
(1228, 489, 297490100),
(1229, 490, 2962495050),
(1230, 491, 2962495070),
(1231, 492, 2962495055),
(1232, 493, 2962495002),
(1233, 494, 2962495002),
(1234, 495, 2962497967),
(1235, 496, 1045),
(1236, 497, 29664240),
(1237, 498, 2966422651),
(1238, 499, 2966429462),
(1239, 500, 2966420543),
(1240, 501, 2966427446),
(1241, 502, 2966438725),
(1242, 503, 2966420189),
(1243, 504, 2966427446),
(1244, 505, 2966424650),
(1245, 506, 2966429344),
(1246, 507, 2966436653),
(1247, 508, 2966426744);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `telefonos`
--
DROP TABLE IF EXISTS `telefonos`;
CREATE TABLE IF NOT EXISTS `telefonos` (
`id_telefono` int(7) NOT NULL AUTO_INCREMENT,
`id_localidad` int(4) NOT NULL,
`nombre_telefono` varchar(60) NOT NULL,
`direccion_telefono` varchar(60) NOT NULL,
`telefono_telefono` varchar(60) NOT NULL,
`paginaweb_telefono` varchar(60) NOT NULL,
`id_categoria` int(4) NOT NULL,
PRIMARY KEY (`id_telefono`)
) ENGINE=MyISAM AUTO_INCREMENT=509 DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `telefonos`
--
INSERT INTO `telefonos` (`id_telefono`, `id_localidad`, `nombre_telefono`, `direccion_telefono`, `telefono_telefono`, `paginaweb_telefono`, `id_categoria`) VALUES
(1, 1, 'Municipalidad', '?????', '02902 48-2075', 'plus.google.com/111033911046825921420/posts', 1),
(2, 1, 'HOSPITAL SAN LUCAS', 'Rio Negro esq. 9 DE Julio', '(02902) 482121/ 4821', '', 3),
(3, 1, 'DIVISIÓN COMISARIA 28 DE NOVIEMBRE', 'Antártida Argentina 510', '2902-482103 (fax)/482049/482166 (Destacamento)', '', 2),
(4, 1, 'DIVISIÓN CUARTEL 14 BOMBEROS', 'Av. <NAME> 467', '2902-482055/482744 (100)', '', 2),
(5, 1, 'E.P.J.A. PRIMARIA Nº 07 SOBERANIA NACIONAL', 'ANTARTIDA ARGENTINA 537', '02902-482078', '', 4),
(6, 1, 'E.P.J.A. SECUNDARIA Nº 02 MAR<NAME>', 'ANTARTIDA ARGENTINA 1164', '02902-482400', '', 4),
(7, 1, 'JARDIN DE INFANTES Nº 21 ALUEN', 'SARMIENTO1445', '02902-482210', '', 4),
(8, 1, 'JARDIN DE INFANTES Nº 48 ARCO IRIS', 'LIBERTAD 139', '02902-482073', '', 4),
(9, 1, 'ESC. PRIMARIA PROV. Nº 32 PROVINCIA DE FORMOSA', 'ANTARTIDA ARGENTINA 537', '02902-482078', '', 4),
(10, 1, 'ESC. PRIMARIA PROV. Nº 67 JORGE AMERICO BLACHERE', 'HIPOLITO IRIGOYEN 1497', '02902-482022', '', 4),
(12, 2, 'ESC. PRIMARIA PROV. RURAL Nº 48 POLICIA DE SANTA CRUZ', '<NAME>', '02966-422291', '', 4),
(13, 3, 'ESC. PRIMARIA PROV. RURAL Nº 37 PADRE DE LA PATRIA', 'RUTA NACIONAL 40', '-', '', 4),
(14, 4, 'Municipalidad de Caleta Olivia', '25 de May 0443', '0297-4851230', 'http://www.caletaolivia.gov.ar/', 1),
(15, 4, 'Terminal Omnibus Caleta Olivia', 'Av. Independencia y San Martin', '0297-4851285/6', '', 5),
(16, 4, 'HOSPITAL ZONAL PADRE <NAME>', 'Av. Peron esq. Gob. Gregores', '(297) 4851389 - 4853417 - 4853417', '', 3),
(17, 4, 'DIRECCIÓN GENERAL DE REGIONAL NORTE', 'Capitán Gutero 480', '297-4852889/4852107/4852200', '', 2),
(18, 4, 'DIVISIÓN COMANDO RADIOELÉCTRICO', 'Capitán Gutero 436', '297-4856320/4835922', '', 5),
(19, 4, 'RE.P.AR. ZONA NORTE', 'Hipólito Irigoyen 2375', '297-4856988', '', 6),
(20, 4, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', 'Ezequiel Gutero 590', '297-4851200/4856087/4856534', '', 2),
(21, 4, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', '<NAME> 1269', '297-4857241(fax)/4853364/4852100', '', 2),
(22, 4, 'DIVISIÓN COMISARIA SECCIONAL TERCERA', 'Av. <NAME> s/n', '297-4859340/4856136 (fax)', '', 2),
(23, 4, 'DIVISIÓN COMISARIA SECCIONAL CUARTA', 'Islas Bahamas 500-598', '297-4859410/4856296', '', 2),
(24, 4, 'DIVISIÓN COMISARIA SECCIONAL QUINTA', 'B. Rotary 23 San Luis s/n', '297-4837165', '', 2),
(25, 4, 'DIVISIÓN COMISARIA DE LA MUJER Y LA FAMILIA', 'Av. <NAME> s/n (pegado galpón lapeidade)', '297-4831551', '', 2),
(26, 4, 'DIVISIÓN CUARTEL 5', 'Dirección: <NAME> y <NAME>', '297-4851666 (100)/4851395 (fax)', '', 2),
(27, 4, 'DIVISIÓN CUARTEL 16', 'B° Unión José Hernández 1228', '297-4830521 (fax)/4858994', '', 2),
(28, 4, 'DIVISIÓN CUARTEL 18', '<NAME> s/n', '297-4850300 (108)/4850457 (fax)', '', 2),
(29, 4, 'E.P.J.A. PRIMARIA Nº 02', '<NAME> 263', '0297-4851852', '', 4),
(30, 4, 'E.P.J.A. PRIMARIA Nº 16', '<NAME> 2545', '0297-4854477', '', 4),
(31, 4, 'E.P.J.A. SECUNDARIA Nº 13 J.J. DE URQUIZA', 'EVA PERON 73', '0297-4851868', '', 4),
(32, 4, 'E.P.J.A. SECUNDARIA Nº 21', '<NAME> 263', '', '', 4),
(33, 4, 'CENTRO MUNICIPAL DE EDUCACION POR EL ARTE', 'BARBARA SERRANO E INDEPENDENCIA', '0297-4852944', '', 4),
(34, 4, 'ESCUELA ESPECIAL Nº 02 CECILIA GRIERSON', 'D<NAME> 119', '0297-4851602', '', 4),
(35, 4, 'ESCUELA ESPECIAL Nº 08 VENTANA A LA VIDA', 'RIVADAVIA 420', '0297-4856403', '', 4),
(36, 4, 'ESCUELA ESPECIAL Nº 13 SALVADOR GAVIOTA', 'VELEZ SARSFIELD 300', '0297-4851467', '', 4),
(37, 4, 'ESCUELA ESPECIAL Nº 15', 'MAIPU 37', '0297-4851957', '', 4),
(38, 4, 'CENTRO DE CAPACITACION LABORAL N° 1 SAN <NAME>', 'SAN JOSE OBRERO 1620', '0297-4851603', '', 4),
(41, 4, 'JARDIN DE INFANTES INSTITUTO <NAME>', 'D<NAME> 193', '0297-4851224', '', 4),
(42, 4, 'JARDIN DE INFANTES Nº 11 RUCANTUN', 'VELES SARFIELD 385', '0297-4851646', '', 4),
(43, 4, 'JARDIN DE INFANTES Nº 18 ISLAS MALVINAS ARG.', 'MADROÑAL 530', '0297-4851618', '', 4),
(44, 4, 'JARDIN DE INFANTES Nº 20 AIKEN', 'AV. REPUBLICA 930', '0297-4854614', '', 4),
(45, 4, 'JARDIN DE INFANTES Nº 28 ANTUKELEN', 'SAN MARTIN 558', '0297-4858811', '', 4),
(46, 4, 'JARDIN DE INFANTES Nº 42 PILMAYKEN', '<NAME> 1340', '0297-4851890', '', 4),
(47, 4, 'JARDIN DE INFANTES Nº 51 MAILEN', 'EJERCITO ARGENTINO Y LAS LILAS', '0297-4856740', '', 4),
(48, 4, 'JARDIN DE INFANTES Nº 52 CUMELEN', 'TOMILLO 730', '0297-4857944', '', 4),
(49, 4, 'JARDIN DE INFANTES Nº 57 OMILEN ANTU', 'TIERRA DEL FUEGO 1984', '0297-4837294', '', 4),
(50, 4, 'JARDIN DE INFANTES Nº 58 AYEN HUE', 'ENTRE RIOS 2784', '0297-4837553', '', 4),
(51, 4, 'COLEGIO DE ENSEÑANZA DIGITAL CALETA OLIVIA', 'RUTA PROV N° 3 - ACC SUR', '0297-156246033', '', 4),
(52, 4, 'ESC. PRIMARIA PROV. Nº 13 <NAME>', '<NAME>', '0297-4857949', '', 4),
(53, 4, 'ESC. PRIMARIA PROV. Nº 14 20 DE NOVIEMBRE', '<NAME> 263', '0297-4851614', '', 4),
(54, 4, 'ESC. PRIMARIA PROV. Nº 28 GUARDIA NACIONAL', 'CEFERINO NAMUNCURA 2657', '0297-4851798', '', 4),
(55, 4, 'ESC. PRIMARIA PROV. Nº 29 JUANA MANSO', 'BEAUVOIR 833', '0297-4851152', '', 4),
(56, 4, 'ESC. PRIMARIA PROV. Nº 36 ANTARTIDA ARGENTINA', 'AZCUENAGA 307', '0297-4851347', '', 4),
(57, 4, 'ESC. PRIMARIA PROV. Nº 43 PEDRO B. PALACIOS ALMAFUERTE', '<NAME> 423', '0297-4851643', '', 4),
(58, 4, 'ESC. PRIMARIA PROV. Nº 57 JOSE INGENIEROS', '<NAME> 1372', '0297-4837294', '', 4),
(59, 4, 'ESC. PRIMARIA PROV. Nº 65 MAR ARGENTINO', 'SAN FRANCISCO 930', '0297-4856862', '', 4),
(60, 4, 'ESC. PRIMARIA PROV. Nº 69 HIELOS CONTINENTALES', 'E<NAME> 73', '0297-4851868', '', 4),
(61, 4, 'ESC. PRIMARIA PROV. Nº 74 VIENTOS SUREÑOS', 'BRASIL 521', '0297-4854443', '', 4),
(62, 4, 'ESC. PRIMARIA PROV. Nº 76 KIMEHUEN', 'LAS MARGARITAS 2145', '0297-4856648', '', 4),
(63, 4, 'ESC. PRIMARIA PROV. Nº 79', '<NAME> 575', '0297-4857447', '', 4),
(64, 4, 'ESC. PRIMARIA PROV. Nº 82', 'TIERRA DEL FUEGO 2062', '0297-4837295', '', 4),
(65, 4, 'ESC. PRIMARIA PROV. Nº 88', 'ENTRE RIOS 2730', '0297-4837552', '', 4),
(66, 4, 'ESC. PRIMARIA SAN <NAME>', '<NAME> <NAME> 1850', '0297-4859330', '', 4),
(67, 4, 'ESCUELA PRIVADA ADVENTISTA PERITO MORENO', '<NAME> 111', '0297-4851157', '', 4),
(68, 4, 'INSTITUTO AONIKENK', '<NAME> 1469', '0297-4851818', '', 4),
(69, 4, 'INSTITUTO M<NAME> (PRIMARIA)', '<NAME> 193', '0297-4851224', '', 4),
(71, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 13 LEOPOLDO LUGONES', '<NAME> 121', '0297-4851674', '', 4),
(73, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 22', 'LU<NAME> 2545', '0297-4854477', '', 4),
(74, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 27', 'GOB. PARADELO 939', '0297-4854068', '', 4),
(75, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 42', 'ENTRE RIOS 2784', '-', '', 4),
(76, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 43', '<NAME> 575', '-', '', 4),
(77, 4, 'COLEGIO SECUNDARIO SAN <NAME>', '<NAME> 1850', '0297-4859330', '', 4),
(78, 4, 'INSTITUTO SECUNDARIO MARCELO SPINOLA', 'DON BOSCO 193', '0297-4851224', '', 4),
(79, 4, 'INSTITUTO PROVINCIAL DE EDUCACION SUPERIOR (CO)', 'JOSE KOLTUM 1370', '0297-4851937', '', 4),
(81, 4, 'ESCUELA INDUSTRIAL Nº 01 GRAL. <NAME>', 'ESTRADA 435', '0297-4856780', '', 4),
(82, 5, 'DIVISIÓN COMISARIA Ca<NAME>', 'San Martin y Medanito s/n', '297-4850101 (fax)/4850100', '', 2),
(83, 5, 'JARDIN DE INFANTES Nº 12 TIEMPO DE CRECER', 'BARRANCAS S/N', '0297-4850144', '', 4),
(84, 5, 'ESC. PRIMARIA PROV. Nº 23 26 DE JUNIO', 'CAIMANCITO 6095', '0297-4850103', '', 4),
(85, 5, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 33', 'CAIMANCITO 6095', '0297-4850454', '', 4),
(86, 6, 'Municipalidad', 'Piloto Civil Norberto Fernandez Nº 16', '(02902) – 491020 – 491082', '', 1),
(87, 6, 'Dirección de comercio', '', '491020', '', 1),
(88, 6, 'Secretaría. De Turismo', '', '491090', '', 1),
(89, 6, 'Dpto de Medicina del Trabajo', '', '491020', '', 1),
(90, 6, 'Dirección de Defensa Civil', '', '497103', '', 2),
(91, 6, 'HOSPITAL DISTR. <NAME>', 'Av. Rocca N° 1487', '(02902) 491173', '', 3),
(92, 6, 'DIRECCIÓN GENERAL REGIONAL SUDOESTE', 'Av. Libertador N° 819', '2902-490701 (fax)', '', 2),
(93, 6, 'DIVISIÓN COMISARIA 1RA LAGO ARGENTINO', 'Av. Libertador San Martin N° 819', '2902-491825/491077', '', 2),
(94, 6, 'DIVISIÓN COMISARIA 2DA LAGO ARGENTINO', 'Av. 349 y 17 de Octubre', '2902-491819 (fax)/496871/490077/497026', '', 2),
(95, 6, 'DIVISIÓN COMANDO RADIOELÉCTRICO EL CALAFATE', 'Av. Libertador N° 835 (fondo)', '2902-491824/497694', '', 2),
(96, 6, 'DIVISIÓN CUARTEL 8 BOMBEROS', 'Formenti 17', '2902-491070/492317(100)', '', 2),
(97, 6, 'DIVISIÓN CUARTEL 21 (2249) BOMBEROS', '<NAME> y <NAME>', '2902-490770', '', 2),
(98, 6, 'E.<NAME> Nº 11 <NAME>', '<NAME> 41', '02902-491205', '', 4),
(99, 6, 'E.P.J.A. SECUNDARIA Nº 04', 'J<NAME> 1325', '02902-491560', '', 4),
(100, 6, 'ESCUELA ESPECIAL Nº 05 TENINK AIKEN', 'VALENTIN FEILBERG 169', '02902-491022', '', 4),
(101, 6, 'CENTRO EDUCATIVO JOVEN LABRADOR', 'MONSEÑOR FAGNANO 1457', '02902-495857', '', 4),
(102, 6, 'JARDIN DE INFANTES Nº 10 GRAL. MART<NAME> GUEMES', 'CAMPAÑA DEL DESIERTO 1438', '02902-491438', '', 4),
(103, 6, 'JARDIN DE INFANTES Nº 54 KAU TALENK', 'MA. EVA DUARTE DE PERON 2038', '02902-491914', '', 4),
(104, 6, 'JARDIN DE INFANTES Nº 60', 'PROF. NORMA ROTONDO 191', '02902-490060', '', 4),
(105, 6, 'JARDIN DE INFANTES Nº 63', 'CAMPAÑA DEL DESIERTO 1130', '02902-490980', '', 4),
(106, 6, 'COLEGIO UPSALA S.A.', '<NAME> 366', '02902-493720', '', 4),
(107, 6, 'ESC. PRIMARIA PROV. Nº 09 CONTRALMIRANTE VALENTIN FEILBERG', 'GOBERNADOR GREGORES 893', '02902-491086', '', 4),
(108, 6, 'ESC. PRIMARIA PROV. Nº 73 LAGO ARGENTINO', 'CAMPAÑA DEL DESIERTO 1850', '02902-493088', '', 4),
(110, 6, 'ESC. PRIMARIA PROV. Nº 89', '<NAME> 41', '02902-497305', '', 4),
(111, 6, 'ESCUELA NUESTRA SEÑORA DE LA PATAGONIA', 'CALLE SIN NOMBRE 51', '02902-496490', '', 4),
(112, 6, '<NAME>', 'MONSEÑOR FAGNANO 1457', '02902-491587', '', 4),
(114, 6, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 46', 'PROF. NORMA ROTONDO 53', '02902-489222', '', 4),
(115, 6, 'CENTRO DE ESTUDIOS SUPERIORES PADRE ALBERTO DE AGOSTINI', 'MONSEÑOR FAGNANO 1457', '02902-495857', '', 4),
(116, 6, 'ESCUELA INDUSTRIAL Nº 09', '<NAME> 41', '02902-491209', '', 4),
(117, 7, 'Zona Norte - Parque Nacional Los Glaciares', 'Ruta 3 s/n', '02962 493004', '', 6),
(118, 7, 'Dirección de Turismo, Medio Ambiente y Pesca', 'Ubicación: Terminal de Ómnibus', 'Teléfono: 02962 493370', '', 1),
(119, 7, 'Municipalidad de El Chaltén', 'Av. M. M. de Güemes 21', '02962 493011/262', '', 1),
(120, 7, 'Registro Civil El Chaltén Oficina Seccional 2756', 'Av. Lago del Desierto 341', '02962 493105', '', 1),
(121, 7, 'Juzgado de Paz de El Chaltén', 'Av. Lago del Desierto 335', '02962 493058', '', 1),
(122, 7, 'Dirección de Cultura Ceremonial y Protocolo', 'Av. M. M. de Güemes 21', '02962 493270/011', '', 1),
(123, 7, 'DIVISIÓN COMISARIA', 'Av. San Martin N° 318', '2962-493003/433135', '', 2),
(124, 7, 'DIVISIÓN CUARTEL 17 (3239) BOMBEROS', 'Pasaje Founroge s/n', '2962-493240 (fax)/493142 (fax)/493013', '', 2),
(125, 7, 'E.P.J.A. PRIMARIA Nº 20', 'AVDA. MIGUEL DE GUEMES Y LAS ALDEAS', '02962-493048', '', 4),
(126, 7, 'E.P.J.A. SECUNDARIA Nº 19', 'AVDA. MIGUEL DE GUEMES Y LAS ALDEAS', '02962-493048', '', 4),
(127, 7, 'JARDIN DE INFANTES Nº 46 LOS HUEMULES', 'LAS ADELAS S/N', '02962-493125', '', 4),
(128, 7, 'ESC. PRIMARIA PROV. RURAL Nº 59 LOS NOTROS', 'LAS ADELAS S/N', '02962-493104', '', 4),
(129, 7, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 28', 'AVDA. MIGUEL DE GUEMES Y LAS ALDEAS', '02962-493048', '', 4),
(130, 8, 'ESC. PRIMARIA PROV. RURAL Nº 24 CACIQUE CILCACHO', 'RESERVA INDIGENA CAMUSU AIKE', '-', '', 4),
(131, 9, 'ESC. PRIMARIA PROV. RURAL Nº 31 GENDARME ARGENTINO', 'ESTANCIA EL CONDOR', '02966-421214', '', 4),
(132, 10, 'ESC. PRIMARIA PROV. RURAL Nº 25 CACIQUE CASIMIRO BIGUA', 'EST<NAME>', '-', '', 4),
(133, 11, 'ESC. PRIMARIA PROV. RURAL Nº 26 GENDARMERIA NACIONAL', 'PARAJE LAS VEGAS', '-', '', 4),
(134, 12, 'DIVISIÓN SUBCOMISARIA <NAME>', '<NAME>', 'No poseen', '', 2),
(135, 12, 'JARDIN DE INFANTES Nº 29 TRENCITO DEL SUR', '<NAME>/N', '-', '', 4),
(136, 12, 'ESC. PRIMARIA PROV. Nº 20 MALVINAS ARGENTINAS', '<NAME>/N', '-', '', 4),
(137, 13, 'ESC. PRIMARIA PROV. RURAL Nº 34 FCO. <NAME>', 'ESTANCIA FUENTES DEL COYLE', '-', '', 4),
(138, 13, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 35', 'ESTANCIA FUENTES DEL COYLE', '-', '', 4),
(139, 14, 'Municipalidad de Gobernador Gregores', 'San Martin 514', '491055', '', 1),
(140, 14, 'HOSPITAL DR. <NAME> STA. PAUL', 'M. Castulo Paradelo N° 1025', '(02962) 491001', '', 3),
(141, 14, 'DIVISIÓN COMISARIA', 'San Martin 1087', '2962-491088/491055/491459', '', 2),
(142, 14, 'DIVISIÓN CUARTEL 10', 'Av. San Martin 1087', '2962-491099', '', 2),
(143, 14, 'E.P.J.A. PRIMARIA Nº 10 <NAME>', 'MARIANO PEJKOVIC 667', '02962-491281', '', 4),
(144, 14, 'E.P.J.A. SECUNDARIA Nº 16 <NAME>', '<NAME>JKOVIC 667', '02962-491281', '', 4),
(145, 14, 'JARDIN DE INFANTES Nº 07 <NAME>', 'COLON 583', '02962-491032', '', 4),
(146, 14, 'ESC. HOGAR PRIMARIA PROV. RURAL Nº 2 HEROES DE MALVINAS', 'RUTA PROVINCIAL 27', '-', '', 4),
(147, 14, 'ESC. PRIMARIA PROV. Nº 18 <NAME>', '<NAME> 573', '02962-491031', '', 4),
(148, 14, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 21 <NAME>', 'ROCA 1154', '02962-491250', '', 4),
(149, 14, 'ESCUELA AGROPECUARIA PROV. Nº 1', 'RUTA PROVINCIAL 27', '02962-491119', '', 4),
(150, 15, 'JARDIN DE INFANTES Nº 40 VALLE DE AMANCAY', 'LAS CALANDRIAS 136', '02963-490258', '', 4),
(151, 15, 'ESC. PRIMARIA PROV. RURAL Nº 42 PAT<NAME>', '<NAME> S/N', '02963-490204', '', 4),
(152, 15, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 29', 'SAN MARTIN S/N', '02963-490204', '', 4),
(153, 16, 'DIVISIÓN CO<NAME>', 'Av. Jose Fond s/n', '297-4806018', '', 2),
(154, 16, '<NAME> Nº 32 MACACHIN', '<NAME> S/N', '-', '', 4),
(155, 16, 'ESC. PRIMARIA PROV. Nº 07', '<NAME>. ESTRADA S/N', '0297-4806038', '', 4),
(156, 16, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 31', '<NAME>. ESTRADA S/N', '0297-4806038', '', 4),
(157, 17, 'JARDIN DE INFANTES Nº 23 <NAME>', 'Bº MEDIO', '02902-482916', '', 4),
(158, 17, 'ESC. PRIMARIA PROV. Nº 30 JULIA DUFOUR', 'Bº MEDIO', '02902-482915', '', 4),
(159, 18, 'DIVISIÓN SUBCOMISARIA', '<NAME> s/n', '297-4993881', '', 2),
(160, 18, 'DIVISIÓN CUARTEL 23', '<NAME> s/n', '297-4993883', '', 2),
(161, 18, 'JARDIN DE INFANTES Nº 30 RINCON DE LUZ', 'SARMIENTO S/N', '0297-4993834', '', 4),
(162, 18, 'ESC. PRIMARIA PROV. Nº 21 PROVINCIA DEL CHUBUT', '<NAME>', '0297-4993821', '', 4),
(163, 18, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 32', '<NAME>', '0297-4993821', '', 4),
(164, 19, 'SUBCOMISARIA Lago Posadas', 'Av. San Martin esq. Las Lengas', '2963-490228 (fax)/490295/490220', '', 2),
(165, 20, 'Municipalidad de las Heras', 'Antiguos Pobladores y San Martin', '4974-071/077/110/232', '', 1),
(166, 20, 'Servicios Publicos', 'Hipólito Yrigoyen, 2456', '0297-4851007 ', '', 5),
(167, 20, 'Defensa Civil', '', '4974078', '', 1),
(168, 20, 'Registro Civil las Heras', '', '4975558', '', 1),
(169, 20, 'HOSPITAL SECCIONAL LAS HERAS', '28 de Noviembre esq. El Calafate', '(0297) 4974666', '', 4),
(170, 20, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', '<NAME> y <NAME>', '297-4974030/4975912', '', 2),
(171, 20, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', '28 de Noviembre y 25 de Mayo', '297-4975830/4974550', '', 2),
(172, 20, 'DIVISION CUARTEL 11', '<NAME> s/n', '297-4974444', '', 2),
(173, 20, 'E.P.J.A. PRIMARIA Nº 14', 'GOBERNADOR GREGORES 854', '0297-4975477', '', 4),
(174, 20, 'E.P.J.A. SECUNDARIA Nº 14', 'SARMIENTO 494', '0297-4975116', '', 4),
(175, 20, 'ESCUELA ESPECIAL Nº 07', 'ESTRADA 850', '0297-4974811', '', 4),
(177, 20, 'ESCUELA DE CAPACITACION LABORAL PADRE DUPUY', 'RIVADAVIA 240', '0297-4974002', '', 4),
(178, 20, 'JARDIN DE INFANTES Nº 08 RUCAYLIN', '1º DE MAYO 675', '0297-4975486', '', 4),
(179, 20, 'JARDIN DE INFANTES Nº 47 KOONEK', 'MINISTRO CALDERON 563', '0297-4974803', '', 4),
(180, 20, 'JARDIN DE INFANTES Nº 55 TALENKE-JOSHEN', '28 DE NOVIEMBRE S/N', '0297-4974053', '', 4),
(181, 20, 'JARDIN DE INFANTES Nº 59', 'PUERTO DESEADO 60', '0297-4974850', '', 4),
(182, 20, 'ESC. PRIMARIA PROV. Nº 03 <NAME>', '<NAME> 854', '0297-4974809', '', 4),
(183, 20, 'ESC. PRIMARIA PROV. Nº 53 <NAME>', 'PUERTO DESEADO 47', '0297-4974808', '', 4),
(184, 20, 'ESC. PRIMARIA PROV. Nº 64', '13 DE December 1050', '0297-4975244', '', 4),
(185, 20, 'ESC. PRIMARIA PROV. Nº 77', 'CALAFATE S/N', '0297-4975699', '', 4),
(186, 20, 'ESC. PRIMARIA PROV. Nº 84', 'SARMIENTO 494', '0297-4976272', '', 4),
(188, 20, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 44', '13 DE December 1050', '-', '', 4),
(189, 20, 'INSTITUTO SUPERIOR DE HIDROCARBUROS', 'HIPOLITO YRIGOYEN 150', '0297-4976085', '', 4),
(190, 20, 'ESCUELA INDUSTRIAL Nº 07', '<NAME> S/N', '0297-4975158', '', 4),
(191, 21, 'OFICINA DE TURISMO DE LOS ANTIGUOS', 'Avenida 11 de Julio 446', '02963) 491261', 'http://www.losantiguos.tur.ar/', 6),
(192, 21, 'Municipalidad de los Antiguos', 'Avenida 11 de Julio 432 Cp (9041)', '0296 349 1262', 'https://www.losantiguos.gob.ar/', 1),
(193, 21, 'HOSPITAL SECCIONAL LOS ANTIGUOS', 'Patagonia Argentina N° 68', '(02963) 491303', '', 3),
(194, 21, 'DIVISIÓN COMISARIA CABO E. GRIPPO', 'Gobernador Gregores 12', '2963-491312/491269', '', 2),
(195, 21, 'DIVISIÓN CUARTEL 13', 'Bulgarini y Picadero', '2963-491151/491268 (100)', '', 2),
(196, 21, 'E.P.J.A. PRIMARIA Nº 15', 'PERITO MORENO 253', '02963-491381', '', 4),
(197, 21, 'E.P.J.A. SECUNDARIA Nº 08', 'PERITO MORENO 253', '02963-491381', '', 4),
(198, 21, 'JARDIN DE INFANTES Nº 25', 'FITZ ROY 460', '02963-491039', '', 4),
(199, 21, 'ESC. HOGAR PRIMARIA PROV. RURAL Nº 1 FRANCISCO P. MORENO', 'AVENIDA TEHUELCHES 79', '02963-491344', '', 4),
(200, 21, 'ESC. PRIMARIA PROV. Nº 17 POLICIA FEDERAL ARGENTINA', 'CRUZ DEL SUR 29', '02963-491309', '', 4),
(202, 22, 'Municipalidad Per<NAME>', 'Av.San Martin 1776', '02963-432072/210/2764/222/2656/2157/23/86', '', 1),
(203, 22, 'Terminal Omnibus', 'Acceso Ruta 43', '296343063', '', 5),
(204, 22, 'HOSPITAL SECCIONAL DR. <NAME>', 'Colon N° 1237', '(02963) 432011', '', 3),
(205, 22, 'DIVISIÓN CO<NAME>', '25 de May 1394', '2963-432014 (fax)/432012 (fax)', '', 2),
(206, 22, 'DIVISIÓN CUARTEL 12', '25 de Mayo s/n', '2963-432299', '', 2),
(207, 22, 'E.P.J.A. PRIMARIA Nº 13 <NAME>', '<NAME> 1295', '02963-432697', '', 4),
(208, 22, 'ESCUELA PARA ADULTOS SAN MARTIN DE TOURS', '<NAME> 1662', '02963-432054', '', 4),
(209, 22, 'E.P.J.A. SECUNDARIA Nº 01 <NAME>', 'COLON 1973', '02963-432073', '', 4),
(211, 22, 'INSTITUTO SAN MARTIN DE TOURS', 'SAN MARTIN 1662', '02963-432054', '', 4),
(212, 22, 'J<NAME> INFANTES \"MIS ANGELITOS\"', 'SAAVEDRA 751', '0297-4293993', '', 4),
(213, 22, 'JARDIN DE INFANTES Nº 06 ARISKAIKEN', 'ALMIRANTE BROWN 1966', '02963-432574', '', 4),
(214, 22, 'ESC. PRIMARIA PROV. Nº 12 REMEDIOS ESCALADA DE SAN MARTIN', 'ESTRADA 980', '02963-432001', '', 4),
(215, 22, 'ESC. PRIMARIA PROV. Nº 72 PIONEROS DEL SUR', 'COLON 1973', '02963-432726', '', 4),
(217, 23, 'Municipalidad de Pico Truncado', 'Calle 9 de Julio 450, Pico Truncado, Santa Cruz', '0297 499-2160', '', 1),
(218, 23, 'Oficina de Turismo de Pico Truncado', 'Gob. Gregores y Urquiza', '0297-4992202', '', 6),
(219, 23, 'Correo Argentino', 'Rivadavia 455', '297-4992156', '', 5),
(220, 23, 'HOSPITAL SECCIONAL PICO TRUNCADO', 'Velez Sarfield N° 305', '(0297) 4992192', '', 3),
(221, 23, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', 'B. Rivadavia 495', '297-4999616 (fax)/ 49992111/4992862', '', 2),
(222, 23, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', 'Ramón Lista 400', 'Teléfonos: 297-4993111/4994111', '', 2),
(223, 23, 'DIVISIÓN COMISARIA DE LA MUJER Y FAMILIA', 'Viamonte 836', '297-4992790 (fax)', '', 2),
(224, 23, 'DIVISIÓN CUARTEL 6', 'Roca 638', '297-4993303 (fax)/4990703/4992000 (100)/ 4992333 (100)', '', 2),
(225, 23, 'E.P.J.A. PRIMARIA Nº 05 BEATRIZ BLANCO NAVARRO', 'BELGRANO 172', '0297-4992079', '', 4),
(226, 23, 'E.P.J.A. SECUNDARIA Nº 03', 'ESPAÑA 461', '0297-4992860', '', 4),
(227, 23, 'ESCUELA ESPECIAL Nº 03', '<NAME> 1164', '0297-4990800', '', 4),
(229, 23, 'ESCUELA DE CAPACITACION LABORAL Nº 2 NAZARETH', 'RAMON LISTA 832', '0297-4999974', '', 4),
(230, 23, 'COLEGIO JUAN XXIII (INICIAL)', 'MARIANO MORENO 455', '0297-4992612', '', 4),
(231, 23, 'JARDIN DE INFANTES Nº 14 LIHUEN', '9 DE July 0372', '0297-4991200', '', 4),
(232, 23, 'JARDIN DE INFANTES Nº 26 KIKEN', 'TUCUMAN 412', '0297-4990700', '', 4),
(233, 23, 'JARDIN DE INFANTES Nº 49 TRINKIL AIKE', 'PELLEGRINI 1189', '0297-4992959', '', 4),
(234, 23, 'JARDIN DE INFANTES Nº 62', 'URDIN 140', '0297-4993181', '', 4),
(235, 23, '<NAME>', 'HIPOLITO YRIGOYEN 950', '0297-4994203', '', 4),
(236, 23, '<NAME> (PRIMARIO)', 'MAR<NAME> 455', '0297-4992612', '', 4),
(237, 23, 'COLEGIO DE ENSEÑANZA DIGITAL PICO TRUNCADO', '<NAME> Y 20 DE NOVIEMBRE', '0297-4996058', '', 4),
(238, 23, 'ESC. PRIMARIA PROV. Nº 08 CAPITAN DE LOS ANDES', 'SARMIENTO 688', '0297-4992134', '', 4),
(239, 23, 'ESC. PRIMARIA PROV. Nº 35 FELIX GREGORIO FRIAS', 'RAMON LISTA 716', '0297-4992132', '', 4),
(240, 23, 'ESC. PRIMARIA PROV. Nº 40 <NAME>', 'PELLEGRINI 1047', '0297-4992146', '', 4),
(241, 23, 'ESC. PRIMARIA PROV. Nº 45 PATAGONIA ARGENTINA', 'SAAVEDRA 322', '0297-4992234', '', 4),
(242, 23, 'ESC. PRIMARIA PROV. Nº 52 <NAME>', 'ESPAÑA 461', '0297-4992860', '', 4),
(243, 23, 'ESC. PRIMARIA PROV. Nº 85', 'BELGRANO 172', '0297-4991766', '', 4),
(244, 23, 'CO<NAME> (SECUNDARIO)', '<NAME> 455', '0297-4992612', '', 4),
(246, 23, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 45', 'SARMIENTO 688', '-', '', 4),
(247, 23, 'ESCUELA INDUSTRIAL Nº 02', 'ESPAÑA 1075', '0297-4990669', '', 4),
(248, 24, 'HOSPITAL SECCIONAL DR. <NAME>', '<NAME> s/n', '(02962) 497125', '', 4),
(249, 24, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', 'Lavalle Este 70', '2962-497117/497063 (fax)', '', 2),
(250, 24, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', 'Ruta Nacional N° 3 Km 2373 Mz.205 B', '2966-463785', '', 2),
(251, 24, 'DIVISIÓN COMISARIA DE LA MUJER Y LA FAMILIA', 'San Martin 242', '2962-497192 (fax)', '', 2),
(252, 24, 'DIVISIÓN CUARTEL 15 BOMBEROS', '<NAME> s/n', '2962-497577/497818(fax)', '', 2),
(253, 24, 'E.P.J.A. PRIMARIA Nº 12', 'MITRE 478', '02962-497346', '', 4),
(254, 24, 'E.P.J.A. SECUNDARIA Nº 07 PROF <NAME>', 'MITRE 478', '02962-497338', '', 4),
(256, 24, 'JARDIN DE INFANTES Nº 05 RASTREADOR GUARANI', 'SIMON BOLIVAR 315', '02962-497500', '', 4),
(257, 24, 'JARDIN DE INFANTES Nº 61', '<NAME> - CASA 151', '02962-492035', '', 4),
(258, 24, 'ESC. PRIMARIA PROV. Nº 06 IS<NAME>', '<NAME> 178', '02962-497261', '', 4),
(259, 24, 'ESC. PRIMARIA PROV. Nº 86', 'MITRE 478', '02962-497338', '', 4),
(260, 24, '<NAME>', 'BARRIO 118 VIV. IDUV', '02962-497758', '', 4),
(261, 24, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 01 <NAME>', '<NAME> 421', '02962-497732', '', 4),
(262, 25, 'Municipalidad de Puerto Deseado', 'Alte. Brown nº 415 ', '4872248', '', 1),
(263, 25, 'Correo Argentino - Sucursal Puerto Deseado', 'San Martin nº 1075 ', '4870362', '', 5),
(264, 25, 'HOSPITAL DISTR. PTO. DESEADO', 'España N° 991 - (0297) 4872364', '(0297) 4872364', '', 3),
(266, 25, 'DIVISIÓN COMISARIA DEL A MUJER Y LA FAMILIA', 'Belgrano 420', '297-4870914', '', 2),
(267, 25, 'DIVISIÓN CUARTEL 22', '12 de Octubre y <NAME>', '297-4870066/4872625/4872557/4872625 (Planta Verif)', '', 2),
(268, 25, 'DIVISIÓN CUARTEL 4', 'Ameghino F. 1068', '297-4871346', '', 2),
(269, 25, 'E.P.J.A. PRIMARIA Nº 06 <NAME>', '12 DE October 1608', '0297-4872579', '', 4),
(270, 25, 'E.P.J.A. SECUNDARIA Nº 18', '<NAME> 230', '0297-4870259', '', 4),
(271, 25, 'ESCUELA ESPECIAL Nº 11 CANTO A LA VIDA', 'SARMIENTO 255', '0297-4871069', '', 4),
(273, 25, 'JARDIN DE INFANTES Nº 09 CHALTEN', 'VENEZUELA 1364', '0297-4870586', '', 4),
(274, 25, 'J<NAME> Nº 39 AONIKENKE', 'GOB. GREGORES 1254', '0297-4871194', '', 4),
(275, 25, '<NAME> Nº 56 A<NAME>', 'B<NAME> 1386', '0297-4872342', '', 4),
(276, 25, 'ESC. PRIMARIA PROV. Nº 05 CAP<NAME>', 'ESTRADA 1163', '0297-4870246', '', 4),
(277, 25, 'ESC. PRIMARIA PROV. Nº 56 KREWEN KAU', 'VEN<NAME>', '0297-4870239', '', 4),
(278, 25, 'ESC. PRIMARIA PROV. Nº 66 FUERTE SAN CARLOS', 'CAPITAN ONETO 1355', '0297-4872623', '', 4),
(279, 25, 'ESC. PRIMARIA PROV. Nº 87', 'ING. PORTELLA 1549', '0297-4871326', '', 4),
(281, 25, 'INSTITUTO SALESIANO SAN JOSE (PRIMARIO)', '12 DE October 0577', '0297-4870147', '', 4),
(282, 25, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 24 17 DE AGOSTO', '<NAME> 230', '0297-4870259', '', 4),
(283, 25, 'INSTITUTO SALESIAN<NAME> (SECUNDARIO)', '12 DE October 0577', '0297-4870147', '', 4),
(284, 25, 'ESCUELA INDUSTRIAL Nº 03 OSCAR SMITH', 'AV. MAYOR LOTUFO 91', '0297-4872741', '', 4),
(285, 26, 'Municipalidad de Puerto San Julian', 'Av. San Martin y Rivadavia', '02962-452076/4155/2353', '', 1),
(286, 26, 'Terminal de Omnibus', 'Av. San Martin 1570', '', '', 5),
(287, 26, 'A<NAME>', 'Av. San Martin 335', '02962-45141', '', 5),
(288, 26, 'HOSPITAL DISTR. PTO. SAN JULIAN', 'Av. Costanera esq. El Cano', '(02962) 452188', '', 4),
(289, 26, 'DIRECCIÓN GENERAL DE REGIONAL CENTRO', 'Roca 980', '2962-452170', '', 2),
(290, 26, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', 'Av. San Martin 864', '2962-452202/452122 (fax)', '', 2),
(291, 26, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', '<NAME> 2115', '2962-452254/452355 (fax)/452446', '', 2),
(292, 26, 'DIVISIÓN COMANDO RADIOELECTRICO', 'Av. San Martin 882', '2962-452170', '', 2),
(293, 26, 'DIVISIÓN UNIDAD OPERATIVA TRES CERROS', '<NAME>', '2966-538629', '', 2),
(294, 26, 'DIVISIÓN CUARTEL 3 BOMBEROS', 'Roca 970', '2962-452065', '', 2),
(295, 26, 'E.P.J.A. PRIMARIA Nº 09 PREFECTURA NAVAL ARGENTINA', 'AV <NAME> 145', '02962-452400', '', 4),
(296, 26, 'E.P.J.A. SECUNDARIA Nº 15', '<NAME>', '02962-452311', '', 4),
(297, 26, 'ESCUELA ESPECIAL Nº 12', 'VELEZ SARSFIELD 886', '02962-454468', '', 4),
(298, 26, '<NAME>', 'COLON 251', '02962-454188', '', 4),
(299, 26, 'JARDIN DE INFANTES Nº 04 GRANADEROS DE SAN MARTIN', 'DARWIN 1760', '02962-452127', '', 4),
(300, 26, 'JARDIN DE INFANTES Nº 64', 'PERIODICO EL ECO 1616', '-', '', 4),
(301, 26, 'ESC. PRIMARIA PROV. Nº 04 FLORENTINO AMEGHINO', 'VIEYTES 775', '02962-452101', '', 4),
(302, 26, 'ESC. PRIMARIA PROV. Nº 75 SANTO GIULIANO DE CESAREA', 'DARWIN 1651', '02962-454231', '', 4),
(304, 26, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 02 FLORIDA BLANCA', 'ALBERDI 1759', '02962-452061', '', 4),
(305, 26, 'ESCUELA INDUSTRIAL Nº 08', 'ALBERDI 1759', '02962-414536', '', 4),
(306, 27, 'Municipio de Puerto Santa Cruz', 'Dirección Belgrano Nº 527', '', 'https://www.puertosantacruz.gob.ar/?q=contacto', 1),
(307, 27, 'HOSPITAL SECCIONAL EDUARDO CANOSA', '<NAME> N° 448', '(02962) 498153', '', 3),
(308, 27, 'DIVISIÓN COMISARIA', 'San Juan Bosco y <NAME>', '2962-498111/498166', '', 2),
(309, 27, 'UNIDAD DE BOMBEROS 7 BOMBEROS', 'San Juan Bosco 470', '2962-498300', '', 2),
(310, 27, 'E.P.J.A. PRIMARIA Nº 17 \"GUARDACOSTAS RIO IGUAZU\"', '9 DE July 0610', '02962-498751', '', 4),
(311, 27, 'E.P.J.A. SECUNDARIA Nº 05', 'ALFEREZ BALESTRA 556', '02962-498127', '', 4),
(313, 27, 'J<NAME> Nº 03 TAMBORCITO DE TACUARI', '<NAME> 248', '02962-498224', '', 4),
(314, 27, 'ESC. PRIMARIA PROV. Nº 02 <NAME>', '25 DE May 0460', '02962-498318', '', 4),
(316, 27, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 08 NACIONES UNIDAS', 'ALFERES BALESTRA 556', '02962-498127', '', 4),
(317, 28, 'DIVISIÓN UNIDAD OPERATIVA RAMÓN SANTOS', 'Ruta Nacional N° 3 Limite con Pcia. de Chubut', '2966-549055', '', 2),
(318, 29, 'Medisur SA', 'Maipú 55', '2966 423000', 'medisur-rgl.com.ar', 3),
(319, 29, '<NAME>', 'San Martín 350', '2966 420555', 'medisur-rgl.com.ar', 3),
(320, 29, '<NAME>', 'Santiago del estero 236', '2966 421200', 'medisur-rgl.com.ar', 3),
(321, 29, 'San Jose', 'Corrientes 253', '02966 42-0214', '', 3),
(322, 29, 'Defensa Civil', 'Gdor. Ram<NAME> 327', '02966-420042', '', 5),
(323, 29, 'Subsecretaria de la Mujer', 'Moreno Nº 175', '02966 – 436811 / GUARDIA: (02966) 15464122 02966 – 15644943', '', 2),
(324, 29, 'Municipalidad de Rio Gallegos', 'Avda. San Martin 791', '2966-422365/6', 'https://www.riogallegos.gov.ar/', 1),
(325, 29, 'Servicios Publicos', 'Av. Pte. <NAME>, 669', '(02966)-422322 - 0800-222-7773', 'http://www.spse.com.ar/ ', 5),
(326, 29, 'Vialidad Provincial', 'Av. Lisandro de la Torre 952', '02966 44-2367', 'http://www.agvp.gov.ar/', 5),
(327, 29, 'ANSES ', 'V<NAME>field 399', '02966 42-0999', 'https://www.anses.gob.ar/', 1),
(328, 29, 'Camuzzi - Gas del Sur', 'C Pellegrini 241 PB', '2966-427582 - 0810-555-3698', 'http://www.camuzzigas.com/', 5),
(329, 29, 'Registro Civil Provincia de Santa Cruz', 'Moreno 123', '2966-422651', '', 5),
(330, 29, 'Servicios Generales', '', '457804', '', 5),
(331, 29, 'Control Animal', 'Paseo de los Arrieros y Ruta N° 3', '442571', '', 5),
(332, 29, 'Terminal Omnibus Rio Gallegos', 'Eva Perón 1451-1499', '02966 44-2169', '', 5),
(333, 29, 'Correo Argentino - Sucursal Rio Gallegos', 'Av.Pte.Nestor Kirchner 893', '02966-420193', '', 5),
(334, 29, 'L.O.A.S', 'Períto Moreno 116 esq. Zapiola', '(02966) 422631', '', 6),
(335, 29, 'Canal 9', 'Hipólito Irigoyen 250', '2966 428862', 'http://canalnuevesantacruz.tv/web/', 5),
(336, 29, 'DIRECCIÓN GENERAL REGIONAL SUR', 'Prospero Palazzo 820', '2966-426745 / 426759', '', 2),
(337, 29, 'DIVISIÓN COMANDO RADIOELÉCTRICO', 'J<NAME> 451', '2966-420505/437804/429002/420979', '', 2),
(338, 29, 'DIVISIÓN COMISARIA SECCIONAL PRIMERA', 'Av. Pdte. <NAME> 534', '2966-420993/420016/449976/424134 (fax)', '', 2),
(339, 29, 'DIVISIÓN COMISARIA SECCIONAL SEGUNDA', 'Ameghino 85', '2966-420031/436612/423200(fax)', '', 2),
(340, 29, 'DIVISIÓN COMISARIA SECCIONAL TERCERA', 'Av. Paradelo s/n', '2966-420100 (fax)/420313', '', 2),
(341, 29, 'DIVISIÓN COMISARIA SECCIONAL CUARTA', '<NAME> 301 y <NAME>', '2966-423222/428376 (fax)', '', 2),
(342, 29, 'DIVISIÓN COMISARIA SECCIONAL QUINTA', '<NAME> H. 2330', '2966-432714/431794', '', 2),
(343, 29, 'DIVISIÓN COMISARIA SECCIONAL SEXTA', 'Lola Mora 441', '2966-423257/423616 (fax)', '', 2),
(344, 29, 'DIVISIÓN COMISARIA SECCIONAL SÉPTIMA', 'B° San Benito – Calle 13 y 32', '2966-669638 (claro) / 2966-463592 / 2966-463593', '', 2),
(345, 29, 'DIVISIÓN COMISARIA DE LA MUJER Y LA FAMILIA', 'Mitre 170', '2966-428685', '', 2),
(346, 29, 'DIVISIÓN UNIDAD OPERATIVA COMISARIA GUER AIKE', 'Ruta Nacional N° 3', '2966-648535', '', 2),
(347, 29, 'DIVISIÓN UNIDAD OPERATIVA COMISARIA CHIMEN AIKE', 'Ruta Nacional N° 3', '2966-637221', '', 2),
(348, 29, 'DIVISIÓN UNIDAD OPERATIVA LA ESPERANZA', 'Ruta 40 – Paraje La Esperanza', '2966-422291', '', 2),
(349, 29, 'DIVISIÓN CUARTEL CENTRAL DE BOMBEROS', 'Av. <NAME> (s/n) y <NAME> (1084)', '2966-420861/422260', '', 2),
(350, 29, 'DIVISIÓN CUARTEL 1o BOMBEROS', 'Gobernador Lista 385', '2966-420232/431247', '', 2),
(351, 29, 'DIVISIÓN CUARTEL 2o BOMBEROS', 'Posadas Gervacio s/n', '2966-420600', '', 2),
(352, 29, 'DIVISIÓN CUARTEL 19o BOMBEROS', 'Avenida Paradelo 120', '2966-444463', '', 2),
(353, 29, 'DIVISIÓN CUARTEL 24o BOMBEROS', 'Calle 32 esquina calle 17', '2966-639019', '', 2),
(354, 29, 'CENTRO DE SALUD Nº 1', 'Pasteur esquina Perito Moreno', '(2966) - 428968', '', 3),
(355, 29, 'CENTRO DE SALUD N° 2', 'Psje. Zucarino S/N entre calles corrientes y Amegnino', '(2966) - 422874', '', 3),
(356, 29, 'CENTRO DE SALUD N° 3', 'Alvear esq. Los Pozos', '(2966) - 42-8970', '', 3),
(357, 29, 'CENTRO DE SALUD N° 4', '<NAME>', '(2966) 42-8975', '', 3),
(358, 29, 'CENTRO DE SALUD N° 5', '<NAME> S/N', '(2966) 42-8979', '', 3),
(359, 29, 'CENTRO DE SALUD N° 6', 'Av. Perito moreno S/N', '(2966) 44-2296', '', 3),
(360, 29, 'CENTRO DE SALUD N° 7', '13 de Julio esq. <NAME>', '(2966) 422759', '', 3),
(361, 29, 'CENTRO DE SALUD N° 8', 'B° San Benito', '?????????????', '', 3),
(362, 29, 'HOSPITAL REGIONAL RIO GALLEGOS', 'Jose Ingenieros Nº 98', '(2966) 420641 - 426221 - 421448', '', 3),
(363, 29, 'HOSPITAL MILITAR', 'Av. <NAME> Martín 2270', '?????????????', '', 3),
(364, 29, 'CENTRO DE CAPACITACION LABORAL DOMINGO SAVIO', 'DEFENSA 633', '02966-431988', '', 4),
(365, 29, 'E.P.J.A. PRIMARIA Nº 01 <NAME>', 'AV.KIRCHNER 1432', '02966-420511', '', 4),
(366, 29, 'E.P.J.A. PRIMARIA Nº 04 FRAGATA LIBERTAD', 'AMEGHINO 1218', '02966-431270', '', 4),
(367, 29, 'E.P.J.A. PRIMARIA Nº 08', 'BELGRANO 1386', '02966-429069', '', 4),
(368, 29, 'E.P.J.A. SECUNDARIA Nº 09', 'JARAMILLO 620', '02966-436646', '', 4),
(369, 29, 'E.P.J.A. SECUNDARIA Nº 10', 'BELGRANO 390', '02966-438090', '', 4),
(370, 29, 'E.P.J.A. SECUNDARIA Nº 12 MANUEL BELGRANO', 'COMODORO PY 361', '02966-437288', '', 4),
(371, 29, 'E.P.J.A. SECUNDARIA Nº 17 CENTENARIO DE RIO GALLEGOS', 'PERITO MORENO 630', '02966-430419', '', 4),
(372, 29, 'E.P.J.A. SECUNDARIA Nº 20', 'ALVEAR 1427', '', '', 4),
(373, 29, 'ESCUELA ESPECIAL Nº 01 TALENGH-KAU', 'RAM<NAME> 413', '02966-420257', '', 4),
(374, 29, 'ESCUELA ESPECIAL Nº 04', 'VELEZ SARSFIELD 1087', '02966-435623', '', 4),
(375, 29, 'ESCUELA ESPECIAL Nº 06', 'LAS PIEDRAS 345', '02966-426593', '', 4),
(376, 29, 'ESCUELA ESPECIAL Nº 10', 'COMODORO PY 315', '02966-426836', '', 4),
(377, 29, 'ESCUELA ESPECIAL Nº 14 USH NASH', 'POSADAS 753', '02966-426184', '', 4),
(378, 29, 'INSTITUTO PARA TRASTORNOS DEL ESPECTRO AUTISTA', 'MURATORE 444', '02966-444857', '', 4),
(380, 29, '<NAME>', 'FAGNANO 142', '02966 -420394', '', 4),
(381, 29, '<NAME>', 'CHACABUCO 107', '02966-420071', '', 4),
(382, 29, '<NAME>', 'HIPOLITO YRIGOYEN 454', '02966-432943', '', 4),
(383, 29, 'JARDIN DE INFANTES Nº 01 <NAME>', 'ALVEAR 67', '02966-420138', '', 4),
(384, 29, 'JARDIN DE INFANTES Nº 13 <NAME>', 'PETREL 1125', '02966-420219', '', 4),
(385, 29, 'JARDIN DE INFANTES Nº 15 EJERCITO ARGENTINO', 'PERITO MORENO 590', '02966-437528', '', 4),
(386, 29, 'JARDIN DE INFANTES Nº 16 MERCEDITAS DE SAN MARTIN', 'AVENIDA PARADELO 305', '02966-422019', '', 4),
(387, 29, 'JARDIN DE INFANTES Nº 17 FEDERICO FROEBEL', 'PELLEGRINI 367', '02966-421999', '', 4),
(388, 29, 'JARDIN DE INFANTES Nº 19 SAN VICENTE DE PAUL', 'COLON 560', '02966-424004', '', 4),
(389, 29, 'JARDIN DE INFANTES Nº 22 KOSPI', 'DEFENSA 660', '02966-436041', '', 4),
(390, 29, 'JARDIN DE INFANTES Nº 24 LOS CHARITOS', 'FITZ ROY 124', '02966-421406', '', 4),
(391, 29, 'JARDIN DE INFANTES Nº 35 TALENKE AMEL', 'AV. EVA PERON 1325', '02966-435158', '', 4),
(392, 29, 'JARDIN DE INFANTES Nº 37 EVITA', 'POSADAS 616', '02966-426396', '', 4),
(393, 29, 'JARDIN DE INFANTES Nº 41 CHEELKENEU', 'LUIS GOTTI 614', '02966-436768', '', 4),
(11, 1, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 12 DR. M. CASTULO P', 'ANTARTIDA ARGENTINA 1164', '02902-482400', '', 4),
(39, 4, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'PJE. DURAZNILLO S/N', '0297-4830962', '', 4),
(40, 4, 'INSTITUTO PRIVADO DE ENSEÑANZA BILINGUE \"<NAME>', 'PRESIDENTE PERON 358', '0297-4831344', '', 4),
(70, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 06 NICOLAS AVELLANE', 'JULIO BENITEZ 1390', '0297-4851215', '', 4),
(72, 4, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 20 GRAL. <NAME> SA', '<NAME> 1370', '0297-4854056', '', 4),
(80, 4, 'ESCUELA DE BIOLOGIA MARINA Y LABORATORISTA Nº 1 ATLANTICO SU', 'EVA PERON 73', '0297-4854058', '', 4),
(109, 6, 'ESC. PRIMARIA PROV. Nº 80 M. <NAME>', 'PROF. NORMA ROTONDO 53', '02902-492637', '', 4),
(113, 6, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 09 POLICIA DE PCIA ', 'JULIO ARGENTINO ROCA 1325', '02902-491412', '', 4),
(176, 20, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'INACTIVO A LA FECHA', '', '', 4),
(187, 20, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 03 <NAME>STR', 'HIPOLITO YRIGOYEN 970', '0297-4974678', '', 4),
(201, 21, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 15 <NAME>', 'PERITO MORENO 253', '02963-491381', '', 4),
(210, 22, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'AVDA. <NAME> 1733', '-', '', 4),
(216, 22, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 05 <NAME> DE', 'COLON 1577', '02963-432290', '', 4),
(228, 23, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'SIN DIRECCION ASIGNADA', '', '', 4),
(245, 23, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 14 CENT. DE LA CONQ', '<NAME> 1222', '0297-4992206', '', 4),
(255, 24, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'INACTIVO A LA FECHA', '-', '', 4),
(265, 25, 'DIVISIÓN COMISARIA PTO.DESEADO', 'Ameghino F. 1080', '297-4870946 (fax)/4872777/4871321/4871208/4872556(101)/48711', '', 2),
(272, 25, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'AV. MAYOR LOTUFO 91', '-', '', 4),
(280, 25, 'INSTITUTO MARIA AUXILIADORA (PD) (INICIAL - PRIMARIA - SECUN', '<NAME> 411', '0297-4870252', '', 4),
(303, 26, 'INSTITUTO MARIA AUXILIADORA (PSJ) (INICIAL - PRIMARIA - SECU', 'ZEBALLOS 1191', '02962-452063', '', 4),
(312, 27, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', '25 DE May 0460', '02962-498318', '', 4),
(315, 27, 'INSTITUTO MARIA AUXILIADORA (PSC) (INICIAL - PRIMARIA - SECU', '25 DE May 0540', '02962-498290', '', 4),
(379, 29, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'MITRE 291', '02966-433949', '', 4),
(394, 29, 'JARDIN DE INFANTES Nº 43 BARRILETE VIAJERO', 'JARAMILLO 666', '02966-436130', '', 4),
(395, 29, 'JARDIN DE INFANTES Nº 44 MARIA TERESA POMI', 'BELGRANO S/N', '02966-420885', '', 4),
(396, 29, 'JARDIN DE INFANTES Nº 50 KAU SI AIKE', 'ALCORTA 805', '02966-436206', '', 4),
(397, 29, 'JARDIN DE INFANTES Nº 53 KETENK AIKE', 'SAN LORENZO entre FERRADÁ y GARCÍA', '02966-422628', '', 4),
(398, 29, 'JARDIN DE INFANTES Nº 65', 'CALLE 19 ESQ. CALLE 14 (Bº SAN BENITO)', '', '', 4),
(399, 29, 'JARDIN DE INFANTES Nº 66', 'EINSTEIN ESQ. ENTRAIGA (Bº EVITA)', '', '', 4),
(400, 29, 'JARDIN DE INFANTES XOSHEN AIKE', 'MARIANO MORENO 986', '02966-426252', '', 4),
(401, 29, 'ESC. PRIMARIA NUESTRA SEÑORA DE LUJAN', 'FAGNANO 142', '02966-420394', '', 4),
(402, 29, 'ESC. PRIMARIA PROV. Nº 01 <NAME>', 'MAIPU 53', '02966-426769', '', 4),
(403, 29, 'ESC. PRIMARIA PROV. Nº 10 HIPOLITO IRIGOYEN', 'AV. DE LOS INMIGRANTES 700', '02966-420806', '', 4),
(404, 29, 'ESC. PRIMARIA PROV. Nº 11 SESQUICENTENARIO DE LA REVOL.DE MA', 'PERITO MORENO 590', '02966-420149', '', 4),
(405, 29, 'ESC. PRIMARIA PROV. Nº 15 PCIA. DE SANTIAGO DEL ESTERO', 'PELLEGRINI 357', '02966-420703', '', 4),
(406, 29, 'ESC. PRIMARIA PROV. Nº 19 CTE. <NAME>', 'AV.KIRCHNER 1432', '02966-420511', '', 4),
(407, 29, 'ESC. PRIMARIA PROV. Nº 33 COM. INSP. VICTORIANO E<NAME>', 'LIBERTAD 1390', '02966-422178', '', 4),
(408, 29, 'ESC. PRIMARIA PROV. Nº 38 GRAL.SAN MARTIN', 'CAÑADON SECO 400', '02966-422012', '', 4),
(409, 29, 'ESC. PRIMARIA PROV. Nº 39 PABLO VI', 'COLON 520', '02966-424085', '', 4),
(410, 29, 'ESC. PRIMARIA PROV. Nº 41 REP.DE VENEZUELA', 'LAS PIEDRAS 1158', '02966-438185', '', 4),
(411, 29, 'ESC. PRIMARIA PROV. Nº 44 19 DE DICIEMBRE', 'SAN JOSE OBRERO 654', '02966-422263', '', 4),
(412, 29, 'ESC. PRIMARIA PROV. Nº 46 INTEGRACION LATINOAMERICANA', 'JARAMILLO 620', '02966-436646', '', 4),
(413, 29, 'ESC. PRIMARIA PROV. Nº 47 NTRA. SRA. DE LORETO', 'AVDA. EVA PERON 1351', '02966-426605', '', 4),
(414, 29, 'ESC. PRIMARIA PROV. Nº 55 VAPOR TRANSP. VILLARINO', 'PRESIDENTE PERON 454', '02966-427497', '', 4),
(415, 29, 'ESC. PRIMARIA PROV. Nº 58 CRUCERO ARA GRAL. BELGRANO', 'BELGRANO 1386', '02966-429069', '', 4),
(416, 29, 'ESC. PRIMARIA PROV. Nº 61 CELIA SUAREZ DE SUSACASA', '<NAME> 2150', '02966-436205', '', 4),
(417, 29, 'ESC. PRIMARIA PROV. Nº 62 \"RENE GERONIMO FAVALORO\"', '<NAME> 577', '02966-442832', '', 4),
(418, 29, 'ESC. PRIMARIA PROV. Nº 63 <NAME>', 'JOSE INGENIEROS 1850', '02966-437850', '', 4),
(419, 29, 'ESC. PRIMARIA PROV. Nº 70 DR. <NAME>', 'ERRAZURIZ 145', '02966-434159', '', 4),
(420, 29, 'ESC. PRIMARIA PROV. Nº 71 PIONEROS <NAME>', '<NAME> 183', '02966-420258', '', 4),
(421, 29, 'ESC. PRIMARIA PROV. Nº 78 <NAME>', 'COMODORO PY 361', '02966-437288', '', 4),
(422, 29, 'ESC. PRIMARIA PROV. Nº 81 \"<NAME>\"', 'AMEGHINO 1218', '02966-429025', '', 4),
(423, 29, 'ESC. PRIMARIA PROV. Nº 83', 'ITUZAINGO 689', '02966-426960', '', 4),
(424, 29, 'ESC. PRIMARIA PROV. Nº 90 \"HUGO GIMENEZ AGÜERO\"', 'LUIS GOTTI 577', '02966-442832', '', 4),
(425, 29, 'ESCUELA NUESTRA SEÑORA DE FATIMA', 'ESTRADA 751', '02966-422737', '', 4),
(426, 29, 'INSTITUTO CRISTIANO DE ENSEÑANZA PATAGONICO', 'MAIPU 2470', '02966-433710', '', 4),
(427, 29, 'INSTITUTO MARIA AUXILIADORA (RGL) (INICIAL - PRIMARIO)', 'AV. KIRCHNER 529', '02966-420229', '', 4),
(428, 29, 'INSTITUTO PRIVADO AUSTRO', 'HIPOLITO YRIGOYEN 450', '02966-444726', '', 4),
(429, 29, 'INSTITUTO PRIVADO DE EDUCACION INTEGRAL', 'ZAPIOLA 155', '02966-423727', '', 4),
(430, 29, 'CENTRO POLIVALENTE DE ARTE N° 1', 'COMODORO PY 312', '02966-424939', '', 4),
(431, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 07 DR. <NAME>', 'DON BOSCO 105', '02966-426198', '', 4),
(432, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 10 GOB. <NAME>', 'PERITO MORENO 630', '02966-426859', '', 4),
(433, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 11 GRAL. <NAME>', 'BELLA VISTA 660', '02966-430560', '', 4),
(434, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 16 <NAME>', 'AMEGHINO 1218', '02966-438518', '', 4),
(435, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 17 <NAME>', '<NAME>', '02966-426787', '', 4),
(436, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 18 TOPOGRAFO D<NAME>', '<NAME> 2150', '02966-436205', '', 4),
(437, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 19 CINCUENTENARIO L', 'ALVEAR 1427', '02966-431500', '', 4),
(438, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 23 REP. DE GUATEMAL', '<NAME> 183', '02966-420258', '', 4),
(439, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 25 LAGO DEL DESIERT', 'ALBERDI 518', '02966-427467', '', 4),
(440, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 26 <NAME>', 'BELGRANO 390', '02966-422914', '', 4),
(441, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 36', 'DR. BORIS GOS 1111', '', '', 4),
(442, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 37', 'DON BOSCO 105', '02966-426198', '', 4),
(443, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 38', 'PERITO MORENO 630', '02966-426859', '', 4),
(444, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 39', '<NAME> 1147', '02966-426787', '', 4),
(445, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 40', 'ALVEAR 1427', '02966-431500', '', 4),
(446, 29, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 41', '', '-', '', 4),
(447, 29, 'COLEGIO SECUNDARIO NUESTRA SEÑORA DE FATIMA', 'ESTRADA 751', '02966-422737', '', 4),
(448, 29, 'COLEGIO SECUNDARIO NUESTRA SEÑORA DE LUJAN', 'FAGNANO 142', '02966-420394', '', 4),
(449, 29, 'INSTITUTO MARIA AUXILIADORA (RGL) (SECUNDARIO)', 'AV. KIRCHNER 529', '02966-420229', '', 4),
(450, 29, 'INSTITUTO CRISTIANO DE ENSEÑANZA PATAGONICO', 'MAIPU 2470', '02966-433710', '', 4),
(451, 29, 'INSTITUTO PRIVADO DE EDUCACIÓN INTEGRAL', 'ZAPIOLA 155', '02966-423727', '', 4),
(452, 29, 'POPLARS JUNIOR SCHOOL', 'ESTRADA 355', '02966-425703', '', 4),
(453, 29, 'CONSERVATORIO PROV. DE MUSICA PADRE EUGENIO ROSSO', 'ALVEAR 315', '02966-436463', '', 4),
(454, 29, 'ESCUELA TECNICA DE VIALIDAD Nº 5', '<NAME> 1147', '02966-429173', '', 4),
(455, 29, 'INSTITUTO PROVINCIAL DE EDUCACION SUPERIOR (RGL)', '<NAME> 183', '02966-436189', '', 4),
(456, 29, 'INSTITUTO SALESIANO DE ESTUDIOS SUPERIORES', 'FAGNANO 142', '02966-420394', '', 4),
(457, 29, 'INSTITUTO SUPERIOR DE ENSEÑANZA TECNICA', 'ALCORTA 250', '02966-430624', '', 4),
(458, 29, 'INSTITUTO SUPERIOR DE FORMACION POLICIAL \"CRIO. INSP. (R) VI', 'RUTA Nº 3 - KM. 2579', '02966-420085', '', 4),
(459, 29, 'ESCUELA INDUSTRIAL Nº 04 <NAME>', 'MITRE 291', '02966-427707', '', 4),
(460, 29, 'ESCUELA INDUSTRIAL Nº 06 Xº BRIGADA AEREA', 'RUTA NACIONAL Nº 3', '02966-15639012', '', 4),
(461, 30, 'Caja De Servicios Sociales', '', '(2902) 42 - 1496 / 42 - 2779', '', 1),
(462, 30, 'Servicos Publicos ', '', '(2902) 42 - 2363 /42 - 1256', '', 5),
(463, 30, 'Municipalidad de Rio Turbio', '<NAME> <NAME>, Z9407 Río Turbio, Santa Cruz, A', '02902 42-1160', 'https://www.municipalidad.com.ar/Home/Menu', 1),
(464, 30, 'HOSPITAL DE LA CUENCA CARBONIFERA', 'Gendarmeria nacional N° 126', '(02902) 421335', '', 3),
(465, 30, 'DIVISIÓN COMISARIA RIO TURBIO', 'Av. D. Castillo s/n', '2902-421171/421172/421196 (fax)/ 410569 (Destacamento Turbio', '', 2),
(466, 30, 'DIVISIÓN COMANDO RADIOELECTRICO RIO TURBIO', 'Av. D. Castillo s/n', '2902-421171/421172/421196 (fax)', '', 2),
(467, 30, 'DIVISIÓN UNIDAD OPERATIVA JULIA DUFOUR', '<NAME> – Ruta 40', '2902-482920 (fax) / 482644 (Destacamento Krashh)', '', 2),
(468, 30, 'DIVISIÓN CUARTEL 9 BOMBEROS', 'Teniente del Castillo s/n', '2902-421233', '', 2),
(469, 30, 'E.P.J.A. PRIMARIA Nº 03 CAMPAMENTO DE MARINA', 'GLACIAR BOLADOS 221', '02902-421111', '', 4),
(470, 30, 'E.P.J.A. SECUNDARIA Nº 06', '<NAME> 221', '02902-421258', '', 4),
(471, 30, 'ESCUELA ESPECIAL Nº 09 KEOKEN', 'CTE. LUIS PIEDRA BUENA 268', '02902-421646', '', 4),
(472, 30, 'CENTRO EDUCATIVO DE FORMACION Y ACTUALIZACION PROFESIONAL Nº', 'AVDA. Y.C.F. 50', '02902-421185', '', 4),
(473, 30, '<NAME>', 'AVENIDA SAN MARTIN 661', '02902-421177', '', 4),
(474, 30, 'JARDIN DE INFANTES Nº 02 FUERZA AEREA ARGENTINA', 'HIPOLITO YRIGOYEN 96', '02902-421084', '', 4),
(475, 30, 'JARDIN DE INFANTES Nº 45 UAMEN TALENKE', 'GLACIAR UPSALA 60', '02902-422251', '', 4),
(476, 30, '<NAME>', 'AV SAN MARTIN 661', '02902-421177', '', 4),
(477, 30, 'ESC. PRIMARIA PROV. Nº 54 WOLF SCHCOLNIK', '<NAME> 17', '02902-421722', '', 4),
(478, 30, 'ESC. PRIMARIA PROV. Nº 60 ING. NEO ZULIANI', 'GLACIAR BOLADOS 221', '02902-422312', '', 4),
(479, 30, 'ESC. PRIMARIA PROV. Nº 68', 'JULIO ARGENTINO ROCA 259', '02902-421657', '', 4),
(480, 30, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 04 PERITO F. PASCAC', '<NAME> 221', '02902-421258', '', 4),
(481, 30, '<NAME>', '<NAME> 247', '02902-421835', '', 4),
(482, 30, '<NAME>', 'AV. SAN MARTIN 661', '02902-421177', '', 4),
(483, 30, 'ESCUELA INDUSTRIAL Nº 05 TTE A. DEL CASTILLO', 'AVDA.Y.C.F. 50', '02902-421185', '', 4),
(484, 31, 'E.P.J.A. SECUNDARIA Nº 11', 'BARRIO MILITAR Nº 2', '02902-482827', '', 4),
(485, 31, 'JARDIN DE INFANTES Nº 33 NTRA SRA.DE LA NIEVES', 'BARRIO MILITAR Nº 2', '02902-482831', '', 4),
(486, 31, 'ESC. PRIMARIA PROV. Nº 50 MONSEÑOR JUAN CAGLIERO', 'BARRIO MILITAR Nº 2', '02902-482827', '', 4),
(487, 31, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 34', 'BARRIO MILITAR Nº 2', '02902-482827', '', 4),
(488, 32, 'ESCUELA PRIMARIA RURAL \"<NAME>\"', 'EST. S<NAME>', '02962-497207', '', 4),
(489, 33, 'ESC. PRIMARIA PROV. RURAL Nº 51', 'RUTA Nº 281 KM 20', '0297-490100', '', 4),
(490, 34, 'SUBCOMISARIA', 'San Martin 18', '2962-495050 (fax) /495073 (101)', '', 2),
(491, 34, 'UNIDAD DE BOMBEROS 20', 'Crio. <NAME> s/n', '2962-495070 (fax)/495035/495064 (100)', '', 2),
(492, 34, 'JARDIN DE INFANTES Nº 27 SOBERANIA NACIONAL', 'AV. SAN MARTIN S/N', '02962-495055', '', 4),
(493, 34, 'ESC. PRIMARIA PROV. RURAL Nº 16 RVDO. PADRE FEDERICO TORRES', 'AVDA. S<NAME> S/N', '02962-495002', '', 4),
(494, 34, 'COLEGIO PROV. DE EDUCACION SECUNDARIA Nº 30', 'AVDA. S<NAME> S/N', '02962-495002', '', 4),
(495, 24, 'Municipalidad Piedrabuena', '', '(2962) 49-7967', '', 1),
(496, 29, 'Asip', 'Av. Pres. Dr. <NAME> 1045', '02966-420454', 'https://www.asip.gob.ar/', 1),
(497, 29, 'Caja de previsión Social', 'Avenida San Martín N° 1058', '54 2966 424074', 'https://cps.gov.ar/', 1),
(498, 29, 'Registro Civil Santa Cruz', 'Moreno 123', '2966-422651', '', 1),
(499, 29, 'Ministerio de la Producción, Comercio e Industria', 'Avellaneda Nº 801', '(02966) – 429462-427446', 'http://minpro.gob.ar/', 1),
(500, 29, 'Secretaria de Estado de Mineria', 'Av. Presidente <NAME> Nº 1551', '(02966) 420543 - 437224', '', 1),
(501, 29, 'Secretaria de Estado de Comercio e Industria', 'Avellaneda Nº 801', '(02966) 427446 - 429462', '', 1),
(502, 29, 'Secretaria de Estado de Pesca y Agricultura', 'Avellaneda 801', ' (02966) - 438725 / 437412', '<EMAIL>', 1),
(503, 29, 'Secretaria de Transporte', 'Alvear Nº 625 ', '(02966) - 420189 - 438728', '', 1),
(504, 29, 'Subsecretaria de Coordinacion Administrativa', 'Avellaneda Nº 801', '(02966) 427446 - 429462', '', 1),
(505, 29, '<NAME>', 'Alberdi Nº 643', '(02966) 424650 - 426175', 'www.fomicruz.com', 1),
(506, 29, 'Unidad Ejecutora Portuaria Santa Cruz', 'Gobernador Lista Nº 395 ', '(02966) 429344', '', 1),
(507, 29, 'Instituto de Energia Santa Cruz', '<NAME> Nº 146/148 -', '(02966) - 436653', '', 1),
(508, 29, 'Consejo Provincial de Educacion\r\n', 'Mariano Moreno Nº 576', '(02966) 426744 – 437658', '', 1);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `tiposervicio`
--
DROP TABLE IF EXISTS `tiposervicio`;
CREATE TABLE IF NOT EXISTS `tiposervicio` (
`id_servicio` int(5) NOT NULL,
`tipo_servicio` varchar(60) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `tiposervicio`
--
INSERT INTO `tiposervicio` (`id_servicio`, `tipo_servicio`) VALUES
(1, 'Ente de gobierno'),
(2, 'Seguridad'),
(3, 'Salud'),
(4, 'Educacion '),
(5, 'Servicios'),
(6, 'Otro');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/src/pages/municipios/municipios.ts
import { Component } from '@angular/core';
import { NavController, LoadingController } from 'ionic-angular';
import { HttpClient } from '@angular/common/http'; //// Para que tome al php
//import { HttpHeaders } from '@angular/common/http';
import {AbstractItemsProvider} from '../../providers/abstract-items/abstract-items';
import { ROGallegosPage } from '../r-ogallegos/r-ogallegos';
import { MostrarTelefonosPage } from '../mostrar-telefonos/mostrar-telefonos';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
@Component({
selector: 'page-municipios',
templateUrl: 'municipios.html'
})
export class MunicipiosPage {
items: any[];
longitud : any;
constructor(
public navCtrl: NavController,
public http: HttpClient,
private provider:AbstractItemsProvider,
public loadingCtrl: LoadingController) {
if (this.provider.Tipo_localidad >= 3){
this.provider.Categoria_id = 0;
}
this.items = [];
var ip_getmunicipios = this.provider.ip_carpeta+"get_municipios.php";
var longitud : any;
var datos_consulta = JSON.stringify({
"tipo_localidad": this.provider.Tipo_localidad, //municipo, paraje, etc
});
console.log("Datos consulta municipio:" + datos_consulta );
this.provider.ShowLoader();
this.http
.post<string>(ip_getmunicipios,datos_consulta)
.subscribe((data : any) =>
{
this.provider.loading.dismiss();
this.longitud = data['lenght'];
for(let i = 0; i < this.longitud; i++){
//console.log(data[i][0]);
this.items.push({
nombre: data[i]['nombre_municipio'],
id_municipio: data[i]['id_municipio'],
id: i
});
} //Fin For
/*
document.getElementById("espiner3").style.visibility = "hidden";
document.getElementById("espiner3").style.position = "absolute";
*/
},
(error : any) =>
{
this.provider.error_conexion();
});
} //Fin constructor
ver_municipio(municipio,nombre){
console.log("ID municipio seleccionado: "+municipio);
this.provider.Localidad_id = municipio;
this.provider.Localidad_id = +this.provider.Localidad_id;
this.provider.Localidad_Nombre = nombre;
if (this.provider.Tipo_localidad == 1 || this.provider.Tipo_localidad == 2 )
{
this.navCtrl.push(ROGallegosPage);
}else{
this.navCtrl.push(MostrarTelefonosPage);
}
}
}
<file_sep>/src/providers/abstract-items/abstract-items.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {CallNumber} from '@ionic-native/call-number';
import { AlertController,LoadingController } from 'ionic-angular';
/*
Generated class for the AbstractItemsProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class AbstractItemsProvider {
Localidad_id:number; //Id de la localidad
Localidad_Nombre:string; //Nombre de la localidad
Tipo_localidad:number; //Tipo de la localidad seleccionada
Categoria_id:number; //Categoria seleccionada
items: any; //Array con detalles del contacto
ip_carpeta = 'https://www.phcristopher.xyz/Atajos/'; //Servidor Externo
//ip_carpeta = 'http://localhost/Atajos/'; //Servidor Local
loading : any;
Llamar(numero){
const confirm = this.AlertController.create({
title: '¿Llamar?',
buttons: [
{
text: 'Cancelar',
handler: () => {
//console.log('cancelado');
}
},
{
text: 'Si',
handler: () => {
console.log('Llamando numero: '+ numero);
this.CallNumber.callNumber(numero,true)
.then(res => console.log("Funco",res))
.catch(err => console.log("No Funco",err))
}
}
]
});
confirm.present();
}
constructor(
public http: HttpClient,
private CallNumber:CallNumber ,
public AlertController: AlertController,
public loadingCtrl: LoadingController) {
}
error_conexion(){
const alert = this.AlertController.create({
title: 'NO HAY CONEXIÓN :(',
subTitle: '',
buttons: ['OK']
});
alert.present();
}
ShowLoader(){
this.loading = this.loadingCtrl.create({
content:"Cargando..."
});
this.loading.present();
}
/*
probar_conexion(){
var prueba_conexion = this.ip_carpeta + "conexion.php";
this.http.get(prueba_conexion)
.subscribe((data : any) =>
{
console.log(prueba_conexion);
console.log("Encontro IP");
},
(error : any) =>
{
console.log(prueba_conexion);
console.log("No encontro");
//this.ip_carpeta = prompt("No se encontro el servidor", "http://192.168.0.36/Atajos/");
this.probar_conexion();
// "http://xxx.xxx.x.xxx/pruebas/Ionic/prueba.php"
});
}
*/
}
| fead1a7228c3659131a16e85dfebb4fba2ec8687 | [
"SQL",
"TypeScript",
"PHP"
] | 20 | TypeScript | acheuqueman/atajos_0.2-MASTER | b73df5dfb295fea3d44aec46a569d967a751dd95 | 7635120823b0fd1da893830d038aa12926b83291 | |
refs/heads/master | <repo_name>brunofirme10/caixa-eletronico-bf<file_sep>/pega_maior.php
<?php
function pega_maior($quant_notas, $m)
{
global $valida_pega_maior;
$inicio = 0;
$fim = 0;
$maior = 0;
$valor = 0;
if ($m == 5) {
$inicio = 2;
$fim = 4;
$valor = $quant_notas[$inicio];
}
if ($m == 4) {
$inicio = 1;
$fim = 2;
$valor = $quant_notas[$inicio];
}
if ($m == 3) {
$inicio = 0;
$fim = 3;
$valor = $quant_notas[$inicio];
}
if ($m == 2) {
$inicio = 0;
$fim = 2;
$valor = $quant_notas[$inicio];
}
if ($m == 1) {
$inicio = 1;
$fim = 1;
$valor = $quant_notas[$inicio];
}
if ($m == 0) {
$inicio = 0;
$fim = 0;
$valor = $quant_notas[$inicio];
}
if (($quant_notas[$i]) >= ($valor)) {
$maior = $i;
$valor = $quant_notas[$i];
}
}
//Este if impede que a opção trocado seja exibida na tela, se o slot selecionado pelo algoritmo, estiver vazio.
if ($quant_notas[$maior] == 0) {
$valida_pega_maior = false;
}
return $maior;
}
<file_sep>/invalido4.php
<?php
//Este formulário será exibido, caso a quantidade de cédulas exceda o limite máximo dispensação! .
?>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action=index.php method=POST>
<table BORDER=2 BGCOLOR="#66FFFF" SIZE=15 ALIGN=MIDDLE WIDTH=300>
<tr>
<TD ALIGN=MIDDLE WIDTH=200>
<br>Saque excedeu o limite máximo de cédulas que podem
ser dispensadas!
<p>Dirija-se a outro terminal ou digite um valor inferior!</p>
<input type="submit" name="OK" STYLE="color:#FFFFFF; background-color:#FF0000" />
</tr>
</td>
</table>
</form>
</body>
</html><file_sep>/vetores.php
<?php
$vet_notas = array(2, 5, 10, 20, 50, 100); //Array que armazena os tipos de notas contidas no terminal.
$vet_quant = array(200, 100, 100, 100, 100, 100); //Array que armazena a quantidade das respectivas notas contidas no terminal.
$vet_indice_inteiro = array(); //Array que armazena os indices de notas($vet_notas) que serão consumidas para a "opção inteiro".
$vet_indice_trocado = array(); //Array que armazena os indices de notas($vet_notas)que serão consumidas para a "opção trocado".
$vet_quant_temp_inteiro = $vet_quant; //Array cópia temporária de $vet_quant.
$vet_quant_temp_trocado = $vet_quant; //Array cópia temporária de $vet_quant.
$vet_quant_notas_trocadas = array(); //Array que armazena a quantidade de notas trocadas que serão consumidas para a "opção trocado".
$vet_soma_quant_notas_trocadas = array(); //Array que armazena a quantidade total de notas consumidas para cada valor de "$vet_indice_trocado[$i]".
$tamanho = 0; //Descrição no código.
$trocado = ""; //Descrição no código.
$soma = 0;
$j = 0;
$i = 0;
$k = 1;
$conte = 1;
$v = ""; //Esta variável receberá uma concatenação da quantidade e valor(2x100) consumidas para cada índice "$vet_indice_inteiro".
$m = 0;
$n = 0;
?><file_sep>/principal.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
//Este formulário é o nucleo do sistema, ele efetua a maioria do processamento.
$saque = $_POST['valor'];
include 'vetores.php';
include 'multiplo.php';
include 'pega_maior.php';
if ($saque == "")
//Autoexplicativo
{
echo '<form action=index.php method=POST>
<table border = 2 bgcolor="#66FFFF" SIZE=15
ALIGN=MIDDLE WIDTH=300><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Digite um valor para efetuar o saque!</p>
<p>Clique
em
OK
e
para
reiniciar
a
transação!</p>
<input
type="submit"
name="OK"
value="OK"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
</tr></td>
</table>
</form>';
exit;
}
if ($saque <= 0)
//Autoexplicativo
{
echo '<form action=index.php method=POST>
<table border = 2 bgcolor="#66FFFF" SIZE=15 ALIGN=MIDDLE
WIDTH=300><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Valor invalido!</p>
<p>Digite um valor valido!</p>
<input
type="submit"
name="OK"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
</tr></td>
</table>
</form>';
exit;
}
if ($saque <= $limite_minimo)
//Autoexplicativo
{
echo '<form action=index.php method=POST>
<table border = 2 bgcolor="#66FFFF" SIZE=15
ALIGN=MIDDLE WIDTH=300><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Valor abaixo do limite minimo!</p>
<p>Digite um novo valor acima do limite minimo!!
</p>
<input
type="submit"
name="OK"
value="OK"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
</tr></td>
</table>
</form>';
exit;
}
verifica_multiplo($vet_notas, $vet_quant, $saque); //Função que verifica se o valordigitado pelo cliente é multiplo das notas armazenadas no terminal.
while (($saque > $saldo) || ($saque > $limite_diario) || ($saque < $limite_minimo))
//Este enquanto verifica a validade do valor do saque.
{
if ($saque > $limite_diario)
//Autoexplicativo
{
echo '<form action=index.php method=POST>
<table border = 2 bgcolor="#66FFFF" SIZE=15
ALIGN=MIDDLE WIDTH=300><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Valor acima do limite diario!</p>
<p>Digite um novo valor abaixo do limite diario!
</p>
<input
type="submit"
name="OK"
value="OK"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
</tr></td>
</table>
</form>';
exit;
}
if ($saque > $saldo)
//Autoexplicativo
{
echo '<form action=index.php method=POST>
<table border = 2 bgcolor="#66FFFF" SIZE=15
ALIGN=MIDDLE WIDTH=300><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Saldo insuficiente!</p>
<p>Digite um novo valor abaixo do seu saldo!</p>
<input
type="submit"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
</tr></td>
</table>
</form>';
exit;
}
if ($saque <= $limite_minimo)
//Autoexplicativo
{
echo '<form action=index.php method=POST>
<table border = 2 bgcolor="#66FFFF" SIZE=15
ALIGN=MIDDLE WIDTH=300><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Valor abaixo do limite minimo!</p>
<p>Digite um novo valor acima do limite minimo!!
</p>
<input
type="submit"
name="OK"
value="OK"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
</tr></td>
</table>
</form>';
exit;
}
}
$i = 5;
$vetor_saque = str_split($saque); //Transforma o $saque em um array de
string .
$a = sizeof($vetor_saque); //Salva em $a o tamanho de $vetor_saque.
$a--; //Decrementa o $a.
$b = $vetor_saque[$a]; //$b recebe o ultimo elemento de $vetor_saque.
$saque = (int)$saque; //$saque é convertido para inteiro.
while ($soma != $saque)
//Este enquanto faz a seleção da quantidade mínima possível de notas para atender ao saque,”Opção inteiro”
{
while (($vet_quant_temp_inteiro[$i]) == 0)
//Este enquanto impede que um saque seja feito em um slot vazio
{
$i--;
if (($i < 0))
//Este if identifica que as notas acabaram.
{
//Em uma implementação real, neste ponto rodará um script que solicitará um abastecimento para o respectivo slot.
header('Location: invalido3.php');
exit;
}
}
if ((($b == 6) || ($b == 8)) && ($i == 1))
//Este if impede a dispensação de notas de R$5,00 para saques com valores finalizados com os valores 6 ou 8.
{
$i--;
}
$soma = $soma + $vet_notas[$i];
$vet_quant_temp_inteiro[$i]--;
$vet_indice_inteiro[$j] = $i;
$j++;
if ($soma > $saque)
//Se o $soma exceder o valor do saque, o valor é devolvido e o processo é reiniciado com $i--
{
$soma = $soma - $vet_notas[$i];
$vet_quant_temp_inteiro[$i]++;
$i--;
$j--;
}
}
for ($i = 0; $i < $j; $i++)
//Armazena as notas selecionadas para ”Opção inteiro” na variável $v
{
if ($sair == true)
//Este if
//impede a comparação dos arrays($vet_indice_inteiro[$i]==$vet_indice_inteiro[$k])); //para um $k maior que $j.
{
$valor = $vet_notas[($vet_indice_inteiro[$i])];
$v .= " $conte xR$" . $valor;
continue;
}
if ($vet_indice_inteiro[$i] == $vet_indice_inteiro[$k])
//Este if contabiliza as ocorrências de um mesmo valor no $vet_indice_inteiro.
{
$conte++;
} else
//Este else armazena a quantidade e as notas selecionadas.
{
$valor = $vet_notas[($vet_indice_inteiro[$i])];
$v .= " $conte xR$" . $valor;
$conte = 1;
}
$k++;
if ($k == $j)
//Autoexplicativo
{
$sair = true;
}
}
if (sizeof($vet_indice_inteiro) > 50)
//Este if impede uma dispensação de cédulas superior a 50.
{
header('Location: invalido4.php');
exit;
}
//Neste ponto termina a rotina opção inteiro e inicia-se a rotina para da opção
trocado .
$cont = 0;
$conte = 0;
$tamanho = sizeof($vet_indice_inteiro); //$tamanho recebe quantidade de notasinteiras que serão quebradas em notas trocadas.
$valida_pega_maior = true; //Variável boleana que valida o resultado da função pega_maior que será chamada abaixo.
for ($i = 0; $i < $tamanho; $i++)
// Este for contabiliza a ocorrências de R$100,00 em $vet_indice_inteiro[$i].
{
if ($vet_indice_inteiro[$i] == 5) {
$cont++;
}
}
$quant_notas_cem = 0;
if (($cont == 3))
//Autoexplicativo
{
$conte = ($cont / 2);
$conte--;
$quant_notas_cem = round($conte);
}
if ($cont >= 4)
//Autoexplicativo
{
$conte = ($cont / 2);
$quant_notas_cem = round($conte);
}
for ($i = 0; $i < $tamanho; $i++)
//Este for faz a seleção das notas para atender ao saque, ”Opção trocado”
{
$m = $vet_indice_inteiro[$i];
$n = pega_maior($vet_quant_temp_trocado, $m); //pega_maior é uma função que seleciona o slot com maior quantidade de notas.
if (($quant_notas_cem > 0) && ($vet_quant_temp_trocado[5] != 0))
//Este if inclui algumas notas de R$100 na "opção trocado", afim de balancear a distribuição.
{
$n = 5;
$quant_notas_cem--;
}
$vet_indice_trocado[$i] = $n;
$vet_quant_notas_trocadas[$i] = $tabela[$m][$n];
$vet_quant_temp_trocado[$n] = ($vet_quant_temp_trocado[$n] -
$vet_quant_notas_trocadas[$i]);
}
if ($vet_indice_inteiro == $vet_indice_trocado)
//Este if impede a exibição na tela de "opção inteiro" e "opção trocado" com os mesmo valores. Como por exemplo em caso de apenas um slot com notas.
{
$sao_iguais = true;
}
if (array_sum($vet_quant_notas_trocadas) > 50)
//Este if impede uma dispensação de cédulas superior a 50.
{
$excedeu_trocado = true;
}
$novo_vet_ind_trocado[0] = -1;
for ($i = 0; $i < $tamanho; $i++)
//Este for contabiliza as ocorrências de um mesmo valor no $vet_indice_trocado.
{
if (in_array($vet_indice_trocado[$i], $novo_vet_ind_trocado))
//Este if impede a recontagem de um mesmo valor.
{
continue;
} else {
$j = $i;
$j++;
$novo_vet_ind_trocado[$j] = $vet_indice_trocado[$i];
while ($j < $tamanho)
//Este while contabiliza as ocorrências de um mesmo valor no $vet_indice_trocado.
{
if ($vet_indice_trocado[$i] == $vet_indice_trocado[$j]) {
@$vet_soma_notas_trocadas[($vet_indice_trocado[$i])] = $vet_soma_notas_trocadas[($vet_indice_trocado[$i])] + $vet_quant_notas_trocadas[$j];
}
$j++;
}
@$vet_soma_notas_trocadas[($vet_indice_trocado[$i])] = $vet_soma_notas_trocadas[($vet_indice_trocado[$i])] + $vet_quant_notas_trocadas[$i];
//O @ impede a exibição de notice.
}
}
for ($i = 5; $i >= 0; $i--)
//Este for armazena as notas selecionadas para ”Opção trocado” na variável $trocado.
{
if (array_key_exists($i, $vet_soma_notas_trocadas)) {
$trocado .= " $vet_soma_notas_trocadas[$i] xR$" . $vet_notas[$i];
}
}
if (($saque < 10) || ($valida_pega_maior == false) || (@$sao_iguais == true) || (@$excedeu_trocado == true)
)
//Este if verifica as condições onde somente a opção inteiro é exibida na tela.
{
echo '<form action="painel.php" method="POST" >
<table
border
=
2
bgcolor="#66FFFF"
SIZE=15 ALIGN=MIDDLE WIDTH=300 ><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<center><br>Saque
de:
R$
' .
$saque . ',00<br></center>
<center><br>Escolha o conjunto de notas
desejadas dentre as opções abaixo:<br></center><br>
<input
type="hidden"
name="valor"
value="' . $saque . '"/>
<input
type="submit" name="executar1"
<input name="Cancelar"
value="' . $v . '"/><br>
<br>
type="submit"
value="Cancelar"
STYLE="color:#FFFFFF;
color:#FF0000"/>
</tr></td>
</table>
</form>';
} else
//Este else exibe na tela as opções inteiro e trocado.
{
echo '<form action="painel.php" method="POST" >
<table
border
=
2
bgcolor="#66FFFF"
SIZE=15 ALIGN=MIDDLE WIDTH=300 ><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<center><br>Saque
de:
R$
' .
$saque . ',00<br></center>
<center><br>Escolha o conjunto de notas
desejadas dentre as opções abaixo:<br></center><br>
<input
type="hidden"
name="valor"
value="' . $saque . '"/>
<input type="submit" name="executar1"
<input type="submit" name="executar2"
<input name="Cancelar"
value="' . $v . '"/>
value="' . $trocado . '"/><br>
<br>
type="submit"
value="Cancelar"
STYLE="color:#FFFFFF;
color:#FF0000"/>
</tr></td>
</table>
</form>';
}
?>
</body>
</html><file_sep>/notas.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
include 'vetores.php';
?>
<form action="abastecimento.php" method="POST">
<table BORDER=2 BGCOLOR="#66FFFF" SIZE=15 ALIGN=MIDDLE WIDTH=300>
<tr>
<TD ALIGN=MIDDLE WIDTH=200>
<tr><br>Selecione uma das notas dentre as opções abaixo para abastecer:<br></tr><br>
<input type="submit" name="executar0" value="R$2,00" />
<input type="submit" name="executar1" value="R$5,00" />
<input type="submit" name="executar2" value="R$10,00" />
<input type="submit" name="executar3" value="R$20,00" /><br><br>
<input type="submit" name="executar4" value="R$50,00" />
<input type="submit" name="executar5" value="R$100,00" /><br><br>
<input type="submit" value="Cancelar" STYLE="color:#FFFFFF;
name=" Cancelar" background- color:#FF0000" />
</tr>
</td>
</table>
</form>
</body>
</html><file_sep>/index.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="principal.php" method="POST">
<table BORDER=2 BGCOLOR="#66FFFF" SIZE=15 ALIGN=MIDDLE WIDTH=300>
<tr>
<TD ALIGN=MIDDLE WIDTH=200>
<tr><br>Opção Saque:<br></tr>
<tr><br>Notas Disponíveis:</tr>
<?php
//Este formulário é a tela inicial do sistema. Nele o cliente irá digitar o valor do saque que deseja.
$vazio = true;
$cont = 0;
include 'vetores.php';
for ($i = 0; $i <= 5; $i++)
//Verifica e exibe na tela quais os slots podem fornecer cédulas(notas disponiveis)
{
if (($vet_quant[$i]) != 0) {
$vet_nota_disponivel[$i] = $i;
echo " R$", $vet_notas[$vet_nota_disponivel[$i]];
$vazio = false;
}
}
if ($vazio == false)
//Este if omite os botões confirmar e cancela, no caso de terminal vazio.
{
$a = '<br></center>
<br>valor <input type="text" name="valor"/><br>
<center><br> <input name="Cancelar" type="submit" value="Cancelar"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
<input type="submit" name="Confirmar" value="Confirmar"
STYLE="color:#FFFFFF; background-color:#006400"/></center>
</form>';
echo $a;
exit;
}
for ($i = 0; $i <= 5; $i++)
//Verifica se todos os slots estão vazios(notas disponiveis=vazio)
{
if (empty($vet_quant[$i])) {
$cont++;
//Em uma implementação real, neste ponto rodará um script que solicitará um abastecimento para o respectivo slot.
}
if ($cont == 5) {
echo "Terminal vazio!";
echo "<p>Dirija-se a outro terminal!</p>";
}
}
?>
</tr>
</td>
</table>
</body>
</html><file_sep>/multiplo.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
function verifica_multiplo($notas, $quant_notas, &$valor_saque)
//Função que verifica se o valor digitado pelo cliente é multiplo das notas armazenadas no terminal.
{
$multiplo = false;
while ($multiplo == false) {
for ($i = 0; $i <= 5; $i++) {
if (($valor_saque % $notas[$i] == 0) && ($quant_notas[$i] != 0)) {
$multiplo = true;
break;
}
}
if ($multiplo == false) {
echo '<form action=index.php method=POST>
<table border = 2 bgcolor="#66FFFF" SIZE=15 ALIGN=MIDDLE WIDTH=300><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Valor digitado não e multiplo das notas armazenadas neste terminal!</p>
<p>Clique em OK e digite um valor multiplo das notas disponivies!</p>
<input type="submit" name="OK" value="OK"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
</tr></td>
</table>
</form>';
//exit;
exit;
}
}
}
?>
</body>
</html><file_sep>/painel.php
<?php
include 'vetores.php';
if (isset($_POST['executar1']))
//Este if recebe dados de principal.php. Se o cliente cliquar na opção inteiro a variáve matriz $vet_quant é atualizada com $vet_quant_temp_in teiro.
{
$vet_quant = $vet_quant_temp_inteiro;
echo '<form action=index.php method=POST>
<table
border
=
2
bgcolor="#66FFFF"
SIZE=15
ALIGN=MIDDLE WIDTH=300><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Saque opção inteiro realizado com sucesso!</p>
<p>Retire as notas no dispensador!</p>
<p>Clique em OK e para finalizar a transação!</p>
<input
type="submit"
name="OK"
value="OK"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
</tr></td>
</table>
</form>';
}
if (isset($_POST['executar2']))
//Este if recebe dados de principal.php. Se o cliente cliquar na opção trocado a variável matriz $vet_quant é atualizada com $vet_q uan t_t e m p _ tr o cad o .
{
$vet_quant = $vet_quant_temp_trocado;
}
echo '<form action=index.php method=POST>
<table border=2 bgcolor="#66FFFF"
SIZE=15
ALIGN=MIDDLE WIDTH=300><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Saque opção trocado realizado com sucesso!</p>
<p>Retire as notas no dispensador!</p>
<p>Clique em OK e para finalizar a transação!</p>
<input
type="submit"
name="OK"
value="OK"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
</tr></td>
</table>
</form>';
if (isset($_POST['Cancelar']))
//Este if recebe dados de principal.php, opção cancelar.
{
echo '<form action=index.php method=POST>
<table
border
=
2
bgcolor="#66FFFF"
SIZE=15
ALIGN=MIDDLE WIDTH=300><tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Operação Cancelada!</p>
<p>Clique em OK e para reiniciar a transação!</p>
<input
type="submit"
name="OK"
value="OK"
STYLE="color:#FFFFFF; background-color:#FF0000"/>
</tr></td>
</table>
</form>';
}
if (isset($_POST['Continuar']))
//Este if recebe dados de concluir.php, se o tecnico de suporte cliquar em "continuar" será direcionado para notas.php.
{
header('Location: notas.php');
exit;
}
if (isset($_POST['Sair']))
//Este if recebe dados de concluir.php, se o tecnico de suporte cliquar em "sair " se r d ire c ion a do para index .php libe rando o ter minal para uso dos clientes.
{
header('Location: index.php');
exit;
}
<file_sep>/invalido2.php
<?php
////Este formulário será exibido, caso o técnico de suporte digite um valor superior a capacidade de armazenamento do slot em abastecimento.php.
?>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action=notas.php method=POST>
<table BORDER=2 BRCOLOR="#66FFFF" SIZE=15 ALIGN=MIDDLE WIDTH=300>
<tr>
<TD ALIGN=MIDDLE WIDTH=200>
<p>Valor invalido!</p>
<p>Digite um valor de no maximo 1000!</p>
<input type="submit" name="OK" value="OK" STYLE="color:#FFFFFF; background-color:#FF0000" />
</tr>
</td>
</table>
</form>
</body>
</html> | 45bee71cca779b48f5cf446018b37ebe6eff851e | [
"PHP"
] | 9 | PHP | brunofirme10/caixa-eletronico-bf | 57e75dce1619803cb6bd45a115386ad9de4108e9 | dc79c5d2c8acce43394828da15816dbf586719be | |
refs/heads/main | <repo_name>Mizarchi/peso-en-marte<file_sep>/saludo/main.js
const input = document.getElementById('nombre')
const button = document.getElementById('button')
button.addEventListener('click', () => {
alert(input.value)
})<file_sep>/v2/main.js
const gravedadTierra = 9.81
const gravedadMarte = 3.71
const input = document.getElementById('peso')
const button = document.getElementById('button')
const contenedor = document.getElementById('resultado')
button.addEventListener('click', () => {
const miPeso = input.value
const resultPeso = (miPeso / gravedadTierra) * gravedadMarte
const resultado = 'Tu peso en marte es ' + ~~resultPeso + 'kg'
contenedor.innerText = resultado
})
<file_sep>/nombre/main.js
const nombre = prompt('cuál es tu nombre?')
const saludo = 'hola ' + nombre
document.write(saludo)
| 096489600035e81dfb1539b2a5088d4ccbae1789 | [
"JavaScript"
] | 3 | JavaScript | Mizarchi/peso-en-marte | 3ce52d43fbb4b4925b41606c5f19e41bd0c61476 | 261db10f1a899e17bfc28b423200200287ff4ae2 | |
refs/heads/master | <file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
sap.ui.jsview("sap.apf.ui.reuse.view.stepToolbar",{getControllerName:function(){return"sap.apf.ui.reuse.controller.stepToolbar";},createContent:function(c){this.chartToolbar=new sap.ca.ui.charts.ChartToolBar({showLegend:true,showFullScreen:true});return this.chartToolbar;}});
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
sap.ui.define(['jquery.sap.global', './Base'], function(jQuery, Base) {
"use strict";
/**
* Change handler for moving of a elements.
*
* @constructor
* @alias sap.ui.fl.changeHandler.MoveElements
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.34.0
*/
var MoveElements = function() {
};
MoveElements.prototype = jQuery.sap.newObject(Base.prototype);
MoveElements.CHANGE_TYPE = "moveElements";
/**
* Moves an element from one aggregation to another.
*
* @param {sap.ui.fl.Change}
* oChange change object with instructions to be applied on the control map
* @param {sap.ui.core.Control}
* oSourceParent control that matches the change selector for applying the change, which is the source of the
* move
* @public
*/
MoveElements.prototype.applyChange = function(oChange, oSourceParent) {
var that = this;
var mContent = oChange.getContent();
if (oSourceParent.getId() !== oChange.getSelector().id) {
throw new Error("Source parent id (selector) doesn't match the control on which to apply the change");
}
var sSourceAggregation = oChange.getSelector().aggregation;
if (!sSourceAggregation) {
throw new Error("No source aggregation supplied via selector for move");
}
if (!mContent.target || !mContent.target.selector) {
throw new Error("No target supplied for move");
}
var oTargetParent = this._byId(mContent.target.selector.id);
if (!oTargetParent) {
throw new Error("Move target parent not found");
}
var sTargetAggregation = mContent.target.selector.aggregation;
if (!sTargetAggregation) {
throw new Error("No target aggregation supplied for move");
}
if (!mContent.movedElements) {
throw new Error("No moveElements supplied");
}
mContent.movedElements.forEach(function(mMovedElement) {
var oMovedElement = that._byId(mMovedElement.selector.id);
if (!oMovedElement) {
throw new Error("Unkown element with id '" + mMovedElement.selector.id + "' in moveElements supplied");
}
if ( typeof mMovedElement.targetIndex !== "number") {
throw new Error("Missing targetIndex for element with id '" + mMovedElement.selector.id
+ "' in moveElements supplied");
}
that.removeAggregation(oSourceParent, sSourceAggregation, oMovedElement);
that.addAggregation(oTargetParent, sTargetAggregation, oMovedElement, mMovedElement.targetIndex);
});
};
/**
* Completes the change by adding change handler specific content
*
* @param {sap.ui.fl.Change}
* oChange change object to be completed
* @param {object}
* mSpecificChangeInfo as an empty object since no additional attributes are required for this operation
* @public
*/
MoveElements.prototype.completeChangeContent = function(oChange, mSpecificChangeInfo) {
var that = this;
var mSpecificInfo = this.getSpecificChangeInfo(mSpecificChangeInfo);
var mChangeData = oChange.getDefinition();
mChangeData.changeType = MoveElements.CHANGE_TYPE;
mChangeData.selector = mSpecificInfo.source;
mChangeData.content = {
movedElements : [],
target : {
selector : mSpecificInfo.target
}
};
mSpecificInfo.movedElements.forEach(function(mElement) {
var oElement = mElement.element || that._byId(mElement.id);
mChangeData.content.movedElements.push({
selector : {
id : oElement.getId(),
type : that._getType(oElement)
},
sourceIndex : mElement.sourceIndex,
targetIndex : mElement.targetIndex
});
});
};
/**
* Enrich the incoming change info with the change info from the setter, to get the complete data in one format
*/
MoveElements.prototype.getSpecificChangeInfo = function(mSpecificChangeInfo) {
var oSourceParent = this._getParentElement(this._mSource || mSpecificChangeInfo.source);
var oTargetParent = this._getParentElement(this._mTarget || mSpecificChangeInfo.target);
var sSourceAggregation = this._mSource && this._mSource.aggregation || mSpecificChangeInfo.source.aggregation;
var sTargetAggregation = this._mTarget && this._mTarget.aggregation || mSpecificChangeInfo.target.aggregation;
var mSpecificInfo = {
source : {
id : oSourceParent.getId(),
aggregation : sSourceAggregation,
type : this._getType(oSourceParent)
},
target : {
id : oTargetParent.getId(),
aggregation : sTargetAggregation,
type : this._getType(oTargetParent)
},
movedElements : this._aMovedElements || mSpecificChangeInfo.movedElements
};
return mSpecificInfo;
};
/**
* @param {array}
* aElements
* @param {string}
* aElements.elementId id of the moved element, can be omitted if element is passed
* @param {sap.ui.core.Element}
* aElements.element moved element, optional fallback for elementId
* @param {number}
* aElements.sourceIndex index of the moved elements in the source aggregation
* @param {number}
* aElements.targetIndex index of the moved elements in the target aggregation
*/
MoveElements.prototype.setMovedElements = function(aElements) {
this._aMovedElements = aElements;
};
/**
* @param {object}
* mSource
* @param {string}
* mSource.id id of the source parent, can be omitted if element is passed
* @param {sap.ui.core.Element}
* mSource.parent optional fallback for id
* @param {string}
* mSource.aggregation original aggregation of the moved elements
*/
MoveElements.prototype.setSource = function(mSource) {
this._mSource = mSource;
};
/**
* @param {object}
* mTarget
* @param {string}
* mTarget.id id of the target parent
* @param {sap.ui.core.Element}
* mTarget.parent optional fallback for id, can be omitted if parent is passed
* @param {string}
* mTarget.aggregation target aggregation of the moved elements in the target element
*/
MoveElements.prototype.setTarget = function(mTarget) {
this._mTarget = mTarget;
};
MoveElements.prototype._byId = function(sId) {
return sap.ui.getCore().byId(sId);
};
MoveElements.prototype._getType = function(oElement) {
return oElement.getMetadata().getName();
};
MoveElements.prototype._getParentElement = function(mData) {
var oElement = mData.parent;
if (!oElement) {
oElement = this._byId(mData.id);
}
return oElement;
};
return MoveElements;
},
/* bExport= */true);
<file_sep>/**
* Compiled inline version. (Library mode)
*/
/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
/*globals $code */
(function(exports, undefined) {
"use strict";
var modules = {};
function require(ids, callback) {
var module, defs = [];
for (var i = 0; i < ids.length; ++i) {
module = modules[ids[i]] || resolve(ids[i]);
if (!module) {
throw 'module definition dependecy not found: ' + ids[i];
}
defs.push(module);
}
callback.apply(null, defs);
}
function define(id, dependencies, definition) {
if (typeof id !== 'string') {
throw 'invalid module definition, module id must be defined and be a string';
}
if (dependencies === undefined) {
throw 'invalid module definition, dependencies must be specified';
}
if (definition === undefined) {
throw 'invalid module definition, definition function must be specified';
}
require(dependencies, function() {
modules[id] = definition.apply(null, arguments);
});
}
function defined(id) {
return !!modules[id];
}
function resolve(id) {
var target = exports;
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length; ++fi) {
if (!target[fragments[fi]]) {
return;
}
target = target[fragments[fi]];
}
return target;
}
function expose(ids) {
var i, target, id, fragments, privateModules;
for (i = 0; i < ids.length; i++) {
target = exports;
id = ids[i];
fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length - 1; ++fi) {
if (target[fragments[fi]] === undefined) {
target[fragments[fi]] = {};
}
target = target[fragments[fi]];
}
target[fragments[fragments.length - 1]] = modules[id];
}
// Expose private modules for unit tests
if (exports.AMDLC_TESTS) {
privateModules = exports.privateModules || {};
for (id in modules) {
privateModules[id] = modules[id];
}
for (i = 0; i < ids.length; i++) {
delete privateModules[ids[i]];
}
exports.privateModules = privateModules;
}
}
// Included from: js/DomTextMatcher.js
/**
* DomTextMatcher.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*eslint no-labels:0, no-constant-condition: 0 */
/**
* This class logic for filtering text and matching words.
*
* @class tinymce.tinymcespellcheckerplugin.TextFilter
* @private
*/
define("tinymce/tinymcespellcheckerplugin/DomTextMatcher", [], function() {
// Based on work developed by: <NAME> http://james.padolsey.com
// released under UNLICENSE that is compatible with LGPL
// TODO: Handle contentEditable edgecase:
// <p>text<span contentEditable="false">text<span contentEditable="true">text</span>text</span>text</p>
return function(node, editor, wordCharPattern) {
var m, dom = editor.dom;
var blockElementsMap, hiddenTextElementsMap, shortEndedElementsMap, ignoreClass = "mce-spellchecker-ignore";
blockElementsMap = editor.schema.getBlockElements(); // H1-H6, P, TD etc
hiddenTextElementsMap = editor.schema.getWhiteSpaceElements(); // TEXTAREA, PRE, STYLE, SCRIPT
shortEndedElementsMap = editor.schema.getShortEndedElements(); // BR, IMG, INPUT
function createMatch(m, data) {
if (!m[0]) {
throw 'findAndReplaceDOMText cannot handle zero-length matches';
}
return {
start: m.index,
end: m.index + m[0].length,
text: m[0],
data: data
};
}
function getText(node) {
var txt;
if (node.nodeType === 3) {
return node.data;
}
if (hiddenTextElementsMap[node.nodeName] && !blockElementsMap[node.nodeName]) {
return '';
}
txt = '';
if (blockElementsMap[node.nodeName] || shortEndedElementsMap[node.nodeName]) {
txt += '\n';
}
if ((node = node.firstChild)) {
do {
txt += getText(node);
} while ((node = node.nextSibling));
}
return txt;
}
function getUniqueValuesFromArray(arrayToCheck) {
function arrayContains(arrayToCheck, value) {
for (var i = 0; i < arrayToCheck.length; i++) {
if (arrayToCheck[i] === value) {
return true;
}
}
return false;
}
var arrayToKeep = [];
for (var i = 0; i < arrayToCheck.length; i++) {
if (!arrayContains(arrayToKeep, arrayToCheck[i])) {
arrayToKeep.push(arrayToCheck[i]);
}
}
return arrayToKeep;
}
function getWords(node) {
var matches = getText(node).match(wordCharPattern);
return matches ? getUniqueValuesFromArray(matches) : [];
}
function stepThroughMatches(node, matches, replaceFn) {
var startNode, endNode, startNodeIndex,
endNodeIndex, innerNodes = [], atIndex = 0, curNode = node,
matchLocation, matchIndex = 0;
matches = matches.slice(0);
matches.sort(function(a, b) {
return a.start - b.start;
});
matchLocation = matches.shift();
out: while (true) {
if (blockElementsMap[curNode.nodeName] || shortEndedElementsMap[curNode.nodeName]) {
atIndex++;
}
if (curNode.nodeType === 3) {
if (!endNode && curNode.length + atIndex >= matchLocation.end) {
// We've found the ending
endNode = curNode;
endNodeIndex = matchLocation.end - atIndex;
} else if (startNode) {
// Intersecting node
innerNodes.push(curNode);
}
if (!startNode && curNode.length + atIndex > matchLocation.start) {
// We've found the match start
startNode = curNode;
startNodeIndex = matchLocation.start - atIndex;
}
atIndex += curNode.length;
}
if (startNode && endNode) {
//We need to check if this is an ignored element
var ignored = false;
for (var currNode = startNode; currNode != node; currNode = currNode.parentNode) {
if (currNode.className === ignoreClass) {
ignored = true;
}
}
if (!ignored) {
curNode = replaceFn({
startNode: startNode,
startNodeIndex: startNodeIndex,
endNode: endNode,
endNodeIndex: endNodeIndex,
innerNodes: innerNodes,
match: matchLocation.text,
matchIndex: matchIndex
});
// replaceFn has to return the node that replaced the endNode
// and then we step back so we can continue from the end of the
// match:
atIndex -= (endNode.length - endNodeIndex);
}
startNode = null;
endNode = null;
innerNodes = [];
matchLocation = matches.shift();
matchIndex++;
if (!matchLocation) {
break; // no more matches
}
} else if ((!hiddenTextElementsMap[curNode.nodeName] || blockElementsMap[curNode.nodeName]) && curNode.firstChild) {
// Move down
curNode = curNode.firstChild;
continue;
} else if (curNode.nextSibling) {
// Move forward:
curNode = curNode.nextSibling;
continue;
}
// Move forward or up:
while (true) {
if (curNode.nextSibling) {
curNode = curNode.nextSibling;
break;
} else if (curNode.parentNode !== node) {
curNode = curNode.parentNode;
} else {
break out;
}
}
}
}
/**
* Generates the actual replaceFn which splits up text nodes
* and inserts the replacement element.
*/
function genReplacer(matches, callback) {
function makeReplacementNode(fill, matchIndex) {
var match = matches[matchIndex];
if (!match.stencil) {
match.stencil = callback(match);
}
var clone = match.stencil.cloneNode(false);
clone.setAttribute('data-mce-index', matchIndex);
if (fill) {
clone.appendChild(dom.doc.createTextNode(fill));
}
return clone;
}
return function(range) {
var before, after, parentNode, startNode = range.startNode,
endNode = range.endNode, matchIndex = range.matchIndex,
doc = dom.doc;
if (startNode === endNode) {
var node = startNode;
parentNode = node.parentNode;
if (range.startNodeIndex > 0) {
// Add "before" text node (before the match)
before = doc.createTextNode(node.data.substring(0, range.startNodeIndex));
parentNode.insertBefore(before, node);
}
// Create the replacement node:
var el = makeReplacementNode(range.match, matchIndex);
parentNode.insertBefore(el, node);
if (range.endNodeIndex < node.length) {
// Add "after" text node (after the match)
after = doc.createTextNode(node.data.substring(range.endNodeIndex));
parentNode.insertBefore(after, node);
}
node.parentNode.removeChild(node);
return el;
}
// Replace startNode -> [innerNodes...] -> endNode (in that order)
before = doc.createTextNode(startNode.data.substring(0, range.startNodeIndex));
after = doc.createTextNode(endNode.data.substring(range.endNodeIndex));
var elA = makeReplacementNode(startNode.data.substring(range.startNodeIndex), matchIndex);
var innerEls = [];
for (var i = 0, l = range.innerNodes.length; i < l; ++i) {
var innerNode = range.innerNodes[i];
var innerEl = makeReplacementNode(innerNode.data, matchIndex);
innerNode.parentNode.replaceChild(innerEl, innerNode);
innerEls.push(innerEl);
}
var elB = makeReplacementNode(endNode.data.substring(0, range.endNodeIndex), matchIndex);
parentNode = startNode.parentNode;
parentNode.insertBefore(before, startNode);
parentNode.insertBefore(elA, startNode);
parentNode.removeChild(startNode);
parentNode = endNode.parentNode;
parentNode.insertBefore(elB, endNode);
parentNode.insertBefore(after, endNode);
parentNode.removeChild(endNode);
return elB;
};
}
/**
* Returns the index of a specific match object or -1 if it isn't found.
*
* @param {Match} match Text match object.
* @return {Number} Index of match or -1 if it isn't found.
*/
function indexOf(matches, match) {
var i = matches.length;
while (i--) {
if (matches[i] === match) {
return i;
}
}
return -1;
}
/**
* Filters the matches. If the callback returns true it stays if not it gets removed.
*
* @param {Function} callback Callback to execute for each match.
* @return {DomTextMatcher} Current DomTextMatcher instance.
*/
function filter(matches, callback) {
var filteredMatches = [];
each(matches, function(match, i) {
if (callback(match, i)) {
filteredMatches.push(match);
}
});
matches = filteredMatches;
/*jshint validthis:true*/
return filteredMatches;
}
/**
* Executes the specified callback for each match.
*
* @param {Function} callback Callback to execute for each match.
* @return {DomTextMatcher} Current DomTextMatcher instance.
*/
function each(matches, callback) {
for (var i = 0, l = matches.length; i < l; i++) {
if (callback(matches[i], i) === false) {
break;
}
}
/*jshint validthis:true*/
return this;
}
/**
* Wraps the current matches with nodes created by the specified callback.
* Multiple clones of these matches might occur on matches that are on multiple nodex.
*
* @param {Function} callback Callback to execute in order to create elements for matches.
* @return {DomTextMatcher} Current DomTextMatcher instance.
*/
function wrap(matches, callback, node) {
if (matches.length) {
stepThroughMatches(node, matches, genReplacer(matches, callback));
}
/*jshint validthis:true*/
return this;
}
/**
* Finds the specified regexp and adds them to the matches collection.
*
* @param {RegExp} regex Global regexp to search the current node by.
* @param {Object} [data] Optional custom data element for the match.
* @return {DomTextMatcher} Current DomTextMatcher instance.
*/
function find(regex, data, node) {
var matches = [];
var textToMatch = getText(node);
if (textToMatch && regex.global) {
while ((m = regex.exec(textToMatch))) {
matches.push(createMatch(m, data));
}
}
return matches;
}
return {
getText: getText,
getWords: getWords,
each: each,
filter: filter,
find: find,
wrap: wrap,
indexOf: indexOf
};
};
});
// Included from: js/SpellingCache.js
/**
* SpellingCache.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class is used to store spelling suggestions and more in one place.
*
* @class tinymce.tinymcespellcheckerplugin.TextFilter
* @private
*/
define("tinymce/tinymcespellcheckerplugin/SpellingCache", [
"tinymce/util/JSON"
], function(JSON) {
return function() {
var storageItemName = "tinyMCESpellingCache",
fallbackCache = {},
suggestionsLimit = 5;
function cleanWord(word) {
return word.replace(/\uFEFF/g, '');
}
function addWordToCache(language, word, misspelled, suggestions) {
var spellingCache = getCache(language),
fixedWord = cleanWord(word),
cacheObject = {
misspelled: misspelled,
suggestions: suggestions
};
spellingCache[language][fixedWord] = cacheObject;
if (storageSupported()) {
sessionStorage.setItem(storageItemName, JSON.serialize(spellingCache));
} else {
fallbackCache = spellingCache;
}
}
function storageSupported() {
return typeof (Storage) !== "undefined";
}
function checkCacheLanguage(language, spellingCache) {
if (!spellingCache[language]) {
spellingCache[language] = {};
}
return spellingCache;
}
function getCache(language) {
//if the cache isn't there yet
var spellingCache = storageSupported() && sessionStorage.getItem(storageItemName) ?
JSON.parse(sessionStorage.getItem(storageItemName)) : fallbackCache;
return checkCacheLanguage(language, spellingCache);
}
function retrieveWordFromCache(language, word) {
var spellingCache = getCache(language),
fixedWord = cleanWord(word),
cacheObject = spellingCache[language][fixedWord] ? spellingCache[language][fixedWord] : false;
//If the suggestions array exists, and has a length greater than
if (cacheObject && cacheObject.suggestions && cacheObject.suggestions.length > suggestionsLimit) {
//limit the suggestions
cacheObject.suggestions = cacheObject.suggestions.slice(0, suggestionsLimit);
}
return cacheObject;
}
return {
addWordToCache: addWordToCache,
retrieveWordFromCache: retrieveWordFromCache
};
};
});
// Included from: js/Plugin.js
/**
* Plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*jshint camelcase:false */
/**
* This class contains all core logic for the spellchecker plugin.
*
* @class tinymce.tinymcespellcheckerplugin.Plugin
* @private
*/
define("tinymce/tinymcespellcheckerplugin/Plugin", [
"tinymce/tinymcespellcheckerplugin/DomTextMatcher",
"tinymce/tinymcespellcheckerplugin/SpellingCache",
"tinymce/PluginManager",
"tinymce/util/Tools",
"tinymce/ui/Menu",
"tinymce/dom/DOMUtils",
"tinymce/util/XHR",
"tinymce/util/URI",
"tinymce/util/JSON"
], function(DomTextMatcher, SpellingCache, PluginManager, Tools, Menu, DOMUtils, XHR, URI, JSON) {
PluginManager.add('tinymcespellchecker', function(editor, url) {
var self = this, suggestionsMenu, settings = editor.settings, spellcheckerVersion = 1,
word_regexp = '[' + '\\w' + '\'' + '\\-' + '\\u00C0-\\u00FF' + '\\uFEFF' + '\\u2018\\u2019' + ']+',
languagesString = settings.spellchecker_languages ||
'US English=en,UK English=en_gb,Danish=da,Dutch=nl,Finnish=fi,French=fr,' +
'German=de,Italian=it,Norwegian=nb,Brazilian Portuguese=pt,Iberian Portuguese=pt_pt,' +
'Spanish=es,Swedish=sv',
languageMenuItems, wordClass = "mce-spellchecker-word", ignoreClass = "mce-spellchecker-ignore", currentParentNode,
spellchecking = true, spellcheckButton, spellcheckMenuItem,
successes, failed, successCount, requestCount, maxLetters = 15000;
function getTextMatcher() {
if (!self.textMatcher) {
self.textMatcher = new DomTextMatcher(editor.getBody(), editor, getWordCharPattern());
}
return self.textMatcher;
}
function getSpellingCache() {
if (!self.spellingCache) {
self.spellingCache = new SpellingCache();
}
return self.spellingCache;
}
function showSuggestions(word, spans) {
var items = [], suggestions = getSpellingCache().retrieveWordFromCache(settings.spellchecker_language, word).suggestions;
Tools.each(suggestions, function(suggestion) {
items.push({
text: suggestion,
onclick: function() {
editor.insertContent(editor.dom.encode(suggestion));
editor.dom.remove(spans);
}
});
});
items.push({text: '-'});
items.push.apply(items, [
{text: 'Ignore', onclick: function() {
ignoreWord(word, spans);
}},
{text: 'Ignore all', onclick: function() {
ignoreWord(word, spans, true);
}}
]);
// Render menu
suggestionsMenu = new Menu({
items: items,
context: 'contextmenu',
onautohide: function(e) {
if (e.target.className.indexOf('spellchecker') != -1) {
e.preventDefault();
}
},
onhide: function() {
suggestionsMenu.remove();
suggestionsMenu = null;
}
});
suggestionsMenu.renderTo(document.body);
// Position menu
var pos = DOMUtils.DOM.getPos(editor.getContentAreaContainer());
var targetPos = editor.dom.getPos(spans[0]);
var root = editor.dom.getRoot();
// Adjust targetPos for scrolling in the editor
if (root.nodeName == 'BODY') {
targetPos.x -= root.ownerDocument.documentElement.scrollLeft || root.scrollLeft;
targetPos.y -= root.ownerDocument.documentElement.scrollTop || root.scrollTop;
} else {
targetPos.x -= root.scrollLeft;
targetPos.y -= root.scrollTop;
}
pos.x += targetPos.x;
pos.y += targetPos.y;
suggestionsMenu.moveTo(pos.x, pos.y + spans[0].offsetHeight);
}
function getWordCharPattern() {
// Regexp for finding word specific characters this will split words by
// spaces, quotes, copy right characters etc. It's escaped with unicode characters
// to make it easier to output scripts on servers using different encodings
// so if you add any characters outside the 128 byte range make sure to escape it
return editor.getParam('spellchecker_wordchar_pattern') || new RegExp(word_regexp, "g");
}
function cleanWord(word) {
return word.replace(/\uFEFF/g, '');
}
function getCachedCleanedWords(words) {
var cachedData = {},
wordsToCheck = [],
cleanedWordsForServer = [];
//For each word we were going to send to the server
for (var i = 0; i < words.length; i++) {
//Attempt to get the cached word instead
var cachedWord = getSpellingCache().retrieveWordFromCache(settings.spellchecker_language, words[i]);
//If we have the word cached already and it's misspelled
//we need to add it to the cachedData object under the unclean version of the word
if (cachedWord && cachedWord.misspelled) {
cachedData[words[i]] = cachedWord;
}
if (!cachedWord) { //Otherwise if we don't have it cached yet
wordsToCheck.push({
original: words[i],
cleaned: cleanWord(words[i])
});
cleanedWordsForServer.push(cleanWord(words[i]));
}
}
return {
cachedData: cachedData,
wordsToCheck: wordsToCheck,
cleanedWordsForServer: cleanedWordsForServer
};
}
function spellingSuccessCallback(result, cachedCleanedWords, node) {
result = JSON.parse(result);
if (!result) {
spellingErrorCallback("Server response wasn't proper JSON.");
failed = true;
} else {
successes.push(result);
successCount++;
if (!failed && successCount === requestCount) {
editor.setProgressState(false);
cacheAndMarkSuggestions(cachedCleanedWords.cachedData, successes, cachedCleanedWords.wordsToCheck, node);
}
}
}
function spellingErrorCallback(message) {
if (!failed) {
editor.setProgressState(false);
editor.notificationManager.open({text: message, type: 'error'});
}
}
function getApiKey() {
return settings.api_key || settings.spellchecker_api_key;
}
function makeServerRequest(data, cachedCleanedWords, node) {
var postSuffix = "/" + spellcheckerVersion + "/correction";
var request = {
url: new URI(url).toAbsolute(settings.spellchecker_rpc_url + postSuffix),
type: "post",
content_type: 'application/json',
data: JSON.serialize(data),
success: function(result) {
spellingSuccessCallback.call(self, result, cachedCleanedWords, node);
},
error: function(type, xhr) {
spellingErrorCallback("Spellchecker request error: " + xhr.status);
failed = true;
}
};
var apiKey = getApiKey();
if (apiKey) {
request.requestheaders = [
{
key: 'tiny-api-key',
value: apiKey
}
];
}
return request;
}
function chunkServerRequestData(words) {
var chunkLetters = 0, lastIndex = 0, requests = [];
for (var i = 0; i < words.length; i++) {
chunkLetters += words[i].length;
if (chunkLetters > maxLetters) {
requests.push({
words: words.slice(lastIndex, i + 1),
language: settings.spellchecker_language
});
lastIndex = i + 1;
chunkLetters = 0;
}
}
if (lastIndex != words.length) {
requests.push({
words: words.slice(lastIndex, words.length),
language: settings.spellchecker_language
});
}
requestCount = requests.length;
successes = [];
successCount = 0;
failed = false;
return requests;
}
function spellcheckServerCall(words, node) {
var cachedCleanedWords = getCachedCleanedWords(words);
//If we have some words to check
if (cachedCleanedWords.wordsToCheck.length > 0) {
var datas = chunkServerRequestData(cachedCleanedWords.cleanedWordsForServer);
for (var i = 0; i < datas.length; i++) {
var request = makeServerRequest(datas[i], cachedCleanedWords, node);
XHR.send(request);
}
} else {
cacheAndMarkSuggestions(cachedCleanedWords.cachedData, [], cachedCleanedWords.wordsToCheck, node);
}
}
function spellcheck(node) {
spellcheckServerCall(getTextMatcher().getWords(node), node);
editor.focus();
}
function ignoreWord(word, spans, all) {
editor.selection.collapse();
if (all) {
Tools.each(editor.dom.select('span.' + wordClass), function(span) {
if (span.getAttribute('data-mce-word') == word) {
//editor.dom.remove(span, true);
span.className = ignoreClass;
}
});
} else {
//editor.dom.remove(spans, true);
Tools.each(spans, function(span) {
span.className = ignoreClass;
});
}
}
function getElmIndex(elm) {
var value = elm.getAttribute('data-mce-index');
if (typeof value == "number") {
return "" + value;
}
return value;
}
function findSpansByIndex(index, node) {
var nodes, spans = [];
nodes = Tools.toArray(node.getElementsByTagName('span'));
if (nodes.length) {
for (var i = 0; i < nodes.length; i++) {
var nodeIndex = getElmIndex(nodes[i]);
if (nodeIndex === null || !nodeIndex.length) {
continue;
}
if (nodeIndex === index.toString()) {
spans.push(nodes[i]);
}
}
}
return spans;
}
function updateSelection(e) {
var selectedLanguage = settings.spellchecker_language;
Tools.each(e.control.items(), function(item) {
item.active(item.data.data === selectedLanguage);
});
}
function setUpActiveStateToggle(e) {
e.control.on('show', function(ee) {
updateSelection(ee);
});
}
function setUpActiveSpellcheckingToggle(e) {
spellcheckMenuItem = e.control;
e.control.on('show', function() {
this.active(spellchecking);
});
spellcheckMenuItem.active(spellchecking);
}
function cacheAndCombineResults(cachedData, wordResults, words) {
var combinedResults = {};
//Add cached results to combined data object
for (var cachedField in cachedData) {
if (cachedData[cachedField] && cachedData[cachedField].misspelled) {
combinedResults[cachedField] = cachedData[cachedField].suggestions;
}
}
//For each misspelled result we have from the server, we need to add it to the cache.
for (var field in wordResults) {
getSpellingCache().addWordToCache(settings.spellchecker_language, field, true, wordResults[field]);
//For each word we were going to check, if the cleaned version of the word matches the currently being checked field
for (var w = 0; w < words.length; w++) {
//We've found our word
if (words[w].cleaned === field) {
combinedResults[words[w].original] = wordResults[field];
break;
}
}
}
return combinedResults;
}
function cacheCorrectlySpelledWords(words) {
//Finally, now that we have the combinedresults of a cache and service
for (var i = 0; i < words.length; i++) {
//If a word we were searching for isn't cached, and isn't part of the results
//We need to assume that the word is in the dictionary
var cachedWord = getSpellingCache().retrieveWordFromCache(settings.spellchecker_language, words[i].cleaned);
if (!cachedWord) {
getSpellingCache().addWordToCache(settings.spellchecker_language, words[i].cleaned, false, []);
}
}
}
function cacheAndMarkSuggestions(cachedData, responses, words, node) {
var wordResults = {};
for (var i = 0; i < responses.length; i++) {
for (var field in responses[i].spell) {
wordResults[field] = responses[i].spell[field];
}
}
var combinedResults = cacheAndCombineResults(cachedData, wordResults, words);
cacheCorrectlySpelledWords(words);
markErrors(combinedResults, node);
}
function unwrapWordNode(wordNode) {
var parentNode = wordNode.parentNode;
var childNodes = wordNode.childNodes;
while (childNodes.length > 0) {
parentNode.insertBefore(childNodes[0], wordNode);
}
wordNode.parentNode.removeChild(wordNode);
}
function clearWordMarks(node) {
var wrappedWords = editor.dom.select('span.' + wordClass, node);
//Unwrap from node
for (var i = 0; i < wrappedWords.length; i++) {
unwrapWordNode(wrappedWords[i]);
}
}
/**
* Find the specified words and marks them. It will also show suggestions for those words.
*
* @example
* editor.plugins.tinymcespellcheckerplugin.markErrors({
* dictionary: true,
* words: {
* "word1": ["suggestion 1", "Suggestion 2"]
* }
* });
* @param {Object} data Data object containing the words with suggestions.
*/
function markErrors(data, node) {
var bm = editor.selection.getBookmark();
clearWordMarks(node);
var matches = getTextMatcher().find(getWordCharPattern(), undefined, node);
matches = getTextMatcher().filter(matches, function(match) {
return !!data[match.text];
});
getTextMatcher().wrap(matches, function(match) {
return editor.dom.create('span', {
"class": wordClass,
"data-mce-bogus": 1,
"data-mce-word": match.text
});
}, node);
editor.selection.moveToBookmark(bm);
}
function getParentBlock(currNode) {
var rootNode = editor.getBody(),
parentNode = rootNode, blockElements = editor.schema.getBlockElements();
for (currNode = currNode; currNode != rootNode; currNode = currNode.parentNode) {
if (currNode === null || currNode === undefined) {
break;
}
if (blockElements[currNode.nodeName]) {
parentNode = currNode;
break;
}
}
return parentNode;
}
function buildMenuItems(listName, languageValues) {
var items = [];
Tools.each(languageValues, function(languageValue) {
items.push({
selectable: true,
text: languageValue.name,
data: languageValue.value,
onclick: function() {
settings.spellchecker_language = languageValue.value;
if (spellchecking) {
spellcheck(editor.getBody());
}
}
});
});
return items;
}
languageMenuItems = buildMenuItems('Language',
Tools.map(languagesString.split(','), function(langPair) {
langPair = langPair.split('=');
return {
name: langPair[0],
value: langPair[1]
};
})
);
function toggleSpellcheck() {
if (spellchecking) {
unBindEvents();
clearWordMarks(editor.getBody());
} else {
bindEvents();
spellcheck(editor.getBody());
}
spellchecking = !spellchecking;
spellcheckButton.active(spellchecking);
if (spellcheckMenuItem) {
spellcheckMenuItem.active(spellchecking);
}
}
var buttonArgs = {
tooltip: 'Spellcheck',
onclick: toggleSpellcheck,
onPostRender: function(e) {
e.control.active(spellchecking);
}
};
if (languageMenuItems.length > 1) {
buttonArgs.type = 'splitbutton';
buttonArgs.menu = languageMenuItems;
buttonArgs.onshow = updateSelection;
buttonArgs.onpostrender = function(e) {
spellcheckButton = e.control;
};
}
editor.addButton('spellchecker', buttonArgs);
editor.addCommand('mceSpellCheck', toggleSpellcheck);
editor.addMenuItem('spellchecker', {
text: 'Spellcheck',
context: 'tools',
onclick: toggleSpellcheck,
onPostRender: setUpActiveSpellcheckingToggle,
selectable: true
});
editor.addMenuItem('spellcheckerlanguage', {
text: 'Spellcheck Language',
context: 'tools',
menu: languageMenuItems,
onPostRender: setUpActiveStateToggle
});
function editorRemove() {
if (suggestionsMenu) {
suggestionsMenu.remove();
suggestionsMenu = null;
}
}
function editorKeydown(e) {
//We probably don't want to unwrap the word we're in if we're just pressing arrow keys around
if ((e.which || e.keycode) === 37 ||
(e.which || e.keycode) === 38 ||
(e.which || e.keycode) === 39 ||
(e.which || e.keycode) === 40) {
return;
}
var currNode = editor.selection.getNode();
if (DOMUtils.DOM.hasClass(currNode, wordClass) || DOMUtils.DOM.hasClass(currNode, ignoreClass)) {
var parentNode = getParentBlock(currNode),
wordNodes = findSpansByIndex(getElmIndex(currNode), parentNode);
//Unwrap the ignored/misspelled word
if (wordNodes.length > 0) {
var bm = editor.selection.getBookmark();
for (var i = 0; i < wordNodes.length; i++) {
unwrapWordNode(wordNodes[i]);
}
editor.selection.moveToBookmark(bm);
}
}
}
function editorKeyup(e) {
var currNode = editor.selection.getNode(),
parentNode = getParentBlock(currNode);
if ((e.which || e.keycode) === 32) {
spellcheck(parentNode);
}
}
function editorNodeChange(e) {
//We don't really need two events...
if (e.selectionChange) {
return;
}
var previousParentNode = currentParentNode;
currentParentNode = getParentBlock(e.element);
//If the node we just changed from is the exact same as the current node
//we should prevent sending a request
if (previousParentNode === currentParentNode) {
return;
}
if (previousParentNode) {
spellcheck(previousParentNode);
}
}
function editorContextMenu(e) {
var target = e.target;
if (DOMUtils.DOM.hasClass(target, wordClass)) {
var spans = findSpansByIndex(getElmIndex(target), getParentBlock(target));
if (spans.length > 0) {
var rng = editor.dom.createRng();
rng.setStartBefore(spans[0]);
rng.setEndAfter(spans[spans.length - 1]);
editor.selection.setRng(rng);
showSuggestions(target.getAttribute('data-mce-word'), spans, e);
}
e.preventDefault();
e.stopImmediatePropagation();
}
}
function bindEvents() {
editor.on('remove', editorRemove);
editor.on('keydown', editorKeydown);
editor.on('keyup', editorKeyup);
editor.on('nodechange', editorNodeChange);
}
function unBindEvents() {
editor.off('remove', editorRemove);
editor.off('keydown', editorKeydown);
editor.off('keyup', editorKeyup);
editor.off('nodechange', editorNodeChange);
}
editor.on('contextmenu', editorContextMenu, true);
bindEvents();
this.getTextMatcher = getTextMatcher;
this.getWordCharPattern = getWordCharPattern;
this.markErrors = markErrors;
this.getLanguage = function() {
return settings.spellchecker_language;
};
// Set default spellchecker language if it's not specified
settings.spellchecker_language = settings.spellchecker_language || settings.language || 'en';
});
});
expose(["tinymce/tinymcespellcheckerplugin/DomTextMatcher","tinymce/tinymcespellcheckerplugin/SpellingCache"]);
})(this);<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
/* global window*/
jQuery.sap.require('sap.apf.ui.utils.helper');
/**
*@class stepToolbar
*@name stepToolbar
*@memberOf sap.apf.ui.reuse.controller
*@description controller for view.stepToolbar
*/
sap.ui.controller("sap.apf.ui.reuse.controller.stepToolbar", {
/**
*@this {sap.apf.ui.reuse.controller.stepToolbar}
*/
chartIconInserted: false,
alternateRepresentationIcon: false,
alternateRepresentationBool: false,
selectedRepresentation: null,
alternateRepresentationBtn: {},
selectedNumber: null,
selectedNumberLink: null,
isSwitchRepresentation: false,
viewSettingsIcon: null,
onInit: function() {
this.oCoreApi = this.getView().getViewData().oCoreApi;
this.oUiApi = this.getView().getViewData().uiApi;
if (sap.ui.Device.system.desktop) {
this.getView().addStyleClass("sapUiSizeCompact");
}
},
/**
*@memberOf sap.apf.ui.reuse.controller.stepToolbar
*@method addCompactStyleClassForDialog
*@param Dialog Instance on which style class has to be applied
*@description Sets compact mode for dialogs when application is running in desktop
*/
addCompactStyleClassForDialog: function(oDialog) {
if (sap.ui.Device.system.desktop) {
oDialog.addStyleClass("sapUiSizeCompact");
}
},
/**
*@memberOf sap.apf.ui.reuse.controller.stepToolbar
*@method drawAlternateRepresentation
*@description Inserts the alternate representation icon to the chart toolbar
*/
drawAlternateRepresentation: function() {
var that = this;
this.alternateRepresentationBtn = new sap.m.Button({
icon: this.oCoreApi.getActiveStep().getSelectedRepresentation().getAlternateRepresentation().picture,
tooltip: this.oCoreApi.getTextNotHtmlEncoded("TableRepresentation"),
press: function() {
var oStep = that.oCoreApi.getActiveStep();
var currentRepresentation = oStep.getSelectedRepresentation();
var activeStepIndex = that.oCoreApi.getSteps().indexOf(oStep);
that.selectedRepresentation = "table";
currentRepresentation.bIsAlternateView = true;
if (currentRepresentation.toggleInstance === undefined) {
currentRepresentation.toggleInstance = that.oUiApi.getStepContainer().getController().createAlternateRepresentation(activeStepIndex);
} else {
var data = currentRepresentation.getData(),
metadata = currentRepresentation.getMetaData();
if (data !== undefined && metadata !== undefined) {
currentRepresentation.toggleInstance.setData(data, metadata);
}
currentRepresentation.toggleInstance.adoptSelection(currentRepresentation);
}
that.oUiApi.getAnalysisPath().getController().refresh(-1);
that.oUiApi.getStepContainer().getController().drawStepContent();
that.oUiApi.getAnalysisPath().getCarousel().getStepView(activeStepIndex).getController().drawThumbnailContent(true);
}
}).addStyleClass("alternateButton");
this.insertViewSettingsIcon();
this.getView().chartToolbar.getToolBar().insertContentRight(this.alternateRepresentationBtn);
},
/**
*@memberOf sap.apf.ui.reuse.controller.stepToolbar
*@method drawMultipleRepresentation
*@description Method to insert icons for multiple representations
*/
insertViewSettingsIcon: function() {
var that = this;
var viewSettingsDialog;
this.sortButton = new sap.m.Button({
icon: "sap-icon://drop-down-list",
tooltip: this.oCoreApi.getTextNotHtmlEncoded("view-Settings"),
press: function() {
if (that.oCoreApi.getActiveStep().getSelectedRepresentation().type !== sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
viewSettingsDialog = that.oCoreApi.getActiveStep().getSelectedRepresentation().toggleInstance.viewSettingsDialog;
that.addCompactStyleClassForDialog(viewSettingsDialog);
viewSettingsDialog.open();
} else {
viewSettingsDialog = that.oCoreApi.getActiveStep().getSelectedRepresentation().viewSettingsDialog;
that.addCompactStyleClassForDialog(viewSettingsDialog);
viewSettingsDialog.open();
}
}
}).addStyleClass("sortButton");
this.getView().chartToolbar.getToolBar().insertContentRight(this.sortButton);
},
/**
*@memberOf sap.apf.ui.reuse.controller.stepToolbar
*@method showSelectionCount
*@description Shows the selected count(label) and delete icon of the representation
*/
showSelectionCount: function() {
var oActiveStep = this.oCoreApi.getActiveStep();
var selectedRepresentation = oActiveStep.getSelectedRepresentation();
var selectionCount = selectedRepresentation.getSelections().length || selectedRepresentation.getSelectionCount(); // read the selections from selection count or selections, which ever is available
var bRequirefFilterPresent = selectedRepresentation.getParameter().requiredFilters !== undefined && selectedRepresentation.getParameter().requiredFilters.length !== 0;
var bMetadataPresent = selectedRepresentation.getMetaData !== undefined && selectedRepresentation.getMetaData() !== undefined && selectedRepresentation.getMetaData().hasOwnProperty("getPropertyMetadata");
var selectedDimension = bRequirefFilterPresent && bMetadataPresent ? selectedRepresentation.getMetaData().getPropertyMetadata(selectedRepresentation.getParameter().requiredFilters[0]).label : null;
if (selectedDimension === null || selectionCount === 0) {
jQuery(".showSelection").hide();
jQuery(".resetSelection").hide();
} else if (selectionCount > 0) {
this.selectedNumber.setText("(" + this.oCoreApi.getTextNotHtmlEncoded("selected-objects", [selectedDimension]));
this.selectedNumberLink.setText(selectionCount);
this.selectedNumberEndText.setText(')');
jQuery(".showSelection").show();
jQuery(".resetSelection").show();
}
},
/**
*@memberOf sap.apf.ui.reuse.controller.stepToolbar
*@method insertContentLeft
*@description Inserts the Selection label,count and delete icon to the step toolbar
*/
insertContentLeft: function() {
var that = this;
// insert left content to the toolbar
this.currentStepText = new sap.m.Label({
wrapping: true,
text: this.oCoreApi.getTextNotHtmlEncoded("currentStep")
}).addStyleClass("currentStep");
this.selectedNumber = new sap.m.Label({
wrapping: true
}).addStyleClass("showSelection");
this.selectedNumberEndText = new sap.m.Label({
wrapping: true
}).addStyleClass("showSelection");
this.selectedNumberEndText.addStyleClass("selectedNumberEndText");
this.selectedNumberLink = new sap.m.Link({
press: function() {
if (that.selectionDisplayDialog) {
that.selectionDisplayDialog.destroy();
}
that.selectionDisplayDialog = new sap.ui.jsfragment("sap.apf.ui.reuse.fragment.selectionDisplay", that);
that.addCompactStyleClassForDialog(that.selectionDisplayDialog);
that.selectionDisplayDialog.open();
}
}).addStyleClass("showSelection");
this.selectedNumberLink.addStyleClass("selectedNumberLink");
// delete icon for selected items
this.resetSelection = new sap.m.Link({
text: this.oCoreApi.getTextNotHtmlEncoded("resetSelection")
}).attachPress(function() {
jQuery(".showSelection").hide();
jQuery(".resetSelection").hide();
if (that.oCoreApi.getActiveStep().getSelectedRepresentation().bIsAlternateView) {
that.oCoreApi.getActiveStep().getSelectedRepresentation().toggleInstance.removeAllSelection();
}
that.oCoreApi.getActiveStep().getSelectedRepresentation().removeAllSelection();
}).addStyleClass("resetSelection");
this.getView().chartToolbar.getToolBar().insertContentRight(this.resetSelection);
this.getView().chartToolbar.getToolBar().insertContentLeft(this.selectedNumberEndText);
this.getView().chartToolbar.getToolBar().insertContentLeft(this.selectedNumberLink);
this.getView().chartToolbar.getToolBar().insertContentLeft(this.selectedNumber);
this.getView().chartToolbar.getToolBar().insertContentLeft(this.currentStepText);
},
/**
*@memberOf sap.apf.ui.reuse.controller.stepToolbar
*@method drawSingleRepresentation
*@description Method to insert icon for single representation
*/
drawSingleRepresentation: function() {
var that = this;
var activeStep = this.oCoreApi.getActiveStep();
activeStep.selectedRepresentaionType = activeStep.getSelectedRepresentationInfo();
if (activeStep.selectedRepresentaionType.parameter && activeStep.selectedRepresentaionType.parameter.orderby) {
var representationSortDetail = new sap.apf.ui.utils.Helper(that.oCoreApi).getRepresentationSortInfo(activeStep.selectedRepresentaionType);
activeStep.selectedRepresentaionType.sortDescription = representationSortDetail;
}
var selectedMultipleRepresentationBtn = new sap.m.Button({
icon: activeStep.selectedRepresentaionType.picture,
tooltip: this.oCoreApi.getTextNotHtmlEncoded(activeStep.selectedRepresentaionType.label) + "\n" + ((activeStep.selectedRepresentaionType.sortDescription !== undefined) ? this.oCoreApi.getTextNotHtmlEncoded("sortBy") + ": " + activeStep.selectedRepresentaionType.sortDescription : ""),
press: function() {
var oStep = that.oCoreApi.getActiveStep();
var currentRepresentation = oStep.getSelectedRepresentation();
currentRepresentation.bIsAlternateView = false;
that.oUiApi.getStepContainer().getController().drawStepContent();
var activeStepIndex = that.oCoreApi.getSteps().indexOf(oStep);
that.oUiApi.getAnalysisPath().getCarousel().getStepView(activeStepIndex).getController().drawThumbnailContent(true);
}
});
this.getView().chartToolbar.getToolBar().insertContentRight(selectedMultipleRepresentationBtn, 0);
this.insertContentLeft();
},
/**
*@memberOf sap.apf.ui.reuse.controller.stepToolbar
*@method drawMultipleRepresentation
*@description Method to insert icons for multiple representations
*/
drawMultipleRepresentation: function() {
var that = this;
var activeStep = this.oCoreApi.getActiveStep();
activeStep.representationtypes = activeStep.getRepresentationInfo();
activeStep.representationtypes.forEach(function(oRepresentation) {
if (oRepresentation.parameter && oRepresentation.parameter.orderby) { //if orderby has a value then only get the sort description
var representationSortDetail = new sap.apf.ui.utils.Helper(that.oCoreApi).getRepresentationSortInfo(oRepresentation);
oRepresentation.sortDescription = representationSortDetail;
}
});
activeStep.selectedRepresentaionType = activeStep.getSelectedRepresentationInfo();
if (activeStep.selectedRepresentaionType.parameter && activeStep.selectedRepresentaionType.parameter.orderby) {
var representationSortDetail = new sap.apf.ui.utils.Helper(this.oCoreApi).getRepresentationSortInfo(activeStep.selectedRepresentaionType);
activeStep.selectedRepresentaionType.sortDescription = representationSortDetail;
}
var reperesentationTypesLength = activeStep.representationtypes.length;
var selectedMultipleRepresentationBtn;
var drawSelectedRepresentation = function(data) {
var activeStep = that.oCoreApi.getSteps()[data.nActiveStepIndex];
activeStep.getSelectedRepresentation().bIsAlternateView = false;
activeStep.setSelectedRepresentation(data.oRepresentationType.representationId);
that.oUiApi.getAnalysisPath().getController().refresh(data.nActiveStepIndex);
that.oCoreApi.updatePath(that.oUiApi.getAnalysisPath().getController().callBackForUpdatePath.bind(that.oUiApi.getAnalysisPath().getController()));
};
this.openList = function(oEvent) {
var data = oEvent.getParameter("listItem").getCustomData()[0].getValue();
drawSelectedRepresentation(data);
selectedMultipleRepresentationBtn.setIcon(data.icon);
selectedMultipleRepresentationBtn.setTooltip(that.oCoreApi.getTextNotHtmlEncoded(data.oRepresentationType.label) + "\n" + (data.oRepresentationType.sortDescription !== undefined ? that.oCoreApi.getTextNotHtmlEncoded("sortBy") + ": " + data.oRepresentationType.sortDescription : ""));
};
var oAllChartList = new sap.m.List({
mode: sap.m.ListMode.SingleSelectMaster,
showSeparators: sap.m.ListSeparators.None,
includeItemInSelection: true,
select: jQuery.proxy(function(oEvent) {
this.openList(oEvent);
}, this)
});
var bAdaptTitleSize = sap.ui.Device.system.desktop ? false : true;
for (var j = 0; j < reperesentationTypesLength; j++) {
var oItem = new sap.m.StandardListItem({
description: activeStep.representationtypes[j].sortDescription && this.oCoreApi.getTextNotHtmlEncoded("sortBy") + ": " + activeStep.representationtypes[j].sortDescription,
icon: activeStep.representationtypes[j].picture,
title: that.oCoreApi.getTextNotHtmlEncoded(activeStep.representationtypes[j].label),
adaptTitleSize: bAdaptTitleSize,
customData: [new sap.ui.core.CustomData({
key: 'data',
value: {
oRepresentationType: activeStep.representationtypes[j],
nActiveStepIndex: that.oCoreApi.getSteps().indexOf(that.oCoreApi.getActiveStep()),
icon: activeStep.representationtypes[j].picture
}
})]
});
if (sap.ui.Device.system.desktop) {
oItem.addStyleClass("repItem");
}
oAllChartList.addItem(oItem);
}
var oShowAllChartPopover = new sap.m.Popover({
placement: sap.m.PlacementType.Bottom,
showHeader: false,
content: [oAllChartList]
}).addStyleClass("sapCaUiChartToolBarShowAllChartListPopover");
//full-screen buttons
function fnPress(oEvent) {
var data = oEvent.getSource().getCustomData()[0].getValue();
drawSelectedRepresentation(data);
}
for (var k = 0; k < reperesentationTypesLength; k++) {
var button = new sap.m.Button({
tooltip: that.oCoreApi.getTextNotHtmlEncoded(activeStep.representationtypes[k].label) + "\n" + ((activeStep.representationtypes[k].sortDescription !== undefined) ? this.oCoreApi.getTextNotHtmlEncoded("sortBy") + ": " + activeStep.representationtypes[k].sortDescription : ""),
icon: activeStep.representationtypes[k].picture,
customData: [new sap.ui.core.CustomData({
key: 'data',
value: {
oRepresentationType: activeStep.representationtypes[k],
nActiveStepIndex: that.oCoreApi.getSteps().indexOf(that.oCoreApi.getActiveStep()),
icon: activeStep.representationtypes[k].picture
}
})],
press: fnPress
});
button.addStyleClass("iconLeft");
this.getView().chartToolbar.getToolBar().insertContentRight(button);
}
selectedMultipleRepresentationBtn = new sap.m.Button({
icon: activeStep.selectedRepresentaionType.picture,
tooltip: this.oCoreApi.getTextNotHtmlEncoded(activeStep.selectedRepresentaionType.label) + "\n" + ((activeStep.selectedRepresentaionType.sortDescription !== undefined) ? this.oCoreApi.getTextNotHtmlEncoded("sortBy") + ": " + activeStep.selectedRepresentaionType.sortDescription : ""),
press: function() {
oShowAllChartPopover.openBy(this);
}
}).addStyleClass("iconList");
this.getView().chartToolbar.getToolBar().insertContentRight(selectedMultipleRepresentationBtn, 0);
this.insertContentLeft();
},
/**
*@memberOf sap.apf.ui.reuse.controller.stepToolbar
*@method drawToolBar
*@description renders the toolbar specific for single or multiple representations and shows/hide legend icon/alternate representation icon
*/
drawToolBar: function() {
var that = this;
this.showAndHideIcons = function() {
var that = this;
that.isSwitchRepresentation = false;
if (that.getView().chartToolbar.getFullScreen() === true) {
//full-screen
jQuery(".iconList").hide();
jQuery(".iconLeft").show();
} else {
//initial
jQuery(".iconList").show();
jQuery(".iconLeft").hide();
}
//show table sort icon, show only if the representation is table and if the alternate representation is table
if ((that.oCoreApi.getActiveStep().getSelectedRepresentation().bIsAlternateView && that.oCoreApi.getActiveStep().getSelectedRepresentation().getAlternateRepresentation().id === sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) || that.oCoreApi.getActiveStep().getSelectedRepresentation().type === sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
jQuery(".sortButton").show();
} else {
jQuery(".sortButton").hide();
}
// selection count and label
if (that.oCoreApi.getSteps().length >= 1) {
that.showSelectionCount();
}
// for iPhone and when screen resizes, the chartToolbar width will be equal to window width
var toolbarId = that.getView().chartToolbar.getId();
if (that.oCoreApi.getActiveStep().getSelectedRepresentation().getAlternateRepresentation() !== undefined) {
if ((!that.oCoreApi.getActiveStep().getSelectedRepresentation().bIsAlternateView && that.oCoreApi.getActiveStep().getSelectedRepresentation().getAlternateRepresentation().id !== sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) || that.oCoreApi.getActiveStep().getSelectedRepresentation().type !== sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
if ((window.innerWidth === jQuery("#" + toolbarId + " > div:first-child > div:nth-child(2)").width())) {
jQuery(that.getView().chartToolbar._oShowLegendButton.getDomRef()).show();
}
}
}
};
this.renderIcons = function() {
var that = this;
var oActiveStep = that.oCoreApi.getActiveStep();
if (oActiveStep !== undefined) {
//tooltip added for fullscreen
that.getView().chartToolbar._oFullScreenButton.setTooltip(that.oCoreApi.getTextNotHtmlEncoded("toggle-fullscreen"));
that.getView().chartToolbar._oFullScreenExitButton.setTooltip(that.oCoreApi.getTextNotHtmlEncoded("toggle-fullscreen"));
//draw table
if (that.alternateRepresentationIcon === false && that.oCoreApi.getActiveStep().getSelectedRepresentation().type !== sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
that.drawAlternateRepresentation();
that.alternateRepresentationIcon = true;
}
//table sort icon
if (that.oCoreApi.getActiveStep().getSelectedRepresentation().type === sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
if (that.viewSettingsIcon === false) {
that.insertViewSettingsIcon();
}
that.viewSettingsIcon = true;
}
//draw representation
if (that.oCoreApi.getActiveStep().getRepresentationInfo().length > 1) {
if (that.chartIconInserted === false) {
that.drawMultipleRepresentation();
}
that.chartIconInserted = true;
} else if (that.oCoreApi.getActiveStep().getRepresentationInfo().length === 1) { // table representation can exists as single representation
if (that.chartIconInserted === false) {
that.drawSingleRepresentation();
}
that.chartIconInserted = true;
}
//Disable if the representation is table or geomap
if ((that.oCoreApi.getActiveStep().getSelectedRepresentation().bIsAlternateView && that.oCoreApi.getActiveStep().getSelectedRepresentation().getAlternateRepresentation().id === sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) || that.oCoreApi.getActiveStep().getSelectedRepresentation().type === (sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION || sap.apf.ui.utils.CONSTANTS.representationTypes.GEO_MAP)) {
that.getView().chartToolbar._oShowLegendButton.setVisible(false);
} else {
that.getView().chartToolbar._oShowLegendButton.setVisible(true);
that.getView().chartToolbar._oShowLegendButton.setTooltip(that.oCoreApi.getTextNotHtmlEncoded("legend"));
}
//If representation is switched then show the legend
if (that.isSwitchRepresentation === true) {
that.getView().chartToolbar.setShowLegend(true);
}
}
};
this.getView().chartToolbar.addEventDelegate({
onAfterRendering: function() {
if (that.oCoreApi.getSteps().length > 0) {
that.showAndHideIcons();
}
var oStep = that.oCoreApi.getActiveStep();
if (oStep) { //If step exists then toggle the legend
var currentRepresentation = oStep.getSelectedRepresentation();
var formatString;
var stepRepresentation = oStep.getSelectedRepresentation().chart || {};
//Show/Hide Legend
if (currentRepresentation.bIsLegendVisible === true || currentRepresentation.bIsLegendVisible === undefined) {
if (stepRepresentation.setVizProperties) { //Check if Viz Frame Charts
stepRepresentation.setVizProperties({
legend: {
visible: true
},
sizeLegend: {
visible: true
}
});
} else { //Fallback for Viz Charts
if (stepRepresentation.setLegend !== undefined) {
stepRepresentation.setLegend(new sap.viz.ui5.types.legend.Common({
visible: true,
title: new sap.viz.ui5.types.legend.Common_title({
visible: true
})
}));
}
if (stepRepresentation.setSizeLegend !== undefined) {
formatString = stepRepresentation.getSizeLegend().getFormatString();
stepRepresentation.setSizeLegend(new sap.viz.ui5.types.legend.Common({
visible: true,
title: new sap.viz.ui5.types.legend.Common_title({
visible: true
})
}));
if (formatString !== null) {
stepRepresentation.getSizeLegend().setFormatString(formatString);
}
}
}
} else {
if (stepRepresentation.setVizProperties) { //Check if Viz Frame Charts
stepRepresentation.setVizProperties({
legend: {
visible: false
},
sizeLegend: {
visible: false
}
});
} else { //Fallback for Viz Charts
if (stepRepresentation.setLegend !== undefined) {
stepRepresentation.setLegend(new sap.viz.ui5.types.legend.Common({
visible: false,
title: new sap.viz.ui5.types.legend.Common_title({
visible: false
})
}));
}
if (stepRepresentation.setSizeLegend !== undefined) {
formatString = stepRepresentation.getSizeLegend().getFormatString();
stepRepresentation.setSizeLegend(new sap.viz.ui5.types.legend.Common({
visible: false,
title: new sap.viz.ui5.types.legend.Common_title({
visible: false
})
}));
if (formatString !== null) {
stepRepresentation.getSizeLegend().setFormatString(formatString);
}
}
}
}
}
},
onBeforeRendering: function() {
if (that.oCoreApi.getSteps().length > 0) {
that.renderIcons();
}
}
});
},
/**
*@memberOf sap.apf.ui.reuse.controller.stepToolbar
*@method drawRepresentation
*@description This method clears the toolbar content, insert chart and renders toolbar
*/
drawRepresentation: function(oChart) {
var that = this;
this.isSwitchRepresentation = true;
this.getView().chartToolbar.getToolBar().removeAllContentLeft();
this.getView().chartToolbar.getToolBar().removeAllContentRight();
this.chartIconInserted = false;
this.alternateRepresentationIcon = false;
this.viewSettingsIcon = false;
this.getView().chartToolbar.removeAllCharts();
this.getView().chartToolbar.insertChart(oChart);
if (this.getView().chartToolbar.getFullScreen() === true) {
this.getView().chartToolbar.rerender(); //re-render's main chart on fullscreen
//re-render the table after the selection mode is changed
if (this.oCoreApi.getActiveStep().getSelectedRepresentation().bIsAlternateView || this.oCoreApi.getActiveStep().getSelectedRepresentation().type === sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
var selectionMode = this.oCoreApi.getActiveStep().getSelectedRepresentation().getParameter().requiredFilters.length > 0 ? "MultiSelect" : "None";
this.getView().chartToolbar.getCharts()[0].getContent()[0].getContent()[1].getContent()[0].setMode(selectionMode);
this.getView().chartToolbar.getCharts()[0].getContent()[0].getContent()[1].getContent()[0].rerender();
}
}
this.drawToolBar();
//Handle Legend Show/Hide Mapped to Representations
this.getView().chartToolbar.onAfterRendering = function() {
var legendIcon = this._oShowLegendButton.getDomRef();
//Bind Click Event on legend icon to switch the state of hide/show boolean
var evtType = sap.ui.Device.browser.mobile ? "tap" : "click";
jQuery(legendIcon).on(evtType, function() {
var oStep = that.oCoreApi.getActiveStep();
var currentRepresentation = oStep.getSelectedRepresentation();
if (currentRepresentation.bIsLegendVisible === true || currentRepresentation.bIsLegendVisible === undefined) {
currentRepresentation.bIsLegendVisible = false;
} else {
currentRepresentation.bIsLegendVisible = true;
}
});
};
}
});<file_sep>/* @copyright */
/**
* Constructor for the Feed Component.
*
* Accepts an object literal <code>mSettings</code> that defines initial
* property values, aggregated and associated objects as well as event handlers.
*
*
* @param {string} [sId] id for the new component, generated automatically if no id is given
* @param {map} [mSettings] initial settings for the new component. See the documentation of the component's properties for the structure of the expected data.
*
* @class
* The Feed Component is an SAPUI5 component that allows you to display SAP Jam feeds.
* It includes the option to add new posts and reply to entries and view other users' social profiles from SAP Jam,
*
* @extends sap.ui.core.UIComponent
* @version ${version}
* @since 1.30
*
* @constructor
* @public
* @name sap.collaboration.components.feed.Component
*
*/
(function() {
var sComponentName = "sap.collaboration.components.feed.Component";
jQuery.sap.require("sap.ui.core.UIComponent");
jQuery.sap.require("sap.suite.ui.commons.library");
jQuery.sap.declare(sComponentName);
sap.ui.core.UIComponent.extend(sComponentName, {
metadata : {
stereotype: "component",
version: "1.0",
includes: ["../resources/css/MorePopover.css"],
dependencies: {
libs: [],
components: [],
ui5version: ""
},
library: "sap.collaboration",
properties: {
"axisOrientation": {type:"sap.suite.ui.commons.TimelineAxisOrientation",group:"Misc",defaultValue:sap.suite.ui.commons.TimelineAxisOrientation.Vertical},
"feedSources": {type:"object|string[]"}
},
rootView : null, // the rootView to open (view name as string or view configuration object)
publicMethods: [ "setSettings", "getSelectedGroup" ],
aggregations: {
},
routing: {
},
config: {
},
customizing: {
}
},
/**
* Initializes the Component instance after creation.
* @protected
* @memberOf sap.collaboration.components.feed.Component
*/
init: function() {
this._logger = new jQuery.sap.log.getLogger(sComponentName);
sap.ui.core.UIComponent.prototype.init.apply(this); // call superclass; needed to call createContent
},
/**
* Cleans up the component instance before destruction.
* @protected
* @memberOf sap.collaboration.components.feed.Component
*/
exit: function() {
},
/**
* Function is called when the rendering of the Component Container is started.
* @protected
* @memberOf sap.collaboration.components.feed.Component
*/
onBeforeRendering: function() {
},
/**
* Function is called when the rendering of the Component Container is completed.
* @protected
* @memberOf sap.collaboration.components.feed.Component
*/
onAfterRendering: function() {
},
/**
* The method to create the Content (UI Control Tree) of the Component.
* @protected
* @memberOf sap.collaboration.components.feed.Component
*/
createContent: function() {
this._view = sap.ui.view({
id: this.createId("group_feed_view"),
height: "100%",
type:sap.ui.core.mvc.ViewType.XML,
viewName:"sap.collaboration.components.feed.views.GroupFeed"
});
this.setAxisOrientation(this.getAxisOrientation());
return this._view;
},
/**
* Sets all the properties passed in oSettings.
* @param {map} settings - key/value map for settings
* @memberOf sap.collaboration.components.feed.Component
* @public
*/
setSettings: function(settings) {
for(var key in settings) {
if(settings.hasOwnProperty(key)) {
this._setProperty(key, settings[key]);
}
}
},
/**
* Returns the selected Group.
* @memberOf sap.collaboration.components.feed.Component
* @return {map} a map containing information about the selected Group (e.g. Id, Name, etc...)
* @public
*/
getSelectedGroup: function() {
return this._view.getModel().getProperty("/groupSelected");
},
/**
* Set the property's new value in the component and in the view's model
* @param {string} propertyName
* @param {string} propertyValue
* @memberOf sap.collaboration.components.feed.Component
*/
_setProperty: function(propertyName, propertyValue) {
this._logger.info(propertyName + ": " + propertyValue);
this._view.getModel().setProperty("/" + propertyName, propertyValue);
this.setProperty(propertyName, propertyValue);
},
/**
* Set the axis orientation for the timeline
*
* @override
* @param {sap.suite.ui.commons.TimelineAxisOrientation} axisOrientation
* @memberOf sap.collaboration.components.feed.Component
*/
setAxisOrientation: function(axisOrientation) {
this._setProperty("axisOrientation", axisOrientation);
},
/**
* Sets the sources for the feed
* - Array of strings representing the Jam group IDs (e.g. ["groupid1", "groupid2"])
*
* @override
* @param {object} feedSources
* @memberOf sap.collaboration.components.feed.Component
*/
setFeedSources: function(feedSources) {
this._setProperty("feedSources", feedSources);
}
});
})();
<file_sep>/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// -------------------------------------------------------------------------------
// Generates the view metadata required for a field using SAP-Annotations metadata
// -------------------------------------------------------------------------------
sap.ui.define([
'jquery.sap.global', 'sap/m/CheckBox', 'sap/m/ComboBox', 'sap/m/DatePicker', 'sap/m/TimePicker', 'sap/m/HBox', 'sap/m/Input', 'sap/m/Text', 'sap/ui/comp/navpopover/SmartLink', 'sap/ui/comp/odata/MetadataAnalyser', 'sap/ui/comp/smartfield/ODataHelper', 'sap/ui/comp/smartfield/SmartField', 'sap/ui/comp/odata/ODataType', 'sap/ui/comp/util/FormatUtil'
], function(jQuery, CheckBox, ComboBox, DatePicker, TimePicker, HBox, Input, Text, SmartLink, MetadataAnalyser, ODataHelper, SmartField, ODataType, FormatUtil) {
"use strict";
// TODO: CleanUp!
/**
* Constructs a class to generate the view/data model metadata for the controls - that can be used in table/forms etc.
*
* @constructor
* @experimental This module is only for internal/experimental use!
* @public
* @param {object} mPropertyBag - PropertyBag having members model, entitySet
* @author <NAME>
*/
var ControlProvider = function(mPropertyBag) {
if (mPropertyBag) {
this._oParentODataModel = mPropertyBag.model;
this._oMetadataAnalyser = mPropertyBag.metadataAnalyser;
this._aODataFieldMetadata = mPropertyBag.fieldsMetadata;
this._oDateFormatSettings = mPropertyBag.dateFormatSettings;
this._bEnableDescriptions = mPropertyBag.enableDescriptions;
this._oCurrencyFormatSettings = mPropertyBag.currencyFormatSettings;
this._oDefaultDropDownDisplayBehaviour = mPropertyBag.defaultDropDownDisplayBehaviour || "descriptionAndId";
this.useSmartField = mPropertyBag.useSmartField === "true";
this._sEntitySet = mPropertyBag.entitySet;
}
if (!this._oMetadataAnalyser && this._oParentODataModel) {
this._oMetadataAnalyser = new MetadataAnalyser(this._oParentODataModel);
this._intialiseMetadata();
}
this._mSmartField = {};
this._oHelper = new ODataHelper(this._oMetadataAnalyser.oModel);
this._aValueListProvider = [];
this._aValueHelpProvider = [];
};
/**
* Initialises the necessary metadata
*
* @private
*/
ControlProvider.prototype._intialiseMetadata = function() {
if (!this._aODataFieldMetadata) {
this._aODataFieldMetadata = this._oMetadataAnalyser.getFieldsByEntitySetName(this.sEntity);
}
};
/**
* Get the field metadata
*
* @param {object} oFieldODataMetadata - OData metadata for the field
* @param {boolean} isEditable - specifies if the control shall be editable
* @returns {Object} the field view metadata object
* @public
*/
ControlProvider.prototype.getFieldViewMetadata = function(oFieldODataMetadata, isEditable) {
var oFieldViewMetadata = this._createFieldMetadata(oFieldODataMetadata);
// Create and set the template
this._createFieldTemplate(oFieldViewMetadata, isEditable);
return oFieldViewMetadata;
};
/**
* Creates and extends the field view with a template for the UI content
*
* @param {object} oViewField - the view field metadata
* @param {boolean} isEditable - specifies if the control shall be editable
* @private
*/
ControlProvider.prototype._createFieldTemplate = function(oViewField, isEditable) {
if (this.useSmartField) {
oViewField.template = new SmartField({
value: {
path: oViewField.name
},
entitySet: this._sEntitySet,
contextEditable: {
path: "sm4rtM0d3l>/editable",
mode: "OneWay"
},
controlContext: "table",
wrapping: false
});
if (ODataType.isNumeric(oViewField.type) || ODataType.isDateOrTime(oViewField.type)) {
oViewField.template.setTextAlign("End");
oViewField.template.setWidth("100%");
}
this._completeSmartField(oViewField);
oViewField.template._setPendingEditState(isEditable);
} else {
oViewField.template = isEditable ? this._createEditableTemplate(oViewField) : this._createDisplayOnlyTemplate(oViewField);
}
};
/**
* Completes the Smart Field template, adds especially meta data.
*
* @param {object} oViewField The current meta data
* @private
*/
ControlProvider.prototype._completeSmartField = function(oViewField) {
var oData = {
annotations: {},
path: oViewField.name
};
if (!this._mSmartField.entitySetObject) {
this._mSmartField.entitySetObject = this._oHelper.oMeta.getODataEntitySet(this._sEntitySet);
this._mSmartField.entityType = this._oHelper.oMeta.getODataEntityType(this._mSmartField.entitySetObject.entityType);
}
oData.modelObject = this._oParentODataModel;
oData.entitySetObject = this._mSmartField.entitySetObject;
// ODataHelper expects entitySet and not entitySetObject!
oData.entitySet = this._mSmartField.entitySetObject;
oData.entityType = this._mSmartField.entityType;
this._oHelper.getProperty(oData);
oData.annotations.uom = this._oHelper.getUnitOfMeasure2(oData);
oData.annotations.text = this._oHelper.getTextProperty2(oData);
oData.annotations.lineitem = this._oMetadataAnalyser.getLineItemAnnotation(oData.entitySetObject.entityType);
oData.annotations.semantic = this._oMetadataAnalyser.getSemanticObjectAnnotationFromProperty(oData.property.property);
this._oHelper.getUOMTextAnnotation(oData);
if (oData.property.property["sap:value-list"] || oData.property.property["com.sap.vocabularies.Common.v1.ValueList"]) {
oData.annotations.valuelist = this._oHelper.getValueListAnnotationPath(oData);
if (oData.property.property["sap:value-list"]) {
oData.annotations.valuelistType = oData.property.property["sap:value-list"];
} else {
oData.annotations.valuelistType = this._oMetadataAnalyser.getValueListSemantics(oData.property.property["com.sap.vocabularies.Common.v1.ValueList"]);
}
}
this._oHelper.getUOMValueListAnnotationPath(oData);
delete oData.entitySet;
oViewField.template.data("configdata", {
"configdata": oData
});
oViewField.template.data("dateFormatSettings", this._oDateFormatSettings);
oViewField.template.data("currencyFormatSettings", this._oCurrencyFormatSettings);
oViewField.template.data("defaultDropDownDisplayBehaviour", this._oDefaultDropDownDisplayBehaviour);
if (oData.annotations.uom || ODataType.isNumeric(oViewField.type) || ODataType.isDateOrTime(oViewField.type)) {
var sAlign = oViewField.template.getTextAlign();
if (sAlign === "Initial") {
sAlign = "End";
}
oViewField.align = sAlign;
oViewField.textDirection = "LTR";
}
};
/**
* Creates and extends the field view with a template for editable UI content
*
* @param {object} oViewField - the view field
* @param {boolean} bBlockSmartLinkCreation - if true, no SmartLink is created independent of the semanitcObject notation
* @returns {sap.ui.core.Control} the template control
* @private
*/
ControlProvider.prototype._createEditableTemplate = function(oViewField, bBlockSmartLinkCreation) {
var oTemplate = null, oFormatOptions, oConstraints, oType;
if (oViewField.type === "Edm.DateTime" || oViewField.type === "Edm.DateTimeOffset") {
// Create DatePicker for Date display fields
if (oViewField.displayFormat === "Date") {
oFormatOptions = this._oDateFormatSettings;
oConstraints = {
displayFormat: "Date"
};
oTemplate = new DatePicker({
dateValue: {
path: oViewField.name
}
});
}
} else if (oViewField.type === "Edm.Boolean") {
oTemplate = new CheckBox({
selected: {
path: oViewField.name
}
});
} else if (oViewField.type === "Edm.Decimal") {
oConstraints = {
precision: oViewField.precision,
scale: oViewField.scale
};
}
oType = ODataType.getType(oViewField.type, oFormatOptions, oConstraints);
// semantic link
if (oViewField.semanticObject && (!bBlockSmartLinkCreation)) {
oTemplate = this._createSmartLinkFieldTemplate(oViewField, oType, function() {
var oInnerControl = this._createEditableTemplate(oViewField, true);
// This callback implementation done by SmartLink in the SmartTable - does not take into account that wrapping should be enabled.
// There could also be other issues e.g. w.r.t alignment of the controls.
// Set the wrapping style of SmartLink, also on the inner control.
if (oInnerControl.setWrapping && oViewField.template && oViewField.template.getWrapping) {
oInnerControl.setWrapping(oViewField.template.getWrapping());
}
return oInnerControl;
}.bind(this));
}
// TODO: ComboBox handling!
// Default ==> sap.m.Input
if (!oTemplate) {
if (oViewField.type === "Edm.Time") {
oTemplate = new TimePicker({
value: {
path: oViewField.name,
type: oType
}
});
} else {
oTemplate = new Input({
value: {
path: oViewField.name,
type: oType
}
});
if (oViewField.isMeasureField) {
oTemplate.bindProperty("description", {
path: oViewField.unit
});
oTemplate.setTextAlign("End");
oTemplate.setTextDirection("LTR");
oTemplate.setFieldWidth("80%");
} else if (this._bEnableDescriptions && oViewField.description) {
oTemplate.bindProperty("description", {
path: oViewField.description
});
} else if (ODataType.isNumeric(oViewField.type) || ODataType.isDateOrTime(oViewField.type)) {
oTemplate.setTextAlign("End");
oTemplate.setTextDirection("LTR");
}
if (oViewField.hasValueListAnnotation) {
this._associateValueHelpAndSuggest(oTemplate, oViewField);
}
}
}
return oTemplate;
};
/**
* Associates the control with a ValueHelp Dialog and suggest using the details retrieved from the metadata (annotation)
*
* @param {object} oControl - The control
* @param {object} oFieldViewMetadata - The metadata merged from OData metadata and additional control configuration
* @private
*/
ControlProvider.prototype._associateValueHelpAndSuggest = function(oControl, oFieldViewMetadata) {
// F4 Help with selection list
oControl.setShowValueHelp(true);
this._aValueHelpProvider.push(new sap.ui.comp.providers.ValueHelpProvider({
loadAnnotation: true,
fullyQualifiedFieldName: oFieldViewMetadata.fullName,
metadataAnalyser: this._oMetadataAnalyser,
control: oControl,
model: this._oParentODataModel,
preventInitialDataFetchInValueHelpDialog: true,
dateFormatSettings: this._oDateFormatSettings,
takeOverInputValue: false,
fieldName: oFieldViewMetadata.fieldName,
type: oFieldViewMetadata.type,
maxLength: oFieldViewMetadata.maxLength,
displayFormat: oFieldViewMetadata.displayFormat,
displayBehaviour: oFieldViewMetadata.displayBehaviour,
title: oFieldViewMetadata.label
}));
oControl.setShowSuggestion(true);
oControl.setFilterSuggests(false);
this._aValueListProvider.push(new sap.ui.comp.providers.ValueListProvider({
loadAnnotation: true,
fullyQualifiedFieldName: oFieldViewMetadata.fullName,
metadataAnalyser: this._oMetadataAnalyser,
control: oControl,
model: this._oParentODataModel,
dateFormatSettings: this._oDateFormatSettings,
typeAheadEnabled: true,
aggregation: "suggestionRows",
displayFormat: oFieldViewMetadata.displayFormat,
displayBehaviour: oFieldViewMetadata.displayBehaviour
}));
};
/**
* Creates and extends the field view with a template for display only UI content
*
* @param {object} oViewField - the view field
* @param {boolean} bBlockSmartLinkCreation - if true, no SmartLink is created independent of the semanitcObject notation
* @returns {sap.ui.core.Control} the template control
* @private
*/
ControlProvider.prototype._createDisplayOnlyTemplate = function(oViewField, bBlockSmartLinkCreation) {
var oTemplate = null, oType = null, oFormatOptions, oConstraints, sAlign, sDisplayBehaviour, oBindingInfo;
// Create Date type for Date display fields
if (oViewField.displayFormat === "Date") {
oFormatOptions = this._oDateFormatSettings;
oConstraints = {
displayFormat: "Date"
};
} else if (oViewField.type === "Edm.Decimal") {
oConstraints = {
precision: oViewField.precision,
scale: oViewField.scale
};
}
oType = ODataType.getType(oViewField.type, oFormatOptions, oConstraints);
if (ODataType.isNumeric(oViewField.type) || ODataType.isDateOrTime(oViewField.type)) {
sAlign = "End";
}
if (oViewField.isMeasureField) {
oViewField.textDirection = "LTR";
oTemplate = this._createMeasureFieldTemplate(oViewField, oType);
} else if (oViewField.semanticObject && (!bBlockSmartLinkCreation)) {
oTemplate = this._createSmartLinkFieldTemplate(oViewField, oType, function() {
var oInnerControl = this._createDisplayOnlyTemplate(oViewField, true);
// This callback implementation done by SmartLink in the SmartTable - does not take into account that wrapping should be enabled.
// There could also be other issues e.g. w.r.t alignment of the controls.
// Set the wrapping style of SmartLink, also on the inner control.
if (oInnerControl.setWrapping && oViewField.template && oViewField.template.getWrapping) {
oInnerControl.setWrapping(oViewField.template.getWrapping());
}
return oInnerControl;
}.bind(this));
} else {
oBindingInfo = {
path: oViewField.name,
type: oType
};
if (this._bEnableDescriptions && oViewField.description) {
sDisplayBehaviour = oViewField.displayBehaviour;
oBindingInfo = {
parts: [
{
path: oViewField.name,
type: oType
}, {
path: oViewField.description
}
],
formatter: function(sId, sDescription) {
return FormatUtil.getFormattedExpressionFromDisplayBehaviour(sDisplayBehaviour, sId, sDescription);
}
};
}
oTemplate = new Text({
wrapping: false,
textAlign: sAlign,
textDirection: sAlign === "End" ? "LTR" : undefined,
text: oBindingInfo
});
}
oViewField.align = sAlign;
return oTemplate;
};
/**
* Creates and extends the field view with a template for currency (display only) content
*
* @param {object} oViewField - the view field
* @param {object} oType - the binding data type
* @param {function} fCreateControl - callback function which creates the control which would have been created instead of the SmartLink
* @returns {Object} the template
* @private
*/
ControlProvider.prototype._createSmartLinkFieldTemplate = function(oViewField, oType, fCreateControl) {
var oBindingInfo = {
path: oViewField.name,
type: oType
};
if (this._bEnableDescriptions && oViewField.description) {
oBindingInfo = {
parts: [
{
path: oViewField.name,
type: oType
}, {
path: oViewField.description
}
],
formatter: function(sId, sDescription) {
return FormatUtil.getFormattedExpressionFromDisplayBehaviour(oViewField.displayBehaviour, sId, sDescription);
}
};
}
// semantic link
var oTemplate = new SmartLink({
semanticObject: oViewField.semanticObject,
semanticObjectLabel: oViewField.label,
fieldName: oViewField.name,
text: oBindingInfo
});
oTemplate.setCreateControlCallback(fCreateControl);
return oTemplate;
};
/**
* Creates and extends the field view with a template for currency (display only) content
*
* @param {object} oViewField - the view field
* @param {object} oType - the odata binding data type
* @private
* @returns {Object} the template
*/
ControlProvider.prototype._createMeasureFieldTemplate = function(oViewField, oType) {
var oTemplate, oValueText, oUnitText, bEnableCurrencySymbol = false;
bEnableCurrencySymbol = !!(oViewField.isCurrencyField && this._oCurrencyFormatSettings && this._oCurrencyFormatSettings.showCurrencySymbol);
oValueText = new Text({
wrapping: false,
textAlign: "End",
text: {
parts: [
{
path: oViewField.name,
type: oType
}, {
path: oViewField.unit
}
],
formatter: oViewField.isCurrencyField ? FormatUtil.getAmountCurrencyFormatter() : FormatUtil.getMeasureUnitFormatter(),
useRawValues: oViewField.isCurrencyField
}
});
oUnitText = new Text({
wrapping: false,
textAlign: "Begin",
width: "2.5em",
text: {
path: oViewField.unit,
formatter: bEnableCurrencySymbol ? FormatUtil.getCurrencySymbolFormatter() : undefined
}
});
// Create measure format using HBox --> we need to 2 controls to properly align the value and unit part
oTemplate = new HBox({
justifyContent: "End",
items: [
oValueText, oUnitText
]
});
oTemplate.addStyleClass("sapUiCompUOMInTableLTR");
return oTemplate;
};
/**
* Calculates and sets additional flags and attributes for a field
*
* @param {object} oFieldODataMetadata - OData metadata for the field
* @returns {object} the field view metadata
* @private
*/
ControlProvider.prototype._createFieldMetadata = function(oFieldODataMetadata) {
var oFieldViewMetadata = jQuery.extend({}, oFieldODataMetadata);
oFieldViewMetadata.label = oFieldODataMetadata.fieldLabel || oFieldODataMetadata.name;
oFieldViewMetadata.quickInfo = oFieldODataMetadata.quickInfo || oFieldViewMetadata.label;
oFieldViewMetadata.displayBehaviour = oFieldViewMetadata.displayBehaviour || this._oDefaultDropDownDisplayBehaviour;
oFieldViewMetadata.filterType = this._getFilterType(oFieldODataMetadata);
this._updateValueListMetadata(oFieldViewMetadata, oFieldODataMetadata);
this._setAnnotationMetadata(oFieldViewMetadata);
return oFieldViewMetadata;
};
/**
* Update the metadata for ValueList annotation
*
* @param {Object} oFieldViewMetadata - view metadata for the filter field
* @param {object} oFieldODataMetadata - OData metadata for the filter field
* @private
*/
ControlProvider.prototype._updateValueListMetadata = function(oFieldViewMetadata, oFieldODataMetadata) {
// First check for "sap:value-list" annotation
oFieldViewMetadata.hasValueListAnnotation = oFieldODataMetadata["sap:value-list"] !== undefined;
if (oFieldViewMetadata.hasValueListAnnotation) {
oFieldViewMetadata.hasFixedValues = oFieldODataMetadata["sap:value-list"] === "fixed-values";
} else if (oFieldODataMetadata["com.sap.vocabularies.Common.v1.ValueList"]) {
// Then check for "com.sap.vocabularies.Common.v1.ValueList", and retrieve the semantics
oFieldViewMetadata.hasValueListAnnotation = true;
oFieldViewMetadata.hasFixedValues = this._oMetadataAnalyser.getValueListSemantics(oFieldODataMetadata["com.sap.vocabularies.Common.v1.ValueList"]) === "fixed-values";
}
};
/**
* Set any annotation(s) metadata on the control
*
* @param {Object} oFieldViewMetadata - the field view metadata
* @private
*/
ControlProvider.prototype._setAnnotationMetadata = function(oFieldViewMetadata) {
var mAnnotation = null;
if (!this.useSmartField && oFieldViewMetadata && oFieldViewMetadata.fullName) {
// Update with SemanticObject annotation data
mAnnotation = this._oMetadataAnalyser.getSemanticObjectAnnotation(oFieldViewMetadata.fullName);
if (mAnnotation) {
oFieldViewMetadata.semanticObject = mAnnotation.semanticObject;
}
}
};
/**
* Returns the filterType of the field based on metadata, else undefined
*
* @param {object} oField - OData metadata for the field
* @returns {string} the filter type for the field
* @private
*/
ControlProvider.prototype._getFilterType = function(oField) {
if (ODataType.isNumeric(oField.type)) {
return "numeric";
} else if (oField.type === "Edm.DateTime" && oField.displayFormat === "Date") {
return "date";
} else if (oField.type === "Edm.String") {
return "string";
} else if (oField.type === "Edm.Boolean") {
return "boolean";
} else if (oField.type === "Edm.Time") {
return "time";
}
return undefined;
};
/**
* Destroys the object
*
* @public
*/
ControlProvider.prototype.destroy = function() {
var i;
if (this._oMetadataAnalyser && this._oMetadataAnalyser.destroy) {
this._oMetadataAnalyser.destroy();
}
this._oMetadataAnalyser = null;
if (this._aValueHelpProvider) {
i = this._aValueHelpProvider.length;
while (i--) {
this._aValueHelpProvider[i].destroy();
}
}
this._aValueHelpProvider = null;
if (this._aValueListProvider) {
i = this._aValueListProvider.length;
while (i--) {
this._aValueListProvider[i].destroy();
}
}
if (this._oHelper) {
this._oHelper.destroy();
}
this._oHelper = null;
this._mSmartField = null;
this._aValueListProvider = null;
this._aODataFieldMetadata = null;
this._oCurrencyFormatter = null;
this.bIsDestroyed = true;
};
return ControlProvider;
}, /* bExport= */true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define([
'jquery.sap.global', 'sap/ui/fl/changeHandler/Base', 'sap/ui/fl/Utils'
], function(jQuery, Base, FlexUtils) {
"use strict";
/**
* Change handler for moving of fields within/between groups.
* @constructor
* @alias sap.ui.fl.changeHandler.MoveFields
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*/
var MoveFields = function() {
};
MoveFields.prototype = jQuery.sap.newObject(Base.prototype);
/**
* Moves field(s) within a group or between groups.
*
* @param {object} oChange change object with instructions to be applied on the control
* @param {object} oGroup Smart form group instance which is referred to in change selector section
* @public
*/
MoveFields.prototype.applyChange = function(oChange, oGroup) {
if (!oChange) {
throw new Error("No change instance");
}
var oChangeJson = oChange.getDefinition();
if (!oChangeJson.selector || !oChangeJson.content || !oChangeJson.content.moveFields || oChangeJson.content.moveFields.length === 0 || Object.keys(oChangeJson.selector).length !== 1) {
throw new Error("Change format invalid");
}
if (!oGroup || !oGroup.getGroupElements || !oGroup.getId) {
throw new Error("No smart form group instance supplied");
}
// determine target group of move
var oTargetGroup = oGroup;
var bTargetDiffers = false;
if (oChangeJson.content.targetId) {
var sSourceKey = oGroup.getId();
if (sSourceKey !== oChangeJson.content.targetId) {
oTargetGroup = sap.ui.getCore().byId(oChangeJson.content.targetId);
bTargetDiffers = true;
}
}
// Array of fields of smart form group in old order
var aFields = oGroup.getGroupElements();
if (!aFields) {
return;
}
var iFieldNumber = aFields.length;
// move is within a group - adapt order of fields in aFields according to the change
// move is between groups - remove field from source group and insert it at target group
var oField = {}, oMoveField = {};
var iMoveFields = oChangeJson.content.moveFields.length;
var iIndex, i, j;
for (i = 0; i < iMoveFields; i++) {
oMoveField = oChangeJson.content.moveFields[i];
if (!oMoveField.id) {
throw new Error("Change format invalid - moveFields element has no id attribute");
}
if (typeof (oMoveField.index) !== "number") {
throw new Error("Change format invalid - moveFields element index attribute is no number");
}
// determine the index of the field to move in aFields
iIndex = -1;
for (j = 0; j < iFieldNumber; j++) {
var sControlId = aFields[j].getId();
if (sControlId === oMoveField.id) {
iIndex = j;
break;
}
}
// move within group and position of field is unchanged
if (bTargetDiffers === false && iIndex === oMoveField.index) {
continue;
}
// field not found in source group
if (iIndex === -1) {
continue;
}
// get the field to move
oField = aFields[iIndex];
// move is between groups - remove field from source group
// and insert it at target group
if (bTargetDiffers === true) {
oGroup.removeGroupElement(oField);
oTargetGroup.insertGroupElement(oField, oMoveField.index);
continue;
}
// move is within a group
// remove the field to move from aFields
aFields.splice(iIndex, 1);
// reinsert the field to aFields at the new index
if (bTargetDiffers === false) {
aFields.splice(oMoveField.index, 0, oField);
}
}
// in case of move between groups we are done
if (bTargetDiffers === true) {
return;
}
// remove all fields from smart form group (source)
oGroup.removeAllGroupElements();
// reinsert fields into smart form group in new order (source)
for (i = 0; i < iFieldNumber; i++) {
oGroup.insertGroupElement(aFields[i], i);
}
};
/**
* Completes the change by adding change handler specific content
*
* @param {object} oChange change object to be completed
* @param {object} oSpecificChangeInfo with attribute moveFields which contains an array which holds objects which have attributes
* id and index - id is the id of the field to move and index the new position of the field in the smart form group
* @public
* @function
* @name sap.ui.fl.changeHandler.MoveGroups#completeChangeContent
*/
MoveFields.prototype.completeChangeContent = function(oChange, oSpecificChangeInfo) {
var oChangeJson = oChange.getDefinition();
if (oSpecificChangeInfo.moveFields) {
var oMoveField = {};
var i, iLength = oSpecificChangeInfo.moveFields.length;
if (iLength === 0) {
throw new Error("MoveFields array is empty");
}
for (i = 0; i < iLength; i++) {
oMoveField = oSpecificChangeInfo.moveFields[i];
if (!oMoveField.id) {
throw new Error("MoveFields element has no id attribute");
}
if (typeof (oMoveField.index) !== "number") {
throw new Error("Index attribute at MoveFields element is no number");
}
}
if (!oChangeJson.content) {
oChangeJson.content = {};
}
if (!oChangeJson.content.moveFields) {
oChangeJson.content.moveFields = [];
}
oChangeJson.content.moveFields = oSpecificChangeInfo.moveFields;
if (oSpecificChangeInfo.targetId) {
oChangeJson.content.targetId = oSpecificChangeInfo.targetId;
}
} else {
throw new Error("oSpecificChangeInfo.moveFields attribute required");
}
};
return MoveFields;
},
/* bExport= */true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
sap.ui.define(["jquery.sap.global","sap/ui/fl/changeHandler/HideControl","sap/ui/fl/changeHandler/UnhideControl","sap/ui/fl/changeHandler/MoveElements","sap/ui/fl/changeHandler/PropertyChange"],function(q,H,U,M,P){"use strict";var S={hideControl:{changeType:"hideControl",changeHandler:H},unhideControl:{changeType:"unhideControl",changeHandler:U},moveElements:{changeType:"moveElements",changeHandler:M},propertyChange:{changeType:"propertyChange",changeHandler:P}};return S;},true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
sap.ui.define([
"sap/ui/fl/Utils", "jquery.sap.global", "sap/ui/fl/registry/ChangeRegistryItem", "sap/ui/fl/registry/SimpleChanges", "sap/ui/fl/registry/ChangeTypeMetadata", "sap/ui/fl/registry/Settings"
], function(Utils, jQuery, ChangeRegistryItem, SimpleChanges, ChangeTypeMetadata, Settings) {
"use strict";
/**
* Central registration for available change types on controls
* @constructor
* @alias sap.ui.fl.registry.ChangeRegistry
*
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*
*/
var ChangeRegistry = function() {
this._registeredItems = {};
this.simpleChanges = SimpleChanges;
this.initSettings();
};
ChangeRegistry._instance = undefined;
ChangeRegistry.getInstance = function() {
if (!ChangeRegistry._instance) {
ChangeRegistry._instance = new ChangeRegistry();
}
return ChangeRegistry._instance;
};
ChangeRegistry.prototype.registerControlsForChanges = function(mControlChanges) {
var that = this;
Object.keys(mControlChanges).forEach(function(sControlType){
mControlChanges[sControlType].forEach(function(oChangeType){
that.registerControlForSimpleChange(sControlType, oChangeType);
});
});
};
/**
* Adds registration for a control and a simple change
* @param {String} sControlType - Name of the control, for example "sap.ui.comp.smartfilterbar.SmartFilterBar"
* @param {sap.ui.fl.registry.SimpleChange.member} oSimpleChange - One of the simple changes
*
* @public
*/
ChangeRegistry.prototype.registerControlForSimpleChange = function(sControlType, oSimpleChange) {
var oChangeRegistryItem;
if (!sControlType) {
return;
}
if (!oSimpleChange || !oSimpleChange.changeType || !oSimpleChange.changeHandler) {
return;
}
oChangeRegistryItem = this._createChangeRegistryItemForSimpleChange(sControlType, oSimpleChange);
if (oChangeRegistryItem) {
this.addRegistryItem(oChangeRegistryItem);
}
};
/**
* Adds registration for a control and a simple change
* @param {String} sControlType - Name of the control, for example "sap.ui.comp.smartfilterbar.SmartFilterBar"
* @param {sap.ui.fl.registry.SimpleChange.member} oSimpleChange - One of the simple changes
* @returns {sap.ui.fl.registry.ChangeRegistryItem} the registry item
*
* @public
*/
ChangeRegistry.prototype._createChangeRegistryItemForSimpleChange = function(sControlType, oSimpleChange) {
var mParam, oChangeTypeMetadata, oChangeRegistryItem;
//Create change type metadata
mParam = {
name: oSimpleChange.changeType,
changeHandler: oSimpleChange.changeHandler
};
oChangeTypeMetadata = new ChangeTypeMetadata(mParam);
//Create change registry item
mParam = {
changeTypeMetadata: oChangeTypeMetadata,
controlType: sControlType
};
oChangeRegistryItem = new ChangeRegistryItem(mParam);
return oChangeRegistryItem;
};
/**
* Add a registry item for the controlType and changeType. If the item already exists, it will be overwritten
* @param {sap.ui.fl.registry.ChangeRegistryItem} oRegistryItem the registry item
* @public
*/
ChangeRegistry.prototype.addRegistryItem = function(oRegistryItem) {
var sChangeType, sControlType;
if (!oRegistryItem) {
return;
}
sChangeType = oRegistryItem.getChangeTypeName();
sControlType = oRegistryItem.getControlType();
this._registeredItems[sControlType] = this._registeredItems[sControlType] || {};
this._registeredItems[sControlType][sChangeType] = oRegistryItem;
};
/**
* Remove a registration for:
* - A single change type (only changeTypeName parameter set)
* - The complete registration on a certain control (only controlType parameter set)
* - Or all registrations of a change type on any control (both changeTypeName AND controlType set)
* @param {Object} mParam Description see below
* @param {String} [mParam.changeTypeName] Change type name which should be removed
* @param {String} [mParam.controlType] Control type which should be removed.
*
* @public
*/
ChangeRegistry.prototype.removeRegistryItem = function(mParam) {
if (!mParam.changeTypeName && !mParam.controlType) {
Utils.log.error("sap.ui.fl.registry.ChangeRegistry: ChangeType and/or ControlType required");
return;
}
//Either remove a specific changeType from a specific control type
if (mParam.controlType && mParam.changeTypeName) {
if (this._registeredItems[mParam.controlType]) {
if (Object.keys(this._registeredItems[mParam.controlType]).length === 1) { //only one changeType...
delete this._registeredItems[mParam.controlType];
} else {
delete this._registeredItems[mParam.controlType][mParam.changeTypeName];
}
}
//or remove by control type
} else if (mParam.controlType) {
if (this._registeredItems[mParam.controlType]) {
delete this._registeredItems[mParam.controlType];
}
//or via changeType on all control types
} else if (mParam.changeTypeName) {
for ( var controlTypeKey in this._registeredItems) {
var controlItem = this._registeredItems[controlTypeKey];
delete controlItem[mParam.changeTypeName];
}
}
};
/**
* Get a registration for:
* - All registration items with specific change type name on all controls (only changeTypeName parameter set)
* - The complete registration(s) on a certain control (only controlType parameter set)
* - Or all registrations of a change type name on any control (both changeTypeName AND controlType set)
* @param {Object} mParam Description see below
* @param {String} [mParam.changeTypeName] Change type to find registration(s) for this changeType
* @param {String} [mParam.controlType] Control type to find registration(s) for this controlType
* @param {String} [mParam.layer] Layer where changes are currently applied. If not provided no filtering for valid layers is done.
* @returns {Object} Returns an object in the format
* @example {
* "sap.ui.core.SampleControl":{
* "labelChange":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>},
* "visibility":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>}
* },
* "sap.ui.core.TestControl":{
* "visibility":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>}
* }
* }
* @public
*/
ChangeRegistry.prototype.getRegistryItems = function(mParam) {
if (!mParam.changeTypeName && !mParam.controlType) {
Utils.log.error("sap.ui.fl.registry.ChangeRegistry: Change Type Name and/or Control Type required");
}
var result = null;
if (mParam.controlType && mParam.changeTypeName) {
var controlRegistrations = this._registeredItems[mParam.controlType];
if (controlRegistrations) {
if (controlRegistrations[mParam.changeTypeName]) {
result = {};
result[mParam.controlType] = {};
result[mParam.controlType][mParam.changeTypeName] = controlRegistrations[mParam.changeTypeName];
}
}
} else if (mParam.controlType) {
if (this._registeredItems[mParam.controlType]) {
result = {};
//keep the actual registry items but clone the control-changetype object structure to not modify the registry during filtering
result[mParam.controlType] = {};
jQuery.each(this._registeredItems[mParam.controlType], function(sChangeTypeName, oRegistryItem) {
result[mParam.controlType][sChangeTypeName] = oRegistryItem;
});
}
} else if (mParam.changeTypeName) {
result = {};
for ( var controlTypeKey in this._registeredItems) {
if (this._registeredItems[controlTypeKey][mParam.changeTypeName]) {
result[controlTypeKey] = {};
result[controlTypeKey][mParam.changeTypeName] = this._registeredItems[controlTypeKey][mParam.changeTypeName];
}
}
}
//filter out disabled change types
this._filterChangeTypes(result, mParam.layer);
return result;
};
/**
* Retrieves the Flex Settings for a UI5 component.
*
* @param {string} sComponentName the UI5 component name for which settings are requested;
* if not provided, hardcoded settings will be used.
*
* @private
*/
ChangeRegistry.prototype.initSettings = function(sComponentName) {
this._oSettings = Settings.getInstanceOrUndef(sComponentName);
if (!this._oSettings) {
this._oSettings = new Settings({});
}
};
/**
* Removes registry items that are not enabled for the current writable layer.
* @param {object} oRegistryItems see example
* @param {string} sLayer persistency layer, if not provided no filtering is done.
* @example {
* "sap.ui.core.SampleControl":{
* "labelChange":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>},
* "visibility":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>}
* },
* "sap.ui.core.TestControl":{
* "visibility":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>}
* }
* }
* @private
*/
ChangeRegistry.prototype._filterChangeTypes = function(oRegistryItems, sLayer) {
if (this._oSettings && sLayer && oRegistryItems) {
var that = this;
jQuery.each(oRegistryItems, function(sControlType, oControlReg) {
jQuery.each(oControlReg, function(sChangeType, oRegistryItem) {
var bIsChangeTypeEnabled = that._oSettings.isChangeTypeEnabled(sChangeType, sLayer);
if (!bIsChangeTypeEnabled) {
delete oControlReg[sChangeType];
}
});
});
}
};
ChangeRegistry.prototype.getDragInfo = function(sControlType) {
var controlTypeItems = this._registeredItems[sControlType];
if (controlTypeItems) {
return controlTypeItems.getDragInfo();
}
return null;
};
return ChangeRegistry;
}, true);
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP SE. All rights reserved
*/
jQuery.sap.require("sap.apf.ui.utils.constants");
jQuery.sap.require("sap.apf.core.constants");
jQuery.sap.require("sap.apf.modeler.ui.utils.textPoolHelper");
/**
* @class representation
* @memberOf sap.apf.modeler.ui.controller
* @name representation
* @description controller for view.representation
*/
sap.ui.controller("sap.apf.modeler.ui.controller.representation", {
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#onInit
* @description Called on initialization of the view.
* Sets the static texts for all controls in UI.
* Sets the scroll height for the container.
* Adds style classes to all UI controls.
* Prepares dependencies.
* Sets dynamic text for input controls
* Set a preview button in footer
* */
onInit : function() {
// Data
this.getView().addStyleClass("sapUiSizeCompact");//For non touch devices- compact style class increases the information density on the screen by reducing control dimensions
this.oViewData = this.getView().getViewData();
this.oConfigurationHandler = this.oViewData.oConfigurationHandler;
this.oConfigurationEditor = this.oViewData.oConfigurationEditor;
this.oTextPool = this.oConfigurationHandler.getTextPool();
this.getText = this.oViewData.getText;
this.getEntityTypeMetadata = this.oViewData.getEntityTypeMetadata;
this.getRepresentationTypes = this.oViewData.getRepresentationTypes;
this.mParam = this.oViewData.oParams;
var self = this;
if (!this.oConfigurationEditor) {
this.oConfigurationHandler.loadConfiguration(this.mParam.arguments.configId, function(configurationEditor) {
self.oConfigurationEditor = configurationEditor;
});
}
this._setDisplayText();
this.setDetailData();
// Insert Preview Button into the Footer.
this._oPreviewButton = new sap.m.Button({
text : this.getText("preview"),
press : self._handlePreviewButtonPress.bind(this)
// the current context should be bound to the event handler
});
this._insertPreviewButtonInFooter();
},
onAfterRendering : function() {
this._enableDisableItemsInDisplayOptionOrDisplayOptionBox();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_setDisplayText
* @description Sets static texts in UI and place holders.
* */
_setDisplayText : function() {
this.byId("idVisualization").setTitle(this.getText("visualization"));
this.byId("idChartTypeLabel").setText(this.getText("chartType"));
this.byId("idChartTypeLabel").setTooltip(this.getText("chartType"));
this.byId("idBasicData").setTitle(this.getText("basicData"));
this.byId("idSorting").setTitle(this.getText("sorting"));
this.byId("idThumbnailTexts").setTitle(this.getText("cornerTextLabel"));
this.byId("idLeftUpper").setPlaceholder(this.getText("leftTop"));
this.byId("idRightUpper").setPlaceholder(this.getText("rightTop"));
this.byId("idLeftLower").setPlaceholder(this.getText("leftBottom"));
this.byId("idRightLower").setPlaceholder(this.getText("rightBottom"));
},
/**
* @private
* @description Handler for change event on chartTypes drop down.
* Updates the property drop downs according to the new chart type.
* Updates the representation object with corresponding data.
* Updates the tree node with selected representation type.
* Updates the title and bread crumb.
* @name sap.apf.modeler.ui.controller.representation#handleChangeForChartType
* @param {oEvent} oEvt - Selection Event
**/
handleChangeForChartType : function(oEvt) {
var sNewChartType = oEvt.getParameter("selectedItem").getKey();
var sPrevChart = this.sCurrentChartType;//getting prevChart type
this.sCurrentChartType = sNewChartType;
this._updateAndSetDatasetsByChartType(sNewChartType);
var aRepresentationTypes = sap.apf.ui.utils.CONSTANTS.representationTypes;
var aBarClassChart = aRepresentationTypes.BAR_CHART;
var aColumnClassCharts = [ aRepresentationTypes.COLUMN_CHART, aRepresentationTypes.STACKED_COLUMN_CHART, aRepresentationTypes.PERCENTAGE_STACKED_COLUMN_CHART, aRepresentationTypes.LINE_CHART ];
var bIsBarClassType = (aBarClassChart === sNewChartType);
this.bIsBarClassType = bIsBarClassType;
// Checking selected chart belongs to ColumnClass,Line Chart
var bIsColumnClassType = aColumnClassCharts.indexOf(sNewChartType) !== -1;
//Checking selected chart belongs to same ChartClass
var bIsColumnClassSameType = (aColumnClassCharts.indexOf(sNewChartType) !== -1 && aColumnClassCharts.indexOf(sPrevChart) !== -1);
if (bIsBarClassType || (bIsColumnClassType && !bIsColumnClassSameType)) {
this._switchLabelForCharts();//Switches the text for "BarClassCharts","ColumnClassCharts" & LineChart
}
this.oRepresentation.setRepresentationType(sNewChartType);
var sAlternateRepresentation;
if (sNewChartType !== sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
sAlternateRepresentation = sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION;
}
var sSelectedChartIcon = this._getChartPictureDataset().sSelectedChartPicture;
this.oRepresentation.setAlternateRepresentationType(sAlternateRepresentation);
// Update Tree Node
var sRepresentationTypeText = this.getText(this.oRepresentation.getRepresentationType());
var aStepCategories = this.oConfigurationEditor.getCategoriesForStep(this.oParentStep.getId());
if (aStepCategories.length === 1) {//In case the step of representation is only assigned to one category
this.oViewData.updateSelectedNode({
name : sRepresentationTypeText,
icon : sSelectedChartIcon
});
} else {
this.oViewData.updateTree();
}
var sTitle = this.getText("representation") + ": " + sRepresentationTypeText;
this.oViewData.updateTitleAndBreadCrumb(sTitle);
this.oConfigurationEditor.setIsUnsaved();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_switchLabelForCharts
* @description Get all property rows in basic data layout & reads aggregation role & kind
* */
_switchLabelForCharts : function() {
var oSelf = this;
var oBasicDataLayout = this.byId("idBasicDataLayout").getItems();
var sAggRole, sKind;
oBasicDataLayout.forEach(function(dataLayout) {
//Getting Aggregation role for each property row
sAggRole = dataLayout.getContent()[0].getBindingContext().getProperty("sAggregationRole");
//Getting kind for each property row
sKind = dataLayout.getContent()[0].getBindingContext().getProperty("sKind");
if (sAggRole && sKind) {
var sText = oSelf._createDimMeasForCharts(sAggRole, sKind);
if (sAggRole === "dimension") {
sText = oSelf.getText("display", [ sText ]);
}
dataLayout.getContent()[0].setText(sText);//setting newly created text for property row label
}
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_createDimMeasForCharts
* @return sText :Text for label
* @description Creates text for property row labels(Dimension&Measure)in respect of chart type
*
* */
_createDimMeasForCharts : function(sAggRole, sKind) {
var sHorizontal = sap.apf.core.constants.representationMetadata.kind.XAXIS;
var sVertical = sap.apf.core.constants.representationMetadata.kind.YAXIS;
//if chart is bar and Aggregation role is 'dimension' & sKind is 'Horizontal' set sKind = 'Vertical'
if (sAggRole === "dimension" && sKind === sHorizontal) {
sKind = sHorizontal;
if (this.bIsBarClassType) {
sKind = sVertical;
}
} else if (sAggRole === "measure" && sKind === sVertical) {//if chart is bar and Aggregation role is 'measure' set sKind = 'Horizontal'
sKind = sVertical;
if (this.bIsBarClassType) {
sKind = sHorizontal;
}
}
var sUiAggRole = this.getText(sAggRole);
var sUiKind = this.getText(sKind);
var sText = this.getText("dim-measure-label", [ sUiAggRole, sUiKind ]);
//if chart is dual line with kind of "yAxis" in measure then need to change the label
if (this.bIsDualLineChart && sKind === sVertical && sAggRole === "measure") {
var sUiLeft = this.getText("leftVerticalAxis");
sText = this.getText("dim-measure-label", [ sUiAggRole, sUiLeft ]);
}
return sText; //Newly created text for Label in respect of Chart type
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#handleChangeForCornerText
* @param {oEvent} oEvt - Selection Event
* @description Handler for change event on corner text input boxes.
* Sets the corresponding corner text on the representation object.
* */
handleChangeForCornerText : function(oEvt) {
var oCornerTextInput = oEvt.getSource();
var sCornerTextValue = oCornerTextInput.getValue();
var oTranslationFormat = sap.apf.modeler.ui.utils.TranslationFormatMap.REPRESENTATION_CORNER_TEXT;
var sCornerTextId = this.oTextPool.setText(sCornerTextValue, oTranslationFormat);
var sCornerTextName = oCornerTextInput.getBindingPath('value').replace("/", "");
var sSetCornerTextMethodName = [ "set", sCornerTextName, "CornerTextKey" ].join("");
this.oRepresentation[sSetCornerTextMethodName](sCornerTextId);
this.oConfigurationEditor.setIsUnsaved();
// Run the fall back logic to update the corner text.
this.mDataset.oCornerTextsDataset[sCornerTextName] = this._getCornerTextsDataset()[sCornerTextName];
this.mModel.oCornerTextsModel.updateBindings();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_addAutoCompleteFeatureOnInputs
* @description Adds auto complete feature on all the four corner texts.
* */
_addAutoCompleteFeatureOnInputs : function() {
var oSelf = this;
var oTextPoolHelper = new sap.apf.modeler.ui.utils.TextPoolHelper(this.oTextPool);
// Add Feature on Corner Texts
var oDependenciesForText = {
oTranslationFormat : sap.apf.modeler.ui.utils.TranslationFormatMap.REPRESENTATION_CORNER_TEXT,
type : "text"
};
var aCornerTextInputIds = [ "idLeftUpper", "idRightUpper", "idLeftLower", "idRightLower" ];
aCornerTextInputIds.forEach(function(sId) {
var oInputControl = oSelf.getView().byId(sId);
oTextPoolHelper.setAutoCompleteOn(oInputControl, oDependenciesForText);
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_bindBasicRepresentationData
* @description Binds sap.apf.modeler.ui.controller.representation#mModel.oPropertyModel to Basic Data layout.
* Iteratively binds the data to each and every control in Basic Data Layout.
* */
_bindBasicRepresentationData : function() {
var oSelf = this;
var nPropertyRowIndex, sPathOfPropertyRow, oCopyPropertyRowTemplate, oLabelDisplayOptionBox;
var oBasicDataLayout = this.byId("idBasicDataLayout");
var oPropertyRowTemplate = new sap.ui.layout.Grid({ // add the labels and input control to the grid
width : "100%"
});
// Label
var oAggregationKindLabel = new sap.m.Label({
width : "100%",
textAlign : "End",
layoutData : new sap.ui.layout.GridData({
span : "L2 M2 S2"
}),
text : {
path : "/",
formatter : function() {
var oLabelControl = this, sLabel, sAggRoleText;
var sAggRole = this.getBindingContext().getProperty("sAggregationRole");
var sKind = this.getBindingContext().getProperty("sKind");
var sChartName = oSelf.sCurrentChartType;
var aRepresentationTypes = sap.apf.ui.utils.CONSTANTS.representationTypes;
var aBarClassCharts = [ aRepresentationTypes.BAR_CHART, aRepresentationTypes.STACKED_BAR_CHART, aRepresentationTypes.PERCENTAGE_STACKED_BAR_CHART ];
oSelf.bIsBarClassType = (aBarClassCharts.indexOf(sChartName) !== -1);
oSelf.bIsDualLineChart = (aRepresentationTypes.LINE_CHART_WITH_TWO_VERTICAL_AXES.indexOf(sChartName) !== -1);//Is current chart dual line chart?
if (sAggRole && sKind) {
if (oSelf.bIsBarClassType || oSelf.bIsDualLineChart) { //BarCharts or Dual line Chart
sLabel = oSelf._createDimMeasForCharts(sAggRole, sKind);
} else {
sAggRoleText = oSelf.getText(sAggRole);
sKind = oSelf.getText(sKind);
sLabel = oSelf.getText("dim-measure-label", [ sAggRoleText, sKind ]);
}
if (sAggRole === "dimension") {
sLabel = oSelf.getText("display", [ sLabel ]);
}
oLabelControl.setTooltip(sLabel);
return sLabel;
}
}
}
});
oPropertyRowTemplate.addContent(oAggregationKindLabel);
// Select Box
var oPropertySelectBox = new sap.m.Select({
width : "100%",
layoutData : new sap.ui.layout.GridData(),
items : {
path : "aAllProperties",
template : new sap.ui.core.ListItem({
key : "{sName}",
text : "{sName}"
}),
templateShareable : true
},
selectedKey : "{sSelectedProperty}",
change : oSelf._handleChangeForBasicDataSelectProperty.bind(this)
// the current context should be bound to the event handler
});
oPropertyRowTemplate.addContent(oPropertySelectBox);
// Label for 'Label'
var oLabel = new sap.m.Label({
textAlign : "End",
width : "100%",
layoutData : new sap.ui.layout.GridData({
span : "L2 M2 S2"
}),
text : {
path : "/",
formatter : function() {
var sText;
var sDefaultLabel, sSelectedProperty;
var sLabel = this.getBindingContext().getProperty("sLabel");
var oLabelControl = this;
if (this.getParent().getContent()[1].getSelectedItem()) {
sSelectedProperty = this.getParent().getContent()[1].getSelectedItem().getText();
} else {
sSelectedProperty = this.getBindingContext().getProperty("sSelectedProperty");
}
sText = oSelf.getText("label"); //"label" title has to be displayed
//if label is default , only then it should be overridden
if (sSelectedProperty && sSelectedProperty !== oSelf.getText("none")) {// if a property is selected other than none
var oPropertyMetadata = oSelf.oEntityMetadata.getPropertyMetadata(sSelectedProperty);
sDefaultLabel = oPropertyMetadata.label ? oPropertyMetadata.label : oPropertyMetadata.name;// read the default label from metadata
if (!sLabel || (sLabel && sDefaultLabel && (sLabel === sDefaultLabel))) { // if the label is not defined or label is same as default label
sText = oSelf.getText("label") + "(" + oSelf.getText("default") + ")"; // "Default" has to be prefixed to label title
}
}
oLabelControl.setTooltip(sText);
return sText;
}
}
}).addStyleClass("repFormRightLabel");
oPropertyRowTemplate.addContent(oLabel);
// Input for 'Label'
var oInputLabel = new sap.m.Input({
width : "100%",
layoutData : new sap.ui.layout.GridData({
span : "L3 M2 S2"
}),
value : {
path : "sLabel",
formatter : function() {
var sDefaultLabel, sSelectedProperty;
if (!this.mEventRegistry.suggest && this.getShowSuggestion() === false) {
var oTextPoolHelper = new sap.apf.modeler.ui.utils.TextPoolHelper(oSelf.oTextPool);
// Add Auto Complete Feature on Label inputs.
var oDependenciesForText = {
oTranslationFormat : sap.apf.modeler.ui.utils.TranslationFormatMap.REPRESENTATION_LABEL,
type : "text"
};
oTextPoolHelper.setAutoCompleteOn(this, oDependenciesForText);
}
if (this.getParent().getContent()[1].getSelectedItem()) {
sSelectedProperty = this.getParent().getContent()[1].getSelectedItem().getText();
} else {
sSelectedProperty = this.getBindingContext().getProperty("sSelectedProperty");
}
if (sSelectedProperty && sSelectedProperty !== oSelf.getText("none")) {
var oPropertyMetadata = oSelf.oEntityMetadata.getPropertyMetadata(sSelectedProperty);
sDefaultLabel = oPropertyMetadata.label ? oPropertyMetadata.label : oPropertyMetadata.name;
}
var sLabel = this.getBindingContext().getProperty("sLabel");
// if there is a selected property other than none and the label is not defined for it or label is defined and it is same as default label
if ((sSelectedProperty && sSelectedProperty !== oSelf.getText("none") && !sLabel) || (sLabel && sDefaultLabel && (sLabel === sDefaultLabel))) {
return sDefaultLabel; //default label should be displayed
}
return sLabel; //else manual entered label has to be displayed
}
},
change : oSelf._handleChangeForBasicDataPropertyRowLabelInput.bind(this)
// the current context should be bound to the event handler
});
oPropertyRowTemplate.addContent(oInputLabel);
// Add Icon
var oAddIcon = new sap.ui.core.Icon({
width : "100%",
src : "sap-icon://add",
tooltip : oSelf.getText("addButton"),
visible : {
path : "nMax",
formatter : function(nMax) {
return (nMax === "*");
}
},
press : oSelf._handlerForBasicDataAddPropertyRow.bind(this)
// the current context should be bound to the event handler
}).addStyleClass("addIconRepresentation");
// Remove Icon
var oRemoveIcon = new sap.ui.core.Icon({
width : "100%",
src : "sap-icon://less",
tooltip : oSelf.getText("deleteButton"),
visible : {
path : "/",
formatter : function() {
var bIsFirstOfItsKind = true;
var oBindingContext = this.getBindingContext();
var nCurrentIndex = parseInt(oBindingContext.getPath().split("/").pop(), 10);
if (nCurrentIndex) {
var aPropertyRows = oSelf.mDataset.oPropertyDataset.aPropertyRows;
var sCurrentKind = aPropertyRows[nCurrentIndex].sKind;
var sCurrentAggRole = aPropertyRows[nCurrentIndex].sAggregationRole;
var nPreviousIndex = nCurrentIndex - 1;
var sPreviousKind = aPropertyRows[nPreviousIndex].sKind;
var sPreviousAggRole = aPropertyRows[nPreviousIndex].sAggregationRole;
bIsFirstOfItsKind = !(sCurrentKind === sPreviousKind && sCurrentAggRole === sPreviousAggRole);
}
return !bIsFirstOfItsKind;
}
},
press : oSelf._handlerForBasicDataDeletePropertyRow.bind(this)
// the current context should be bound to the event handler
}).addStyleClass("lessIconRepresentation");
var oIconLayout = new sap.m.HBox({ //layout to hold the add/less icons
layoutData : new sap.ui.layout.GridData({
span : "L1 M2 S2"
}),
items : [ oAddIcon, oRemoveIcon ]
});
oPropertyRowTemplate.addContent(oIconLayout);
oBasicDataLayout.bindAggregation("items", "/aPropertyRows", function(sId, oModelData) {
oCopyPropertyRowTemplate = jQuery.extend(true, {}, oPropertyRowTemplate);
sPathOfPropertyRow = oModelData.sPath.split("/");
nPropertyRowIndex = sPathOfPropertyRow[sPathOfPropertyRow.indexOf("aPropertyRows") + 1];
oCopyPropertyRowTemplate.getContent()[1].getLayoutData().setSpan("L4 M4 S4");
if (oSelf.mModel.oPropertyModel.getData().aPropertyRows[nPropertyRowIndex].sAggregationRole === "dimension") {
oLabelDisplayOptionBox = new sap.m.Select({
width : "100%",
layoutData : new sap.ui.layout.GridData({
span : "L2 M2 S2"
}),
items : {
path : "aLabelDisplayOptionTypes",
template : new sap.ui.core.ListItem({
key : "{key}",
text : "{value}"
}),
templateShareable : true
},
selectedKey : "{sLabelDisplayOptionProperty}",
change : oSelf._handleChangeForLabelDisplayOption.bind(oSelf)
});
oCopyPropertyRowTemplate.insertContent(oLabelDisplayOptionBox, 2);
oCopyPropertyRowTemplate.getContent()[1].getLayoutData().setSpan("L2 M2 S2");
}
return oCopyPropertyRowTemplate.clone(sId);
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_handleChangeForBasicDataSelectProperty
* @param {oControl}
* @description Handler for change in select property
* Sets the corresponding properties on the representation object.
* */
_handleChangeForBasicDataSelectProperty : function(oSelectEvent) {
var oLabelDisplayOptionControl;
var sSelectedKey = oSelectEvent.getSource().getSelectedKey();
var oPropertyRow = oSelectEvent.getSource().getParent().getContent();
var oLabelControl = oSelectEvent.getSource().getBindingContext().getProperty("sAggregationRole") === "dimension" ? oPropertyRow[3] : oPropertyRow[2];
var oLabelInputControl = oSelectEvent.getSource().getBindingContext().getProperty("sAggregationRole") === "dimension" ? oPropertyRow[4] : oPropertyRow[3];
if (sSelectedKey && (sSelectedKey !== this.getText("none"))) { // if a property is selected
this._setDefaultLabelForSelectedProperty(sSelectedKey, oLabelControl); //pass the selected property and the label control as an argument
} else {
oLabelControl.setText(this.getText("label")); // if no property is selected, set the label value as empty string
oLabelInputControl.setValue("");
}
this._setPropertiesFromCurrentDataset(); // set the current properties on the representation
if (oSelectEvent.getSource().getBindingContext().getProperty("sAggregationRole") === "dimension") {
this._setDefaultLabelDisplayOption(sSelectedKey);
oLabelDisplayOptionControl = oSelectEvent.getSource().getParent().getContent()[2];
oLabelDisplayOptionControl.setSelectedKey(this.oRepresentation.getLabelDisplayOption(sSelectedKey));
this._enableDisableItemsInDisplayOptionOrDisplayOptionBox();
}
this.oConfigurationEditor.setIsUnsaved();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_handleChangeForBasicDataPropertyRowLabelInput
* @param {oControl}
* @description Handler for change in label for the property row
* Sets the corresponding properties on the representation object.
* */
_handleChangeForBasicDataPropertyRowLabelInput : function(oInputEvent) {
var sProperty = oInputEvent.getSource().getBindingContext().getProperty("sSelectedProperty");
var oPropertyRow = oInputEvent.getSource().getParent().getContent();
var oLabelControl = oInputEvent.getSource().getBindingContext().getProperty("sAggregationRole") === "dimension" ? oPropertyRow[3] : oPropertyRow[2];
if (sProperty && sProperty !== this.getText("none")) {
this._updatLabelInPropertyRow(sProperty, oInputEvent.getSource().getValue(), oLabelControl);
}
this._setPropertiesFromCurrentDataset();
this.oConfigurationEditor.setIsUnsaved();
},
_handleChangeForLabelDisplayOption : function(oEvent) {
var sSelectedDisplayOption = oEvent.getSource().getSelectedKey();
var sProperty = oEvent.getSource().getBindingContext().getProperty("sSelectedProperty");
this.oRepresentation.setLabelDisplayOption(sProperty, sSelectedDisplayOption);
this.oConfigurationEditor.setIsUnsaved();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_handlerForBasicDataAddPropertyRow
* @param {oPropertyRow}
* @description Handler for the "+" icon in the property row
* adds a new property row in the representation basic data and also sets the corresponding properties on the representation object.
* */
_handlerForBasicDataAddPropertyRow : function(oAddRowEvent) {
var oBindingContext = oAddRowEvent.getSource().getBindingContext();
var oCurrentObjectClone = jQuery.extend(true, {}, oBindingContext.getObject());
delete oCurrentObjectClone.sSelectedProperty;
delete oCurrentObjectClone.sLabel;
delete oCurrentObjectClone.sLabelDisplayOptionProperty;
var nCurrentIndex = parseInt(oBindingContext.getPath().split("/").pop(), 10);
var aPropertyRows = this.mDataset.oPropertyDataset.aPropertyRows;
aPropertyRows.splice(nCurrentIndex + 1, 0, oCurrentObjectClone);
this._setPropertiesFromCurrentDataset();
this.mModel.oPropertyModel.updateBindings();
this._enableDisableItemsInDisplayOptionOrDisplayOptionBox();
this.oConfigurationEditor.setIsUnsaved();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_handlerForBasicDataDeletePropertyRow
* @param {oAddRowEvent}
* @description Handler for the "-" icon in the property row
* remove a property row from the representation basic data and also sets the corresponding properties on the representation object.
* */
_handlerForBasicDataDeletePropertyRow : function(oDeleteRowEvent) {
var oBindingContext = oDeleteRowEvent.getSource().getBindingContext();
var nCurrentIndex = parseInt(oBindingContext.getPath().split("/").pop(), 10);
var aPropertyRows = this.mDataset.oPropertyDataset.aPropertyRows;
aPropertyRows.splice(nCurrentIndex, 1);
this.mModel.oPropertyModel.updateBindings();
this._setPropertiesFromCurrentDataset();
this.oConfigurationEditor.setIsUnsaved();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_updatLabelInPropertyRow
* @param {sSelectedProperty,sLabelValue,oLabel} - Selected property in the drop down, the new value of the lable and the lable control
* @description gets the default label from the metadata, compares if the same value is given by user
* and accordingly adds the "default" prefix to the label. Also sets the text on the label control for every select property.
* */
_updatLabelInPropertyRow : function(sSelectedProperty, sLabelValue, oLabelControl) {
var oPropertyMetadata = this.oEntityMetadata.getPropertyMetadata(sSelectedProperty);
var sDefaultLabel = oPropertyMetadata.label ? oPropertyMetadata.label : oPropertyMetadata.name;
var sLableControlText, sLabelControlValue;
if (sDefaultLabel !== sLabelValue && sLabelValue.length !== 0) {
sLableControlText = this.getText("label");
sLabelControlValue = sLabelValue;
} else {
sLableControlText = this.getText("label") + "(" + this.getText("default") + ")";
sLabelControlValue = sDefaultLabel;
}
this.mDataset.oPropertyDataset.aPropertyRows.forEach(function(oPropertyRow) {
if (oPropertyRow.sSelectedProperty === sSelectedProperty) { //Update the dataset with default value of input label
oPropertyRow.sLabel = sLabelControlValue;
}
});
this.mModel.oPropertyModel.updateBindings();
oLabelControl.setText(sLableControlText);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_setDefaultLabelForSelectedProperty
* @param {sSelectedProperty,oLabelControl} - Selected property in the drop down and the label control
* @description gets the default label from the metadata, adds the "default" prefix to the label.
* Also sets the default text on the label control for every select property.
* */
_setDefaultLabelForSelectedProperty : function(sSelectedProperty, oLabelControl) {
var oPropertyMetadata = this.oEntityMetadata.getPropertyMetadata(sSelectedProperty);
var sDefaultLabel = oPropertyMetadata.label ? oPropertyMetadata.label : oPropertyMetadata.name;
var sLabelText = this.getText("label") + "(" + this.getText("default") + ")";
this.mDataset.oPropertyDataset.aPropertyRows.forEach(function(oPropertyRow) {
if (oPropertyRow.sSelectedProperty === sSelectedProperty) {
oPropertyRow.sLabel = sDefaultLabel; //Update the dataset with default value of input label
}
});
this.mModel.oPropertyModel.updateBindings();
oLabelControl.setText(sLabelText);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_bindSortLayoutData
* @description Binds sap.apf.modeler.ui.controller.representation#mModel.oSortModel to Sort layout.
* Iteratively binds the data to both the controls in Sort Data Layout.
* */
_bindSortLayoutData : function() {
var oSelf = this;
var oSortLayout = this.byId("idSortLayout");
var oSortRowTemplate = new sap.ui.layout.Grid({ // add the select box controls to the grid.
width : "100%"
});
// "Sort Label" Label
var oSortFieldLabel = new sap.m.Label({
width : "100%",
textAlign : "End",
layoutData : new sap.ui.layout.GridData({
span : "L2 M2 S2"
}),
text : this.getText("sortingField"),
tooltip : this.getText("sortingField")
});
oSortRowTemplate.addContent(oSortFieldLabel);
// "Sort Fields" Select Box
var oSortPropertySelectBox = new sap.m.Select({
width : "100%",
layoutData : new sap.ui.layout.GridData({
span : "L4 M4 S4"
}),
items : {
path : "aAllProperties",
template : new sap.ui.core.ListItem({
key : "{sName}",
text : "{sName}"
}),
templateShareable : true
},
selectedKey : "{sSortProperty}",
change : oSelf._handleChangeForSortDataProperty.bind(this)
// the current context should be bound to the event handler
});
oSortRowTemplate.addContent(oSortPropertySelectBox);
// "Direction" Label
var oDirectionLabel = new sap.m.Label({
layoutData : new sap.ui.layout.GridData({
span : "L2 M2 S2"
}),
width : "100%",
textAlign : "End",
text : this.getText("direction"),
tooltip : this.getText("direction")
});
oSortRowTemplate.addContent(oDirectionLabel);
// "Direction" Select Box
var oDirectionSelectBox = new sap.m.Select({
width : "100%",
layoutData : new sap.ui.layout.GridData({
span : "L3 M2 S2"
}),
items : [ {
key : this.getText("ascending"),
text : this.getText("ascending")
}, {
key : this.getText("descending"),
text : this.getText("descending")
} ],
selectedKey : "{sDirection}",
change : oSelf._handleChangeForSortDirection.bind(this)
// the current context should be bound to the event handler
});
oSortRowTemplate.addContent(oDirectionSelectBox);
// Add Icon
var oAddIcon = new sap.ui.core.Icon({
width : "100%",
src : "sap-icon://add",
tooltip : this.getText("addButton"),
visible : true,
press : oSelf._handleChangeForAddSortRow.bind(this)
// the current context should be bound to the event handler
}).addStyleClass("addIconRepresentation");
// Remove Icon
var oRemoveIcon = new sap.ui.core.Icon({
width : "100%",
src : "sap-icon://less",
tooltip : this.getText("deleteButton"),
visible : {
path : "/",
formatter : function() {
var oBindingContext = this.getBindingContext();
var nCurrentIndex = parseInt(oBindingContext.getPath().split("/").pop(), 10);
return !!nCurrentIndex;
}
},
press : oSelf._handleChangeForDeleteSortRow.bind(this)
// the current context should be bound to the event handler
}).addStyleClass("lessIconRepresentation");
// Layout to hold the add/less icons
var oIconLayout = new sap.m.HBox({
layoutData : new sap.ui.layout.GridData({
span : "L1 M2 S2"
}),
items : [ oAddIcon, oRemoveIcon ]
});
oSortRowTemplate.addContent(oIconLayout);
oSortLayout.bindAggregation("items", "/aSortRows", oSortRowTemplate);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_handleChangeForSortDataProperty
* @description handler for the change in sort property in representation.
* */
_handleChangeForSortDataProperty : function() {
this._setSortFieldsFromCurrentDataset();
this.oConfigurationEditor.setIsUnsaved();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_handleChangeForSortDirection
* @description handler for the change in sort direction for a property in representation.
* */
_handleChangeForSortDirection : function(oSelectEvent) {
var sSortProperty = oSelectEvent.getSource().getBindingContext().getProperty("sSortProperty");
if (sSortProperty !== this.getText("none")) {
this._setSortFieldsFromCurrentDataset();
this.oConfigurationEditor.setIsUnsaved();
}
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_handleChangeForAddSortRow
* @param {oAddRowEvent}
* @description Handler for the "+" icon in the sort property row
* adds a new sort property row in the representation sort data and also sets the corresponding properties on the representation object.
* */
_handleChangeForAddSortRow : function(oAddRowEvent) {
var oBindingContext = oAddRowEvent.getSource().getBindingContext();
var oCurrentObjectClone = jQuery.extend(true, {}, oBindingContext.getObject());
delete oCurrentObjectClone.sSortProperty;
delete oCurrentObjectClone.sDirection;
var nCurrentIndex = parseInt(oBindingContext.getPath().split("/").pop(), 10);
var aSortRows = this.mDataset.oSortDataset.aSortRows;
aSortRows.splice(nCurrentIndex + 1, 0, oCurrentObjectClone);
this.mModel.oSortModel.updateBindings();
this._setSortFieldsFromCurrentDataset();
this.oConfigurationEditor.setIsUnsaved();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_handleChangeForDeleteSortRow
* @param {oDeleteRowEvent}
* @description Handler for the "-" icon in the sort property row
* removes a sort property row from the representation sort data and also sets the corresponding properties on the representation object.
* */
_handleChangeForDeleteSortRow : function(oDeleteRowEvent) {
var oBindingContext = oDeleteRowEvent.getSource().getBindingContext();
var nCurrentIndex = parseInt(oBindingContext.getPath().split("/").pop(), 10);
var aSortRows = this.mDataset.oSortDataset.aSortRows;
aSortRows.splice(nCurrentIndex, 1);
this.mModel.oSortModel.updateBindings();
this._setSortFieldsFromCurrentDataset();
this.oConfigurationEditor.setIsUnsaved();
},
_setPropertiesForTable : function() {
var oSelf = this;
var aDimensions = this.oRepresentation.getDimensions();
var aMeasures = this.oRepresentation.getMeasures();
//Add dimensions and measures as properties for table representation for old configurations
aDimensions.forEach(function(sProperty) {
oSelf.oRepresentation.addProperty(sProperty);
oSelf.oRepresentation.setPropertyTextLabelKey(sProperty, oSelf.oRepresentation.getDimensionTextLabelKey(sProperty));
oSelf.oRepresentation.setPropertyKind(sProperty, sap.apf.core.constants.representationMetadata.kind.COLUMN);
});
aMeasures.forEach(function(sProperty) {
oSelf.oRepresentation.addProperty(sProperty);
oSelf.oRepresentation.setPropertyTextLabelKey(sProperty, oSelf.oRepresentation.getMeasureTextLabelKey(sProperty));
oSelf.oRepresentation.setPropertyKind(sProperty, sap.apf.core.constants.representationMetadata.kind.COLUMN);
});
aDimensions.forEach(function(sDimension) {
oSelf.oRepresentation.removeDimension(sDimension);
});
aMeasures.forEach(function(sMeasure) {
oSelf.oRepresentation.removeMeasure(sMeasure);
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_validateRepresentationData
* @description Validates the dimensions and measures of a representation by comparing them with the select properties of the step
* Removes dimensions or measures that are not part of the step's select properties
* */
_validateRepresentationData : function() {
var oSelf = this;
//Dimensions set to the representation
var aDimensions = this.oRepresentation.getDimensions().map(function(dimension) {
return {
sType : "Dimension",
sName : dimension
};
});
//Measures set to the representation
var aMeasures = this.oRepresentation.getMeasures().map(function(measure) {
return {
sType : "Measure",
sName : measure
};
});
//Properties set to the representation in case of Table representation
var aProperties = this.oRepresentation.getProperties().map(function(property) {
return {
sType : "Property",
sName : property
};
});
var aRepProperties = aDimensions.concat(aMeasures).length ? aDimensions.concat(aMeasures) : aProperties;
//Compare representation properties and step properties
aRepProperties.forEach(function(repProperty) {
var bPropertyPresent = false;
oSelf.aSelectProperties.forEach(function(selectProperty) {
if (repProperty.sName === selectProperty.sName) {
bPropertyPresent = true;
}
});
//If property is not present in the step's select properties remove the property(dimension or measure) from the representation
if (bPropertyPresent === false) {
var sRemoveMethodName = [ "remove", repProperty.sType ].join("");
oSelf.oRepresentation[sRemoveMethodName](repProperty.sName);
oSelf.oConfigurationEditor.setIsUnsaved();
}
});
},
_enableDisableItemsInDisplayOptionOrDisplayOptionBox : function() {
var index, itemIndex, displayLabelOptionBox, bIsTextPropertyPresent, aPropertyRows;
if (this.byId('idBasicDataLayout').getModel()) {
aPropertyRows = this.byId("idBasicDataLayout").getModel().getData().aPropertyRows;
var basicDataLayout = this.byId("idBasicDataLayout");
for(index = 0; index < aPropertyRows.length; index++) {
if (aPropertyRows[index].sAggregationRole === "dimension") {
displayLabelOptionBox = basicDataLayout.getItems()[index].getContent()[2];
if (aPropertyRows[index].sSelectedProperty === this.getText("none")) {
basicDataLayout.getItems()[index].getContent()[2].setEnabled(false);
continue;
} else {
basicDataLayout.getItems()[index].getContent()[2].setEnabled(true);
}
bIsTextPropertyPresent = this._checkIfTextPropertyOfDimensionIsPresent(aPropertyRows[index].sSelectedProperty);
for(itemIndex = 0; itemIndex < displayLabelOptionBox.getItems().length; itemIndex++) {
if (itemIndex > 0) {
displayLabelOptionBox.getItems()[itemIndex].setEnabled(bIsTextPropertyPresent);
}
}
}
}
}
},
_checkIfTextPropertyOfDimensionIsPresent : function(dimension) {
var isPresent = false;
var oDimensionMetadata = this.oEntityMetadata.getPropertyMetadata(dimension);
if (oDimensionMetadata.text) {
var aSelectProperties = this.oParentStep.getSelectProperties();
isPresent = aSelectProperties.indexOf(oDimensionMetadata.text) === -1 ? false : true;
}
return isPresent;
},
_setDefaultLabelDisplayOption : function(dimension) {
var isTextPropertyPresent = this._checkIfTextPropertyOfDimensionIsPresent(dimension);
if (isTextPropertyPresent) {
this.oRepresentation.setLabelDisplayOption(dimension, sap.apf.core.constants.representationMetadata.labelDisplayOptions.KEY_AND_TEXT);
} else {
this.oRepresentation.setLabelDisplayOption(dimension, sap.apf.core.constants.representationMetadata.labelDisplayOptions.KEY);
}
this.oConfigurationEditor.setIsUnsaved();
},
_setDefaultLabelDisplayOptionToDimensions : function() {
var oSelf = this;
this.oRepresentation.getDimensions().forEach(function(dimension) {
if (oSelf.oRepresentation.getLabelDisplayOption(dimension) === undefined) {
oSelf._setDefaultLabelDisplayOption(dimension);
}
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#setDetailData
* @description Prepares data set and model map to be used within the view.
* */
setDetailData : function() {
var mContextParam = this.mParam.arguments;
this.oParentStep = this.oConfigurationEditor.getStep(mContextParam.stepId);
this.oEntityMetadata = this.getEntityTypeMetadata(this.oParentStep.getService(), this.oParentStep.getEntitySet());
this.aSelectProperties = this._getSelectPropertiesFromParentStep();
this.oRepresentation = this.oParentStep.getRepresentation(mContextParam.representationId);
if (!this.oRepresentation) {
this.oRepresentation = this.oParentStep.createRepresentation();
// Set Default Chart Type
this._setDefaultRepresentationType();
// Set Default Dimensions/Measures
this._setDefaultProperties();
this.oConfigurationEditor.setIsUnsaved();
}
if (this.oRepresentation.getRepresentationType() === sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
this._setPropertiesForTable();
}
this._validateRepresentationData();
this._setDefaultLabelDisplayOptionToDimensions();
// Datasets
var oChartTypeDataset = this._getChartTypeDataset();
var oPropertyDataset = this._getPropertyDataset();
var oSortDataset = this._getSortDataset();
var oCornerTextsDataset = this._getCornerTextsDataset();
var oChartPictureDataset = this._getChartPictureDataset();
this.mDataset = {
oChartTypeDataset : oChartTypeDataset,
oPropertyDataset : oPropertyDataset,
oSortDataset : oSortDataset,
oCornerTextsDataset : oCornerTextsDataset,
oChartPictureDataset : oChartPictureDataset
};
// Models
var oChartTypeModel = new sap.ui.model.json.JSONModel(this.mDataset.oChartTypeDataset);
var oPropertyModel = new sap.ui.model.json.JSONModel(this.mDataset.oPropertyDataset);
var oSortModel = new sap.ui.model.json.JSONModel(this.mDataset.oSortDataset);
var oCornerTextsModel = new sap.ui.model.json.JSONModel(this.mDataset.oCornerTextsDataset);
var oChartPictureModel = new sap.ui.model.json.JSONModel(this.mDataset.oChartPictureDataset);
this.mModel = {
oChartTypeModel : oChartTypeModel,
oPropertyModel : oPropertyModel,
oSortModel : oSortModel,
oCornerTextsModel : oCornerTextsModel,
oChartPictureModel : oChartPictureModel
};
// Bindings
this.byId("idChartType").setModel(this.mModel.oChartTypeModel);
var sChartType = this.sCurrentChartType;
this._updateAndSetDatasetsByChartType(sChartType);
this.byId("idBasicDataLayout").setModel(this.mModel.oPropertyModel);
this._bindBasicRepresentationData();
this.byId("idSortLayout").setModel(this.mModel.oSortModel);
this._bindSortLayoutData();
this.byId("idLeftLower").setModel(this.mModel.oCornerTextsModel);
this.byId("idRightLower").setModel(this.mModel.oCornerTextsModel);
this.byId("idLeftUpper").setModel(this.mModel.oCornerTextsModel);
this.byId("idRightUpper").setModel(this.mModel.oCornerTextsModel);
this.byId("idChartIcon").setModel(this.mModel.oChartPictureModel);
// Actions
this._addAutoCompleteFeatureOnInputs();
//disable/enable the sort field based on the top N setting on the step
var bIsSortFieldEnabled;
if (this.oParentStep.getTopN()) {
bIsSortFieldEnabled = false;
} else {
bIsSortFieldEnabled = true;
}
this._changeEditableOfSortProperty(bIsSortFieldEnabled);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_changeEditableOfSortProperty
* @description enables/disables the sort property in the representation based on the top N availibility in the parent step
* */
_changeEditableOfSortProperty : function(bIsSortFieldEnabled) {
var sSortContent = this.byId("idSortLayout").getItems();
sSortContent.forEach(function(oSortRow, nIndexFirstSortRow) {
oSortRow.getContent().forEach(function(oControl) {
if (oControl instanceof sap.m.Select) { //disable the select controls in the sort field
oControl.setEnabled(bIsSortFieldEnabled);
}
if (oControl instanceof sap.m.HBox) { //add and delete icons are inside a HBox
oControl.getItems().forEach(function(item, nIndexDeleteIcon) {
if (item instanceof sap.ui.core.Icon) {
item.setVisible(bIsSortFieldEnabled);
if (nIndexFirstSortRow === 0 && nIndexDeleteIcon === 1) { // delete icon should not be shown for the first sort row
item.setVisible(false);
}
}
});
}
});
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_insertPreviewButtonInFooter
* @description Inserts the preview Button into the footer.
* */
_insertPreviewButtonInFooter : function() {
var oFooter = this.oViewData.oFooter;
oFooter.addContentRight(this._oPreviewButton);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_removePreviewButtonFromFooter
* @description Removes the preview Button from the footer.
* */
_removePreviewButtonFromFooter : function() {
var oFooter = this.oViewData.oFooter;
oFooter.removeContentRight(this._oPreviewButton);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_handlePreviewButtonPress
* @description Handler for press event on preview Button.
* Opens a dialog and inserts the preview content in it.
* */
_handlePreviewButtonPress : function() {
var oPreviewDetails = this._getPreviewDetails();
var oPreviewContent = new sap.ui.view({
type : sap.ui.core.mvc.ViewType.XML,
viewName : "sap.apf.modeler.ui.view.previewContent",
viewData : oPreviewDetails
});
var oPreviewDialog = new sap.m.Dialog({
title : this.getText("preview"),
content : oPreviewContent,
endButton : new sap.m.Button({
text : this.getText("close"),
press : function() {
oPreviewDialog.close();
}
})
});
oPreviewDialog.open();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#onExit
* @description Called when sub-view is destroyed by configuration list controller.
* Removes the preview button from footer.
* */
onExit : function() {
this._removePreviewButtonFromFooter();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getPreviewDetails
* @description Prepares the argument for sap.apf.modeler.ui.controller.PreviewContent.
* Iterates through all the models and populates the result object.
* @returns {Object} Argument for sap.apf.modeler.ui.controller.PreviewContent
* */
_getPreviewDetails : function() {
var oSelf = this;
var sChartType = this.mDataset.oChartTypeDataset.sSelectedChartType;
var sStepTitle = this._getParentStepTitle();
var sStepLongTitle = this._getParentStepLongTitle() || sStepTitle;
var aDimensions = [], aMeasures = [], aProperties = [];
this.aSelectProperties.forEach(function(oSelectProperty) {
if (sChartType === sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
aProperties.push(oSelectProperty.sName);
} else {
if (oSelectProperty.sAggregationRole === "dimension") {
aDimensions.push(oSelectProperty.sName);
} else if (oSelectProperty.sAggregationRole === "measure") {
aMeasures.push(oSelectProperty.sName);
}
}
});
var oChartParameter = {
dimensions : [],
measures : [],
properties : [],
requiredFilters : []
};
this.mDataset.oPropertyDataset.aPropertyRows.forEach(function(oPropertyRow) {
if (oPropertyRow.sSelectedProperty !== oSelf.getText("none")) {
var sAggregationRole = (oPropertyRow.sAggregationRole !== "property") ? oPropertyRow.sAggregationRole + "s" : [ oPropertyRow.sAggregationRole.slice(0, -1), "ies" ].join("");
oChartParameter[sAggregationRole].push({
fieldDesc : oPropertyRow.sLabel,
fieldName : oPropertyRow.sSelectedProperty,
kind : oPropertyRow.sKind
});
}
});
// Sort Fields
var aSort = [];
this.mDataset.oSortDataset.aSortRows.forEach(function(oSortRow) {
var sSortProperty = oSortRow.sSortProperty || (oSortRow.aAllProperties.length && oSortRow.aAllProperties[0].sName);
if (sSortProperty && sSortProperty !== oSelf.getText("none")) {
var bAscending = !oSortRow.sDirection || (oSortRow.sDirection === oSelf.getText("ascending"));
aSort.push({
sSortField : sSortProperty,
bDescending : !bAscending
});
}
});
var aCornerTexts = {
sLeftUpper : this.mDataset.oCornerTextsDataset.LeftUpper,
sRightUpper : this.mDataset.oCornerTextsDataset.RightUpper,
sLeftLower : this.mDataset.oCornerTextsDataset.LeftLower,
sRightLower : this.mDataset.oCornerTextsDataset.RightLower
};
return {
sChartType : sChartType,
sStepTitle : sStepTitle,
sStepLongTitle : sStepLongTitle,
aDimensions : aDimensions,
aMeasures : aMeasures,
aProperties : aProperties,
oChartParameter : oChartParameter,
aSort : aSort,
aCornerTexts : aCornerTexts
};
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getParentStepLongTitle
* @description Getter for parent step's long title
* @returns {String|undefined} Parent Step's Long Title or undefined if not available.
* */
_getParentStepLongTitle : function() {
var sStepLongTitleId = this.oParentStep.getLongTitleId();
sStepLongTitleId = !this.oTextPool.isInitialTextKey(sStepLongTitleId) ? sStepLongTitleId : undefined;
var oStepLongTitleText = sStepLongTitleId && this.oTextPool.get(sStepLongTitleId);
var sStepLongTitle = oStepLongTitleText && oStepLongTitleText.TextElementDescription;
return sStepLongTitle;
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getParentStepTitle
* @description Getter for parent step's title
* @returns {String|undefined} Parent Step's Title or undefined if not available.
* */
_getParentStepTitle : function() {
var sStepTitleId = this.oParentStep.getTitleId();
var oStepTitleText = sStepTitleId && this.oTextPool.get(sStepTitleId);
var sStepTitle = oStepTitleText && oStepTitleText.TextElementDescription;
return sStepTitle;
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getSelectPropertiesFromParentStep
* @description Getter for Select Property List from parent step.
* @returns {Object[]} Array of select properties of the form :
* {
* sName - Name of the property.
* sAggregationRole - dimension/measure.
* sLabel - Label of the property
* }
* */
_getSelectPropertiesFromParentStep : function() {
var sAbsolutePathToServiceDocument = this.oParentStep.getService();
var sEntitySet = this.oParentStep.getEntitySet();
var oEntityMetadata = this.getEntityTypeMetadata(sAbsolutePathToServiceDocument, sEntitySet);
var aSelectProperties = this.oParentStep.getSelectProperties();
var aResultSet = aSelectProperties.map(function(sProperty) {
var oMetadataForProperty = oEntityMetadata.getPropertyMetadata(sProperty);
return {
sName : sProperty,
sAggregationRole : oMetadataForProperty["aggregation-role"],
sLabel : oMetadataForProperty["label"]
};
});
return aResultSet;
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getCornerTextsFromConfigObject
* @param {sap.apf.modeler.core.Step|sap.apf.modeler.core.Representation} oConfigObject - Instance of a configuration object.
* @description Getter for corner text map of a configuration object.
* @returns {Object} Map of corner Text of the form :
* {
* LeftUpper - Left Upper corner text.
* RightUpper - Right Upper corner text.
* LeftLower - Left Lower corner text.
* RightLower - Right Lower corner text.
* }
* */
_getCornerTextsFromConfigObject : function(oConfigObject) {
var oSelf = this;
var aCornerTextNames = [ "LeftUpper", "RightUpper", "LeftLower", "RightLower" ];
var mDataset = {};
aCornerTextNames.forEach(function(sCornerTextName) {
var sMethodName = [ "get", sCornerTextName, "CornerTextKey" ].join("");
var sCornerTextKey = oConfigObject[sMethodName]();
var oCornerText = sCornerTextKey && oSelf.oTextPool.get(sCornerTextKey);
var sCornterText = oCornerText && oCornerText.TextElementDescription;
mDataset[sCornerTextName] = sCornterText;
});
return mDataset;
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getChartTypeDataset
* @description Returns the data set to be bound to chart type drop down.
* @returns {Object} Data set for chart type drop down of the form:
* {
* aChartTypes : [
* {
* sId - {sap.apf.ui.utils.CONSTANTS.representationTypes} Chart Type.
* sText - {String} Display text for the chart type
* }
* ]
* sSelectedChartType - {sap.apf.ui.utils.CONSTANTS.representationTypes} Currently selected Chart Type.
* }
* */
_getChartTypeDataset : function() {
var self = this;
var aKeys = Object.keys(this._getRepresentationMetadata());
var aChartTypes = aKeys.map(function(sKey) {
return {
sId : sKey,
sText : self.getText(sKey)
};
});
var oDataset = {
aChartTypes : aChartTypes,
sSelectedChartType : this.oRepresentation.getRepresentationType()
};
this.sCurrentChartType = oDataset.sSelectedChartType;
return oDataset;
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getChartPictureDataset
* @description Returns the data set to be bound to representation icon
* @returns {Object}
* {
* id : picture
* }
* */
_getChartPictureDataset : function() {
var oRepnMetaData = this.getRepresentationTypes();
var oDataSet = {};
oRepnMetaData.forEach(function(o) {
var sId = o.id;
oDataSet[sId] = o.picture;
});
oDataSet.sSelectedChartPicture = oDataSet[this.oRepresentation.getRepresentationType()];
return oDataSet;
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_updatePictureDataset
* @description Update the picture model data set
*/
_updatePictureDataset : function(sChartType) {
var oDataSet = this.mModel.oChartPictureModel.getData();
oDataSet.sSelectedChartPicture = oDataSet[sChartType];
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getPropertyDataset
* @description Returns the data set to be bound to basic data layout.
* @returns {Object} Data set for basic data layout of the form:
* {
* aPropertyRows : [
* {
sSelectedProperty - Selected Property of dropdown.
sAggregationRole - dimension/measure.
sLabel - Label of the selected property.
sKind - {sap.apf.core.constants.representationMetadata.kind} kind value of corresponding row.
nMin - Minimum value from representation metadata.
nMax - Maximum value from representation metadata.
}
* ]
* }
* */
_getPropertyDataset : function() {
var oSelf = this;
var aPropertyRows = [];
var fnAddPropertyRowsOfType = function(sType) {
var sChartName = oSelf.oRepresentation.getRepresentationType();
var sGetterMethodName = sType !== "Property" ? [ "get", sType, "s" ].join("") : [ "get", sType.slice(0, -1), "ies" ].join("");
var aPropertyList = oSelf.oRepresentation[sGetterMethodName]();
aPropertyList.forEach(function(sProperty) {
var sLabelKeyMethodName = [ "get", sType, "TextLabelKey" ].join("");
var sLabelKey = oSelf.oRepresentation[sLabelKeyMethodName](sProperty);
var oLabel = sLabelKey && oSelf.oTextPool.get(sLabelKey);
var sLabel = oLabel && oLabel.TextElementDescription;
if (sLabel === undefined || sLabel.length === 0) { // if label is undefined or an empty string
sLabel = oSelf.oEntityMetadata.getPropertyMetadata(sProperty).label || oSelf.oEntityMetadata.getPropertyMetadata(sProperty).name;
}
var sKindMethodName = [ "get", sType, "Kind" ].join("");
var sKind = oSelf.oRepresentation[sKindMethodName](sProperty);
var oRepMetadata = oSelf._getRepresentationMetadata()[sChartName];
var aSupportedKinds = (sChartName === sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) ? oRepMetadata[sType.slice(0, -1).toLowerCase() + "ies"].supportedKinds
: oRepMetadata[sType.toLowerCase() + "s"].supportedKinds;
var nMin, nMax;
aSupportedKinds.forEach(function(oSupportedKind) {
if (oSupportedKind.kind === sKind) {
nMin = oSupportedKind.min;
nMax = oSupportedKind.max;
}
});
aPropertyRows.push({
sSelectedProperty : sProperty,
sAggregationRole : sType.toLowerCase(),
sLabel : sLabel,
sKind : sKind,
nMin : nMin,
nMax : nMax,
sLabelDisplayOptionProperty : sType.toLowerCase() === "dimension" ? oSelf.oRepresentation.getLabelDisplayOption(sProperty) : undefined
});
});
};
fnAddPropertyRowsOfType("Dimension");
fnAddPropertyRowsOfType("Measure");
fnAddPropertyRowsOfType("Property");
return {
aPropertyRows : aPropertyRows
};
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getSortDataset
* @description Returns the data set to be bound to sort data layout.
* @returns {Object} Data set for sort data layout of the form
* {
aSortRows : [ {
aAllProperties : [ {
sName : "None" - "None" value since it is an optional field
}, {
sName : Name of the property
} ],
sSortProperty : Name of the selected sort property,
sDirection : Translated text for 'ascending' and 'descending'
} ]
}
* */
_getSortDataset : function() {
var oSelf = this;
var aOrderBySpecs = this.oRepresentation.getOrderbySpecifications();
var aAllProperties = this.aSelectProperties.slice();
aAllProperties.unshift({
sName : this.getText("none")
});
if (!aOrderBySpecs.length) {
aOrderBySpecs.push({});
}
var aSortRows = aOrderBySpecs.map(function(oOrderBySpec) {
var sOrderByProperty = oOrderBySpec.property;
var sOrderByDirection = oOrderBySpec.ascending !== undefined && !oOrderBySpec.ascending ? oSelf.getText("descending") : oSelf.getText("ascending");
return {
sSortProperty : sOrderByProperty,
sDirection : sOrderByDirection,
aAllProperties : aAllProperties
};
});
return {
aSortRows : aSortRows
};
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getCornerTextsDataset
* @description Returns the data set to be bound to corner texts data layout.
* @returns {Object} Data set for corner texts data layout of the form:
* {
* LeftUpper - Left Upper corner text.
* RightUpper - Right Upper corner text.
* LeftLower - Left Lower corner text.
* RightLower - Right Lower corner text.
* }
* */
_getCornerTextsDataset : function() {
var mRepresentationCornerText = this._getCornerTextsFromConfigObject(this.oRepresentation);
var mParentStepCornerText = this._getCornerTextsFromConfigObject(this.oParentStep);
var oDataset = jQuery.extend({}, mParentStepCornerText, mRepresentationCornerText);
return oDataset;
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_setDefaultRepresentationType
* @description Sets the first key from sap.apf.core.representationTypes() list as the default representation type.
* Updates the tree node after setting the representation type on the representation object and passes the id of newly created representation.
* */
_setDefaultRepresentationType : function() {
var sDefaultChartType;
if (this.getRepresentationTypes()[0].metadata) {
sDefaultChartType = this.getRepresentationTypes()[0].id;
}
this.oRepresentation.setRepresentationType(sDefaultChartType);
this.oRepresentation.setAlternateRepresentationType(sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION);
// Update Tree Node.
var sSelectedChartIcon = this._getChartPictureDataset().sSelectedChartPicture;
var aStepCategories = this.oConfigurationEditor.getCategoriesForStep(this.oParentStep.getId());
if (aStepCategories.length === 1) {//In case the step of representation is only assigned to one category
this.oViewData.updateSelectedNode({
id : this.oRepresentation.getId(),
icon : sSelectedChartIcon
});
} else {
this.oViewData.updateTree();
}
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_setDefaultProperties
* @description Adds the first dimension from parent step's select properties to representation object and gives it xAxis.
* Also adds the first measure to the representation object and gives it yAxis.
* */
_setDefaultProperties : function() {
var sFirstDimension, sFirstMeasure;
this.aSelectProperties.forEach(function(oSelectProperty) {
if (!sFirstDimension) {
if (oSelectProperty.sAggregationRole === "dimension") {
sFirstDimension = oSelectProperty.sName;
}
}
if (!sFirstMeasure) {
if (oSelectProperty.sAggregationRole === "measure") {
sFirstMeasure = oSelectProperty.sName;
}
}
});
// Add dimension
if (sFirstDimension) {
this.oRepresentation.addDimension(sFirstDimension);
this.oRepresentation.setDimensionKind(sFirstDimension, sap.apf.core.constants.representationMetadata.kind.XAXIS);
}
// Add measure
if (sFirstMeasure) {
this.oRepresentation.addMeasure(sFirstMeasure);
this.oRepresentation.setMeasureKind(sFirstMeasure, sap.apf.core.constants.representationMetadata.kind.YAXIS);
}
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_updateAndSetDatasetsByChartType
* @param {sap.apf.ui.utils.CONSTANTS.representationTypes} sChartName - Representation Type against which the property dataset has to be updated.
* @description Updates datasets used in different layouts based on chart type.
* This method mutates the sap.apf.modeler.ui.controller.representation#mDataset based on the chart type which is passed.
* After the mutation it sets the values on the representation object.
* */
_updateAndSetDatasetsByChartType : function(sChartName) {
this._updatePropertyDatasetByChartType(sChartName);
this.mModel.oPropertyModel.updateBindings();
this._setPropertiesFromCurrentDataset();
this._enableDisableItemsInDisplayOptionOrDisplayOptionBox();
this._updateSortDatasetByChartType(sChartName);
this.mModel.oSortModel.updateBindings();
this._setSortFieldsFromCurrentDataset();
this._updatePictureDataset(sChartName);
this.mModel.oChartPictureModel.updateBindings();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_updatePropertyDatasetByChartType
* @param {sap.apf.ui.utils.CONSTANTS.representationTypes} sChartName - Representation Type against which the property dataset has to be updated.
* @description Property dataset that is used in basic data layout is different for differnt chart types.
* This method mutates the sap.apf.modeler.ui.controller.representation#mDataset.oPropertyDataset based on the chart type which is passed.
* Contains logic to retain the data rows if old data in row and data row from passed chart type are same.
* */
_updatePropertyDatasetByChartType : function(sChartName) {
var self = this;
// oDefaultDataset holds the bare-minimum property rows for this particular sChartName.
var oDefaultDataset = {
aPropertyRows : []
};
var oRepMetadata = this._getRepresentationMetadata()[sChartName];
var aAggregationRoles = [ "dimensions", "measures", "properties" ];
aAggregationRoles.forEach(function(sAggregationRole) { // for each aggregation role, check the supported kind
if (oRepMetadata.hasOwnProperty(sAggregationRole)) {
var aSupportedKinds = oRepMetadata[sAggregationRole].supportedKinds;
var sSelectedProperty;
aSupportedKinds.forEach(function(oSupportedKind) { //for each kind, check all the properties
// To chop off the letter 's' form 'dimensions' and 'measures' and 'ies' from table representation
var sAggRole = (sAggregationRole !== "properties") ? sAggregationRole.slice(0, -1) : [ sAggregationRole.slice(0, -3), "y" ].join("");
var aAllProperties = (sAggregationRole !== "properties") ? self.aSelectProperties.filter(function(oProperty) {
return (oProperty.sAggregationRole === sAggRole);
}) : self.aSelectProperties;
var oPropertyRow = {
sAggregationRole : sAggRole,
sKind : oSupportedKind.kind,
nMin : oSupportedKind.min,
nMax : oSupportedKind.max,
aAllProperties : aAllProperties
};
if (oPropertyRow.sAggregationRole === "dimension") {
oPropertyRow.aLabelDisplayOptionTypes = [ {
key : "key",
value : self.getText("key")
}, {
key : "text",
value : self.getText("text")
}, {
key : "keyAndText",
value : self.getText("keyAndText")
} ];
}
if (!parseInt(oSupportedKind.min, 10)) {
oPropertyRow.aAllProperties.unshift({
sName : self.getText("none"),
sAggregationRole : sAggRole
});
}
oPropertyRow.aAllProperties.forEach(function(selectedProperty) { //assign the label to each property in one kind
sSelectedProperty = selectedProperty.sName;
if (sSelectedProperty) {
var sType = sAggRole;
var sAggregationRoleCamelCase = [ sType.charAt(0).toUpperCase(), sType.substring(1) ].join("");
var sLabelKeyMethodName = [ "get", sAggregationRoleCamelCase, "TextLabelKey" ].join("");
var sLabelKey = self.oRepresentation[sLabelKeyMethodName](sSelectedProperty);
var oLabel = sLabelKey && self.oTextPool.get(sLabelKey);
var sLabel = oLabel && oLabel.TextElementDescription;
if (sLabel) { //if the user has given a label manually
selectedProperty.sLabel = sLabel; // assign the label to the property
} else { // else read the default label from the metadata
if (sSelectedProperty !== self.getText("none")) {
var oPropertyMetadata = self.oEntityMetadata.getPropertyMetadata(sSelectedProperty);
var sDefaultLabel = oPropertyMetadata.label ? oPropertyMetadata.label : oPropertyMetadata.name;
if (sDefaultLabel) {
selectedProperty.sLabel = sDefaultLabel; // assign the label to the property
}
}
}
}
});
oDefaultDataset.aPropertyRows.push(oPropertyRow);
});
}
});
// oResultDataset combines the oDefaultDataset with the existing mPropertyDataset to retain the similar data entered by the user if any.
var oResultDataset = {
aPropertyRows : []
};
oDefaultDataset.aPropertyRows.forEach(function(oDefaultPropertyRow) {
var bExitingRowOfSameKindExists = false;
self.mDataset.oPropertyDataset.aPropertyRows.forEach(function(oExistingPropertyRow) {
var bHasSameAggregationRole = oExistingPropertyRow.sAggregationRole === oDefaultPropertyRow.sAggregationRole;
var bHasSameKind = oExistingPropertyRow.sKind === oDefaultPropertyRow.sKind;
var bHasSameMinValue = oExistingPropertyRow.nMin === oDefaultPropertyRow.nMin;
var bHasSameMaxValue = oExistingPropertyRow.nMax === oDefaultPropertyRow.nMax;
if (bHasSameAggregationRole && bHasSameKind && bHasSameMinValue && bHasSameMaxValue) {
bExitingRowOfSameKindExists = true;
var oCompleteRow = jQuery.extend(oExistingPropertyRow, oDefaultPropertyRow);
oResultDataset.aPropertyRows.push(oCompleteRow);
}
});
if (!bExitingRowOfSameKindExists) {
oResultDataset.aPropertyRows.push(oDefaultPropertyRow);
}
});
// Update Dataset
this.mDataset.oPropertyDataset.aPropertyRows = oResultDataset.aPropertyRows;
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_updateSortDatasetByChartType
* @param {sap.apf.ui.utils.CONSTANTS.representationTypes} sChartName - Representation Type against which the property dataset has to be updated.
* @description Sort dataset that is used in sort layout is different for differnt chart types.
* This method mutates the sap.apf.modeler.ui.controller.representation#mDataset.oPropertyDataset based on the chart type which is passed.
* Removes and hides Sort properties if "sortable" is set to false in the metadata of the chart type.
* */
_updateSortDatasetByChartType : function(sChartName) {
var oRepMetadata = this._getRepresentationMetadata()[sChartName];
if (oRepMetadata.sortable !== undefined && !oRepMetadata.sortable) {
var aAllProperties = this.aSelectProperties.slice();
aAllProperties.unshift({
sName : this.getText("none")
});
this.mDataset.oSortDataset.aSortRows = [ {
aAllProperties : aAllProperties,
sDirection : this.getText("ascending")
} ];
this.byId("idSortLayout").setVisible(false);
this.byId("idSorting").setVisible(false);
} else {
this.byId("idSortLayout").setVisible(true);
this.byId("idSorting").setVisible(true);
// <-- Work around to resolve data binding issue while changing visibility. -->
this.mModel.oSortModel.updateBindings();
var oSortLayout = this.byId("idSortLayout");
jQuery.sap.delayedCall(10, oSortLayout, oSortLayout.rerender);
// <-- Work around to resolve data binding issue while changing visibility. -->
}
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_setPropertiesFromCurrentDataset
* @description This function is called on every change event related to properties to adhere to WYSIWYG principle.
* Sets new values on the representation object based on the current property model.
* Clears the old values from representation object.
* Sets new values by iterating through the current property data set.
* */
_setPropertiesFromCurrentDataset : function() {
var oSelf = this;
// Clear all properties from representation
var sDimensions = this.oRepresentation.getDimensions();
sDimensions.forEach(function(sDimension) {
oSelf.oRepresentation.removeDimension(sDimension);
});
var sMeasures = this.oRepresentation.getMeasures();
sMeasures.forEach(function(sMeasure) {
oSelf.oRepresentation.removeMeasure(sMeasure);
});
var sProperties = this.oRepresentation.getProperties();
sProperties.forEach(function(sProperty) {
oSelf.oRepresentation.removeProperty(sProperty);
});
// Loop through current dataset and set properties on representation
this.mDataset.oPropertyDataset.aPropertyRows.forEach(function(oPropertyRow) {
var sSelectedProperty = oPropertyRow.sSelectedProperty || (oPropertyRow.aAllProperties.length && oPropertyRow.aAllProperties[0].sName);
if (sSelectedProperty && sSelectedProperty !== oSelf.getText("none")) {
var sAggregationRole = oPropertyRow.sAggregationRole;
var sAggregationRoleCamelCase = [ sAggregationRole.charAt(0).toUpperCase(), sAggregationRole.substring(1) ].join("");
var oPropertyMetadata = oSelf.oEntityMetadata.getPropertyMetadata(sSelectedProperty);
var sDefaultLabel = oPropertyMetadata.label ? oPropertyMetadata.label : oPropertyMetadata.name;
var sLabelValue = oPropertyRow.sLabel;
var sLabelId;
if (sLabelValue && sLabelValue !== sDefaultLabel) { //if the label exists and it is not same as default label
var oTranslationFormat = sap.apf.modeler.ui.utils.TranslationFormatMap.REPRESENTATION_LABEL;
sLabelId = oSelf.oTextPool.setText(sLabelValue, oTranslationFormat);
}
var sAddMethodName = [ "add", sAggregationRoleCamelCase ].join("");
var sSetKindMethondName = [ "set", sAggregationRoleCamelCase, "Kind" ].join("");
var sSetTextLabelKeyMethodName = [ "set", sAggregationRoleCamelCase, "TextLabelKey" ].join("");
oSelf.oRepresentation[sAddMethodName](sSelectedProperty);
oSelf.oRepresentation[sSetKindMethondName](sSelectedProperty, oPropertyRow.sKind);
oSelf.oRepresentation[sSetTextLabelKeyMethodName](sSelectedProperty, sLabelId);
if (sAggregationRole === "dimension") {
var sLabelDisplayOption = oPropertyRow.sLabelDisplayOptionProperty;
if (!sLabelDisplayOption) {
oSelf._setDefaultLabelDisplayOption(sSelectedProperty);
oPropertyRow.sLabelDisplayOptionProperty = oSelf.oRepresentation.getLabelDisplayOption(sSelectedProperty);
} else {
oSelf.oRepresentation.setLabelDisplayOption(sSelectedProperty, sLabelDisplayOption);
}
}
oPropertyRow.sSelectedProperty = sSelectedProperty;
} else {
oPropertyRow.sLabel = "";//clear the label for "None" from the model, from the property row
oPropertyRow.sSelectedProperty = oSelf.getText("none");//set the selected property to "none" in the model, from the property row
oPropertyRow.sLabelDisplayOptionProperty = undefined;
}
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_setSortFieldsFromCurrentDataset
* @description This function is called on every change event related to sort layout to adhere to WYSIWYG principle.
* Sets new values on the representation object based on the current property model.
* Clears the old values from representation object.
* Sets new values by iterating through the current sort data set.
* */
_setSortFieldsFromCurrentDataset : function() {
var oSelf = this;
// Clears current orderBy properties
this.oRepresentation.getOrderbySpecifications().forEach(function(oOrderBySpec) {
oSelf.oRepresentation.removeOrderbySpec(oOrderBySpec.property);
});
// Loop through current sort model and set orderby properties accordingly.
this.mDataset.oSortDataset.aSortRows.forEach(function(oSortRow) {
var sSortProperty = oSortRow.sSortProperty || (oSortRow.aAllProperties.length && oSortRow.aAllProperties[0].sName);
if (sSortProperty && sSortProperty !== oSelf.getText("none")) {
var bAscending = !oSortRow.sDirection || (oSortRow.sDirection === oSelf.getText("ascending"));
oSelf.oRepresentation.addOrderbySpec(sSortProperty, bAscending);
}
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.representation#_getRepresentationMetadata
* @description Returns the representation metadata by using the getRepresentationTypes API
* */
_getRepresentationMetadata : function() {
var oRepMetadata = {};
this.getRepresentationTypes().forEach(function(representationType) {
if (representationType.metadata) {
oRepMetadata[representationType.id] = representationType.metadata;
}
});
return oRepMetadata;
}
});<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
/**
* @class stepContainer
* @name stepContainer
* @memberOf sap.apf.ui.reuse.view
* @description Holds the step in main area. Includes the step toolbar view and step representation view
* @returns {stepContainerLayout}
*/
sap.ui.jsview("sap.apf.ui.reuse.view.stepContainer", {
/**
* @this {sap.apf.ui.reuse.view.stepContainer}
*
*/
/**
* @memberOf sap.apf.ui.reuse.view.stepContainer
* @method getStepToolbar
* @see sap.apf.ui.reuse.view.stepToolbar
* @description Getter for step toolbar container
* @returns stepToolbar view
*/
getStepToolbar : function() {
return this.oStepToolbar;
},
getControllerName : function() {
return "sap.apf.ui.reuse.controller.stepContainer";
},
createContent : function(oController) {
var oViewData = this.getViewData();
this.oStepToolbar = sap.ui.view({viewName:"sap.apf.ui.reuse.view.stepToolbar", type:sap.ui.core.mvc.ViewType.JS,viewData :oViewData});
this.stepLayout = new sap.ui.layout.VerticalLayout({
content : [ this.oStepToolbar],
width : "100%"
});
this.vLayout = new sap.ui.layout.VerticalLayout({
content : this.stepLayout,
width : "100%"
});
this.vLayout.setBusy(true);
return this.vLayout; //holds chart and toolbar
}
});<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define([
'jquery.sap.global', 'sap/ui/fl/changeHandler/Base', 'sap/ui/fl/Utils'
], function(jQuery, Base, FlexUtils) {
"use strict";
/**
* Change handler for moving of groups inside a smart form.
* @constructor
* @alias sap.ui.fl.changeHandler.MoveGroups
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*/
var MoveGroups = function() {
};
MoveGroups.prototype = jQuery.sap.newObject(Base.prototype);
/**
* Moves group(s) inside a smart form.
*
* @param {object} oChange change object with instructions to be applied on the control
* @param {object} oSmartForm Smart form instance which is referred to in change selector section
* @public
*/
MoveGroups.prototype.applyChange = function(oChange, oSmartForm) {
if (!oChange) {
throw new Error("No change instance");
}
var oChangeJson = oChange.getDefinition();
if (!oChangeJson.selector || !oChangeJson.content || !oChangeJson.content.moveGroups || oChangeJson.content.moveGroups.length === 0 || Object.keys(oChangeJson.selector).length !== 1) {
throw new Error("Change format invalid");
}
if (!oSmartForm || !oSmartForm.getGroups) {
throw new Error("No smart form instance supplied");
}
// Array of groups of smart form in old order
var aGroups = [];
aGroups = oSmartForm.getGroups();
if (aGroups.length === 0) {
return;
}
var iGroupNumber = aGroups.length;
// adapt order of groups in aGroups according to the change
var oGroup = {}, oMoveGroup = {};
var iMoveGroups = oChangeJson.content.moveGroups.length;
var iIndex;
var i, j;
for (i = 0; i < iMoveGroups; i++) {
oMoveGroup = oChangeJson.content.moveGroups[i];
if (!oMoveGroup.id) {
throw new Error("Change format invalid - moveGroups element has no id attribute");
}
if (typeof (oMoveGroup.index) !== "number") {
throw new Error("Change format invalid - moveGroups element index attribute is no number");
}
// determine the index of the group to move in aGroups
iIndex = -1;
for (j = 0; j < iGroupNumber; j++) {
if (aGroups[j].getId() === oMoveGroup.id) {
iIndex = j;
break;
}
}
if (iIndex === oMoveGroup.index || iIndex === -1) {
continue;
}
// memorize the group to move
oGroup = aGroups[iIndex];
// remove the group to move from aGroups
aGroups.splice(iIndex, 1);
// reinsert the group to aGroups at the new index
aGroups.splice(oMoveGroup.index, 0, oGroup);
}
// remove all groups from smart form
oSmartForm.removeAllGroups();
// reinsert groups into smart form in new order
for (i = 0; i < iGroupNumber; i++) {
oSmartForm.insertGroup(aGroups[i], i);
}
};
/**
* Completes the change by adding change handler specific content
*
* @param {object} oChange change object to be completed
* @param {object} oSpecificChangeInfo with attribute moveGroups which contains an array which holds objects which have attributes
* id and index - id is the id of the group to move and index the new position of the group in the smart form
* @public
*/
MoveGroups.prototype.completeChangeContent = function(oChange, oSpecificChangeInfo) {
var oChangeJson = oChange.getDefinition();
if (oSpecificChangeInfo.moveGroups) {
var oMoveGroup = {};
var i, iLength = oSpecificChangeInfo.moveGroups.length;
if (iLength === 0) {
throw new Error("MoveGroups array is empty");
}
for (i = 0; i < iLength; i++) {
oMoveGroup = oSpecificChangeInfo.moveGroups[i];
if (!oMoveGroup.id) {
throw new Error("MoveGroups element has no id attribute");
}
if (typeof (oMoveGroup.index) !== "number") {
throw new Error("Index attribute at MoveGroups element is no number");
}
}
if (!oChangeJson.content) {
oChangeJson.content = {};
}
if (!oChangeJson.content.moveGroups) {
oChangeJson.content.moveGroups = [];
}
oChangeJson.content.moveGroups = oSpecificChangeInfo.moveGroups;
} else {
throw new Error("oSpecificChangeInfo.moveGroups attribute required");
}
};
return MoveGroups;
},
/* bExport= */true);
<file_sep>/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.ui.comp.navpopover.SmartLink.
sap.ui.define([
'jquery.sap.global', 'sap/m/Link', 'sap/m/LinkRenderer', 'sap/ui/comp/navpopover/LinkData'
], function(jQuery, Link, LinkRenderer, LinkData) {
"use strict";
/**
* Constructor for a new navpopover/SmartLink.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
* @class The SmartLink control uses a semantic object to display {@link sap.ui.comp.navpopover.NavigationPopover NavigationPopover} for further
* navigation steps.
* @extends sap.m.Link
* @constructor
* @public
* @alias sap.ui.comp.navpopover.SmartLink
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var SmartLink = Link.extend("sap.ui.comp.navpopover.SmartLink", /** @lends sap.ui.comp.navpopover.SmartLink.prototype */
{
metadata: {
library: "sap.ui.comp",
properties: {
/**
* Name of semantic object which is used to fill the navigation popover.
*
* @since 1.28.0
*/
semanticObject: {
type: "string",
defaultValue: null
},
/**
* The semantic object controller controls events for several SmartLink controls. If the controller is not set manually, it tries to
* find a SemanticObjectController in its parent hierarchy.
*
* @since 1.28.0
*/
semanticObjectController: {
type: "any",
defaultValue: null
},
/**
* The metadata field name for this SmartLink control.
*
* @since 1.28.0
*/
fieldName: {
type: "string",
defaultValue: null
},
/**
* Shown label of semantic object.
*
* @since 1.28.0
*/
semanticObjectLabel: {
type: "string",
defaultValue: null
},
/**
* Function that enables the SmartLink control to create an alternative control, which is displayed if no navigation targets are
* available. The function has no parameters and has to return an instance of sap.ui.core.Control.
*
* @since 1.28.0
*/
createControlCallback: {
type: "object",
defaultValue: null
},
/**
* If set to <code>false</code>, the SmartLink control will not replace its field name with the according
* <code>semanticObject</code> property during the calculation of the semantic attributes. This enables the usage of several
* SmartLinks on the same semantic object.
*/
mapFieldToSemanticObject: {
type: "boolean",
defaultValue: true
},
/**
* If set to <code>true</code>, the SmartLink control will render the <code>innerControl</code> or the control provided by
* <code>createControlCallback</code> instead of the actual link. This is used for example by the SemanticObjectController if this
* SmartLink is listed in its <code>ignoredFields</code> or no navigation targets were found during prefetch.
*
* @since 1.28.0
*/
ignoreLinkRendering: {
type: "boolean",
defaultValue: false
}
},
aggregations: {
/**
* Control that is displayed instead of SmartLink, if the SmartLink is disabled (for example, if no navigation targets are available).
* If <code>innerControl</code> is not provided, the SmartLink control tries to create one with property
* <code>createControlCallback</code>.
*
* @since 1.28.0
*/
innerControl: {
type: "sap.ui.core.Control",
multiple: false
}
},
events: {
/**
* Event is fired before the navigation popover opens and before navigation target links are getting retrieved. Event can be used to
* change the parameters used to retrieve the navigation targets. In case of SmartLink, the <code>beforePopoverOpens</code> is fired
* after the link has been clicked.
*
* @since 1.28.0
*/
beforePopoverOpens: {
parameters: {
/**
* The semantic object for which the navigation targets will be retrieved.
*/
semanticObject: {
type: "string"
},
/**
* Map containing the semantic attributes calculated from the binding that will be used to retrieve the navigation targets.
* targets.
*/
semanticAttributes: {
type: "object"
},
/**
* This callback function enables you to define a changed semantic attributes map. Signatures:
* <code>setSemanticAttributes(oSemanticAttributesMap)</code> Parameter:
* <ul>
* <li>{object} oSemanticAttributesMap New map containing the semantic attributes to be used.</li>
* </ul>
*/
setSemanticAttributes: {
type: "function"
},
/**
* This callback function sets an application state key that is used over the cross-application navigation. Signatures:
* <code>setAppStateKey(sAppStateKey)</code> Parameter:
* <ul>
* <li>{string} sAppStateKey</li>
* </ul>
*/
setAppStateKey: {
type: "function"
},
/**
* The ID of the SmartLink.
*/
originalId: {
type: "string"
},
/**
* This callback function triggers the retrieval of navigation targets and leads to the opening of the navigation popover.
* Signatures: <code>open()</code> If the <code>beforePopoverOpens</code> has been registered, the <code>open</code>
* function has to be called manually in order to open the navigation popover.
*/
open: {
type: "function"
}
}
},
/**
* After the navigation targets are retrieved, <code>navigationTargetsObtained</code> is fired and provides the possibility to
* change the targets.
*
* @since 1.28.0
*/
navigationTargetsObtained: {
parameters: {
/**
* The main navigation object.
*/
mainNavigation: {
type: "sap.ui.comp.navpopover.LinkData"
},
/**
* Array of available navigation target objects.
*/
actions: {
type: "sap.ui.comp.navpopover.LinkData[]"
},
/**
* The navigation object for the own application. This navigation option is by default not visible on the popover.
*/
ownNavigation: {
type: "sap.ui.comp.navpopover.LinkData"
},
/**
* The semantic object for which the navigation targets have been retrieved.
*/
semanticObject: {
type: "string"
},
/**
* The ID of the SmartLink.
*/
originalId: {
type: "string"
},
/**
* This callback function shows the actual navigation popover. If the <code>navigationTargetsObtained</code> has been
* registered, the <code>show</code> function has to be called manually in order to open the navigation popover. Signatures:
* <code>show()</code>
* <code>show(oMainNavigation, aAvailableActions, oExtraContent)</code>
* <code>show(sMainNavigationId, oMainNavigation, aAvailableActions, oExtraContent)</code>
* Parameters:
* <ul>
* <li>{string} sMainNavigationId The visible text for the main navigation section. If empty, the main navigation ID is
* calculated using binding context of given source object (for example SmartLink).</li>
* <li>{sap.ui.comp.navpopover.LinkData} oMainNavigation The main navigation object. If empty, property
* <code>mainNavigation</code> will be used.</li>
* <li>{sap.ui.comp.navpopover.LinkData[]} aAvailableActions Array containing the cross application navigation links. If
* empty, property <code>actions</code> will be used.</li>
* <li>{sap.ui.core.Control} oExtraContent Control that will be displayed in extra content section on the popover.</li>
* </ul>
*/
show: {
type: "function"
}
}
},
/**
* This event is fired after a navigation link on the navigation popover has been clicked. This event is only fired, if the user
* left-clicks the link. Right-clicking the link and selecting 'Open in New Window' etc. in the context menu does not fire the event.
*
* @since 1.28.0
*/
innerNavigate: {
parameters: {
/**
* The UI text shown in the clicked link.
*/
text: {
type: "string"
},
/**
* The navigation target of the clicked link.
*/
href: {
type: "string"
},
/**
* The semantic object used to retrieve this target.
*/
semanticObject: {
type: "string"
},
/**
* Map containing the semantic attributes used to retrieve this target.
*/
semanticAttributes: {
type: "object"
},
/**
* The ID of the SmartLink.
*/
originalId: {
type: "string"
}
}
}
}
},
renderer: function(oRm, oControl) {
var bRenderLink = true;
if (oControl.getIgnoreLinkRendering()) {
var oReplaceControl = oControl._getInnerControl();
if (oReplaceControl) {
oRm.write("<div ");
oRm.writeControlData(oControl);
oRm.writeClasses();
oRm.write(">");
oRm.renderControl(oReplaceControl);
oRm.write("</div>");
bRenderLink = false;
}
}
if (bRenderLink) {
LinkRenderer.render.call(LinkRenderer, oRm, oControl);
}
}
});
SmartLink.prototype.init = function() {
// sap.m.Link.prototype.init.call(this);
this.attachPress(this._linkPressed);
this.addStyleClass("sapUiCompSmartLink");
this._oSemanticAttributes = null;
};
/**
* Eventhandler for link's press event
*
* @param {object} oEvent the event parameters.
* @private
*/
SmartLink.prototype._linkPressed = function(oEvent) {
if (this._processingLinkPressed) {
window.console.warn("SmartLink is still processing last press event. This press event is omitted.");
return; // avoid multiple link press events while data is still fetched
}
if (this.getIgnoreLinkRendering()) {
window.console.warn("SmartLink should ignore link rendering. Press event is omitted.");
return; // actual link is not rendered -> ignore press event
}
this._processingLinkPressed = true;
var sAppStateKey;
this._oSemanticAttributes = this._calculateSemanticAttributes();
var that = this;
var fOpen = function() {
that._createPopover();
if (that._oSemanticAttributes) {
that._oPopover.setSemanticAttributes(that._oSemanticAttributes);
}
if (sAppStateKey) {
that._oPopover.setAppStateKey(sAppStateKey);
}
that._oPopover.retrieveNavTargets();
};
if (this.hasListeners("beforePopoverOpens")) {
this.fireBeforePopoverOpens({
semanticObject: this.getSemanticObject(),
semanticAttributes: that._oSemanticAttributes,
setSemanticAttributes: function(oMap) {
that._oSemanticAttributes = oMap;
},
setAppStateKey: function(sKey) {
sAppStateKey = sKey;
},
originalId: this.getId(),
open: fOpen
});
} else {
fOpen();
}
};
/**
* Eventhandler for NavigationPopover's targetObtained event, exposes event or - if not registered - directly opens the dialog
*
* @private
*/
SmartLink.prototype._onTargetsObtainedOpenDialog = function() {
var that = this;
if (!this._oPopover.getMainNavigation()) { // main navigation could not be resolved, so only set link text as MainNavigation
this._oPopover.setMainNavigation(new LinkData({
text: this.getText()
}));
}
this.fireNavigationTargetsObtained({
actions: this._oPopover.getAvailableActions(),
mainNavigation: this._oPopover.getMainNavigation(),
ownNavigation: this._oPopover.getOwnNavigation(),
semanticObject: this.getSemanticObject(),
semanticAttributes: this.getSemanticAttributes(),
originalId: this.getId(),
show: function(sMainNavigationId, oMainNavigation, aAvailableActions, oExtraContent) {
if (sMainNavigationId != null && typeof sMainNavigationId === "string") {
that._oPopover.setMainNavigationId(sMainNavigationId);
} else {
oExtraContent = aAvailableActions;
aAvailableActions = oMainNavigation;
oMainNavigation = sMainNavigationId;
}
if (oMainNavigation) {
that._oPopover.setMainNavigation(oMainNavigation);
}
if (aAvailableActions) {
that._oPopover.removeAllAvailableActions();
if (aAvailableActions && aAvailableActions.length) {
var i, length = aAvailableActions.length;
for (i = 0; i < length; i++) {
that._oPopover.addAvailableAction(aAvailableActions[i]);
}
}
}
if (oExtraContent) {
that._oPopover.setExtraContent(oExtraContent);
}
that._oPopover.show();
that._processingLinkPressed = false;
}
});
if (!this.hasListeners("navigationTargetsObtained")) {
this._oPopover.show();
this._processingLinkPressed = false;
}
};
/**
* Eventhandler for NavigationPopover's navigate event, exposes event
*
* @param {object} oEvent - the event parameters
* @private
*/
SmartLink.prototype._onInnerNavigate = function(oEvent) {
var aParameters = oEvent.getParameters();
this.fireInnerNavigate({
text: aParameters.text,
href: aParameters.href,
originalId: this.getId(),
semanticObject: this.getSemanticObject(),
semanticAttributes: this.getSemanticAttributes()
});
};
/**
* Creates the NavigationPopover.
*
* @private
*/
SmartLink.prototype._createPopover = function() {
if (!this._oPopover) {
var oComponent = this._getComponent();
jQuery.sap.require("sap.ui.comp.navpopover.NavigationPopover");
var NavigationPopover = sap.ui.require("sap/ui/comp/navpopover/NavigationPopover");
this._oPopover = new NavigationPopover({
title: this.getSemanticObjectLabel(),
semanticObjectName: this.getSemanticObject(),
targetsObtained: jQuery.proxy(this._onTargetsObtainedOpenDialog, this),
navigate: jQuery.proxy(this._onInnerNavigate, this),
component: oComponent
});
this._oPopover.setSource(this);
}
};
/**
* Finds the parental component.
*
* @private
* @returns {sap.ui.core.Component} the found parental component or null
*/
SmartLink.prototype._getComponent = function() {
var oParent = this.getParent();
while (oParent) {
if (oParent instanceof sap.ui.core.Component) {
return oParent;
}
oParent = oParent.getParent();
}
return null;
};
/**
* Gets the current binding context and creates a copied map where all empty and unnecessary data is deleted from.
*
* @private
*/
SmartLink.prototype._calculateSemanticAttributes = function() {
var oContext = this.getBindingContext();
if (!oContext) {
return null;
}
var oBinding = this.getBinding("text");
var sCurrentField = oBinding.getPath();
var oResult = {};
var oContext = oContext.getObject(oContext.getPath());
for ( var sAttributeName in oContext) {
// Ignore metadata
if (sAttributeName === "__metadata") {
continue;
}
// Ignore empty values
if (!oContext[sAttributeName]) {
continue;
}
// Map attribute name by semantic object name
var sSemanticObjectName = this._mapFieldToSemanticObject(sAttributeName);
if (sAttributeName === sCurrentField && this.getSemanticObject()) {
sSemanticObjectName = this.getSemanticObject();
}
// Map all available attribute fields to their semanticObjects excluding SmartLink's own SemanticObject
if (sSemanticObjectName === this.getSemanticObject() && !this.getMapFieldToSemanticObject()) {
sSemanticObjectName = sAttributeName;
}
// If more then one attribute fields maps to the same semantic object we take the value of the current binding path.
var oAttributeValue = oContext[sAttributeName];
if (oResult[sSemanticObjectName]) {
if (oContext[sCurrentField]) {
oAttributeValue = oContext[sCurrentField];
}
}
// Copy the value replacing the attribute name by semantic object name
oResult[sSemanticObjectName] = oAttributeValue;
}
return oResult;
};
/**
* Gets the semantic object calculated at the last Link press event
*
* @returns {object} Map containing the copy of the available binding context.
* @public
*/
SmartLink.prototype.getSemanticAttributes = function() {
if (this._oSemanticAttributes === null) {
this._oSemanticAttributes = this._calculateSemanticAttributes();
}
return this._oSemanticAttributes;
};
/**
* Maps the given field name to the corresponding semantic object.
*
* @param {string} sFieldName The field name which should be mapped to a semantic object
* @returns {string} Corresponding semantic object, or the original field name if semantic object is not available.
* @private
*/
SmartLink.prototype._mapFieldToSemanticObject = function(sFieldName) {
var oSOController = this.getSemanticObjectController();
if (!oSOController) {
return sFieldName;
}
var oMap = oSOController.getFieldSemanticObjectMap();
if (!oMap) {
return sFieldName;
}
return oMap[sFieldName] || sFieldName;
};
SmartLink.prototype.setFieldName = function(sFieldName) {
this.setProperty("fieldName", sFieldName);
var oSemanticController = this.getSemanticObjectController();
if (oSemanticController) {
oSemanticController.setIgnoredState(this);
}
};
// BCP 1670108744: when semanticObjectController is set first then semanticObject is still not known in the step where ignoredState is determined
SmartLink.prototype.setSemanticObject = function(sSemanticObject) {
this.setProperty("semanticObject", sSemanticObject, true);
var oSemanticObjectController = this.getSemanticObjectController();
if (oSemanticObjectController) {
oSemanticObjectController.setIgnoredState(this);
}
};
SmartLink.prototype.setSemanticObjectController = function(oController) {
var oOldController = this.getProperty("semanticObjectController");
if (oOldController) {
oOldController.unregisterControl(this);
}
this.setProperty("semanticObjectController", oController, true);
if (oController) {
oController.registerControl(this);
}
this._oSemanticAttributes = null;
};
SmartLink.prototype.getSemanticObjectController = function() {
var oController = this.getProperty("semanticObjectController");
if (!oController) {
var oParent = this.getParent();
while (oParent) {
if (oParent.getSemanticObjectController) {
oController = oParent.getSemanticObjectController();
if (oController) {
this.setSemanticObjectController(oController);
break;
}
}
oParent = oParent.getParent();
}
}
return oController;
};
/**
* Gets the current value assigned to the field with the SmartLink's semantic object name.
*
* @returns {object} The semantic object's value.
* @public
*/
SmartLink.prototype.getSemanticObjectValue = function() {
var oSemanticAttributes = this.getSemanticAttributes();
if (oSemanticAttributes) {
var sSemanticObjectName = this.getSemanticObject();
return oSemanticAttributes[sSemanticObjectName];
}
return null;
};
SmartLink.prototype.setText = function(sText) {
if (this._isRenderingInnerControl()) {
// SmartLink renders inner control => overwrite base setText as it changes the DOM directly
this.setProperty("text", sText, true);
} else {
Link.prototype.setText.call(this, sText);
}
};
SmartLink.prototype._isRenderingInnerControl = function() {
return this.getIgnoreLinkRendering() && this._getInnerControl() != null;
};
/**
* Gets the inner control which is provided by the CreateControlCallback
*
* @returns {sap.ui.core.Control} The control.
* @private
*/
SmartLink.prototype._getInnerControl = function() {
var oInnerControl = this.getAggregation("innerControl");
if (!oInnerControl) {
var fCreate = this.getCreateControlCallback();
if (fCreate) {
oInnerControl = fCreate();
this.setAggregation("innerControl", oInnerControl, true);
}
}
return oInnerControl;
};
/**
* Gets the inner control's value, if no inner control is available, the SmartLink's text will be returned
*
* @returns {object} the value
* @public
*/
SmartLink.prototype.getInnerControlValue = function() {
if (this._isRenderingInnerControl()) {
var oInnerControl = this._getInnerControl();
if (oInnerControl) {
if (oInnerControl.getText) {
return oInnerControl.getText();
}
if (oInnerControl.getValue) {
return oInnerControl.getValue();
}
}
}
return this.getText();
};
/**
* Called before rendering
*/
SmartLink.prototype.onBeforeRendering = function() {
// ensure that the semantic object controller exists, do this first as retrieving the SemanticObjectController can lead to setting the
// ignoreLinkRendering flag
this.getSemanticObjectController();
// if link should not be rendered, but no inner control is available, deactivate SmartLink
if (this.getIgnoreLinkRendering() && this._getInnerControl() == null) {
this.setEnabled(false);
} else {
this.setEnabled(true);
}
};
SmartLink.prototype.exit = function() {
this.setSemanticObjectController(null); // disconnect from SemanticObjectController
};
return SmartLink;
}, /* bExport= */true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define([
'jquery.sap.global', 'sap/ui/fl/changeHandler/Base', 'sap/ui/fl/Utils'
], function(jQuery, Base, FlexUtils) {
"use strict";
/**
* Change handler for reordering of groups.
* @constructor
* @alias sap.ui.fl.changeHandler.OrderGroups
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*/
var OrderGroups = function() {
};
OrderGroups.prototype = jQuery.sap.newObject(Base.prototype);
/**
* Reorders groups.
*
* @param {object} oChange change object with instructions to be applied on the control
* @param {object} oControl control instance which is referred to in change selector section
* @public
*/
OrderGroups.prototype.applyChange = function(oChange, oControl) {
if (!oChange) {
throw new Error("No change instance");
}
var oChangeJson = oChange.getDefinition();
if (!oChangeJson.selector || !oChangeJson.content || !oChangeJson.content.orderGroups || oChangeJson.content.orderGroups.length === 0 || Object.keys(oChangeJson.selector).length !== 1) {
throw new Error("Change format invalid");
}
if (!oControl || !oControl.getGroups) {
throw new Error("No control instance or wrong control instance supplied");
}
// Array of groups of smart form in old order
var aGroup = oControl.getGroups();
var iGroupNumber = aGroup.length;
// Array of ids of groups in new order as defined in the change
var aKeyOrderFromChange = oChangeJson.content.orderGroups;
var iKeyNumberInChange = aKeyOrderFromChange.length;
// build object of groups of smart form which has their ids as key
var oGroups = {}, oGroup = {};
var sKey;
var i;
for (i = 0; i < iGroupNumber; i++) {
oGroup = aGroup[i];
if (!oGroup.getId()) {
return;
}
sKey = oGroup.getId();
oGroups[sKey] = oGroup;
}
// remove all groups from smart form
if (iGroupNumber > 0) {
oControl.removeAllGroups();
}
// reinsert groups into smart form in order given by change
for (i = 0; i < iGroupNumber; i++) {
sKey = aKeyOrderFromChange[i];
if (oGroups[sKey]) {
oControl.insertGroup(oGroups[sKey], i);
oGroups[sKey] = null;
}
}
// add groups not handled by change at the end
i = iKeyNumberInChange;
jQuery.each(oGroups, function(key, group) {
if (group !== null) {
i += 1;
oControl.insertGroup(group, i);
}
});
};
/**
* Completes the change by adding change handler specific content
*
* @param {object} oChange change object to be completed
* @param {object} oSpecificChangeInfo with attribute orderGroups which contains an array which holds the ids of
* the groups of the smart form in the desired order
* @public
*/
OrderGroups.prototype.completeChangeContent = function(oChange, oSpecificChangeInfo) {
var oChangeJson = oChange.getDefinition();
if (oSpecificChangeInfo.orderGroups) {
if (!oChangeJson.content) {
oChangeJson.content = {};
}
if (!oChangeJson.content.orderGroups) {
oChangeJson.content.orderGroups = {};
}
oChangeJson.content.orderGroups = oSpecificChangeInfo.orderGroups;
} else {
throw new Error("oSpecificChangeInfo.orderGroups attribute required");
}
};
return OrderGroups;
},
/* bExport= */true);
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
jQuery.sap.declare("sap.apf.core.utils.uriGenerator");
jQuery.sap.require("sap.apf.core.messageObject");
(function(){
'use strict';
/**
* @descriptions Module for uri generation and location helper functions for the resource location
*/
sap.apf.core.utils.uriGenerator = {};
/**
* @memberOf sap.apf.core.utils.uriGenerator
* @description Returns the absolute URL path of the service root. The slash as last character is fixed, if not existing.
* @param {String} sPathToRoot Absolute Path to the service root like /sap/hba/apps/wca/s/odata/wca.xsodata/ .
* @returns {String}
*/
sap.apf.core.utils.uriGenerator.getAbsolutePath = function(sPathToRoot) {
if (sPathToRoot.slice(-1) === '/') {
return sPathToRoot;
}
return sPathToRoot + "/";
};
/**
* @memberOf sap.apf.core.utils.uriGenerator
* @param {string} sPathToServiceDocument
* @description Returns the relative url path of the oadata service.
* @returns {String}
*/
sap.apf.core.utils.uriGenerator.getODataPath = function(sPathToServiceDocument) {
var aSplitt = sPathToServiceDocument.split('/');
var i;
var aSplittContent = [];
for(i = 0; i < aSplitt.length; i++) {
if (aSplitt[i] !== "") {
aSplittContent.push(aSplitt[i]);
}
}
var sReturn = '';
var len = aSplittContent.length - 1;
for(i = 0; i < len; i++) {
sReturn = sReturn + '/' + aSplittContent[i];
}
return sReturn + '/';
};
/**
* @memberOf sap.apf.core.utils.uriGenerator
* @description adds a relative url to an absolute url
* @param {string} absoluteURL
* @param {string} relativeURL
* @returns {string} composedURL
*/
sap.apf.core.utils.uriGenerator.addRelativeToAbsoluteURL = function(absoluteURL, relativeURL) {
var absoluteUrlParts = absoluteURL.split('/');
var relativeUrlParts = relativeURL.split('/');
relativeUrlParts.forEach(function(part){
if (part === '..') {
absoluteUrlParts.pop();
} else if (part != '.') {
absoluteUrlParts.push(part);
}
});
return absoluteUrlParts.join('/');
};
/**
* @description returns the url for a given component up to this component (not including).
* @param (string} componentName
* @returns {string} absoluteUrlUpToComponent
*/
sap.apf.core.utils.uriGenerator.getBaseURLOfComponent = function(componentName) {
var baseComponentNameParts = componentName.split('.');
baseComponentNameParts.pop();
var base = baseComponentNameParts.join('.');
return jQuery.sap.getModulePath(base);
};
/**
* @memberOf sap.apf.core.utils.uriGenerator
* @description gets the location of the apf libary. sap.apf.core.utils.uriGenerator is required for loading texts, images and so on.
* @returns {String}
*/
sap.apf.core.utils.uriGenerator.getApfLocation = function() {
return jQuery.sap.getModulePath("sap.apf") + '/';
};
/**
* @memberOf sap.apf.core.utils.uriGenerator
* @description builds a URI based on parameters
* @param {sap.apf.core.MessageHandler} oMsgHandler
* @param {string} sEntityType
* @param [aSelectProperties]
* @param {object} oFilter
* @param {object} oParameter - HANA XSE parameter entity set parameters
* @param {object} [sortingFields]
* @param {object} oPaging - values of properties 'top','skip' and 'inlineCount' are evaluated and added to '$top','$skip' and '$inlinecount' URI string parameters if available
* @param {string} sFormat of HTTP response,e.g. 'json' or 'xml'. If omitted 'json' is taken as default.
* @param {function} [fnFormatValue] callback method to format the values
* @param {sNavigationProperty} Suffix after the parameter - old default is "Results"
* @returns {string} complete URI
*/
sap.apf.core.utils.uriGenerator.buildUri = function(oMsgHandler, sEntityType, aSelectProperties, oFilter, oParameter, sortingFields, oPaging, sFormat, fnFormatValue, sNavigationProperty) {
var sReturn = "";
sReturn += sEntityType;
sReturn += addParamsToUri(oParameter,sNavigationProperty);
sReturn = sReturn + "?";
sReturn += addSelectPropertiesToUri(aSelectProperties);
sReturn += addFilterToUri(oFilter, fnFormatValue);
sReturn += addSorting(sortingFields, aSelectProperties);
sReturn += addPaging(oPaging);
sReturn += addFormatToUri(sFormat);
return sReturn;
function addParamsToUri(oParameter,sNavigationProperty) {
var sReturn = '';
var bParametersExist = false;
var sParameter;
for(sParameter in oParameter) {
if (!bParametersExist) {
sReturn += '(';
bParametersExist = true;
} else {
sReturn += ',';
}
sReturn += sParameter.toString() + '=' + oParameter[sParameter];
}
if (bParametersExist) {
sReturn += ')/';
}
sReturn += sNavigationProperty || '';
return sReturn;
}
function addSelectPropertiesToUri(aSelectProperties) {
if (!aSelectProperties[0]) {
return '';
}
var field;
var sResult = "$select=";
for( field in aSelectProperties) {
sResult += jQuery.sap.encodeURL(sap.apf.utils.escapeOdata(aSelectProperties[field]));
if (field < aSelectProperties.length - 1) {
sResult += ",";
}
}
return sResult;
}
function addFilterToUri(oFilter, fnFormatValue) {
if (!(oFilter && oFilter instanceof sap.apf.core.utils.Filter)) {
return '';
}
var sFilterValues = oFilter.toUrlParam( { formatValue : fnFormatValue });
if (sFilterValues === "" || sFilterValues === '()' ) {
return '';
}
return '&$filter=' + sFilterValues;
}
function addSorting(sortingFields, aSelectProperties) {
var sOrderByValues = '';
var sSingleValue = '';
var i;
if (!sortingFields) {
return '';
}
switch (true) {
case jQuery.isArray(sortingFields):
for( i = 0; i < sortingFields.length; i++) {
sSingleValue = makeOrderByValue(sortingFields[i], aSelectProperties);
if (sOrderByValues.length > 0 && sSingleValue.length > 0) {
sOrderByValues += ',';
}
sOrderByValues += sSingleValue;
}
break;
case jQuery.isPlainObject(sortingFields):
sOrderByValues += makeOrderByValue(sortingFields, aSelectProperties);
break;
case typeof sortingFields === 'string':
sOrderByValues += makeOrderByValue({
property : sortingFields
}, aSelectProperties);
break;
}
if (sOrderByValues.length > 0) {
return "&$orderby=" + sOrderByValues;
}
return '';
function makeOrderByValue(oOrderBy, aSelectProperties) {
var sValue = '';
if (jQuery.inArray(oOrderBy.property, aSelectProperties) > -1) {
sValue += oOrderBy.property;
if (oOrderBy.descending === true) {
sValue += ' desc';
} else {
sValue += ' asc';
}
} else {
oMsgHandler.putMessage(oMsgHandler.createMessageObject({
code : '5019',
aParameters : [ sEntityType, oOrderBy.property ]
}));
}
return jQuery.sap.encodeURL(sValue);
}
}
function addPaging(oPaging) {
function checkPropertyOptionsConsistency(oPaging) {
var aPropertyNames, i;
aPropertyNames = Object.getOwnPropertyNames(oPaging);
for (i = 0; i < aPropertyNames.length;i++) {
if (aPropertyNames[i] !== 'top' && aPropertyNames[i] !== 'skip' && aPropertyNames[i] !== 'inlineCount') {
oMsgHandler.putMessage(oMsgHandler.createMessageObject({
code : '5032',
aParameters : [ sEntityType, aPropertyNames[i] ]
}));
}
}
}
var sReturn = '';
if (!oPaging) {
return sReturn;
}
checkPropertyOptionsConsistency(oPaging);
if (oPaging.top) {
sReturn += '&$top=' + oPaging.top;
}
if (oPaging.skip) {
sReturn += '&$skip=' + oPaging.skip;
}
if (oPaging.inlineCount === true) {
sReturn += '&$inlinecount=allpages';
}
return sReturn;
}
function addFormatToUri(sFormat) {
if (!sFormat) {
sFormat = 'json'; // eslint-disable-line
}
return '&$format=' + sFormat;
}
};
}());
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP SE. All rights reserved
*/
/*global sap, jQuery*/
jQuery.sap.declare("sap.apf.modeler.core.textHandler");
(function() {
'use strict';
/**
* @private
* @class Provides access to message texts and ui texts for the modeler
*/
sap.apf.modeler.core.TextHandler = function() {
var oBundleApf, oBundleModelerSpecificTexts;
/**
* @description returns a message text for message handling
* @param {string} sRessourceKey - Key of the message in the Ressourcefile
* @param {string[]} [aParameters] - Parameter for placeholder replacement in the message bundle
* @returns {string}
*/
this.getMessageText = function(sRessourceKey, aParameters) {
return this.getText(sRessourceKey, aParameters);
};
/**
* @description returns text
* @param {string} sRessourceKey - Key of the message in the Ressourcefile
* @param {string[]} [aParameters] - Parameter for placeholder replacement in the message bundle
* @returns {string}
*/
this.getText = function(sRessourceKey, aParameters) {
var sText;
sText = oBundleModelerSpecificTexts.getText(sRessourceKey, aParameters);
if (sText !== sRessourceKey) {
return sText;
}
return oBundleApf.getText(sRessourceKey, aParameters);
};
function initBundles() {
var sUrl;
var sIncludeInfo = sap.ui.getCore().getConfiguration().getOriginInfo();
var sModulePath = jQuery.sap.getModulePath("sap.apf");
sUrl = sModulePath + '/modeler/resources/i18n/texts.properties';
oBundleModelerSpecificTexts = jQuery.sap.resources({
url : sUrl,
includeInfo : sIncludeInfo
});
sUrl = sModulePath + '/resources/i18n/apfUi.properties';
oBundleApf = jQuery.sap.resources({
url : sUrl,
includeInfo : sIncludeInfo
});
}
initBundles();
};
}());<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
jQuery.sap.require('sap.apf.modeler.ui.utils.nullObjectChecker');
jQuery.sap.declare('sap.apf.modeler.ui.utils.staticValuesBuilder');
(function() {
'use strict';
/**
* @class staticValuesBuilder
* @memberOf sap.apf.modeler.ui.utils
* @name staticValuesBuilder
* @description builds static model data
*/
sap.apf.modeler.ui.utils.staticValuesBuilder = function(oTextReader) {
/**
* @private
* @function
* @name sap.apf.modeler.ui.utils.staticValuesBuilder#getNavTargetTypeData
* @returns an array of values of navigation target types
* */
sap.apf.modeler.ui.utils.staticValuesBuilder.prototype.getNavTargetTypeData = function() {
var arr = [ oTextReader("globalNavTargets"), oTextReader("stepSpecific") ];
return arr;
};
};
})();<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides the Design Time Metadata for the sap.ui.comp.smarttable.SmartTable control
sap.ui.define([],
function() {
"use strict";
return {
aggregations : {
customToolbar : {
ignore : true
},
semanticObjectController : {
ignore : true
},
noData : {
ignore : true
}
}
};
}, /* bExport= */ false);<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
jQuery.sap.declare('sap.apf.modeler.ui.utils.constants');sap.apf.modeler.ui.utils.CONSTANTS={configurationObjectTypes:{CONFIGURATION:"configuration",FACETFILTER:"facetFilter",CATEGORY:"category",STEP:"step",REPRESENTATION:"representation",NAVIGATIONTARGET:"navigationTarget",ISNEWCONFIG:"apf1972-"}};
<file_sep>/*!
*
* SAP UI development toolkit for HTML5 (SAPUI5)
* (c) Copyright 2009-2015 SAP SE. All rights reserved
*
*/
/* ----------------------------------------------------------------------------------
* Hint: This is a derived (generated) file. Changes should be done in the underlying
* source files only (*.control, *.js) or they will be lost after the next generation.
* ---------------------------------------------------------------------------------- */
// Provides control sap.suite.ui.commons.ChartContainer.
jQuery.sap.declare("sap.suite.ui.commons.ChartContainer");
jQuery.sap.require("sap.suite.ui.commons.library");
jQuery.sap.require("sap.ui.core.Control");
/**
* Constructor for a new ChartContainer.
*
* Accepts an object literal <code>mSettings</code> that defines initial
* property values, aggregated and associated objects as well as event handlers.
*
* If the name of a setting is ambiguous (e.g. a property has the same name as an event),
* then the framework assumes property, aggregation, association, event in that order.
* To override this automatic resolution, one of the prefixes "aggregation:", "association:"
* or "event:" can be added to the name of the setting (such a prefixed name must be
* enclosed in single or double quotes).
*
* The supported settings are:
* <ul>
* <li>Properties
* <ul>
* <li>{@link #getShowPersonalization showPersonalization} : boolean (default: false)</li>
* <li>{@link #getShowFullScreen showFullScreen} : boolean (default: false)</li>
* <li>{@link #getFullScreen fullScreen} : boolean (default: false)</li>
* <li>{@link #getShowLegend showLegend} : boolean (default: true)</li>
* <li>{@link #getTitle title} : string (default: '')</li>
* <li>{@link #getSelectorGroupLabel selectorGroupLabel} : string</li>
* <li>{@link #getAutoAdjustHeight autoAdjustHeight} : boolean (default: false)</li>
* <li>{@link #getShowZoom showZoom} : boolean (default: true)</li>
* <li>{@link #getShowLegendButton showLegendButton} : boolean (default: true)</li></ul>
* </li>
* <li>Aggregations
* <ul>
* <li>{@link #getDimensionSelectors dimensionSelectors} : sap.ui.core.Control[]</li>
* <li>{@link #getContent content} <strong>(default aggregation)</strong> : sap.suite.ui.commons.ChartContainerContent[]</li>
* <li>{@link #getCustomIcons customIcons} : sap.ui.core.Icon[]</li></ul>
* </li>
* <li>Associations
* <ul></ul>
* </li>
* <li>Events
* <ul>
* <li>{@link sap.suite.ui.commons.ChartContainer#event:personalizationPress personalizationPress} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li>
* <li>{@link sap.suite.ui.commons.ChartContainer#event:contentChange contentChange} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li>
* <li>{@link sap.suite.ui.commons.ChartContainer#event:customZoomInPress customZoomInPress} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li>
* <li>{@link sap.suite.ui.commons.ChartContainer#event:customZoomOutPress customZoomOutPress} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li></ul>
* </li>
* </ul>
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Provides a toolbar with generic functions for tables and charts based on the VizFrame control like zoom, display in fullscreen mode, toggle the legend, switch between chart types, and changes of the chart dimension. The controls of the content aggregation are positioned below the toolbar. Additional functions can be added to the toolbar with the customIcons aggregation.
* @extends sap.ui.core.Control
* @version 1.36.8
*
* @constructor
* @public
* @name sap.suite.ui.commons.ChartContainer
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
sap.ui.core.Control.extend("sap.suite.ui.commons.ChartContainer", { metadata : {
publicMethods : [
// methods
"switchChart", "updateChartContainer", "getSelectedContent"
],
library : "sap.suite.ui.commons",
properties : {
"showPersonalization" : {type : "boolean", group : "Misc", defaultValue : false},
"showFullScreen" : {type : "boolean", group : "Misc", defaultValue : false},
"fullScreen" : {type : "boolean", group : "Misc", defaultValue : false},
"showLegend" : {type : "boolean", group : "Misc", defaultValue : true},
"title" : {type : "string", group : "Misc", defaultValue : ''},
"selectorGroupLabel" : {type : "string", group : "Misc", defaultValue : null, deprecated: true},
"autoAdjustHeight" : {type : "boolean", group : "Misc", defaultValue : false},
"showZoom" : {type : "boolean", group : "Misc", defaultValue : true},
"showLegendButton" : {type : "boolean", group : "Misc", defaultValue : true}
},
defaultAggregation : "content",
aggregations : {
"dimensionSelectors" : {type : "sap.ui.core.Control", multiple : true, singularName : "dimensionSelector"},
"content" : {type : "sap.suite.ui.commons.ChartContainerContent", multiple : true, singularName : "content"},
"toolBar" : {type : "sap.m.OverflowToolbar", multiple : false, visibility : "hidden"},
"customIcons" : {type : "sap.ui.core.Icon", multiple : true, singularName : "customIcon"}
},
events : {
"personalizationPress" : {},
"contentChange" : {},
"customZoomInPress" : {},
"customZoomOutPress" : {}
}
}});
/**
* Creates a new subclass of class sap.suite.ui.commons.ChartContainer with name <code>sClassName</code>
* and enriches it with the information contained in <code>oClassInfo</code>.
*
* <code>oClassInfo</code> might contain the same kind of informations as described in {@link sap.ui.core.Element.extend Element.extend}.
*
* @param {string} sClassName name of the class to be created
* @param {object} [oClassInfo] object literal with informations about the class
* @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.core.ElementMetadata.
* @return {function} the created class / constructor function
* @public
* @static
* @name sap.suite.ui.commons.ChartContainer.extend
* @function
*/
sap.suite.ui.commons.ChartContainer.M_EVENTS = {'personalizationPress':'personalizationPress','contentChange':'contentChange','customZoomInPress':'customZoomInPress','customZoomOutPress':'customZoomOutPress'};
/**
* Getter for property <code>showPersonalization</code>.
* Set to true to display the personalization icon. Set to false to hide it.
*
* Default value is <code>false</code>
*
* @return {boolean} the value of property <code>showPersonalization</code>
* @public
* @name sap.suite.ui.commons.ChartContainer#getShowPersonalization
* @function
*/
/**
* Setter for property <code>showPersonalization</code>.
*
* Default value is <code>false</code>
*
* @param {boolean} bShowPersonalization new value for property <code>showPersonalization</code>
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#setShowPersonalization
* @function
*/
/**
* Getter for property <code>showFullScreen</code>.
* Set to true to display the full screen icon. Set to false to hide it.
*
* Default value is <code>false</code>
*
* @return {boolean} the value of property <code>showFullScreen</code>
* @public
* @name sap.suite.ui.commons.ChartContainer#getShowFullScreen
* @function
*/
/**
* Setter for property <code>showFullScreen</code>.
*
* Default value is <code>false</code>
*
* @param {boolean} bShowFullScreen new value for property <code>showFullScreen</code>
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#setShowFullScreen
* @function
*/
/**
* Getter for property <code>fullScreen</code>.
* Display the chart and the toolbar in full screen or normal mode.
*
* Default value is <code>false</code>
*
* @return {boolean} the value of property <code>fullScreen</code>
* @public
* @name sap.suite.ui.commons.ChartContainer#getFullScreen
* @function
*/
/**
* Setter for property <code>fullScreen</code>.
*
* Default value is <code>false</code>
*
* @param {boolean} bFullScreen new value for property <code>fullScreen</code>
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#setFullScreen
* @function
*/
/**
* Getter for property <code>showLegend</code>.
* Set to true to display the charts' legends. Set to false to hide them.
*
* Default value is <code>true</code>
*
* @return {boolean} the value of property <code>showLegend</code>
* @public
* @name sap.suite.ui.commons.ChartContainer#getShowLegend
* @function
*/
/**
* Setter for property <code>showLegend</code>.
*
* Default value is <code>true</code>
*
* @param {boolean} bShowLegend new value for property <code>showLegend</code>
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#setShowLegend
* @function
*/
/**
* Getter for property <code>title</code>.
* String shown if there are no dimensions to display.
*
* Default value is empty/<code>undefined</code>
*
* @return {string} the value of property <code>title</code>
* @public
* @name sap.suite.ui.commons.ChartContainer#getTitle
* @function
*/
/**
* Setter for property <code>title</code>.
*
* Default value is empty/<code>undefined</code>
*
* @param {string} sTitle new value for property <code>title</code>
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#setTitle
* @function
*/
/**
* Getter for property <code>selectorGroupLabel</code>.
* Custom Label for Selectors Group.
*
* Default value is empty/<code>undefined</code>
*
* @return {string} the value of property <code>selectorGroupLabel</code>
* @public
* @deprecated Since version 1.32.0.
* Obsolete property as sap.m.Toolbar is replaced by sap.m.OverflowToolbar.
* @name sap.suite.ui.commons.ChartContainer#getSelectorGroupLabel
* @function
*/
/**
* Setter for property <code>selectorGroupLabel</code>.
*
* Default value is empty/<code>undefined</code>
*
* @param {string} sSelectorGroupLabel new value for property <code>selectorGroupLabel</code>
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @deprecated Since version 1.32.0.
* Obsolete property as sap.m.Toolbar is replaced by sap.m.OverflowToolbar.
* @name sap.suite.ui.commons.ChartContainer#setSelectorGroupLabel
* @function
*/
/**
* Getter for property <code>autoAdjustHeight</code>.
* Determine whether to stretch the chart height to the maximum possible height of ChartContainer's parent container. As a prerequisite, the parent container needs to have a fixed value height or be able to determine height from its parent.
*
* Default value is <code>false</code>
*
* @return {boolean} the value of property <code>autoAdjustHeight</code>
* @public
* @name sap.suite.ui.commons.ChartContainer#getAutoAdjustHeight
* @function
*/
/**
* Setter for property <code>autoAdjustHeight</code>.
*
* Default value is <code>false</code>
*
* @param {boolean} bAutoAdjustHeight new value for property <code>autoAdjustHeight</code>
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#setAutoAdjustHeight
* @function
*/
/**
* Getter for property <code>showZoom</code>.
* Set to true to display zoom icons. Set to false to hide them.
*
* Default value is <code>true</code>
*
* @return {boolean} the value of property <code>showZoom</code>
* @public
* @name sap.suite.ui.commons.ChartContainer#getShowZoom
* @function
*/
/**
* Setter for property <code>showZoom</code>.
*
* Default value is <code>true</code>
*
* @param {boolean} bShowZoom new value for property <code>showZoom</code>
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#setShowZoom
* @function
*/
/**
* Getter for property <code>showLegendButton</code>.
* Set to true/false to display/hide a button for controlling the visbility of the chart's legend.
*
* Default value is <code>true</code>
*
* @return {boolean} the value of property <code>showLegendButton</code>
* @public
* @name sap.suite.ui.commons.ChartContainer#getShowLegendButton
* @function
*/
/**
* Setter for property <code>showLegendButton</code>.
*
* Default value is <code>true</code>
*
* @param {boolean} bShowLegendButton new value for property <code>showLegendButton</code>
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#setShowLegendButton
* @function
*/
/**
* Getter for aggregation <code>dimensionSelectors</code>.<br/>
* Dimension Selects.
*
* @return {sap.ui.core.Control[]}
* @public
* @name sap.suite.ui.commons.ChartContainer#getDimensionSelectors
* @function
*/
/**
* Inserts a dimensionSelector into the aggregation named <code>dimensionSelectors</code>.
*
* @param {sap.ui.core.Control}
* oDimensionSelector the dimensionSelector to insert; if empty, nothing is inserted
* @param {int}
* iIndex the <code>0</code>-based index the dimensionSelector should be inserted at; for
* a negative value of <code>iIndex</code>, the dimensionSelector is inserted at position 0; for a value
* greater than the current size of the aggregation, the dimensionSelector is inserted at
* the last position
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#insertDimensionSelector
* @function
*/
/**
* Adds some dimensionSelector <code>oDimensionSelector</code>
* to the aggregation named <code>dimensionSelectors</code>.
*
* @param {sap.ui.core.Control}
* oDimensionSelector the dimensionSelector to add; if empty, nothing is inserted
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#addDimensionSelector
* @function
*/
/**
* Removes an dimensionSelector from the aggregation named <code>dimensionSelectors</code>.
*
* @param {int | string | sap.ui.core.Control} vDimensionSelector the dimensionSelector to remove or its index or id
* @return {sap.ui.core.Control} the removed dimensionSelector or null
* @public
* @name sap.suite.ui.commons.ChartContainer#removeDimensionSelector
* @function
*/
/**
* Removes all the controls in the aggregation named <code>dimensionSelectors</code>.<br/>
* Additionally unregisters them from the hosting UIArea.
* @return {sap.ui.core.Control[]} an array of the removed elements (might be empty)
* @public
* @name sap.suite.ui.commons.ChartContainer#removeAllDimensionSelectors
* @function
*/
/**
* Checks for the provided <code>sap.ui.core.Control</code> in the aggregation named <code>dimensionSelectors</code>
* and returns its index if found or -1 otherwise.
*
* @param {sap.ui.core.Control}
* oDimensionSelector the dimensionSelector whose index is looked for.
* @return {int} the index of the provided control in the aggregation if found, or -1 otherwise
* @public
* @name sap.suite.ui.commons.ChartContainer#indexOfDimensionSelector
* @function
*/
/**
* Destroys all the dimensionSelectors in the aggregation
* named <code>dimensionSelectors</code>.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#destroyDimensionSelectors
* @function
*/
/**
* Getter for aggregation <code>content</code>.<br/>
* ChartToolBar Content aggregation. Only vizFrame, sap.m.Table and sap.ui.table.Table can be embedded.
* If not specified explicitly, the rendering order of the charts is determined by the sequence of contents provided by the application via this aggregation. That means, per default the first chart of the aggregation will be rendered within the container.
*
* <strong>Note</strong>: this is the default aggregation for ChartContainer.
* @return {sap.suite.ui.commons.ChartContainerContent[]}
* @public
* @name sap.suite.ui.commons.ChartContainer#getContent
* @function
*/
/**
* Inserts a content into the aggregation named <code>content</code>.
*
* @param {sap.suite.ui.commons.ChartContainerContent}
* oContent the content to insert; if empty, nothing is inserted
* @param {int}
* iIndex the <code>0</code>-based index the content should be inserted at; for
* a negative value of <code>iIndex</code>, the content is inserted at position 0; for a value
* greater than the current size of the aggregation, the content is inserted at
* the last position
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#insertContent
* @function
*/
/**
* Adds some content <code>oContent</code>
* to the aggregation named <code>content</code>.
*
* @param {sap.suite.ui.commons.ChartContainerContent}
* oContent the content to add; if empty, nothing is inserted
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#addContent
* @function
*/
/**
* Removes an content from the aggregation named <code>content</code>.
*
* @param {int | string | sap.suite.ui.commons.ChartContainerContent} vContent the content to remove or its index or id
* @return {sap.suite.ui.commons.ChartContainerContent} the removed content or null
* @public
* @name sap.suite.ui.commons.ChartContainer#removeContent
* @function
*/
/**
* Removes all the controls in the aggregation named <code>content</code>.<br/>
* Additionally unregisters them from the hosting UIArea.
* @return {sap.suite.ui.commons.ChartContainerContent[]} an array of the removed elements (might be empty)
* @public
* @name sap.suite.ui.commons.ChartContainer#removeAllContent
* @function
*/
/**
* Checks for the provided <code>sap.suite.ui.commons.ChartContainerContent</code> in the aggregation named <code>content</code>
* and returns its index if found or -1 otherwise.
*
* @param {sap.suite.ui.commons.ChartContainerContent}
* oContent the content whose index is looked for.
* @return {int} the index of the provided control in the aggregation if found, or -1 otherwise
* @public
* @name sap.suite.ui.commons.ChartContainer#indexOfContent
* @function
*/
/**
* Destroys all the content in the aggregation
* named <code>content</code>.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#destroyContent
* @function
*/
/**
* Getter for aggregation <code>customIcons</code>.<br/>
* This aggregation contains the custom icons that should be displayed additionally on the toolbar.
* It is not guaranteed that the same instance of the sap.ui.core.Icon control will be used within the toolbar,
* but the toolbar will contain a sap.m.OverflowToolbarButton with an icon property equal to the src property
* of the sap.ui.core.Icon provided in the aggregation.
* If a press event is triggered by the icon displayed on the toolbar, then the press handler of
* the original sap.ui.core.Icon control is used. The instance of the control, that has triggered the press event,
* can be accessed using the "controlReference" parameter of the event object.
*
* @return {sap.ui.core.Icon[]}
* @public
* @name sap.suite.ui.commons.ChartContainer#getCustomIcons
* @function
*/
/**
* Inserts a customIcon into the aggregation named <code>customIcons</code>.
*
* @param {sap.ui.core.Icon}
* oCustomIcon the customIcon to insert; if empty, nothing is inserted
* @param {int}
* iIndex the <code>0</code>-based index the customIcon should be inserted at; for
* a negative value of <code>iIndex</code>, the customIcon is inserted at position 0; for a value
* greater than the current size of the aggregation, the customIcon is inserted at
* the last position
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#insertCustomIcon
* @function
*/
/**
* Adds some customIcon <code>oCustomIcon</code>
* to the aggregation named <code>customIcons</code>.
*
* @param {sap.ui.core.Icon}
* oCustomIcon the customIcon to add; if empty, nothing is inserted
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#addCustomIcon
* @function
*/
/**
* Removes an customIcon from the aggregation named <code>customIcons</code>.
*
* @param {int | string | sap.ui.core.Icon} vCustomIcon the customIcon to remove or its index or id
* @return {sap.ui.core.Icon} the removed customIcon or null
* @public
* @name sap.suite.ui.commons.ChartContainer#removeCustomIcon
* @function
*/
/**
* Removes all the controls in the aggregation named <code>customIcons</code>.<br/>
* Additionally unregisters them from the hosting UIArea.
* @return {sap.ui.core.Icon[]} an array of the removed elements (might be empty)
* @public
* @name sap.suite.ui.commons.ChartContainer#removeAllCustomIcons
* @function
*/
/**
* Checks for the provided <code>sap.ui.core.Icon</code> in the aggregation named <code>customIcons</code>
* and returns its index if found or -1 otherwise.
*
* @param {sap.ui.core.Icon}
* oCustomIcon the customIcon whose index is looked for.
* @return {int} the index of the provided control in the aggregation if found, or -1 otherwise
* @public
* @name sap.suite.ui.commons.ChartContainer#indexOfCustomIcon
* @function
*/
/**
* Destroys all the customIcons in the aggregation
* named <code>customIcons</code>.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#destroyCustomIcons
* @function
*/
/**
* Event fired when a user clicks on the personalization icon.
*
* @name sap.suite.ui.commons.ChartContainer#personalizationPress
* @event
* @param {sap.ui.base.Event} oControlEvent
* @param {sap.ui.base.EventProvider} oControlEvent.getSource
* @param {object} oControlEvent.getParameters
* @public
*/
/**
* Attach event handler <code>fnFunction</code> to the 'personalizationPress' event of this <code>sap.suite.ui.commons.ChartContainer</code>.<br/>.
* When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified
* otherwise to this <code>sap.suite.ui.commons.ChartContainer</code>.<br/> itself.
*
* Event fired when a user clicks on the personalization icon.
*
* @param {object}
* [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* [oListener] Context object to call the event handler with. Defaults to this <code>sap.suite.ui.commons.ChartContainer</code>.<br/> itself.
*
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#attachPersonalizationPress
* @function
*/
/**
* Detach event handler <code>fnFunction</code> from the 'personalizationPress' event of this <code>sap.suite.ui.commons.ChartContainer</code>.<br/>
*
* The passed function and listener object must match the ones used for event registration.
*
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* oListener Context object on which the given function had to be called.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#detachPersonalizationPress
* @function
*/
/**
* Fire event personalizationPress to attached listeners.
*
* @param {Map} [mArguments] the arguments to pass along with the event.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @protected
* @name sap.suite.ui.commons.ChartContainer#firePersonalizationPress
* @function
*/
/**
* Event fired when a user changes the displayed content.
*
* @name sap.suite.ui.commons.ChartContainer#contentChange
* @event
* @param {sap.ui.base.Event} oControlEvent
* @param {sap.ui.base.EventProvider} oControlEvent.getSource
* @param {object} oControlEvent.getParameters
* @param {string} oControlEvent.getParameters.selectedItemId Id of the selected item.
* @public
*/
/**
* Attach event handler <code>fnFunction</code> to the 'contentChange' event of this <code>sap.suite.ui.commons.ChartContainer</code>.<br/>.
* When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified
* otherwise to this <code>sap.suite.ui.commons.ChartContainer</code>.<br/> itself.
*
* Event fired when a user changes the displayed content.
*
* @param {object}
* [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* [oListener] Context object to call the event handler with. Defaults to this <code>sap.suite.ui.commons.ChartContainer</code>.<br/> itself.
*
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#attachContentChange
* @function
*/
/**
* Detach event handler <code>fnFunction</code> from the 'contentChange' event of this <code>sap.suite.ui.commons.ChartContainer</code>.<br/>
*
* The passed function and listener object must match the ones used for event registration.
*
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* oListener Context object on which the given function had to be called.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#detachContentChange
* @function
*/
/**
* Fire event contentChange to attached listeners.
*
* Expects following event parameters:
* <ul>
* <li>'selectedItemId' of type <code>string</code> Id of the selected item.</li>
* </ul>
*
* @param {Map} [mArguments] the arguments to pass along with the event.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @protected
* @name sap.suite.ui.commons.ChartContainer#fireContentChange
* @function
*/
/**
* Custom event for zoom in.
*
* @name sap.suite.ui.commons.ChartContainer#customZoomInPress
* @event
* @param {sap.ui.base.Event} oControlEvent
* @param {sap.ui.base.EventProvider} oControlEvent.getSource
* @param {object} oControlEvent.getParameters
* @public
*/
/**
* Attach event handler <code>fnFunction</code> to the 'customZoomInPress' event of this <code>sap.suite.ui.commons.ChartContainer</code>.<br/>.
* When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified
* otherwise to this <code>sap.suite.ui.commons.ChartContainer</code>.<br/> itself.
*
* Custom event for zoom in.
*
* @param {object}
* [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* [oListener] Context object to call the event handler with. Defaults to this <code>sap.suite.ui.commons.ChartContainer</code>.<br/> itself.
*
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#attachCustomZoomInPress
* @function
*/
/**
* Detach event handler <code>fnFunction</code> from the 'customZoomInPress' event of this <code>sap.suite.ui.commons.ChartContainer</code>.<br/>
*
* The passed function and listener object must match the ones used for event registration.
*
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* oListener Context object on which the given function had to be called.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#detachCustomZoomInPress
* @function
*/
/**
* Fire event customZoomInPress to attached listeners.
*
* @param {Map} [mArguments] the arguments to pass along with the event.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @protected
* @name sap.suite.ui.commons.ChartContainer#fireCustomZoomInPress
* @function
*/
/**
* Custom event for zoom out.
*
* @name sap.suite.ui.commons.ChartContainer#customZoomOutPress
* @event
* @param {sap.ui.base.Event} oControlEvent
* @param {sap.ui.base.EventProvider} oControlEvent.getSource
* @param {object} oControlEvent.getParameters
* @public
*/
/**
* Attach event handler <code>fnFunction</code> to the 'customZoomOutPress' event of this <code>sap.suite.ui.commons.ChartContainer</code>.<br/>.
* When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified
* otherwise to this <code>sap.suite.ui.commons.ChartContainer</code>.<br/> itself.
*
* Custom event for zoom out.
*
* @param {object}
* [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* [oListener] Context object to call the event handler with. Defaults to this <code>sap.suite.ui.commons.ChartContainer</code>.<br/> itself.
*
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#attachCustomZoomOutPress
* @function
*/
/**
* Detach event handler <code>fnFunction</code> from the 'customZoomOutPress' event of this <code>sap.suite.ui.commons.ChartContainer</code>.<br/>
*
* The passed function and listener object must match the ones used for event registration.
*
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* oListener Context object on which the given function had to be called.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ChartContainer#detachCustomZoomOutPress
* @function
*/
/**
* Fire event customZoomOutPress to attached listeners.
*
* @param {Map} [mArguments] the arguments to pass along with the event.
* @return {sap.suite.ui.commons.ChartContainer} <code>this</code> to allow method chaining
* @protected
* @name sap.suite.ui.commons.ChartContainer#fireCustomZoomOutPress
* @function
*/
/**
* Switch display content in the container.
*
* @name sap.suite.ui.commons.ChartContainer#switchChart
* @function
* @type sap.suite.ui.commons.ChartContainerContent
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
/**
* Update ChartContainer rerendering all its contents.
*
* @name sap.suite.ui.commons.ChartContainer#updateChartContainer
* @function
* @type void
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
/**
* Returns the currently selected content control.
*
* @name sap.suite.ui.commons.ChartContainer#getSelectedContent
* @function
* @type sap.ui.core.Control
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
// Start of sap/suite/ui/commons/ChartContainer.js
jQuery.sap.require("sap.m.Button");
jQuery.sap.require("sap.m.Select");
jQuery.sap.require("sap.ui.core.ResizeHandler");
jQuery.sap.require("sap.ui.Device");
jQuery.sap.require("sap.m.OverflowToolbarButton");
jQuery.sap.require("sap.ui.core.delegate.ScrollEnablement");
sap.ui.getCore().loadLibrary("sap.viz");
/////////////////////////// PUBLIC SECTION ///////////////////////////
sap.suite.ui.commons.ChartContainer.prototype.setFullScreen = function(fullscreen){
if (this._firstTime) {
// can't set the full screen and toggle since dom is not loaded yet
return;
}
if (this.getFullScreen() == fullscreen) { //check setter is overridden, if not, no need to set the property
return;
}
var fullScreen = this.getProperty("fullScreen");
if (fullScreen !== fullscreen) {
this._toggleFullScreen();
}
};
/**
* Switch currently viewed content (causes rerendering)
*
* @public
* @param {sap.ui.core.Control} chart The new content (Chart or Table) to be displayed
*/
sap.suite.ui.commons.ChartContainer.prototype.switchChart = function(chart) {
this._setSelectedContent(chart);
// fire the change event with id of the newly selected item..
this.rerender(); //invalidate();
};
sap.suite.ui.commons.ChartContainer.prototype.setTitle = function(value) {
this._oChartTitle.setText(value);
this.setProperty("title", value, true);
};
sap.suite.ui.commons.ChartContainer.prototype.setShowLegendButton = function(value) {
//no need to re-set the property to the same value as before
if (this.getShowLegendButton() === value) {
return;
}
this.setProperty("showLegendButton", value, false);
if (!this.getShowLegendButton()) {
this.setShowLegend(false);
}
};
sap.suite.ui.commons.ChartContainer.prototype.setShowLegend = function(value) {
this.setProperty("showLegend", value, false);
//propagate to all charts
var aContents = this.getAggregation("content");
if (aContents) {
for (var i = 0; i < aContents.length; i++) {
var innerChart = aContents[i].getContent();
if (jQuery.isFunction(innerChart.setLegendVisible)) {
innerChart.setLegendVisible(value);
} else {
jQuery.sap.log.info("ChartContainer: chart id " + innerChart.getId() + " is missing the setVizProperties property");
}
}
}
};
sap.suite.ui.commons.ChartContainer.prototype.addAggregation = function(sAggregationName, oObject, bSuppressInvalidate) {
if (sAggregationName === "dimensionSelectors") {
return this.addDimensionSelector(oObject);
} else {
return sap.ui.base.ManagedObject.prototype.addAggregation.apply(this, arguments);
}
};
sap.suite.ui.commons.ChartContainer.prototype.getAggregation = function(sAggregationName, oDefaultForCreation) {
if (sAggregationName === "dimensionSelectors") {
return this.getDimensionSelectors();
} else {
return sap.ui.base.ManagedObject.prototype.getAggregation.apply(this, arguments);
}
};
sap.suite.ui.commons.ChartContainer.prototype.indexOfAggregation = function(sAggregationName, oObject) {
if (sAggregationName === "dimensionSelectors") {
return this.indexOfDimensionSelector(oObject);
} else {
return sap.ui.base.ManagedObject.prototype.indexOfAggregation.apply(this, arguments);
}
};
sap.suite.ui.commons.ChartContainer.prototype.insertAggregation = function(sAggregationName, oObject, iIndex, bSuppressInvalidate) {
if (sAggregationName === "dimensionSelectors") {
return this.insertDimensionSelector(oObject, iIndex);
} else {
return sap.ui.base.ManagedObject.prototype.insertAggregation.apply(this, arguments);
}
};
sap.suite.ui.commons.ChartContainer.prototype.destroyAggregation = function(sAggregationName, bSuppressInvalidate) {
if (sAggregationName === "dimensionSelectors") {
return this.destroyDimensionSelectors();
} else {
return sap.ui.base.ManagedObject.prototype.destroyAggregation.apply(this, arguments);
}
};
sap.suite.ui.commons.ChartContainer.prototype.removeAggregation = function(sAggregationName, vObject, bSuppressInvalidate) {
if (sAggregationName === "dimensionSelectors") {
return this.removeDimensionSelector(vObject);
} else {
return sap.ui.base.ManagedObject.prototype.removeAggregation.apply(this, arguments);
}
};
sap.suite.ui.commons.ChartContainer.prototype.removeAllAggregation = function(sAggregationName, bSuppressInvalidate) {
if (sAggregationName === "dimensionSelectors") {
return this.removeAllDimensionSelectors();
} else {
return sap.ui.base.ManagedObject.prototype.removeAllAggregation.apply(this, arguments);
}
};
sap.suite.ui.commons.ChartContainer.prototype.addDimensionSelector = function(obj) {
this._dimSelectorsAll.push(obj);
return this;
};
sap.suite.ui.commons.ChartContainer.prototype.getDimensionSelectors = function() {
return this._dimSelectorsAll;
};
sap.suite.ui.commons.ChartContainer.prototype.indexOfDimensionSelector = function(oDimensionSelector) {
for (var i = 0; i < this._dimSelectorsAll.length; i++) {
if (this._dimSelectorsAll[i] === oDimensionSelector) {
return i;
}
}
return -1;
};
sap.suite.ui.commons.ChartContainer.prototype.insertDimensionSelector = function(oDimensionSelector, iIndex) {
if (!oDimensionSelector) {
return this;
}
var i;
if (iIndex < 0) {
i = 0;
} else if (iIndex > this._dimSelectorsAll.length) {
i = this._dimSelectorsAll.length;
} else {
i = iIndex;
}
if (i !== iIndex) {
jQuery.sap.log.warning("ManagedObject.insertAggregation: index '" + iIndex + "' out of range [0," + this._dimSelectorsAll.length + "], forced to " + i);
}
this._dimSelectorsAll.splice(i, 0, oDimensionSelector);
return this;
};
sap.suite.ui.commons.ChartContainer.prototype.destroyDimensionSelectors = function() {
if (this._oToolBar) {
for (var i = 0; i < this._dimSelectorsAll.length; i++) {
if (this._dimSelectorsAll[i]) {
this._oToolBar.removeContent(this._dimSelectorsAll[i]);
this._dimSelectorsAll[i].destroy();
}
}
}
this._dimSelectorsAll = [];
return this;
};
sap.suite.ui.commons.ChartContainer.prototype.removeDimensionSelector = function(vDimensionSelector) {
if (this._oToolBar) {
this._oToolBar.removeContent(vDimensionSelector);
}
if (!vDimensionSelector) {
return null;
} else {
var index = this.indexOfDimensionSelector(vDimensionSelector);
if (index === -1) {
return null;
} else {
var aReturn = this._dimSelectorsAll.splice(index, 1);
return aReturn[0];
}
}
};
sap.suite.ui.commons.ChartContainer.prototype.removeAllDimensionSelectors = function() {
var aReturn = this._dimSelectorsAll.slice();
if (this._oToolBar) {
for (var i = 0; i < this._dimSelectorsAll.length; i++) {
if (this._dimSelectorsAll[i]) {
this._oToolBar.removeContent(this._dimSelectorsAll[i]);
}
}
}
this._dimSelectorsAll = [];
return aReturn;
};
sap.suite.ui.commons.ChartContainer.prototype.addContent = function(obj) {
this.addAggregation("content", obj);
this._chartContentChange = true;
};
sap.suite.ui.commons.ChartContainer.prototype.insertContent = function(obj, index) {
this.insertAggregation("content", obj, index);
this._chartContentChange = true;
};
/**
* @deprecated Not used anymore
*/
sap.suite.ui.commons.ChartContainer.prototype.updateContent = function() {
this.updateAggregation("content");
this._chartContentChange = true;
};
/**
* Updates ChartContainer and rerenders all its contents.
*
* @public
*/
sap.suite.ui.commons.ChartContainer.prototype.updateChartContainer = function() {
this._chartContentChange = true;
this.rerender();
};
/**
* Set selectorGroupLabel without causing a rerendering of the ChartContainer
* @deprecated
* @param {String} selectorGroupLabel The new selectorGroupLabel to be set
*/
sap.suite.ui.commons.ChartContainer.prototype.setSelectorGroupLabel = function(selectorGroupLabel) {
this.setProperty("selectorGroupLabel", selectorGroupLabel, true);
};
/**
* Returns the currently selected content control.
*
* @public
* @return {sap.ui.core.Control} The currently selected content
*/
sap.suite.ui.commons.ChartContainer.prototype.getSelectedContent = function() {
return this._oSelectedContent;
};
/**
* Returns the currently instance of the delegate to other controls.
*
* @public
* @return {sap.ui.core.delegate.ScrollEnablement} The currently instance of the delegate
*/
sap.suite.ui.commons.ChartContainer.prototype.getScrollDelegate = function() {
return this._oScrollEnablement;
};
////////////////////////// Life cycle methods ///////////////////////////
sap.suite.ui.commons.ChartContainer.prototype.init = function() {
var that = this;
this._bValue = null;
this._firstTime = true;
this._aChartIcons = [];
this._selectedChart = null;
this._dimSelectorsAll = [];
this._customIconsAll = [];
this._oShowLegendButton = null;
this._oActiveChartButton = null;
this._oSelectedContent = null;
this._bSegmentedButtonSaveSelectState = false;
this._mOriginalVizFrameHeights = {};
this.oResBundle = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.commons");
//Right side..
//Full screen button
this._oFullScreenButton = new sap.m.OverflowToolbarButton({
icon : "sap-icon://full-screen",
type : sap.m.ButtonType.Transparent,
text : this.oResBundle.getText("CHARTCONTAINER_FULLSCREEN"),
tooltip : this.oResBundle.getText("CHARTCONTAINER_FULLSCREEN"),
press: function() {
that._bSegmentedButtonSaveSelectState = true;
that._toggleFullScreen();
}
});
//Popup for chart content
this._oPopup = new sap.ui.core.Popup({
modal : true,
shadow : false,
autoClose : false
});
//legend button
this._oShowLegendButton = new sap.m.OverflowToolbarButton({
icon : "sap-icon://legend",
type : sap.m.ButtonType.Transparent,
text : this.oResBundle.getText("CHARTCONTAINER_LEGEND"),
tooltip : this.oResBundle.getText("CHARTCONTAINER_LEGEND"),
press: function() {
that._bSegmentedButtonSaveSelectState = true;
that._onLegendButtonPress();
}
});
//personalization button
this._oPersonalizationButton = new sap.m.OverflowToolbarButton({
icon : "sap-icon://action-settings",
type : sap.m.ButtonType.Transparent,
text : this.oResBundle.getText("CHARTCONTAINER_PERSONALIZE"),
tooltip : this.oResBundle.getText("CHARTCONTAINER_PERSONALIZE"),
press: function() {
that._oPersonalizationPress();
}
});
//zoom in button
this._oZoomInButton = new sap.m.OverflowToolbarButton({
icon : "sap-icon://zoom-in",
type : sap.m.ButtonType.Transparent,
text : this.oResBundle.getText("CHARTCONTAINER_ZOOMIN"),
tooltip : this.oResBundle.getText("CHARTCONTAINER_ZOOMIN"),
press: function() {
that._zoom(true);
}
});
//zoom out button
this._oZoomOutButton = new sap.m.OverflowToolbarButton({
icon : "sap-icon://zoom-out",
type : sap.m.ButtonType.Transparent,
text : this.oResBundle.getText("CHARTCONTAINER_ZOOMOUT"),
tooltip : this.oResBundle.getText("CHARTCONTAINER_ZOOMOUT"),
press: function() {
that._zoom(false);
}
});
//segmentedButton for chart and table
this._oChartSegmentedButton = new sap.m.SegmentedButton({
select: function(oEvent) {
var sChartId = oEvent.getParameter("button").getCustomData()[0].getValue();
that._bSegmentedButtonSaveSelectState = true;
that._switchChart(sChartId);
}
});
//Left side...
//display title if no dimensionselectors
this._oChartTitle = new sap.m.Label();
//overflow toolbar
this._oToolBar = new sap.m.OverflowToolbar({
// Use ToolBarDesign.Auto
content : [new sap.m.ToolbarSpacer()],
width: "auto"
});
this.setAggregation("toolBar", this._oToolBar);
this._currentRangeName = sap.ui.Device.media.getCurrentRange(sap.ui.Device.media.RANGESETS.SAP_STANDARD).name;
sap.ui.Device.media.attachHandler(this._handleMediaChange, this, sap.ui.Device.media.RANGESETS.SAP_STANDARD);
this.sResizeListenerId = null;
if (jQuery.device.is.desktop) {
this.sResizeListenerId = sap.ui.core.ResizeHandler.register(this, jQuery.proxy(this._performHeightChanges, this));
} else {
sap.ui.Device.orientation.attachHandler(this._performHeightChanges, this);
sap.ui.Device.resize.attachHandler(this._performHeightChanges, this);
}
};
sap.suite.ui.commons.ChartContainer.prototype.onAfterRendering = function() {
var that = this;
if ((this.sResizeListenerId === null) && (jQuery.device.is.desktop)) {
this.sResizeListenerId = sap.ui.core.ResizeHandler.register(this, jQuery.proxy(this._performHeightChanges, this));
}
if (this.getAutoAdjustHeight() || this.getFullScreen()) {
//fix the flickering issue when switch chart in full screen mode
jQuery.sap.delayedCall(500, this, function() {
that._performHeightChanges();
});
}
var bVizFrameSelected = this.getSelectedContent() && this.getSelectedContent().getContent() instanceof sap.viz.ui5.controls.VizFrame;
this._oScrollEnablement = new sap.ui.core.delegate.ScrollEnablement(this, this.getId() + "-wrapper", {
horizontal : !bVizFrameSelected,
vertical : !bVizFrameSelected
});
this._firstTime = false;
};
sap.suite.ui.commons.ChartContainer.prototype.onBeforeRendering = function() {
var onPress = function(oEvent, oData) {
oData.icon.firePress({
controlReference : oEvent.getSource()
});
};
if (this._chartContentChange || this._firstTime) {
this._chartChange();
}
if (this.getAggregation("customIcons") && this.getAggregation("customIcons").length > 0) {
if (this._customIconsAll.length === 0) {
for (var i = 0; i < this.getAggregation("customIcons").length; i++) {
var oIcon = this.getAggregation("customIcons")[i];
var oButton = new sap.m.OverflowToolbarButton({
icon : oIcon.getSrc(),
text : oIcon.getTooltip(),
tooltip : oIcon.getTooltip(),
type : sap.m.ButtonType.Transparent,
width : "3rem"
});
oButton.attachPress({
icon : oIcon
}, onPress);
this._customIconsAll.push(oButton);
}
}
} else {
this._customIconsAll = [];
}
this._adjustDisplay();
};
sap.suite.ui.commons.ChartContainer.prototype.exit = function() {
sap.ui.Device.media.detachHandler(this._handleMediaChange, this, sap.ui.Device.media.RANGESETS.SAP_STANDARD);
if (this._oFullScreenButton) {
this._oFullScreenButton.destroy();
this._oFullScreenButton = undefined;
}
if (this._oPopup) {
this._oPopup.destroy();
this._oPopup = undefined;
}
if (this._oShowLegendButton) {
this._oShowLegendButton.destroy();
this._oShowLegendButton = undefined;
}
if (this._oPersonalizationButton) {
this._oPersonalizationButton.destroy();
this._oPersonalizationButton = undefined;
}
if (this._oActiveChartButton) {
this._oActiveChartButton.destroy();
this._oActiveChartButton = undefined;
}
if (this._oChartSegmentedButton) {
this._oChartSegmentedButton.destroy();
this._oChartSegmentedButton = undefined;
}
if (this._oSelectedContent) {
this._oSelectedContent.destroy();
this._oSelectedContent = undefined;
}
if (this._oToolBar) {
this._oToolBar.destroy();
this._oToolBar = undefined;
}
if (this._dimSelectorsAll) {
for (var i = 0; i < this._dimSelectorsAll.length; i++){
if (this._dimSelectorsAll[i]) {
this._dimSelectorsAll[i].destroy();
}
}
this._dimSelectorsAll = undefined;
}
if (this._oScrollEnablement) {
this._oScrollEnablement.destroy();
this._oScrollEnablement = undefined;
}
if (jQuery.device.is.desktop && this.sResizeListenerId) {
sap.ui.core.ResizeHandler.deregister(this.sResizeListenerId);
this.sResizeListenerId = null;
} else {
sap.ui.Device.orientation.detachHandler(this._performHeightChanges, this);
sap.ui.Device.resize.detachHandler(this._performHeightChanges, this);
}
if (this._oZoomInButton) {
this._oZoomInButton.destroy();
this._oZoomInButton = undefined;
}
if (this._oZoomOutButton) {
this._oZoomOutButton.destroy();
this._oZoomOutButton = undefined;
}
};
////////////////////////// PRIVATE SECTION ///////////////////////////
/**
* Toggle normal and full screen mode
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._toggleFullScreen = function() {
var bFullScreen,
sId,
sHeight,
aContent,
oObjectContent;
bFullScreen = this.getProperty("fullScreen");
if (bFullScreen) {
aContent = this.getAggregation("content");
this._closeFullScreen();
this.setProperty("fullScreen", false, true);
for (var i = 0; i < aContent.length; i++) {
oObjectContent = aContent[i].getContent();
oObjectContent.setWidth("100%");
sHeight = this._mOriginalVizFrameHeights[oObjectContent.getId()];
if (sHeight) {
oObjectContent.setHeight(sHeight);
}
}
this.invalidate();
} else {
//fix chart disappear when toggle chart with full screen button
//by surpressing the invalid for the setProperty, this delay shouldn't be needed.
this._openFullScreen();
this.setProperty("fullScreen", true, true);
}
var sIcon = (bFullScreen ? "sap-icon://full-screen" : "sap-icon://exit-full-screen");
this._oFullScreenButton.setIcon(sIcon);
this._oFullScreenButton.focus();
};
/**
* Open chartcontainer content with Full Screen
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._openFullScreen = function() {
this.$content = this.$();
if (this.$content) {
this.$tempNode = jQuery("<div></div>"); // id='" + this.$content.attr("id")+"-overlay"+ "'
this.$content.before(this.$tempNode);
this._$overlay = jQuery("<div id='" + jQuery.sap.uid() + "'></div>");
this._$overlay.addClass("sapSuiteUiCommonsChartContainerOverlay");
this._$overlay.append(this.$content);
this._oPopup.setContent(this._$overlay);
} else {
jQuery.sap.log.warn("Overlay: content does not exist or contains more than one child");
}
this._oPopup.open(200, null, jQuery("body"));
};
/**
* Close Full Screen and return to normal mode
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._closeFullScreen = function() {
if (this._oScrollEnablement !== null) {
this._oScrollEnablement.destroy();
this._oScrollEnablement = null;
}
this.$tempNode.replaceWith(this.$content);
this._oToolBar.setDesign(sap.m.ToolbarDesign.Auto);
this._oPopup.close();
this._$overlay.remove();
};
/**
* Height change when toggle full and normal mode
* Mobile swap between portrait and landscape will execute height change too
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._performHeightChanges = function() {
var $this,
iChartContainerHeight,
iToolBarHeight,
iToolbarBottomBorder,
iNewChartHeight,
iExistingChartHeight,
oInnerChart;
if (this.getAutoAdjustHeight() || this.getFullScreen()) {
$this = this.$();
// Only adjust height after both toolbar and chart are rendered in DOM
if (($this.find('.sapSuiteUiCommonsChartContainerToolBarArea').children()[0]) && ($this.find('.sapSuiteUiCommonsChartContainerChartArea').children()[0])) {
iChartContainerHeight = $this.height();
iToolBarHeight = $this.find('.sapSuiteUiCommonsChartContainerToolBarArea').children()[0].clientHeight;
iToolbarBottomBorder = Math.round(parseFloat($this.find('.sapSuiteUiCommonsChartContainerToolBarArea').children().css("border-bottom")));
if (isNaN(iToolbarBottomBorder)) {
iToolbarBottomBorder = 0;
}
iNewChartHeight = iChartContainerHeight - iToolBarHeight - iToolbarBottomBorder;
iExistingChartHeight = $this.find('.sapSuiteUiCommonsChartContainerChartArea').children()[0].clientHeight;
oInnerChart = this.getSelectedContent().getContent();
if ((oInnerChart instanceof sap.viz.ui5.controls.VizFrame) || (sap.chart && sap.chart.Chart && oInnerChart instanceof sap.chart.Chart)) {
if (iNewChartHeight > 0 && iNewChartHeight !== iExistingChartHeight) {
this._rememberOriginalHeight(oInnerChart);
oInnerChart.setHeight(iNewChartHeight + "px");
}
} else if (oInnerChart.getDomRef().offsetWidth !== this.getDomRef().clientWidth) {
// For table/non-vizFrame case, if width changes during resize event, force a rerender to have it fit 100% width
this.rerender();
}
}
}
};
/**
* In the fullscreen mode it is necessary to remember the original height of the current chart
* to be able to restore it later on in non fullscreen mode
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._rememberOriginalHeight = function(chart) {
var sId,
sHeight;
sId = chart.getId();
if (jQuery.isFunction(chart.getHeight)) {
sHeight = chart.getHeight();
} else {
sHeight = 0;
}
this._mOriginalVizFrameHeights[sId] = sHeight;
};
/**
* Legend button pressed
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._onLegendButtonPress = function() {
if (this.getSelectedContent()) {
var selectedChart = this.getSelectedContent().getContent();
//only support if content has legendVisible property
if (jQuery.isFunction(selectedChart.getLegendVisible)) {
var legendOn = selectedChart.getLegendVisible();
selectedChart.setLegendVisible(!legendOn);
this.setShowLegend(!legendOn);
} else {
this.setShowLegend(!this.getShowLegend());
}
} else {
this.setShowLegend(!this.getShowLegend());
}
};
/**
* Personalization button pressed
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._oPersonalizationPress = function() {
this.firePersonalizationPress();
};
/**
* Switch Chart - i.e. default with bubble chart and click bar chart button
*
* @private
* @param {String} chartId The ID of the chart to be searched
*/
sap.suite.ui.commons.ChartContainer.prototype._switchChart = function(chartId) {
var oChart = this._findChartById(chartId);
this._setSelectedContent(oChart);
this.fireContentChange({
selectedItemId : chartId
}); // fire the change event with id of the newly selected item..
this.rerender(); //invalidate();
};
/**
* Collect all charts
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._chartChange = function() {
var aCharts = this.getContent();
this._destroyButtons(this._aChartIcons);
this._aChartIcons = [];
if (this.getContent().length === 0) {
this._oChartSegmentedButton.removeAllButtons();
this._setDefaultOnSegmentedButton();
this.switchChart(null);
}
if (aCharts) {
for (var i = 0; i < aCharts.length; i++) {
var innerChart = aCharts[i].getContent();
// In case the content is not visible, skip this content.
if (!aCharts[i].getVisible()) {
continue;
}
if (innerChart.setVizProperties) {
innerChart.setVizProperties({
legend : {
visible : this.getShowLegend()
},
sizeLegend : {
visible : this.getShowLegend()
}
});
}
if (innerChart.setWidth) {
innerChart.setWidth("100%");
}
if (jQuery.isFunction(innerChart.setHeight) && this._mOriginalVizFrameHeights[innerChart.getId()]) {
innerChart.setHeight(this._mOriginalVizFrameHeights[innerChart.getId()]);
}
var oButtonIcon = new sap.m.Button({
icon : aCharts[i].getIcon(),
type : sap.m.ButtonType.Transparent,
//fix the chart button and chart itself disappear when switch chart in full screen mode
width: "3rem",
tooltip : aCharts[i].getTitle(),
customData : [new sap.ui.core.CustomData({
key : 'chartId',
value : innerChart.getId()
})],
press : jQuery.proxy(function(oEvent) {
var sChartId = oEvent.getSource().getCustomData()[0].getValue();
this._switchChart(sChartId);
}, this)
});
this._aChartIcons.push(oButtonIcon);
if (i === 0) {
this._setSelectedContent(aCharts[i]);
this._oActiveChartButton = oButtonIcon;
}
}
}
this._chartContentChange = false;
};
/**
* Set selected content
* @param {sap.ui.core.Control} obj The object to be set as currently viewed
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._setSelectedContent = function(obj) {
if (obj === null) {
this._oShowLegendButton.setVisible(false);
return;
}
var oChart = obj.getContent();
var sChartId = oChart.getId();
var oRelatedButton = null;
for (var i = 0; !oRelatedButton && i < this._aChartIcons.length; i++) {
if (this._aChartIcons[i].getCustomData()[0].getValue() === sChartId &&
oChart.getVisible() === true) {
oRelatedButton = this._aChartIcons[i];
this._oChartSegmentedButton.setSelectedButton(oRelatedButton);
break;
}
}
//show/hide the showLegend buttons
var bShowChart = (oChart instanceof sap.viz.ui5.controls.VizFrame) || (jQuery.isFunction(oChart.setLegendVisible)); //hide legend icon if table, show if chart
if (this.getShowLegendButton()){
this._oShowLegendButton.setVisible(bShowChart);
}
var bShowZoom = (this.getShowZoom()) && (sap.ui.Device.system.desktop) && (oChart instanceof sap.viz.ui5.controls.VizFrame);
this._oZoomInButton.setVisible(bShowZoom);
this._oZoomOutButton.setVisible(bShowZoom);
this._oSelectedContent = obj;
};
/**
* Get chart inside the content aggregation by id
*
* @private
* @param {String} id The ID of the content control being searched for
* @returns {sap.ui.core.Control} The object found or null
*/
sap.suite.ui.commons.ChartContainer.prototype._findChartById = function(id) {
var aObjects = this.getAggregation("content");
if (aObjects) {
for (var i = 0; i < aObjects.length; i++) {
if (aObjects[i].getContent().getId() === id) {
return aObjects[i];
}
}
}
return null;
};
/**
* Adjusts customizable icons of overflow toolbar, displays chart buttons
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._adjustIconsDisplay = function() {
for (var i = 0; i < this._customIconsAll.length; i++ ) {
this._oToolBar.addContent(this._customIconsAll[i]);
}
if (!this._firstTime) {
this._oChartSegmentedButton.removeAllButtons();
}
var iLength = this._aChartIcons.length;
if (iLength > 1) {
for (var i = 0; i < iLength; i++) {
this._oChartSegmentedButton.addButton(this._aChartIcons[i]);
}
this._oToolBar.addContent(this._oChartSegmentedButton);
}
if (this.getShowLegendButton()){
this._oToolBar.addContent(this._oShowLegendButton);
}
if (this.getShowPersonalization()) {
this._oToolBar.addContent(this._oPersonalizationButton);
}
if (this.getShowZoom() && (sap.ui.Device.system.desktop)) {
this._oToolBar.addContent(this._oZoomInButton);
this._oToolBar.addContent(this._oZoomOutButton);
}
if (this.getShowFullScreen()) {
this._oToolBar.addContent(this._oFullScreenButton);
}
};
/**
* The first button inside the segmented button is only set as default if the
* user did not click explicitly on another button inside the segmented button
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._setDefaultOnSegmentedButton = function() {
if (!this._bSegmentedButtonSaveSelectState) {
this._oChartSegmentedButton.setSelectedButton(null);
}
this._bSegmentedButtonSaveSelectState = false;
};
/**
* Adjust dimensionselector display
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._adjustSelectorDisplay = function() {
var dimensionSelectors = this.getDimensionSelectors();
if (dimensionSelectors.length === 0) {
this._oChartTitle.setVisible(true);
this._oToolBar.addContent(this._oChartTitle);
return;
}
for (var i = 0; i < dimensionSelectors.length; i++) {
if (jQuery.isFunction(dimensionSelectors[i].setAutoAdjustWidth)) {
dimensionSelectors[i].setAutoAdjustWidth(true);
}
this._oToolBar.insertContent(dimensionSelectors[i], i);
}
};
/**
* Adjust toolbar dimensionselector, customicons, buttons ...
*
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._adjustDisplay = function() {
this._oToolBar.removeAllContent();
this._adjustSelectorDisplay();
this._oToolBar.addContent(new sap.m.ToolbarSpacer());
this._adjustIconsDisplay();
};
/**
* @param {sap.ui.base.Event} evt The SAPUI5 Event Object
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._handleMediaChange = function(evt) {
this._currentRangeName = sap.ui.Device.media.getCurrentRange(sap.ui.Device.media.RANGESETS.SAP_STANDARD).name;
this._adjustDisplay();
};
/**
* Zoom in or out ChartContainer content
*
* @param {Boolean} zoomin Set to true to perform zoom-in action. Set to false (or omit) to zoom out.
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._zoom = function(zoomin) {
var oChart = this.getSelectedContent().getContent();
if (oChart instanceof sap.viz.ui5.controls.VizFrame) {
if (zoomin) {
oChart.zoom({"direction": "in"});
} else {
oChart.zoom({"direction": "out"});
}
}
if (zoomin){
this.fireCustomZoomInPress();
} else {
this.fireCustomZoomOutPress();
}
};
/**
* Buttons which are not needed anymore are destroyed here.
*
* @param {sap.ui.core.Control[]} buttons The buttons which need to be destroyed.
* @private
*/
sap.suite.ui.commons.ChartContainer.prototype._destroyButtons = function(buttons) {
buttons.forEach(function(oButton) {
oButton.destroy();
});
};
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2015 SAP SE. All rights reserved
*/
sap.ui.define([
"sap/ui/core/Control", "sap/ui/core/Core", "sap/m/OverflowToolbar", "sap/m/OverflowToolbarLayoutData", "sap/m/OverflowToolbarPriority", "sap/m/ToolbarSpacer", "sap/m/FlexBox", "sap/m/FlexDirection", "sap/m/FlexJustifyContent",
"sap/m/Button", "sap/m/ButtonType", "sap/m/SegmentedButton", "sap/m/Select",
"sap/ui/core/Item", "sap/m/ViewSettingsDialog", "sap/m/ViewSettingsCustomTab", "sap/m/PlacementType",
"sap/m/CheckBox", "sap/ui/core/Orientation", "./AssociateContainer", "sap/gantt/legend/LegendContainer", "sap/gantt/misc/Utility", "sap/m/Slider", "sap/m/Popover"
], function (Control, Core, OverflowToolbar, OverflowToolbarLayoutData, OverflowToolbarPriority, ToolbarSpacer, FlexBox, FlexDirection, FlexJustifyContent,
Button, ButtonType, SegmentedButton, Select, CoreItem, ViewSettingsDialog, ViewSettingsCustomTab, PlacementType, CheckBox,
Orientation, AssociateContainer, LegendContainer, Utility, Slider, Popover) {
"use strict";
var Toolbar = Control.extend("sap.gantt.control.Toolbar", {
metadata : {
properties : {
width : {type : "CSSSize", defaultValue: "100%"},
height : {type : "CSSSize", defaultValue: "100%"},
type: {type: "string", defaultValue: sap.gantt.control.ToolbarType.Global},
sourceId:{type: "string"},
zoomRate:{type: "float"},
zoomInfo: {type: "object"},
sliderStep: {type: "int"},
enableTimeScrollSync: {type: "boolean", defaultValue: true},
enableRowScrollSync: {type: "boolean", defaultValue: false},
enableCursorLine: {type: "boolean", defaultValue: true},
enableNowLine: {type: "boolean", defaultValue: true},
enableVerticalLine: {type: "boolean", defaultValue: true},
/*
* Configuration property.
*/
modes: {
type: "array",
defaultValue: [sap.gantt.config.DEFAULT_MODE]
},
mode: {
type: "string",
defaultValue: sap.gantt.config.DEFAULT_MODE_KEY
},
/*
* Configuration property.
*/
toolbarSchemes: {
type: "array",
defaultValue: [
sap.gantt.config.DEFAULT_CONTAINER_TOOLBAR_SCHEME,
sap.gantt.config.DEFAULT_GANTTCHART_TOOLBAR_SCHEME,
sap.gantt.config.EMPTY_TOOLBAR_SCHEME
]
},
/*
* Configuration property.
*/
hierarchies: {
type: "array",
defaultValue: [sap.gantt.config.DEFAULT_HIERARCHY]
},
/*
* Configuration property.
*/
containerLayouts: {
type: "array",
defaultValue: [
sap.gantt.config.DEFAULT_CONTAINER_SINGLE_LAYOUT,
sap.gantt.config.DEFAULT_CONTAINER_DUAL_LAYOUT
]
}
},
aggregations : {
legend: {type: "sap.ui.core.Control", multiple: false, visibility: "public"},
customToolbarItems: {type: "sap.ui.core.Control", multiple: true, visibility: "public", singularName: "customToolbarItem"},
_toolbar : {type: "sap.m.OverflowToolbar", multiple: false, visibility: "hidden"}
},
events: {
sourceChange: {
parameters: {
id: {type: "string"}
}
},
layoutChange: {
parameters: {
id: {type: "string"},
value: {type: "string"}
}
},
expandChartChange: {
parameters: {
action: {type: "string"},
expandedChartSchemes: {type: "[]"}
}
},
expandTreeChange: {
parameters: {
action: {type: "string"}
}
},
zoomRateChange: {
parameters:{
zoomRate: {type : "float"}
}
},
settingsChange: {
parameters: {
id: {type: "string"},
value: {type: "boolean"}
}
},
modeChange: {
parameters: {
mode: {type: "string"}
}
}
}
}
});
// shrinkable class name
Toolbar.ToolbarItemPosition = {
Left: "Left",
Right: "Right"
};
Toolbar.prototype.init = function() {
this._oToolbar = new OverflowToolbar({
width: "auto",
design: sap.m.ToolbarDesign.Auto
});
this.setAggregation("_toolbar", this._oToolbar, true);
this._initCustomToolbarInfo();
this._oModesConfigMap = {};
this._oModesConfigMap[sap.gantt.config.DEFAULT_MODE_KEY] = sap.gantt.config.DEFAULT_MODE;
this._oToolbarSchemeConfigMap = {};
this._oToolbarSchemeConfigMap[sap.gantt.config.DEFAULT_CONTAINER_TOOLBAR_SCHEME_KEY] = sap.gantt.config.DEFAULT_CONTAINER_TOOLBAR_SCHEME;
this._oToolbarSchemeConfigMap[sap.gantt.config.DEFAULT_GANTTCHART_TOOLBAR_SCHEME_KEY] = sap.gantt.config.DEFAULT_GANTTCHART_TOOLBAR_SCHEME;
this._oToolbarSchemeConfigMap[sap.gantt.config.EMPTY_TOOLBAR_SCHEME_KEY] = sap.gantt.config.EMPTY_TOOLBAR_SCHEME;
this._oHierarchyConfigMap = {};
this._oHierarchyConfigMap[sap.gantt.config.DEFAULT_HIERARCHY_KEY] = sap.gantt.config.DEFAULT_HIERARCHY;
this._oContainerLayoutConfigMap = {};
this._oContainerLayoutConfigMap[sap.gantt.config.DEFAULT_CONTAINER_SINGLE_LAYOUT_KEY] = sap.gantt.config.DEFAULT_CONTAINER_SINGLE_LAYOUT;
this._oContainerLayoutConfigMap[sap.gantt.config.DEFAULT_CONTAINER_DUAL_LAYOUT_KEY] = sap.gantt.config.DEFAULT_CONTAINER_DUAL_LAYOUT;
this._oZoomSlider = null;
this._iLastChartWidth = -1;
this._iCustomItemInsertIndex = -1;
this._aCustomItems = [];
// iLiveChangeTimer is used to accumulate zoomRate change event in order to reduce shapes drawing cycle
this._iLiveChangeTimer = -1;
this._aTimers = [];
this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.gantt");
};
Toolbar.prototype._initCustomToolbarInfo = function(){
this._oItemConfiguration = {
Left: [],
Right: []
};
// pos 0 is list left controls, 1 is list of right controls
this._oAllCustomItems = {
Left: [],
Right: []
};
this._iCustomItemInsertIndex = -1;
this._aCustomItems = [];
};
/*
* This method happens after init run. It receives config from constructor.
* If it's a binding, the super method would resolve binding, and the right
* timing to access properties is after super call and before returning.
*/
Toolbar.prototype.applySettings = function (mSettings, oScope){
if (this.getSourceId() && this.getType()) {
this._resetAllCompositeControls();
}
var oRetVal = Control.prototype.applySettings.apply(this, arguments);
return oRetVal;
};
Toolbar.prototype.setLegend = function (oLegendContainer){
this.setAggregation("legend", oLegendContainer);
if (!this._oLegendPop) {
this._oLegendPop = new Popover({
placement: PlacementType.Bottom,
showArrow: false,
showHeader: false
});
}
if (oLegendContainer) {
this._oLegendPop.removeAllContent();
this._oLegendPop.addContent(oLegendContainer);
var iOffsetX;
if (Core.getConfiguration().getRTL() === true) {
iOffsetX = 100;
} else {
var oLegend = sap.ui.getCore().byId(oLegendContainer.getContent());
iOffsetX = 100 - parseInt(oLegend.getWidth(), 10);
}
this._oLegendPop.setOffsetX(iOffsetX);
}
};
Toolbar.prototype.setZoomInfo = function(oZoomInfo) {
if (oZoomInfo && oZoomInfo.iChartWidth > 0 && this._oZoomSlider) {
var fMinZoomRate = oZoomInfo.determinedByChartWidth.fMinRate > oZoomInfo.determinedByConfig.fMinRate ?
oZoomInfo.determinedByChartWidth.fMinRate : oZoomInfo.determinedByConfig.fMinRate,
fMaxZoomRate = oZoomInfo.determinedByConfig.fMaxRate,
fSuitableZoomRate = oZoomInfo.determinedByChartWidth.fSuitableRate ?
oZoomInfo.determinedByChartWidth.fSuitableRate :
oZoomInfo.determinedByConfig.fRate;
var fFinalZoomRate = fSuitableZoomRate,
oZoomSlider = this._oZoomSlider,
iLastChartWidth = this._iLastChartWidth;
oZoomSlider.setMin(Math.log(fMinZoomRate));
oZoomSlider.setMax(Math.log(fMaxZoomRate));
var fZoomRate = this.getProperty("zoomRate");
if (fZoomRate && fZoomRate > 0) {
fFinalZoomRate = fZoomRate;
} else {
if (iLastChartWidth === -1) {
// the Last chart Width is -1 which is set in init method indicates that
// This is the first time load, use the default suitable zoom rate
fFinalZoomRate = fSuitableZoomRate;
} else if (iLastChartWidth !== oZoomInfo.iChartWidth) {
fFinalZoomRate = fMinZoomRate;
}
fFinalZoomRate = Math.max(fFinalZoomRate, oZoomSlider.getMin());
fFinalZoomRate = Math.min(fFinalZoomRate, oZoomSlider.getMax());
this.setProperty("zoomRate", fFinalZoomRate);
}
this.setProperty("zoomInfo", oZoomInfo);
oZoomSlider.setValue(Math.log(fFinalZoomRate));
oZoomSlider.setStep((oZoomSlider.getMax() - oZoomSlider.getMin()) / this.getSliderStep());
this.fireZoomRateChange({ zoomRate: fFinalZoomRate});
this._iLastChartWidth = oZoomInfo.iChartWidth;
}
return this;
};
Toolbar.prototype.setMode = function(sMode) {
this.setProperty("mode", sMode);
//update mode button value, when the toolbar is empty, then there is no _oModeSegmentButton.
if (this._oModeSegmentButton) {
this._oModeSegmentButton.setSelectedButton(this._oModeButtonMap[sMode]);
}
return this;
};
Toolbar.prototype.setHierarchies = function (aHierarchies) {
this.setProperty("hierarchies", aHierarchies);
this._oHierarchyConfigMap = {};
if (aHierarchies) {
for (var i = 0; i < aHierarchies.length; i++) {
this._oHierarchyConfigMap[aHierarchies[i].getKey()] = aHierarchies[i];
}
}
this._resetAllCompositeControls();
return this;
};
Toolbar.prototype.setContainerLayouts = function (aContainerLayouts) {
this.setProperty("containerLayouts", aContainerLayouts);
this._oContainerLayoutConfigMap = {};
if (aContainerLayouts) {
for (var i = 0; i < aContainerLayouts.length; i++) {
this._oContainerLayoutConfigMap[aContainerLayouts[i].getKey()] = aContainerLayouts[i];
}
}
this._resetAllCompositeControls();
return this;
};
Toolbar.prototype.setModes = function (aModes) {
this.setProperty("modes", aModes);
this._oModesConfigMap = {};
if (aModes) {
for (var i = 0; i < aModes.length; i++) {
this._oModesConfigMap[aModes[i].getKey()] = aModes[i];
}
}
return this;
};
Toolbar.prototype.setToolbarDesign = function (sToolbarDesign) {
this._oToolbar.setDesign(sToolbarDesign);
return this;
};
Toolbar.prototype.setToolbarSchemes = function (aToolbarSchemes) {
this.setProperty("toolbarSchemes", aToolbarSchemes);
this._oToolbarSchemeConfigMap = {};
if (aToolbarSchemes) {
for (var i = 0; i < aToolbarSchemes.length; i++) {
this._oToolbarSchemeConfigMap[aToolbarSchemes[i].getKey()] = aToolbarSchemes[i];
}
}
this._resetAllCompositeControls();
return this;
};
Toolbar.prototype.setSourceId = function (sSourceId) {
this.setProperty("sourceId", sSourceId);
this._resetAllCompositeControls();
return this;
};
Toolbar.prototype.setType = function (sType) {
this.setProperty("type", sType);
this._resetAllCompositeControls();
return this;
};
Toolbar.prototype.addCustomToolbarItem = function (oCustomToolbarItem) {
if (this._iCustomItemInsertIndex == -1) {
// -1 means no other items found, so put the item at first!
// and move the index cursor to next
this._oToolbar.insertContent(oCustomToolbarItem, 0);
this._iCustomItemInsertIndex++;
} else {
this._oToolbar.insertContent(oCustomToolbarItem, this._iCustomItemInsertIndex + 1);
this._iCustomItemInsertIndex++;
}
this._aCustomItems.push(oCustomToolbarItem);
return this;
};
Toolbar.prototype.insertCustomToolbarItem = function (oCustomToolbarItem, iIndex) {
var iMaxLength = this._aCustomItems.length;
if (iIndex >= iMaxLength) {
iIndex = iMaxLength;
}
if (this._iCustomItemInsertIndex === -1) {
//-1 means no other items found, put the item at first
this._oToolbar.insertContent(oCustomToolbarItem, 0);
this._aCustomItems.push(oCustomToolbarItem);
} else {
//this._iCustomItemInsertIndex - this._aCustomItems.length + 1 is the start position of the custom item
this._oToolbar.insertContent(oCustomToolbarItem, this._iCustomItemInsertIndex - this._aCustomItems.length + 1 + iIndex);
this._aCustomItems.splice(iIndex, 0, oCustomToolbarItem);
}
this._iCustomItemInsertIndex++;
return this;
};
Toolbar.prototype.removeCustomToolbarItem = function (vCustomToolbarItem) {
if (this._aCustomItems.length === 0) {
return this._aCustomItems;
}
if ((typeof vCustomToolbarItem) === "number") {
var iCustomItemCount = this._aCustomItems.length;
var iRemoveCustomIndex = vCustomToolbarItem > iCustomItemCount ? iCustomItemCount : vCustomToolbarItem;
this._oToolbar.removeContent(this._iCustomItemInsertIndex - iCustomItemCount + iRemoveCustomIndex + 1);
this._iCustomItemInsertIndex--;
return this._aCustomItems.splice(iRemoveCustomIndex, 1);
} else if (vCustomToolbarItem) {
this._oToolbar.removeContent(vCustomToolbarItem);
this._iCustomItemInsertIndex--;
return this._aCustomItems.splice(jQuery.inArray(vCustomToolbarItem, this._aCustomItems), 1);
}
};
Toolbar.prototype.removeAllCustomToolbarItems = function () {
var aRemovedItems = [];
for (var iIndex = 0; iIndex < this._aCustomItems.length; iIndex++) {
aRemovedItems.push(this._oToolbar.removeContent(this._aCustomItems[iIndex]));
}
this._iCustomItemInsertIndex = this._iCustomItemInsertIndex - this._aCustomItems.length;
this._aCustomItems.splice(0, this._aCustomItems.length);
return aRemovedItems;
};
Toolbar.prototype._resetAllCompositeControls = function() {
// determine this._sToolbarSchemeKey, this._sInitMode and this._oToolbarScheme
this._determineToolbarSchemeConfig(this.getSourceId());
this._destroyCompositeControls();
if (!this._sToolbarSchemeKey) {
return;
}
// sort group config into this._oItemConfiguration
this._resolvePositions();
var iIndex,
oContent,
sLeft = Toolbar.ToolbarItemPosition.Left,
sRight = Toolbar.ToolbarItemPosition.Right;
var aLeftItemsConfig = this._oItemConfiguration[sLeft];
for (iIndex = 0; iIndex < aLeftItemsConfig.length; iIndex++) {
if (aLeftItemsConfig[iIndex]) {
// the index might come consecutive
this._createCompositeControl(sLeft, iIndex, aLeftItemsConfig[iIndex]);
}
}
var aRightItemsConfig = this._oItemConfiguration[sRight];
for (iIndex = 0; iIndex < aRightItemsConfig.length; iIndex++) {
if (aRightItemsConfig[iIndex]) {
this._createCompositeControl(sRight, iIndex, aRightItemsConfig[iIndex]);
}
}
var fnAddToolbarContent = function (oContent) {
if (jQuery.isArray(oContent)) {
for (var m = 0; m < oContent.length; m++) {
this._oToolbar.addContent(oContent[m]);
}
} else if (oContent) {
this._oToolbar.addContent(oContent);
}
};
// add left items
for (iIndex = 0; iIndex < this._oAllCustomItems[sLeft].length; iIndex++) {
oContent = this._oAllCustomItems[sLeft][iIndex];
fnAddToolbarContent.call(this, oContent);
}
// add spacer
if (this._oAllCustomItems[sLeft].length !== 0 || this._oAllCustomItems[sRight].length !== 0) {
this._oToolbar.addContent(new ToolbarSpacer());
}
// add right items, reverse order
for (iIndex = this._oAllCustomItems[sRight].length - 1; iIndex >= 0; iIndex--) {
oContent = this._oAllCustomItems[sRight][iIndex];
fnAddToolbarContent.call(this, oContent);
}
var oZoomInfo = this.getProperty("zoomInfo");
if (oZoomInfo) {
this.setZoomInfo(oZoomInfo);
}
};
Toolbar.prototype.getAllToolbarItems = function () {
return this._oToolbar.getContent();
};
Toolbar.prototype._determineToolbarSchemeConfig = function (sSourceId) {
this._sToolbarSchemeKey = null;
// determine toolbarSchemeId
if (this.getType() === sap.gantt.control.ToolbarType.Global && this._oContainerLayoutConfigMap[sSourceId]) {
this._sToolbarSchemeKey = this._oContainerLayoutConfigMap[sSourceId].getToolbarSchemeKey();
this._sInitMode = this.getMode() != sap.gantt.config.DEFAULT_MODE_KEY ? this.getMode() : this._oContainerLayoutConfigMap[sSourceId].getActiveModeKey();
} else if (this.getType() === sap.gantt.control.ToolbarType.Local && this._oHierarchyConfigMap[sSourceId]) {
this._sToolbarSchemeKey = this._oHierarchyConfigMap[sSourceId].getToolbarSchemeKey();
this._sInitMode = this.getMode() != sap.gantt.config.DEFAULT_MODE_KEY ? this.getMode() : this._oHierarchyConfigMap[sSourceId].getActiveModeKey();
}
// determine toolbar scheme config
this._oToolbarScheme = this._oToolbarSchemeConfigMap[this._sToolbarSchemeKey];
if (this._oToolbarScheme && this._oToolbarScheme.getProperty("toolbarDesign")) {
this.setToolbarDesign(this._oToolbarScheme.getProperty("toolbarDesign"));
}
};
Toolbar.prototype._destroyCompositeControls = function() {
this._oToolbar.removeAllContent();
this._initCustomToolbarInfo();
};
Toolbar.prototype._resolvePositions = function() {
if (this._oToolbarScheme) {
jQuery.each(this._oToolbarScheme.getMetadata().getAllProperties(), function (sProperty) {
if (sProperty !== "key" && sProperty !== "toolbarDesign") {
var oProperty = this._oToolbarScheme.getProperty(sProperty);
if (oProperty) {
var oPosition = this._parsePosition(oProperty.getPosition());
this._oItemConfiguration[oPosition.position][oPosition.idx] = $.extend({}, {groupId: sProperty}, oProperty);
}
}
}.bind(this));
var oSchemeConfiguration = this._oItemConfiguration;
var aAlignments = Object.keys(oSchemeConfiguration);
aAlignments.forEach(function(sAlignmentKey) {
var aSchemes = oSchemeConfiguration[sAlignmentKey],
newSchemes = [];
var aSchemeSortedKeys = Object.keys(aSchemes).sort();
aSchemeSortedKeys.forEach(function(sSchemeKey, aSelf) {
newSchemes.push(aSchemes[sSchemeKey]);
});
oSchemeConfiguration[sAlignmentKey] = newSchemes;
});
}
};
Toolbar.prototype._parsePosition = function(sPosition) {
return {
position: sPosition.toUpperCase().substr(0, 1) === "L" ? Toolbar.ToolbarItemPosition.Left : Toolbar.ToolbarItemPosition.Right,
idx: parseInt(sPosition.substr(1, sPosition.length - 1), 10)
};
};
Toolbar.prototype._createCompositeControl = function(sPosition, iIndex, oGroupConfig) {
var vControl;
switch (oGroupConfig.groupId) {
case "sourceSelect":
vControl = this._genSourceSelectGroup(oGroupConfig);
break;
case "layout":
vControl = this._genLayoutGroup(oGroupConfig);
break;
case "expandChart":
vControl = this._genExpandChartGroup(oGroupConfig);
break;
case "expandTree":
vControl = this._genExpandTreeGroup(oGroupConfig);
break;
case "customToolbarItems":
vControl = this._genCustomToolbarItemGroup(sPosition, oGroupConfig);
break;
case "mode":
vControl = this._genModeButtonGroup(oGroupConfig);
break;
case "timeZoom":
vControl = this._genZoomSliderGroupControls(oGroupConfig);
break;
case "legend":
vControl = this._genLegend(oGroupConfig);
break;
case "settings":
vControl = this._genSettings(oGroupConfig);
break;
default:
break;
}
if (vControl) {
this._oAllCustomItems[sPosition] = this._oAllCustomItems[sPosition].concat(vControl);
}
};
Toolbar.prototype._genSourceSelectGroup = function(oGroupConfig) {
var sSourceId = this.getSourceId();
// that is toolbar itself
var that = this;
var aSource;
this._oSourceSelectBox = new Select({
layoutData: new OverflowToolbarLayoutData({priority: oGroupConfig.getOverflowPriority()}),
width: "200px",
change: function (oEvent) {
var oItem = oEvent.getParameter("selectedItem");
var oSourceConfig = oItem.oSourceConfig;
that.fireSourceChange({
id: oItem.getKey(),
config: oSourceConfig
});
}
});
switch (this.getType()){
case sap.gantt.control.ToolbarType.Global:
aSource = this.getContainerLayouts();
this._oSourceSelectBox.setTooltip(this._oRb.getText("TLTP_GLOBAL_HIERARCHY_RESOURCES"));
break;
case sap.gantt.control.ToolbarType.Local:
aSource = this.getHierarchies();
this._oSourceSelectBox.setTooltip(this._oRb.getText("TLTP_LOCAL_HIERARCHY_RESOURCES"));
break;
default:
return null;
}
var oCoreItem;
for (var iIndex = 0; iIndex < aSource.length; iIndex++) {
oCoreItem = new CoreItem({
key: aSource[iIndex].getKey(),
text: aSource[iIndex].getText()
});
oCoreItem.oSourceConfig = aSource[iIndex];
this._oSourceSelectBox.addItem(oCoreItem);
if (oCoreItem.getKey() === sSourceId) {
this._oSourceSelectBox.setSelectedItem(oCoreItem);
}
}
return this._oSourceSelectBox;
};
Toolbar.prototype._genLayoutGroup = function(oGroupConfig) {
if (this.getType === "LOCAL") {
return null;
}
var that = this,
aHierarchies = this.getHierarchies(),
oCoreItem,
i;
// addGanttChart Select
this._oAddGanttChartSelect = new Select({
icon : "sap-icon://add",
type: sap.m.SelectType.IconOnly,
autoAdjustWidth: true,
tooltip: this._oRb.getText("TLTP_ADD_GANTTCHART"),
forceSelection: false,
layoutData: new OverflowToolbarLayoutData({priority: oGroupConfig.getOverflowPriority()}),
change: function (oEvent) {
if (oEvent.getParameter("selectedItem")) {
that.fireLayoutChange({
id: "add",
value: {
hierarchyKey: oEvent.getParameter("selectedItem").getKey(),
hierarchyConfig: oEvent.getParameter("selectedItem").data("hierarchyConfig")
}
});
oEvent.getSource().setSelectedItemId("");
}
}
});
// add items if exist
if (aHierarchies && aHierarchies.length > 0) {
for (i = 0; i < aHierarchies.length; i++) {
oCoreItem = new CoreItem({
text: aHierarchies[i].getText(),
key: aHierarchies[i].getKey()
});
oCoreItem.data("hierarchyConfig", aHierarchies[i]);
this._oAddGanttChartSelect.addItem(oCoreItem);
}
}
// lessGanttChartSelect
this._oLessGanttChartSelect = new Select({
icon: "sap-icon://less",
type: sap.m.SelectType.IconOnly,
tooltip: this._oRb.getText("TLTP_REMOVE_GANTTCHART"),
autoAdjustWidth: true,
forceSelection: false,
layoutData: new OverflowToolbarLayoutData({priority: oGroupConfig.getOverflowPriority()}),
change: function (oEvent) {
if (oEvent.getParameter("selectedItem")) {
that.fireLayoutChange({
id: "less",
value: {
hierarchyKey: oEvent.getParameter("selectedItem").getKey(),
hierarchyConfig: oEvent.getParameter("selectedItem").data("hierarchyConfig"),
ganttChartIndex: oEvent.getParameter("selectedItem").data("ganttChartIndex")
}
});
}
}
});
this._oLessGanttChartSelect.addEventDelegate({
onclick: this._fillLessGanttChartSelectItem
}, this);
// VH Layout Button
var sIcon = this._oContainerLayoutConfigMap[this.getSourceId()].getOrientation() === Orientation.Vertical ?
"sap-icon://resize-vertical" : "sap-icon://resize-horizontal";
this._oVHButton = new Button({
icon: sIcon,
tooltip: this._oRb.getText("TLTP_SWITCH_GANTTCHART"),
type: oGroupConfig.getEnableRichStyle() ? ButtonType.Emphasized : ButtonType.Default,
layoutData: new OverflowToolbarLayoutData({priority: oGroupConfig.getOverflowPriority()}),
press: function (oEvent) {
switch (this.getIcon()){
case "sap-icon://resize-vertical":
this.setIcon("sap-icon://resize-horizontal");
that.fireLayoutChange({
id: "orientation",
value: Orientation.Horizontal
});
break;
case "sap-icon://resize-horizontal":
this.setIcon("sap-icon://resize-vertical");
that.fireLayoutChange({
id: "orientation",
value: Orientation.Vertical
});
break;
default:
break;
}
}
});
// Segmented Button
this._oLayoutButton = [this._oAddGanttChartSelect, this._oLessGanttChartSelect, this._oVHButton];
return this._oLayoutButton;
};
Toolbar.prototype._fillLessGanttChartSelectItem = function () {
var aGanttCharts = this.data("holder").getGanttCharts(),
oItem;
this._oLessGanttChartSelect.removeAllItems();
if (aGanttCharts && aGanttCharts.length > 0) {
for (var i = 0; i < aGanttCharts.length; i++) {
oItem = new CoreItem({
text: this._oHierarchyConfigMap[aGanttCharts[i].getHierarchyKey()].getText(),
key: aGanttCharts[i].getHierarchyKey()
});
oItem.data("hierarchyConfig",
this._oHierarchyConfigMap[aGanttCharts[i].getHierarchyKey()]);
oItem.data("ganttChartIndex", i);
this._oLessGanttChartSelect.insertItem(oItem, i);
}
}
};
Toolbar.prototype._genExpandChartGroup = function (oGroupConfig) {
this._aChartExpandButtons = [];
var fnPressEventHanlder = function(oEvent) {
this.fireExpandChartChange({
isExpand: oEvent.getSource().data("isExpand"),
expandedChartSchemes: oEvent.getSource().data("chartSchemeKeys")
});
};
var aExpandChartButtonConfig = oGroupConfig.getExpandCharts(),
oButton;
for (var i = 0; i < aExpandChartButtonConfig.length; i++) {
var oConfig = aExpandChartButtonConfig[i];
oButton = new Button({
icon: oConfig.getIcon(),
tooltip: oConfig.getTooltip(),
layoutData: new OverflowToolbarLayoutData({priority: oGroupConfig.getOverflowPriority()}),
press: fnPressEventHanlder.bind(this),
type: oGroupConfig.getEnableRichType() && oConfig.getIsExpand() ?
ButtonType.Emphasized : ButtonType.Default,
customData : [
new sap.ui.core.CustomData({
key : "isExpand",
value : oConfig.getIsExpand()
}),
new sap.ui.core.CustomData({
key : "chartSchemeKeys",
value : oConfig.getChartSchemeKeys()
})
]
});
if (oGroupConfig.getShowArrowText()) {
oButton.setText(oConfig.getIsExpand() ? "ꜜ" : "ꜛ");
//"↓" : "↑",// "⬇" : "⬆",//"⤓" : "⤒",//"⇊" : "⇈",//"↓" : "↑", //"⇩" : "⇧"
}
this._aChartExpandButtons.push(oButton);
}
return this._aChartExpandButtons;
};
Toolbar.prototype._genCustomToolbarItemGroup = function (sPosition, oGroupConfig) {
if (this._iCustomItemInsertIndex === -1) {
// Because the order had been sorted, the position for the custom tool bar item
// is right after the previous items.
var iTotalBeforeLength = this._oAllCustomItems[sPosition].length;
if (iTotalBeforeLength === 0) {
// If there is no item at all before custom items, set the cursor to -1
// It's not only an index but also a flag to indicate the current situation.
this._iCustomItemInsertIndex = -1;
} else {
// Otherwise, the position is the end of the previous items.
this._iCustomItemInsertIndex = iTotalBeforeLength - 1;
}
}
return this._aCustomItems;
};
Toolbar.prototype._genExpandTreeGroup = function (oGroupConfig) {
var that = this; // tool bar itself
this._oTreeGroup = [new Button({
icon: "sap-icon://expand",
tooltip: this._oRb.getText("TLTP_EXPAND"),
layoutData: new OverflowToolbarLayoutData({priority: oGroupConfig.getOverflowPriority()}),
press: function (oEvent) {
that.fireExpandTreeChange({
action: "expand"
});
}
}), new Button({
icon: "sap-icon://collapse",
tooltip: this._oRb.getText("TLTP_COLLAPSE"),
layoutData: new OverflowToolbarLayoutData({priority: oGroupConfig.getOverflowPriority()}),
press: function (oEvent) {
that.fireExpandTreeChange({
action: "collapse"
});
}
})];
return this._oTreeGroup;
};
Toolbar.prototype._genModeButtonGroup = function (oGroupConfig) {
var fnModeButtonGroupSelectHandler = function(oEvent) {
var selected = oEvent.getParameter("button");
this.fireModeChange({
mode: selected.data("mode")
});
};
this._oModeSegmentButton = new SegmentedButton({select: fnModeButtonGroupSelectHandler.bind(this)});
this._oModeButtonMap = {};
var fnJqueryeachFunction = function (iIndex, sMode) {
if (this._oModesConfigMap[sMode]) {
var oButton = new Button({
icon: this._oModesConfigMap[sMode].getIcon(),
activeIcon: this._oModesConfigMap[sMode].getActiveIcon(),
tooltip: this._oModesConfigMap[sMode].getText(),
layoutData: new OverflowToolbarLayoutData({priority: oGroupConfig.getOverflowPriority()}),
customData : [
new sap.ui.core.CustomData({
key : "mode",
value : sMode
})
]
});
this._oModeButtonMap[sMode] = oButton;
this._oModeSegmentButton.addButton(oButton);
}
};
jQuery.each(oGroupConfig.getModeKeys(), fnJqueryeachFunction.bind(this));
if (this._sInitMode) {
this._oModeSegmentButton.setSelectedButton(this._oModeButtonMap[this._sInitMode]);
}
return this._oModeSegmentButton;
};
Toolbar.prototype._genZoomSliderGroupControls = function (oGroupConfig) {
var oLayoutData = new OverflowToolbarLayoutData({
priority: oGroupConfig.getOverflowPriority()
});
var fnCalculateZoomRate = function(fSliderValue) {
return Math.pow(Math.E, fSliderValue);
};
var fnFireZoomRateChange = function(fZoomRate) {
jQuery.sap.clearDelayedCall(this._iLiveChangeTimer);
this._iLiveChangeTimer = -1;
var fLastZoomRate = this.getZoomRate();
this.setProperty("zoomRate", fZoomRate);
if (fZoomRate === fLastZoomRate) {
return ;
}
this.fireZoomRateChange({ zoomRate: fZoomRate });
jQuery.sap.log.debug("Toolbar Zoom Rate was changed, zoomRate is: " + fZoomRate);
};
var oZoomSlider = new Slider({
width: "200px",
layoutData: oLayoutData,
liveChange: function(oEvent) {
var fZoomRate = fnCalculateZoomRate(oEvent.getSource().getValue());
// Clear the previous accumulated event
jQuery.sap.clearDelayedCall(this._iLiveChangeTimer);
this._iLiveChangeTimer = jQuery.sap.delayedCall(200, this, fnFireZoomRateChange, [fZoomRate]);
}.bind(this)
});
var fnZoomButtonPressHandler = function(bZoomIn) {
return function(oEvent){
var fZoomRate = 0.0,
sSliderValue = 0.0;
if (bZoomIn) {
sSliderValue = this._oZoomSlider.stepUp(1).getValue();
} else {
sSliderValue = this._oZoomSlider.stepDown(1).getValue();
}
fZoomRate = fnCalculateZoomRate(sSliderValue);
this._oZoomSlider.setValue(Math.log(fZoomRate));
this._iLiveChangeTimer = jQuery.sap.delayedCall(200, this, fnFireZoomRateChange, [fZoomRate]);
};
};
var oZoomInButton = new sap.m.Button({
icon: "sap-icon://zoom-in",
tooltip: this._oRb.getText("TLTP_SLIDER_ZOOM_IN"),
layoutData: oLayoutData.clone(),
press: fnZoomButtonPressHandler(true /**bZoomIn*/).bind(this)
});
var oZoomOutButton = new Button({
icon: "sap-icon://zoom-out",
tooltip: this._oRb.getText("TLTP_SLIDER_ZOOM_OUT"),
layoutData: oLayoutData.clone(),
press: fnZoomButtonPressHandler(false /**bZoomIn*/).bind(this)
});
this._oZoomSlider = oZoomSlider;
return [oZoomInButton, oZoomSlider, oZoomOutButton];
};
Toolbar.prototype._genLegend = function (oGroupConfig) {
if (!this._oLegendPop) {
this._oLegendPop = new Popover({
placement: PlacementType.Bottom,
showArrow: false,
showHeader: false
});
}
if (this.getLegend()) {
this._oLegendPop.removeAllContent();
this._oLegendPop.addContent(this.getLegend());
}
this._oLegendButton = new Button({
icon: "sap-icon://legend",
tooltip: this._oRb.getText("TLTP_SHOW_LEGEND"),
layoutData: new OverflowToolbarLayoutData({priority: oGroupConfig.getOverflowPriority()}),
press: function (oEvent) {
var oLegendPop = this._oLegendPop;
if (oLegendPop.isOpen()){
oLegendPop.close();
} else {
oLegendPop.openBy(this._oLegendButton);
}
}.bind(this)
});
return this._oLegendButton;
};
Toolbar.prototype._genSettings = function (oGroupConfig) {
var aSettingGroupItems = oGroupConfig.getItems() || [];
var that = this;
var aAllSettingItems = aSettingGroupItems.map(function(oGroupItem){
return new CheckBox({
name: oGroupItem.getKey(),
text: oGroupItem.getDisplayText(),
tooltip: oGroupItem.getTooltip(),
selected: oGroupItem.getChecked()
}).addStyleClass("sapUiSettingBoxItem");
});
// Need set the old setting state on the toolbar instance for reference
this._aOldSettingState = aAllSettingItems.map(function(oItem){
return oItem.getSelected();
});
this._setSettingItemStates(aAllSettingItems);
this._oSettingsBox = new FlexBox({
direction: FlexDirection.Column,
items: aAllSettingItems
}).addStyleClass("sapUiSettingBox");
this._oSettingsDialog = new ViewSettingsDialog({
title: this._oRb.getText("SETTINGS_DIALOG_TITLE"),
customTabs: [new ViewSettingsCustomTab({content: this._oSettingsBox})],
confirm: function() {
var aSettingItems = /*that.aSharedSettingItemStatus ?
that.aSharedSettingItemStatus : */this._oSettingsBox.getItems();
var parameters = [];
for (var i = 0; i < aSettingItems.length; i++) {
parameters.push({
id: aSettingItems[i].getName(),
value: aSettingItems[i].getSelected()
});
that._aOldSettingState[i] = aSettingItems[i].getSelected();
}
//store the custom setting item status in toolbar to keep the data consistency when switching views
that.aCustomSettingItems = that._getCustomSettingItems(aSettingItems);
this.fireSettingsChange(parameters);
}.bind(this),
cancel: function() {
// when cancel, the selected state should be restored when reopen
that._setSettingItemStates(aAllSettingItems);
that._restoreCustomOldStates(aAllSettingItems);
}
});
this._oSettingsButton = new Button({
icon: "sap-icon://action-settings",
tooltip: this._oRb.getText("TLTP_CHANGE_SETTINGS"),
layoutData: new OverflowToolbarLayoutData({priority: oGroupConfig.getOverflowPriority()}),
press: function (oEvent) {
this._oSettingsDialog.open();
}.bind(this)
});
return this._oSettingsButton;
};
Toolbar.prototype._setSettingItemStates = function (aAllSettingItems) {
for (var i = 0; i < aAllSettingItems.length; i++) {
switch (aAllSettingItems[i].getName()) {
case sap.gantt.config.SETTING_ITEM_ENABLE_NOW_LINE_KEY:
aAllSettingItems[i].setSelected(this.getEnableNowLine());
break;
case sap.gantt.config.SETTING_ITEM_ENABLE_CURSOR_LINE_KEY:
aAllSettingItems[i].setSelected(this.getEnableCursorLine());
break;
case sap.gantt.config.SETTING_ITEM_ENABLE_VERTICAL_LINE_KEY:
aAllSettingItems[i].setSelected(this.getEnableVerticalLine());
break;
case sap.gantt.config.SETTING_ITEM_ENABLE_TIME_SCROLL_SYNC_KEY:
aAllSettingItems[i].setSelected(this.getEnableTimeScrollSync());
break;
case sap.gantt.config.SETTING_ITEM_ROW_SCROLL_SYNC_KEY:
aAllSettingItems[i].setSelected(this.getEnableRowScrollSync());
break;
default:
this._handleCustomSettingItemStates(aAllSettingItems[i]);
break;
}
}
};
//need to loop and find custom setting items and set them here
Toolbar.prototype._handleCustomSettingItemStates = function (settingItem) {
if (this.aCustomSettingItems && this.aCustomSettingItems.length > 0) {
for (var j = 0; j < this.aCustomSettingItems.length; j++) {
if (settingItem.getName() === this.aCustomSettingItems[j].getName()) {
settingItem.setSelected(this.aCustomSettingItems[j].getSelected());
break;
}
}
}
};
//need to restore the old custom setting item status if canceled.
Toolbar.prototype._restoreCustomOldStates = function (aAllSettingItems) {
var settingItemLength = sap.gantt.config.DEFAULT_TOOLBAR_SETTING_ITEMS.length;
for (var i = settingItemLength; i < aAllSettingItems.length; i++){
aAllSettingItems[i].setSelected(this._aOldSettingState[i]);
}
};
Toolbar.prototype._getCustomSettingItems = function (aSettingItems) {
var customSettingItems = [];
var settingItemLength = sap.gantt.config.DEFAULT_TOOLBAR_SETTING_ITEMS.length;
for (var i = settingItemLength; i < aSettingItems.length; i++){
customSettingItems.push(aSettingItems[i]);
}
return customSettingItems;
};
Toolbar.prototype.getToolbarSchemeKey = function () {
return this._sToolbarSchemeKey;
};
Toolbar.prototype.setEnableNowLine = function(bEnableNowLine) {
this.setProperty("enableNowLine", bEnableNowLine);
if (this._oSettingsBox && this._oSettingsBox.getItems().length > 0) {
this._setSettingItemProperties(sap.gantt.config.SETTING_ITEM_ENABLE_NOW_LINE_KEY, bEnableNowLine);
}
return this;
};
Toolbar.prototype.setEnableCursorLine = function(bEnableCursorLine) {
this.setProperty("enableCursorLine", bEnableCursorLine);
if (this._oSettingsBox && this._oSettingsBox.getItems().length > 0) {
this._setSettingItemProperties(sap.gantt.config.SETTING_ITEM_ENABLE_CURSOR_LINE_KEY, bEnableCursorLine);
}
return this;
};
Toolbar.prototype.setEnableVerticalLine = function(bEnableVerticalLine) {
this.setProperty("enableVerticalLine", bEnableVerticalLine);
if (this._oSettingsBox && this._oSettingsBox.getItems().length > 0) {
this._setSettingItemProperties(sap.gantt.config.SETTING_ITEM_ENABLE_VERTICAL_LINE_KEY, bEnableVerticalLine);
}
return this;
};
Toolbar.prototype.setEnableRowScrollSync = function(bEnableRowScrollSync) {
this.setProperty("enableRowScrollSync", bEnableRowScrollSync);
if (this._oSettingsBox && this._oSettingsBox.getItems().length > 0) {
this._setSettingItemProperties(sap.gantt.config.SETTING_ITEM_ROW_SCROLL_SYNC_KEY, bEnableRowScrollSync);
}
return this;
};
Toolbar.prototype.setEnableTimeScrollSync = function(bEnableTimeScrollSync) {
this.setProperty("enableTimeScrollSync", bEnableTimeScrollSync);
if (this._oSettingsBox && this._oSettingsBox.getItems().length > 0) {
this._setSettingItemProperties(sap.gantt.config.SETTING_ITEM_ENABLE_TIME_SCROLL_SYNC_KEY, bEnableTimeScrollSync);
}
return this;
};
Toolbar.prototype._setSettingItemProperties = function(settingItemKey, settingItemStatus) {
var settingItems = this._oSettingsBox.getItems();
for (var i = 0; i < settingItems.length; i++) {
if (settingItems[i].getName() === settingItemKey) {
settingItems[i].setSelected(settingItemStatus);
break;
}
}
};
Toolbar.prototype.exit = function () {
if (this._oLegendPop) {
this._oLegendPop.destroy(false);
}
if (this._oSettingsPop) {
this._oSettingsPop.destroy(false);
}
};
return Toolbar;
}, true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2015 SAP SE. All rights reserved
*/
sap.ui.define([
"sap/gantt/drawer/Drawer", "sap/gantt/misc/Utility", "sap/ui/core/Core",
// 3rd party lib
"sap/ui/thirdparty/d3"
], function (Drawer, Utility, Core) {
"use strict";
var SelectionPanel = Drawer.extend("sap.gantt.drawer.SelectionPanel");
SelectionPanel.prototype.drawSvg = function (aTableSvg, aSelectionSvg, aData, oGanttChartWithTable) {
// temp save param
this._oGanttChartWithTable = oGanttChartWithTable;
// create top g
// append row_g
if (aData.length == 0){
return null;
}
var dummyData = [];
for (var i = 0; i < aData.length; i++){
if (aData[i].data.__dummy && !aData[i].data.previousNodeNum && !aData[i].data.afterNodeNum){
dummyData.push(aData[i]);
}
}
var aTableRowG = aTableSvg.selectAll(".selectionpanel").data(dummyData);
aTableRowG.enter().append("g").classed("selectionpanel",true);
aTableRowG.exit().remove();
var aSelectionRowG = aSelectionSvg.selectAll(".selectionpanel").data(dummyData);
aSelectionRowG.enter().append("g").classed("selectionpanel",true);
aSelectionRowG.exit().remove();
// draw
if (!aTableRowG.empty() && !aSelectionRowG.empty()) {
var iSelectionWidth = $(aSelectionSvg[0][0]).width();
var iTableWidth = $(aTableSvg[0][0]).width();
this._drawExpandedBackground(aSelectionSvg,iSelectionWidth);
this._drawExpandedBackground(aTableSvg,iTableWidth);
this._drawExpandedContent(aTableSvg, iTableWidth);
}
};
SelectionPanel.prototype._drawExpandedBackground = function (aSvg, iWidth) {
aSvg.selectAll(".selectionpanel").selectAll("rect").remove();
aSvg.selectAll(".selectionpanel").append("rect").classed("sapGanttExpandChartBG",true)
.attr("x", function (d) {
return 0;
})
.attr("y", function (d) {
return d.y;
})
.attr("height", function (d) {
// -1 just for show parent container border
return d.rowHeight - 1;
})
.attr("width", function (d) {
// -1 just for show parent container border
return iWidth - 1;
});
};
SelectionPanel.prototype._drawExpandedContent = function (aSvg, iWidth) {
aSvg.selectAll(".selectionpanel").selectAll("g").remove();
var that = this;
aSvg.selectAll(".selectionpanel").append("g").classed("sapGanttExpandChartContent",true);
var gShape = aSvg.selectAll(".sapGanttExpandChartContent");
var filterGroup = gShape.filter(function(d, i) { return d.index === 1; });
filterGroup.append("image")
.classed("hasTitle", function (d) {
return "image";
})
.attr("xlink:href", function (d) {
return d.icon;
})
.attr("x", function (d) {
if (Core.getConfiguration().getRTL() === true) {
//right width to the parent container for RTL mode
return iWidth - 19 - 16;
} else {
//left width to the parent container
return 19;
}
})
.attr("y", function (d) {
//top height to parent container
return d.y + 4.25;
})
.attr("width", function (d) {
//icon width
return 16;
})
.attr("height", function (d) {
//icon height
return 16;
});
filterGroup.append("text")
.attr("x", function (d) {
if (Core.getConfiguration().getRTL() === true) {
//right width to the parent container for RTL mode
return iWidth - 93 + 56;
} else {
//left width to the parent container
return 38;
}
})
.attr("y", function (d) {
//top height to parent container
return d.y + 16.5;
})
.attr("font-size", function (d) {
return "0.75em";
})
.text(function (d) {
return d.name;
});
filterGroup.append("g")
.attr("transform", function(d){
var sInitialX = 0, sInitialY = d.y + 7;
if (Core.getConfiguration().getRTL() === true) {
//right width to the parent container for RTL mode
sInitialX = iWidth - 93 - 4;
} else {
//left width to the parent container, plus half width of the close button
sInitialX = 93 + 8;
}
return "translate(" + sInitialX + "," + sInitialY + ")";
});
filterGroup.select("g").append("path")
.classed("sapGanttExpandChartCloseButton", true)
.attr("d", "M1 0 h3 v4 h4 v3 h-4 v4 h-3 v-4 h-4 v-3 h4 v-4 z")
.attr("transform", "rotate(45)")
.on("click", function (d) {
var aChartScheme = [];
aChartScheme.push(d.chartScheme);
var oBinding = that._oGanttChartWithTable._oTT.getBinding("rows");
var aRows = oBinding.getContexts(0, oBinding.getLength());
for (var i = 0; i < aRows.length; i++) {
var oContext = aRows[i].getProperty();
if (oContext && d.data.parentData && oContext.id == d.data.parentData.id) {
that._oGanttChartWithTable.fireEvent("collapseDummyRow",{isExpand : false, expandedChartSchemes: aChartScheme, aExpandedIndices : [i]});
}
}
});
var aClosePath = filterGroup.selectAll("path");
aClosePath.select("title").remove();
aClosePath.insert("title", ":first-child")
.text(function(d) {
return sap.ui.getCore().getLibraryResourceBundle("sap.gantt").getText("TLTP_CLOSE");
});
};
return SelectionPanel;
},true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define([
'jquery.sap.global', 'sap/ui/fl/changeHandler/Base'
], function(jQuery, Base) {
"use strict";
/**
* Change handler for removing a smart form group element.
* @constructor
* @alias sap.ui.fl.changeHandler.RemoveField
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*/
var RemoveField = function() {
};
RemoveField.prototype = jQuery.sap.newObject(Base.prototype);
/**
* Removes a smart form group element.
*
* @param {sap.ui.fl.Change} oChangeWrapper change wrapper object with instructions to be applied on the control map
* @param {sap.ui.comp.smartform.GroupElement} oField GroupElement control that matches the change selector for applying the change
* @public
*/
RemoveField.prototype.applyChange = function(oChangeWrapper, oField) {
if (oField.getParent) {
var oGroup = oField.getParent();
if (oGroup.removeGroupElement) {
oGroup.removeGroupElement(oField);
}
} else {
throw new Error("no GroupElement control provided for removing the field");
}
};
/**
* Completes the change by adding change handler specific content
*
* @param {sap.ui.fl.Change} oChangeWrapper change wrapper object to be completed
* @param {object} oSpecificChangeInfo as an empty object since no additional attributes are required for this operation
* @public
*/
RemoveField.prototype.completeChangeContent = function(oChangeWrapper, oSpecificChangeInfo) {
var oChange = oChangeWrapper.getDefinition();
if (!oChange.content) {
oChange.content = {};
}
};
return RemoveField;
},
/* bExport= */true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.ui.comp.smartform.flexibility.DialogContent.
sap.ui.define(['jquery.sap.global', 'sap/m/Button', 'sap/m/FlexAlignItems', 'sap/m/FlexAlignSelf', 'sap/m/FlexDirection', 'sap/m/FlexItemData', 'sap/m/FlexJustifyContent', 'sap/m/HBox', 'sap/m/VBox', 'sap/ui/comp/library', 'sap/ui/comp/odata/FieldSelector', './FieldList', 'sap/ui/core/Control', 'sap/ui/core/ResizeHandler', 'sap/ui/fl/registry/Settings', 'sap/ui/layout/Grid'],
function(jQuery, Button, FlexAlignItems, FlexAlignSelf, FlexDirection, FlexItemData, FlexJustifyContent, HBox, VBox, library, FieldSelector, FieldList, Control, ResizeHandler, Settings, Grid) {
"use strict";
/**
* Constructor for a new smartform/flexibility/DialogContent.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* The content of the personalization dialog of the SmartForm
* @extends sap.ui.core.Control
*
* @constructor
* @public
* @alias sap.ui.comp.smartform.flexibility.DialogContent
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var DialogContent = Control.extend("sap.ui.comp.smartform.flexibility.DialogContent", /** @lends sap.ui.comp.smartform.flexibility.DialogContent.prototype */ { metadata : {
library : "sap.ui.comp",
aggregations : {
/**
* Content of the control itself
*/
content : {type : "sap.ui.core.Control", multiple : false}
}
}});
/**
* Initialisation
*
* @public
*/
DialogContent.prototype.init = function() {
this._oScrollView = new sap.m.ScrollContainer();
var smartFormDialog = sap.ui.getCore().byId("smartFormPersDialog");
if (smartFormDialog) {
this._oResizeDialogHandlerId = ResizeHandler.register(smartFormDialog, jQuery.proxy(this._handleResizeDialog, this));
}
this._textResources = sap.ui.getCore().getLibraryResourceBundle("sap.ui.comp");
this._constructLayout();
this._createButtons();
this._createFieldList();
this._createFieldSelector();
this._createModels();
this._initiateBinding();
this.addStyleClass("sapUiSizeCompact");
this._sFirstIdPart = undefined;
};
DialogContent.prototype._handleResizeDialog = function() {
if (this._oScrollView) {
var height = jQuery("#smartFormPersDialog-cont").height();
var headerHeight = jQuery("#smartFormPersDialogFieldListHeader").height();
this._oScrollView.setHeight(height - headerHeight + "px");
}
};
/**
* Initialises the binding of the subordinate controls like move up/down button, field list, field selector
*
* @private
*/
DialogContent.prototype._initiateBinding = function() {
this._oFieldList.bindAggregation("nodes", {
path: "/children",
factory: this._createNodeFactoryFunction.bind(this)
});
this._oFieldList.attachSelectionChanged(this._onSelectionChanged.bind(this));
this._oFieldList.attachLabelChanged(this._onLabelChanged.bind(this));
this._oFieldList.attachNodeHidden(this._onNodeAddedOrHidden.bind(this));
this._oBtnMoveDown.bindProperty("enabled", {
path: "/isMoveDownButtonEnabled"
});
this._oBtnMoveUp.bindProperty("enabled", {
path: "/isMoveUpButtonEnabled"
});
this._oBtnMoveBottom.bindProperty("enabled", {
path: "/isMoveBottomButtonEnabled"
});
this._oBtnMoveTop.bindProperty("enabled", {
path: "/isMoveTopButtonEnabled"
});
this._oBtnAddField.bindProperty("enabled", {
parts: [
{path: "addFieldButtonDependencies>/selectedField"},
{path: "addFieldButtonDependencies>/groups"}
],
formatter: this._isAddFieldEnabled.bind(this)
});
};
/**
* Initialises the models for controling the display of the "add field" button
*
* @private
*/
DialogContent.prototype._createModels = function() {
this._oAddFieldButtonDependenciesModel = new sap.ui.model.json.JSONModel({
"selectedField": undefined,
"groups": undefined
});
this.setModel(this._oAddFieldButtonDependenciesModel, 'addFieldButtonDependencies');
// used to force retriggering of the binding when visibility of a group within the groups has changed
// (workaround for UI5) the fact that the group stays the same object(reference) let the _oAddFieldButtonDependenciesModel think nothing has chanced
this._emptyModel = new sap.ui.model.json.JSONModel();
};
/**
* Sets the first part of new control ids for the view context
*
* @param {string} sId Control Id
* @public
*/
DialogContent.prototype.setViewId = function(sId) {
this._sViewId = sId;
};
/**
* Returns Ids of the assigned changes of the component (correctly sorted)
*
* @param {sap.ui.model.odata.ODataModel} oODataModel The list of fields will be extracetd from the models metadata
* @param {string} sEntityType The entity type whose fields could be selected
* @param {string} sComponentName The name of the SAPUI5 component
* @param {array} aIgnoredFields List of fields which should be ignored
* @param {Object.<bindingPath:string, fieldListElement:Object>} mBindingPathToFieldListElement Map absolute odata binding paths to the field list elements
* @param {Object.<id:string, fieldListElement:Object>} mIdToFieldListElement Map field list element ids to the field list elements
* @param {map} mPropertyBag - (optional) contains additional data that are needed for reading of changes
* - appDescriptor that belongs to actual component
* - siteId that belongs to actual component
* @public
*/
DialogContent.prototype.initialiseODataFieldSelector = function(oODataModel, sEntityType, sComponentName, aIgnoredFields, mBindingPathToFieldListElement, mIdToFieldListElement, mPropertyBag) {
var oODataFieldSelector;
var bShowCreateExtFieldButton = false;
oODataFieldSelector = this._oFieldSelector;
if (oODataFieldSelector) {
// get the information of the
Settings.getInstance(sComponentName, mPropertyBag).then(function(oSettings) {
if (oSettings.isModelS) {
bShowCreateExtFieldButton = oSettings.isModelS();
}
oODataFieldSelector.setModel(oODataModel, sEntityType, bShowCreateExtFieldButton, aIgnoredFields, mBindingPathToFieldListElement, mIdToFieldListElement);
});
}
};
/**
* Factory function used for the recursive binding of the FieldListNode
*
* @param {string} sId id of the to-be-created FieldListNode
* @param {object} oContext Binding Context
* @returns {FieldListNode} Newly created FieldListNode
* @private
*/
DialogContent.prototype._createNodeFactoryFunction = function(sId, oContext) {
var nodeBindingSettings, oNode;
nodeBindingSettings = {
label: {
path: "label"
},
nodes: {
path: oContext.getPath() + "/children",
factory: this._createNodeFactoryFunction.bind(this)
},
isSelected: {
path: "isSelected"
},
isVisible: {
path: "isVisible"
}
};
oNode = new sap.ui.comp.smartform.flexibility.FieldListNode(sId, nodeBindingSettings);
return oNode;
};
/**
* Event handler called when the selection of a root FieldListNode has changed
*
* @param {object} oEvent Event
* @private
*/
DialogContent.prototype._onSelectionChanged = function(oEvent) {
var oSelectedFieldListNode, oNode;
oSelectedFieldListNode = oEvent.getParameter('node');
oNode = oSelectedFieldListNode.getBindingContext().getObject();
this._changeSelection(oNode);
this.getModel().updateBindings();
};
/**
* Event handler called when a label contained in the field list has changed
*
* @param {object} oEvent Event
* @private
*/
DialogContent.prototype._onLabelChanged = function(oEvent) {
var oChangedFieldListNode, oFieldListElement;
oChangedFieldListNode = oEvent.getParameter('node');
oFieldListElement = oChangedFieldListNode.getBindingContext().getObject();
this._oFieldSelector.updateFieldLabel(oFieldListElement);
};
/**
* Event handler called when a node in the field list was hidden
*
* @param {object} oEvent Event
* @private
*/
DialogContent.prototype._onNodeAddedOrHidden = function(oEvent) {
this._oAddFieldButtonDependenciesModel.setProperty("/groups", this.getModel().getData().children);
this._triggerAddFieldButtonDependenciesBindings();
};
/**
* Changes the selected FieldListNode. Unselects previously selected FieldListNode
*
* @param {object} oNodeToBeSelected JSON object from the model representing the newly selected node
* @private
*/
DialogContent.prototype._changeSelection = function(oNodeToBeSelected) {
// Deselect previously selected node
if (this._oSelectedFieldListNodeData) {
this._oSelectedFieldListNodeData.isSelected = false;
}
// select newly selected node
this._oSelectedFieldListNodeData = oNodeToBeSelected;
this._oSelectedFieldListNodeData.isSelected = true;
this._readDataFromModelAndUpdateMoveButtonEnabledState();
this.getModel().updateBindings();
};
/**
* Reads the data from the model and recalculate the move button enabled state
*
* @private
*/
DialogContent.prototype._readDataFromModelAndUpdateMoveButtonEnabledState = function() {
var oData;
oData = this._getDataFromModel();
this._updateMoveButtonEnabledState(oData);
};
/**
* Checks if node can be moved down
*
* @param {object} oNode Field list node to be moved
* @param {number} nLevelInAdjacenceList Level of node to be moved in field list tree
* @param {array} aAdjacenceList Adjacence list
* @returns {object} object which holds information if the move is possible, how many places
* the node has to be moved in the field list and on the new parent node
* if the move leads to a new one
* @private
*/
DialogContent.prototype._checkMoveDown = function(oNode, nLevelInAdjacenceList, aAdjacenceList) {
var i, oMoveDown = {};
oMoveDown.enabled = false;
oMoveDown.moveStep = 0;
oMoveDown.newParent = undefined;
// moving down possible ?
// first check - are there any children at higher index than the selected node ?
oMoveDown.enabled = oNode.parent.children.length - 1 > oNode.index;
// there is at least one child at higher index - but is it visible ?
if (oMoveDown.enabled) {
for (i = oNode.index + 1; i < oNode.parent.children.length; i++) {
oMoveDown.moveStep += 1;
// found a visible child - moving down possible
if (!oNode.parent.children[i].hasOwnProperty('isVisible') || oNode.parent.children[i].isVisible) {
return oMoveDown;
}
// no visible child at higher index - have to check if moving down to new parent is possible
if (i === (oNode.parent.children.length - 1)) {
oMoveDown.enabled = false;
}
}
}
// no move down possible at the same parent - check if moving down to new parent is possible
if (!oMoveDown.enabled) {
// first check - is there any parent at higher index than the current parent ?
var nParentIndex = aAdjacenceList[nLevelInAdjacenceList - 1].indexOf(oNode.parent);
oMoveDown.enabled = aAdjacenceList[nLevelInAdjacenceList - 1].length - 1 > nParentIndex;
// there is at least one parent at a higher index - but is it visible ?
if (oMoveDown.enabled) {
for (i = nParentIndex + 1; i < aAdjacenceList[nLevelInAdjacenceList - 1].length; i++) {
// found a visible parent - moving down possible
if (!aAdjacenceList[nLevelInAdjacenceList - 1][i].hasOwnProperty('isVisible') || aAdjacenceList[nLevelInAdjacenceList - 1][i].isVisible) {
oMoveDown.newParent = aAdjacenceList[nLevelInAdjacenceList - 1][i];
return oMoveDown;
}
// no visible parent at higher index - moving down is not possible
if (i === (aAdjacenceList[nLevelInAdjacenceList - 1].length - 1)) {
oMoveDown.enabled = false;
}
}
}
}
return oMoveDown;
};
/**
* Checks if node can be moved up
*
* @param {object} oNode Field list node to be moved
* @param {number} nLevelInAdjacenceList Level of node to be moved in field list tree
* @param {array} aAdjacenceList Adjacence list
* @returns {object} object which holds information if the move is possible, how many places
* the node has to be moved in the field list and on the new parent node
* if the move leads to a new one
* @private
*/
DialogContent.prototype._checkMoveUp = function(oNode, nLevelInAdjacenceList, aAdjacenceList) {
var i, oMoveUp = {};
oMoveUp.enabled = false;
oMoveUp.moveStep = 0;
oMoveUp.newParent = undefined;
// moving up possible ?
// first check - is selected node not the top child ?
oMoveUp.enabled = oNode.index > 0;
// not the top child - but is there a visible child above the selected node ?
if (oMoveUp.enabled) {
for (i = oNode.index - 1; i >= 0; i--) {
oMoveUp.moveStep += 1;
// found a visible child - moving up possible
if (!oNode.parent.children[i].hasOwnProperty('isVisible') || oNode.parent.children[i].isVisible) {
return oMoveUp;
}
// no visible child found - have to check if the node can be moved up to a new parent
if (i === 0) {
oMoveUp.enabled = false;
}
}
}
// moving up at the same parent not possible - check if the node can be moved up to a new parent
if (!oMoveUp.enabled) {
var nParentIndex = aAdjacenceList[nLevelInAdjacenceList - 1].indexOf(oNode.parent);
oMoveUp.enabled = nParentIndex > 0;
// there is at least one parent at lower index - but is it visible ?
if (oMoveUp.enabled) {
for (i = nParentIndex - 1; i >= 0; i--) {
// found a visible parent - moving up possible
if (!aAdjacenceList[nLevelInAdjacenceList - 1][i].hasOwnProperty('isVisible') || aAdjacenceList[nLevelInAdjacenceList - 1][i].isVisible) {
oMoveUp.newParent = aAdjacenceList[nLevelInAdjacenceList - 1][i];
return oMoveUp;
}
// no visible parent at lower index - moving up is not possible
if (i === 0) {
oMoveUp.enabled = false;
}
}
}
}
return oMoveUp;
};
/**
* Recalculates the move button enabled state
*
* @param {object} oData The data of the whole JSON model
* @private
*/
DialogContent.prototype._updateMoveButtonEnabledState = function(oData) {
var fn, bIsMoveDownEnabled, bIsMoveUpEnabled, bIsMoveBottomEnabled, bIsMoveTopEnabled;
var that = this;
fn = function(oNode, nLevelInAdjacenceList, aAdjacenceList) {
var oMoveDown = that._checkMoveDown(oNode, nLevelInAdjacenceList, aAdjacenceList);
var oMoveUp = that._checkMoveUp(oNode, nLevelInAdjacenceList, aAdjacenceList);
bIsMoveDownEnabled = oMoveDown.enabled;
bIsMoveUpEnabled = oMoveUp.enabled;
bIsMoveBottomEnabled = bIsMoveDownEnabled;
bIsMoveTopEnabled = bIsMoveUpEnabled;
};
if (this._oSelectedFieldListNodeData) {
this._findNodeInDataModel(oData, this._oSelectedFieldListNodeData.id, fn);
} else { // nothing selected
bIsMoveDownEnabled = false;
bIsMoveUpEnabled = false;
bIsMoveBottomEnabled = false;
bIsMoveTopEnabled = false;
}
oData.isMoveDownButtonEnabled = bIsMoveDownEnabled;
oData.isMoveUpButtonEnabled = bIsMoveUpEnabled;
oData.isMoveBottomButtonEnabled = bIsMoveBottomEnabled;
oData.isMoveTopButtonEnabled = bIsMoveTopEnabled;
};
DialogContent.prototype._constructLayout = function() {
this.oLayout = new HBox({
direction: FlexDirection.Row
});
this.oLayoutLeft = new VBox({
direction: FlexDirection.Column,
layoutData: new FlexItemData({
order: 1,
growFactor: 2
})
});
this.oLayoutLeft.addStyleClass("sapUiCompDialogContentFieldListContainer");
this.oLayoutMiddle = new VBox({
direction: FlexDirection.Column,
layoutData: new FlexItemData({
order: 2,
growFactor: 1
})
});
this.oLayoutMiddle.addStyleClass("sapUiCompDialogContentMiddle");
this.oLayoutTopLeft = new Grid("smartFormPersDialogFieldListHeader");
this.oLayoutTopLeft.addStyleClass("sapUiCompDialogContentFieldListContainerTop");
this.oLayoutLeft.addItem(this.oLayoutTopLeft);
this.oLayoutRight = new VBox({
direction: FlexDirection.Column,
layoutData: new FlexItemData({
order: 3,
growFactor: 9
})
});
this.oLayout.addItem(this.oLayoutLeft);
this.oLayout.addItem(this.oLayoutMiddle);
this.oLayout.addItem(this.oLayoutRight);
this.setContent(this.oLayout);
};
/**
* Creates an instance of the FieldList Control
*
* @private
*/
DialogContent.prototype._createFieldList = function() {
this._oScrollView.setWidth("100%");
this._oScrollView.setVertical(true);
this._oFieldList = new FieldList(this.getId() + '-FieldList');
this._oScrollView.addContent(this._oFieldList);
this._handleResizeDialog();
this.oLayoutLeft.addItem(this._oScrollView);
};
/**
* Creates an instance of the FieldSelector Control
*
* @private
*/
DialogContent.prototype._createFieldSelector = function() {
this._oFieldSelector = new FieldSelector({
layoutData: new FlexItemData({
order: 3,
growFactor: 9
})
});
this._oFieldSelector.attachFieldSelectionChanged(this._writeSelectedFieldToModel.bind(this));
this.oLayoutRight.addItem(this._oFieldSelector);
};
DialogContent.prototype._writeSelectedFieldToModel = function (oSelection) {
this._oAddFieldButtonDependenciesModel.setProperty("/selectedField", oSelection.mParameters);
this._triggerAddFieldButtonDependenciesBindings();
};
DialogContent.prototype._triggerAddFieldButtonDependenciesBindings = function () {
this.setModel(this._emptyModel, 'addFieldButtonDependencies');
if (!this._oAddFieldButtonDependenciesModel.getData().groups) {
this._oAddFieldButtonDependenciesModel.setProperty("groups", this.getModel().getData().children);
}
this.setModel(this._oAddFieldButtonDependenciesModel, 'addFieldButtonDependencies');
};
/**
* Reacts on a change within the intanciated FieldSelector Control
*
* @private
*/
DialogContent.prototype._isAddFieldEnabled = function(oSelectedField, aGroups) {
var bValidFieldSelected = !!oSelectedField && !!oSelectedField.name;
return bValidFieldSelected && aGroups && this._containsVisibleGroups(aGroups);
};
DialogContent.prototype._containsVisibleGroups = function(oGroups) {
var oVisibleFieldListGroups = this._getVisibleGroups(oGroups);
return oVisibleFieldListGroups.length > 0;
};
DialogContent.prototype._getVisibleGroups = function(oGroups) {
var oVisibleFieldListGroups = [];
oGroups.forEach(function (oNode) {
if (oNode.isVisible) {
oVisibleFieldListGroups.push(oNode);
}
});
return oVisibleFieldListGroups;
};
/**
* Creates the Move up/down buttons, add group button, add field button
*
* @private
*/
DialogContent.prototype._createButtons = function() {
var sText, sTooltip;
this._oBtnMoveBottom = new Button(this.getId() + '-MoveBottomButton', {
layoutData : new sap.ui.layout.GridData({
span : "L2 M3 S3"
})
});
this._oBtnMoveBottom.setIcon("sap-icon://expand-group");
this._oBtnMoveBottom.attachPress(this._onMoveBottomClick.bind(this));
sTooltip = this._textResources.getText("FORM_PERS_DIALOG_MOVE_BOTTOM");
this._oBtnMoveBottom.setTooltip(sTooltip);
this.oLayoutTopLeft.addContent(this._oBtnMoveBottom);
this._oBtnMoveDown = new Button(this.getId() + '-MoveDownButton', {
layoutData : new sap.ui.layout.GridData({
span : "L2 M3 S3"
})
});
this._oBtnMoveDown.setIcon("sap-icon://slim-arrow-down");
this._oBtnMoveDown.attachPress(this._onMoveDownClick.bind(this));
sTooltip = this._textResources.getText("FORM_PERS_DIALOG_MOVE_DOWN");
this._oBtnMoveDown.setTooltip(sTooltip);
this.oLayoutTopLeft.addContent(this._oBtnMoveDown);
this._oBtnMoveUp = new Button(this.getId() + '-MoveUpButton', {
layoutData : new sap.ui.layout.GridData({
span : "L2 M3 S3"
})
});
this._oBtnMoveUp.setIcon("sap-icon://slim-arrow-up");
this._oBtnMoveUp.attachPress(this._onMoveUpClick.bind(this));
sTooltip = this._textResources.getText("FORM_PERS_DIALOG_MOVE_UP");
this._oBtnMoveUp.setTooltip(sTooltip);
this.oLayoutTopLeft.addContent(this._oBtnMoveUp);
this._oBtnMoveTop = new Button(this.getId() + '-MoveTopButton', {
layoutData : new sap.ui.layout.GridData({
span : "L2 M3 S3"
})
});
this._oBtnMoveTop.setIcon("sap-icon://collapse-group");
this._oBtnMoveTop.attachPress(this._onMoveTopClick.bind(this));
sTooltip = this._textResources.getText("FORM_PERS_DIALOG_MOVE_TOP");
this._oBtnMoveTop.setTooltip(sTooltip);
this.oLayoutTopLeft.addContent(this._oBtnMoveTop);
this._oBtnAddGroup = new Button(this.getId() + '-AddGroupButton', {
layoutData : new sap.ui.layout.GridData({
span : "L4 M12 S12"
})
});
sText = this._textResources.getText("FORM_PERS_DIALOG_ADD_GROUP");
this._oBtnAddGroup.setText(sText);
this._oBtnAddGroup.attachPress(this._onAddGroupClick.bind(this));
sTooltip = this._textResources.getText("FORM_PERS_DIALOG_ADD_GROUP");
this._oBtnAddGroup.setTooltip(sTooltip);
this.oLayoutTopLeft.addContent(this._oBtnAddGroup);
this._oBtnAddField = new Button(this.getId() + '-AddFieldButton');
this._oBtnAddField.setIcon("sap-icon://slim-arrow-left");
this._oBtnAddField.attachPress(this._onAddFieldClick.bind(this));
sTooltip = this._textResources.getText("FORM_PERS_DIALOG_ADD_FIELD");
this._oBtnAddField.setTooltip(sTooltip);
this.oLayoutMiddle.addItem(this._oBtnAddField);
};
/**
* Event handler called when the move up button is clicked
*
* @private
*/
DialogContent.prototype._onMoveUpClick = function() {
var oModel, oData, sId;
oModel = this.getModel();
if (oModel) {
sId = this._getIdOfSelectedFieldListNode();
oData = this._getDataFromModel();
this._executeMoveUp(oData, sId);
this._updateMoveButtonEnabledState(oData);
oModel.setData(oData);
}
};
/**
* Event handler called when the move down button is clicked
*
* @private
*/
DialogContent.prototype._onMoveDownClick = function() {
var oData, sId, oModel;
oModel = this.getModel();
if (oModel) {
sId = this._getIdOfSelectedFieldListNode();
oData = this._getDataFromModel();
this._executeMoveDown(oData, sId);
this._updateMoveButtonEnabledState(oData);
oModel.setData(oData);
}
};
/**
* Event handler called when the move top button is clicked
*
* @private
*/
DialogContent.prototype._onMoveTopClick = function() {
var oModel, oData, sId;
oModel = this.getModel();
if (oModel) {
sId = this._getIdOfSelectedFieldListNode();
oData = this._getDataFromModel();
this._executeMoveTop(oData, sId);
this._updateMoveButtonEnabledState(oData);
oModel.setData(oData);
}
};
/**
* Event handler called when the move bottom button is clicked
*
* @private
*/
DialogContent.prototype._onMoveBottomClick = function() {
var oData, sId, oModel;
oModel = this.getModel();
if (oModel) {
sId = this._getIdOfSelectedFieldListNode();
oData = this._getDataFromModel();
this._executeMoveBottom(oData, sId);
this._updateMoveButtonEnabledState(oData);
oModel.setData(oData);
}
};
/**
* Event handler called when the add group button is clicked
*
* @private
*/
DialogContent.prototype._onAddGroupClick = function() {
var oData, oModel;
oModel = this.getModel();
if (oModel) {
oData = this._getDataFromModel();
this._executeAddGroup(oData);
oModel.setData(oData);
this._onNodeAddedOrHidden();
}
};
/**
* Returns the id of the currently selected FieldListNode. Undefined if no FieldListNode is selected
*
* @returns {string} Id of selected FieldListNode
* @private
*/
DialogContent.prototype._getIdOfSelectedFieldListNode = function() {
var oNode;
oNode = this._oSelectedFieldListNodeData;
if (oNode) {
return oNode.id;
}
};
/**
* Event handler, called when add field button was clicked
*
* @param {object} oEvent Event
* @private
*/
DialogContent.prototype._onAddFieldClick = function(oEvent) {
var oModel, oData;
oModel = this.getModel();
if (oModel) {
oData = this._getDataFromModel();
this._executeAddField(oData);
oModel.setData(oData);
}
};
/**
* Calculates position where a new field would be added to. Basis for this calculation is the currently selected node.
*
* @param {object} oData JSON data from model
* @returns {object} Map having a member 'parent' (new parent node) and 'index' (Position in parent's children collection)
* @private
*/
DialogContent.prototype._getParentAndIndexNodeForNewField = function(oData) {
var sId, nIndex, oParentNode;
// Search for the currently selected field list node and determine new parent
sId = this._getIdOfSelectedFieldListNode();
this._findNodeInDataModel(oData, sId, function(oNode) {
if (oNode.type === 'group') {
oParentNode = oNode;
if (oParentNode.children && oParentNode.children.length) {
nIndex = oParentNode.children.length;
}
} else {
oParentNode = oNode.parent;
nIndex = oNode.index + 1;
}
});
// if no FieldNode was selected, append to last group
if (!oParentNode) {
oParentNode = this._getBottomGroup(oData);
nIndex = oParentNode.children.length;
}
return {
parent: oParentNode,
index: nIndex
};
};
/**
* Returns the last group
*
* @param {object} oData JSON data from model returns {object} The very last group. Undefined if there are no groups.
* @returns {object} Parent node instance
* @private
*/
DialogContent.prototype._getBottomGroup = function(oData) {
var oBottomGroup;
if (oData && oData.children && oData.children.length > 0) {
var oVisibleGroups = this._getVisibleGroups(oData.children);
oBottomGroup = oVisibleGroups[oVisibleGroups.length - 1]; // get last element
}
return oBottomGroup;
};
/**
* Gets the data from the model
*
* @returns {object} JSON data from model
* @private
*/
DialogContent.prototype._getDataFromModel = function() {
var oModel;
oModel = this.getModel();
if (oModel) {
return oModel.getData();
}
};
/**
* Creates an adjacence list from the provided JSON tree. The data has a single root node and multiple children. Each child can have multiple children
* too. The tree depth is not limited. The adjacence list is an array of arrays. list[i] contains an ordered list of all nodes of the tree, having the
* depth i. This means list[0] equals the root node. As a side effect two additional properties will be added to all nodes of the model: - index:
* Contains the position of this node in the parent's children collection - parent: The parent of this node These properties can be removed with
* _destroyAdjacenceList
*
* @param {object} oData The data from the JSON model
* @returns {Array} Adjacence list
* @private
*/
DialogContent.prototype._createAdjacenceList = function(oData) {
var aAdjacenceList, fCreateAdjacenceList;
aAdjacenceList = [];
fCreateAdjacenceList = function(oNode, oParent, nIndex, nDepth) {
oNode.index = nIndex;
oNode.parent = oParent;
aAdjacenceList[nDepth] = aAdjacenceList[nDepth] || [];
aAdjacenceList[nDepth].push(oNode);
};
this._dfs(oData, fCreateAdjacenceList);
return aAdjacenceList;
};
/**
* Removes the properties from the data model added, which were added when calling _createAdjacenceList
*
* @param {object} oData The data from the JSON model
* @private
*/
DialogContent.prototype._destroyAdjacenceList = function(oData) {
var fDestroyAdjacenceList;
fDestroyAdjacenceList = function(oNode, oParent, nIndex, nDepth) {
delete oNode.index;
delete oNode.parent;
};
this._dfs(oData, fDestroyAdjacenceList);
};
/**
* DFS (depth first search) traverses the full graph an calls fn for each node. Method is recursive
*
* @param {object} oData The data of the current node
* @param {function} fn Function to be called for each node
* @param {object} oParent The parent node
* @param {number} nIndex The index of the cirrent node within the parent's children collection
* @param {number} nDepth The depth within the tree of the current node
* @private
*/
DialogContent.prototype._dfs = function(oData, fn, oParent, nIndex, nDepth) {
var i;
if (!oData) {
return;
}
nDepth = nDepth || 0;
nIndex = nIndex || 0;
fn(oData, oParent, nIndex, nDepth);
if (oData && oData.children) {
for (i = 0; i < oData.children.length; i++) {
this._dfs(oData.children[i], fn, oData, i, nDepth + 1);
}
}
};
/**
* Searches for a node in the data tree and executes the funtion fn for this node
*
* @param {object} oData The data of the JSON model
* @param {String} sId oParent The parent node
* @param {function} fn Function to be executed for this node. Function will be called with these parameters: fn(oNode, nDepth, aAdjacenceList).
* @private
*/
DialogContent.prototype._findNodeInDataModel = function(oData, sId, fn) {
var aAdjacenceList;
aAdjacenceList = this._createAdjacenceList(oData);
(function() {
var nDepth, j, nMaxHierarchyDepth, length, oNode;
nMaxHierarchyDepth = aAdjacenceList.length;
for (nDepth = 0; nDepth < nMaxHierarchyDepth; nDepth++) {
length = aAdjacenceList[nDepth].length;
for (j = 0; j < length; j++) {
oNode = aAdjacenceList[nDepth][j];
if (oNode.id === sId) {
fn(oNode, nDepth, aAdjacenceList);
return;
}
}
}
}());
this._destroyAdjacenceList(oData);
};
/**
* Moves a node down in the data model
*
* @param {object} oNode The JSON node representing a FieldListNode to be moved down
* @param {number} nLevelInAdjacenceList Depth of the node in the tree
* @param {Array} aAdjacenceList Adjacence List
* @private
*/
DialogContent.prototype._moveDownNode = function(oNode, nLevelInAdjacenceList, aAdjacenceList) {
var oMoveDown = this._checkMoveDown(oNode, nLevelInAdjacenceList, aAdjacenceList);
if (oMoveDown.enabled) {
// move leads to new parent node
if (oMoveDown.newParent) {
oNode.parent.children.splice(oNode.index, 1);
oMoveDown.newParent.children = oMoveDown.newParent.children || [];
oMoveDown.newParent.children.splice(0, 0, oNode);
// move within the same parent
} else {
oNode.parent.children.splice(oNode.index, 1);
oNode.parent.children.splice(oNode.index + oMoveDown.moveStep, 0, oNode);
}
}
};
/**
* Moves a node up in the data model
*
* @param {object} oNode The JSON node representing a FieldListNode to be moved up
* @param {number} nLevelInAdjacenceList Depth of the node in the tree
* @param {Array} aAdjacenceList Adjacence List
* @private
*/
DialogContent.prototype._moveUpNode = function(oNode, nLevelInAdjacenceList, aAdjacenceList) {
var oMoveUp = this._checkMoveUp(oNode, nLevelInAdjacenceList, aAdjacenceList);
if (oMoveUp.enabled) {
// move leads to new parent node
if (oMoveUp.newParent) {
oNode.parent.children.splice(oNode.index, 1);
oMoveUp.newParent.children = oMoveUp.newParent.children || [];
oMoveUp.newParent.children.push(oNode);
// move within the same parent
} else {
oNode.parent.children.splice(oNode.index, 1);
oNode.parent.children.splice(oNode.index - oMoveUp.moveStep, 0, oNode);
}
}
};
/**
* Moves a node down to the bottom in the data model
*
* @param {object} oNode The JSON node representing a FieldListNode to be moved down to the bottom
* @param {number} nLevelInAdjacenceList Depth of the node in the tree
* @param {Array} aAdjacenceList Adjacence List
* @private
*/
DialogContent.prototype._moveBottomNode = function(oNode, nLevelInAdjacenceList, aAdjacenceList) {
var oMoveDown = this._checkMoveDown(oNode, nLevelInAdjacenceList, aAdjacenceList);
if (oMoveDown.enabled) {
// move leads to new parent node
if (oMoveDown.newParent) {
oNode.parent.children.splice(oNode.index, 1);
oMoveDown.newParent.children = oMoveDown.newParent.children || [];
oMoveDown.newParent.children.push(oNode);
// move within the same parent
} else {
oNode.parent.children.splice(oNode.index, 1);
oNode.parent.children.push(oNode);
}
}
};
/**
* Moves a node up to the top in the data model
*
* @param {object} oNode The JSON node representing a FieldListNode to be moved up to the top
* @param {number} nLevelInAdjacenceList Depth of the node in the tree
* @param {Array} aAdjacenceList Adjacence List
* @private
*/
DialogContent.prototype._moveTopNode = function(oNode, nLevelInAdjacenceList, aAdjacenceList) {
var oMoveUp = this._checkMoveUp(oNode, nLevelInAdjacenceList, aAdjacenceList);
if (oMoveUp.enabled) {
// move leads to new parent node
if (oMoveUp.newParent) {
oNode.parent.children.splice(oNode.index, 1);
oMoveUp.newParent.children = oMoveUp.newParent.children || [];
oMoveUp.newParent.children.splice(0, 0, oNode);
// move within the same parent
} else {
oNode.parent.children.splice(oNode.index, 1);
oNode.parent.children.splice(0, 0, oNode);
}
}
};
/**
* Moves a node down in the data model
*
* @param {object} oData The data of the JSON model
* @param {String} sId The id of the node to be moved down
* @returns {object} Node in data model after move
* @private
*/
DialogContent.prototype._executeMoveDown = function(oData, sId) {
return this._findNodeInDataModel(oData, sId, this._moveDownNode.bind(this));
};
/**
* Moves a node up in the data model
*
* @param {object} oData The data of the JSON model
* @param {String} sId The id of the node to be moved up
* @returns {object} Node in the data model after the move
* @private
*/
DialogContent.prototype._executeMoveUp = function(oData, sId) {
return this._findNodeInDataModel(oData, sId, this._moveUpNode.bind(this));
};
/**
* Moves a node down to the bottom in the data model
*
* @param {object} oData The data of the JSON model
* @param {String} sId The id of the node to be moved down to the bottom
* @return {object} Bottom node in the data model
* @private
*/
DialogContent.prototype._executeMoveBottom = function(oData, sId) {
return this._findNodeInDataModel(oData, sId, this._moveBottomNode.bind(this));
};
/**
* Moves a node up to the top in the data model
*
* @param {object} oData The data of the JSON model
* @param {String} sId The id of the node to be moved up to the top
* @returns {object} Top node in the data model
* @private
*/
DialogContent.prototype._executeMoveTop = function(oData, sId) {
return this._findNodeInDataModel(oData, sId, this._moveTopNode.bind(this));
};
/**
* Reads the selected field from the field selector and adds it to the data
*
* @param {object} oData The data of the JSON model
* @private
*/
DialogContent.prototype._executeAddField = function(oData) {
var oNewPosition, oNewNode, that = this;
oNewPosition = this._getParentAndIndexNodeForNewField(oData);
oNewNode = this._getNewNodeFromSelectedODataField(oData, this._getSelectedFieldFromFieldSelector());
// check if the field is already delivered as hidden but with configuration. If not add a new field
var oExistingField = this._getExistingField(oNewNode, oData);
if (oExistingField) {
this._findNodeInDataModel(oData, oExistingField.id, function(oNode, nLevelInAdjacenceList, aAdjacenceList){
// set the existing field to visible
oNode.isVisible = true;
// remove the existing node
oNode.parent.children.splice(oNode.index, 1);
// check if the old node will be removed before the new position
if (oNode.parent === oNewPosition.parent) {
if (oNode.index < oNewPosition.index) {
oNewPosition.index--;
}
}
// add the existing node to the new position
that._addField(oNode, oNewPosition.parent, oNewPosition.index);
});
} else {
this._addField(oNewNode, oNewPosition.parent, oNewPosition.index);
}
};
/**
* Tries to add a predefined field
*
* @param {object} oNewNode The node to be added
* @param {object} oData - internal data structure
*
* @returns {boolean} true if the predefined field was added
*/
DialogContent.prototype._getExistingField = function(oNewNode, oData) {
var bFound = false;
var sReferenceValue = '';
if (oNewNode.isBoundToODataService) { // used to identifying existing field which is bound to the odata service
sReferenceValue = oNewNode.entityType + '/' + oNewNode.fieldValue;
} else { // used to identifying existing field which is not bound to the odata service
sReferenceValue = oNewNode.id;
}
var fnCheckIfBoundToODataService = function(index, bindingPath) {
if (bindingPath.path === sReferenceValue) {
bFound = true;
}
};
var fnCheckIfNotBoundToODataService = function(id) {
if (id === sReferenceValue) {
bFound = true;
}
};
if (oData.children) {
for (var i = 0; i < oData.children.length; i++) {
var oChild = oData.children[i];
if (oChild.type === "field") {
if (oChild.isBoundToODataService) {
jQuery.each(oChild.bindingPaths, fnCheckIfBoundToODataService);
} else {
fnCheckIfNotBoundToODataService(oChild.id);
}
}
if (bFound) {
return oChild;
}
var oFoundChild = this._getExistingField(oNewNode, oChild);
if (oFoundChild) {
return oFoundChild;
}
}
}
};
/**
* Adds the new node to the specified position
*
* @param {object} oNewNode The node to be added
* @param {object} oParentNode The new parent of the node
* @param {number} nIndex The position where the new node will be added into the parent's children collection. If undefined, the new node will be
* appended as last node.
* @private
*/
DialogContent.prototype._addField = function(oNewNode, oParentNode, nIndex) {
if (!oNewNode) {
return;
}
// Add new field
oParentNode.children = oParentNode.children || [];
if (nIndex || nIndex === 0) {
oParentNode.children.splice(nIndex, 0, oNewNode);
} else {
oParentNode.children.push(oNewNode);
}
};
/**
* Gets the currently selected field from the OData Field Selector and creates and returns a new node which can be added to the model
* @param {object} oData Data object
* @param {object} oSelectedField Selected field instance
* @returns {object} The new node for the OData field
* @private
*/
DialogContent.prototype._getNewNodeFromSelectedODataField = function(oData, oSelectedField) {
var oNewNode;
if (!oSelectedField) {
return null;
}
// create new entry
oNewNode = {
bindingPaths : (oSelectedField.isBoundToODataService) ? [ { path : oSelectedField.entityName + '/' + oSelectedField.path } ] : [ { path : '' } ],
isBoundToODataService: oSelectedField.isBoundToODataService, // used in _getExistingField
id: (oSelectedField.isBoundToODataService) ? oData.id + "_" + oSelectedField.entityType + "_" + oSelectedField.path.replace("/","_") : oSelectedField.id, // oSelectedField.id only available for fields which are not bound to odata service (are already on the UI view and therefore have an id)
entitySet: oSelectedField.entitySet,
entityType: oSelectedField.entityType,
entityName: oSelectedField.entityName,
label: oSelectedField.field, // "{" + oSelectedField.name + "/@sap:label}"
valueProperty: "value",
fieldValue: oSelectedField.path,
jsType: "sap.ui.comp.smartfield.SmartField",
isVisible: true,
type: "field"
};
return oNewNode;
};
/**
* Gets the currently selected field from the OData Field Selector
*
* @returns {object} Selected OData field as JSON object
* @private
*/
DialogContent.prototype._getSelectedFieldFromFieldSelector = function() {
return this._oFieldSelector.getSelectedField();
};
/**
* Adds a new group as first element to the data
*
* @param {object} oData The data of the JSON model
* @private
*/
DialogContent.prototype._executeAddGroup = function(oData) {
var sText, oNewGroup;
sText = this._textResources.getText("FORM_PERS_DIALOG_NEW_GROUP");
// create new entry
oNewGroup = {
id: this._sViewId + jQuery.sap.uid(),
label: sText,
isVisible: true,
type: "group",
children: []
};
oData.children.splice(0, 0, oNewGroup); // Insert new group as first group
this._changeSelection(oNewGroup);
};
DialogContent.prototype.exit = function() {
if (this._oScrollView) {
this._oScrollView.destroy();
this._oScrollView = null;
}
if (this._oBtnMoveBottom) {
this._oBtnMoveBottom.destroy();
this._oBtnMoveBottom = null;
}
if (this._oBtnMoveDown) {
this._oBtnMoveDown.destroy();
this._oBtnMoveDown = null;
}
if (this._oBtnMoveUp) {
this._oBtnMoveUp.destroy();
this._oBtnMoveUp = null;
}
if (this._oBtnMoveTop) {
this._oBtnMoveTop.destroy();
this._oBtnMoveTop = null;
}
if (this._oBtnAddGroup) {
this._oBtnAddGroup.destroy();
this._oBtnAddGroup = null;
}
if (this._oBtnAddField) {
this._oBtnAddField.destroy();
this._oBtnAddField = null;
}
if (this._oFieldSelector) {
this._oFieldSelector.destroy();
this._oFieldSelector = null;
}
if (this.oLayoutRight) {
this.oLayoutRight.destroy();
this.oLayoutRight = null;
}
if (this.oLayoutMiddle) {
this.oLayoutMiddle.destroy();
this.oLayoutMiddle = null;
}
if (this.oLayoutTopLeft) {
this.oLayoutTopLeft.destroy();
this.oLayoutTopLeft = null;
}
if (this.oLayoutLeft) {
this.oLayoutLeft.destroy();
this.oLayoutLeft = null;
}
if (this.oLayout) {
this.oLayout.destroy();
this.oLayout = null;
}
};
return DialogContent;
}, /* bExport= */ true);
<file_sep>/*
* ! SAP UI development toolkit for HTML5 (SAPUI5) (c) Copyright 2009-2012 SAP AG. All rights reserved
*/
// Provides control sap.ui.vbm.Cluster.
sap.ui.define([
'jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/ui/core/IconPool'
], function(jQuery, library, Control, IconPool) {
"use strict";
/**
* Constructor for a new Cluster.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
* @class Cluster control to visualize clustered objects on a map. The Cluster control does not cluster anything itself, instead it only shows a
* predefined image. The image can be configured with the properties <i>type</i>, <i>color</i>, <i>icon</i> and <i>text</i>. If a
* <i>text</i> is given it is shown in the upper right corner of the control with a rounded border around. With the <i>color</i> property
* any color can be chosen. The <i>type</i> property overwrites a property <i>color</i> with semantic color of the type and provides a
* particular semantic icon in the middle of the control. With the <i>icon</i> property an icon can be defined and may overrule the
* semantic icon; if no icon is defined ( and no type) then the semantic icon for type inactive is chosen.
* @extends sap.ui.core.Control
* @author SAP SE
* @constructor
* @public
* @alias sap.ui.vbm.Cluster
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var Cluster = Control.extend("sap.ui.vbm.Cluster", /** @lends sap.ui.vbm.Cluster.prototype */
{
metadata: {
library: "sap.ui.vbm",
properties: {
/**
* Set the color of the control. If a type is set then the semantic color of the type is taken instead.
*/
color: {
type: "sap.ui.core.CSSColor",
group: "Misc",
defaultValue: null
},
/**
* Set the icon of the control. If a type is set then the semantic icon of the type can be overwritten with this property. If no icon
* and no type is set then the icon for the semantic type 'inactive' is taken.
*/
icon: {
type: "string",
group: "Misc",
defaultValue: null
},
/**
* Set the text of the control.
*/
text: {
type: "string",
group: "Misc",
defaultValue: null
},
/**
* semantic type for cluster. The type specifies the icon and the color of the cluster control.
*/
type: {
type: "sap.ui.vbm.SemanticType",
group: "Behavior",
defaultValue: sap.ui.vbm.SemanticType.None
}
}
}
});
jQuery.sap.require("sap.ui.core.IconPool");
jQuery.sap.require("sap.ui.core.theming.Parameters");
// ...........................................................................//
// This file defines behavior for the control,...............................//
// ...........................................................................//
Cluster.prototype.exit = function() {
};
Cluster.prototype.init = function() {
};
// ...........................................................................//
Cluster.prototype.onAfterRendering = function() {
// when there is preserved content restore it.............................//
if (this.$oldContent.length > 0) {
this.$().append(this.$oldContent);
}
var col = this.getColor();
var type = this.getType();
if (col && type == sap.ui.vbm.SemanticType.None) {
// color manipulation needed
var Id1 = this.getId() + "-" + "backgroundcircle";
var Id2 = Id1 + "-" + "innercircle";
var backgroundcircle = document.getElementById(Id1);
var innercircle = document.getElementById(Id2);
var c = jQuery(backgroundcircle).css("border-bottom-color");
var rgba = Cluster.prototype.string2rgba(c);
rgba = "rgba(" + rgba[0] + "," + rgba[1] + "," + rgba[2] + "," + 0.5 + ")";
jQuery(backgroundcircle).css("border-color", rgba);
jQuery(innercircle).css("border-color", rgba);
}
};
Cluster.prototype.onBeforeRendering = function() {
// this is called before the renderer is called...........................//
this.$oldContent = sap.ui.core.RenderManager.findPreservedContent(this.getId());
};
// ...........................................................................//
// re implement property setters.............................................//
Cluster.prototype.setColor = function(col) {
this.setProperty("color", col);
};
Cluster.prototype.setIcon = function(ic) {
this.setProperty("icon", ic);
};
Cluster.prototype.setText = function(txt) {
this.setProperty("text", txt);
};
Cluster.prototype.string2rgba = function(a) {
var cache;
if ((cache = /^rgb\(([\d]+)[,;]\s*([\d]+)[,;]\s*([\d]+)\)/.exec(a))) {
return [
+cache[1], +cache[2], +cache[3], 1.0, 0
];
} else {
return [
94, 105, 110
];
}
};
return Cluster;
});
<file_sep>/*
* ! SAP UI development toolkit for HTML5 (SAPUI5) (c) Copyright 2009-2012 SAP AG. All rights reserved
*/
// Provides control sap.ui.vbm.FeatureCollection.
sap.ui.define([
'sap/ui/core/theming/Parameters', './GeoJsonLayer', './library'
], function(Parameters, GeoJsonLayer, library) {
"use strict";
/**
* Constructor for a new FeatureCollection.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
* @class FeatureCollection aggregation container. A FeatureCollection can render the content of an assigned GeoJSON. The naming is associated to
* the GeoJSON standard. All features found in the GeoJSON are rendered as separated objects. From the possible feature types only
* <ul>
* <li>Polygon and
* <li>Multipolygon
* </ul>
* are supported so far. The feature type support will be extended in the upcoming releases.<br>
* All features from the GeoJSON will be rendered with the given default colors and are inactive. They do not react on mouse over, except
* with tooltip, or raise any events on click or right click.<br>
* By adding <i>Feature elements</i> to the items aggregation you can make the match (by id) feature from the GeoJSON interactive and give
* it alternative colors.
* @extends sap.ui.vbm.GeoJsonLayer
* @constructor
* @public
* @alias sap.ui.vbm.FeatureCollection
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var FeatureCollection = GeoJsonLayer.extend("sap.ui.vbm.FeatureCollection", /** @lends sap.ui.vbm.FeatureCollection.prototype */
{
metadata: {
library: "sap.ui.vbm",
properties: {},
defaultAggregation: "items",
aggregations: {
/**
* Feature object aggregation
*/
items: {
type: "sap.ui.vbm.Feature",
multiple: true,
singularName: "item"
}
},
events: {
/**
* The event is raised when there is a click action on an aggregated Feature. Clicks on other Features from the GeoJSON are ignored.
*/
click: {
parameters: {
/**
* Id of clicked Feature
*/
featureId: {
type: "string"
}
}
},
/**
* The event is raised when there is a right click or a tap and hold action on an aggregated Feature. Clicks on other Features from
* the GeoJSON are ignored.
*/
contextMenu: {
parameters: {
/**
* Id of clicked Feature
*/
featureId: {
type: "string"
}
}
}
}
}
});
// /**
// * This file defines behavior for the control,
// */
// ...........................................................................//
// model creators............................................................//
FeatureCollection.prototype.getDataObjects = function() {
if (this.mbGeoJSONDirty) {
this._triggerFeatureCreation();
}
// apply the feature properties to the vbi datacontext.....................//
// do a clone of the original data, to be able to handle complete....//
// model changes..........................................................//
var aElements = [], aPolys = [], aLines = [], aPoints = [];
jQuery.extend(aElements, this.mFeatureColl); // shallow copy of array -> need to copy elements before change!
var oOverlayMap = {};
if (aElements.length) {
// create lookup for overlayed features..................................//
var aOverlayFeatures = this.getItems();
for (var nJ = 0, len = aOverlayFeatures ? aOverlayFeatures.length : 0, item; nJ < len; ++nJ) {
item = aOverlayFeatures[nJ];
oOverlayMap[item.getFeatureId()] = item;
}
}
// iterate over feature table.............................................//
for (var nK = 0, oElement, oOverlay, tmp; nK < aElements.length; ++nK) {
oElement = aElements[nK];
if ((oOverlay = oOverlayMap[oElement.K])) {
// Overlay found, apply properties.....................................//
// do not change original element -> make copy first!
var oCopy = {};
jQuery.extend(oCopy, oElement);
oElement = aElements[nK] = oCopy;
// apply changes
oElement.C = oOverlay.getColor();
if ((tmp = oOverlay.getTooltip())) {
oElement.TT = tmp;
}
}
switch (oElement.type) {
case "Polygon":
case "MultiPolygon":
aPolys.push(oElement);
break;
case "LineString":
case "MultiLineString":
aLines.push(oElement);
break;
case "Point":
case "MultiPoint":
aPoints.push(oElement);
break;
default:
jQuery.sap.log.error("FeatureCollection: Unknown feature type: " + oElement.type);
}
}
return [
{
"name": this.getId() + "_Polys",
"type": "N",
"E": aPolys
}, {
"name": this.getId() + "_Lines",
"type": "N",
"E": aLines
}, {
"name": this.getId() + "_Points",
"type": "N",
"E": aPoints
}
];
};
FeatureCollection.prototype.getDataRemoveObjects = function() {
return [
{
"name": this.getId() + "_Polys",
"type": "N"
}, {
"name": this.getId() + "_Lines",
"type": "N"
}, {
"name": this.getId() + "_Points",
"type": "N"
}
];
};
/**
* Returns Properties for Features like name, bounding box, and midpoint
*
* @param {string[]} aFeatureIds Array of Feature Ids. The Feature Id must match the GeoJSON tag.
* @returns {array} Array of Feature Information Objects. Each object in the array has the properties BBox: Bounding Box for the Feature in format
* "lonMin;latMin;lonMax;latMax", Midpoint: Centerpoint for Feature in format "lon;lat", Name: Name of the Feature, and Properties: Array
* of name-value-pairs associated with the Feature
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
FeatureCollection.prototype.getFeaturesInfo = function(aFeatureIds) {
var result = [];
for (var nJ = 0, len = aFeatureIds.length, featureId; nJ < len; ++nJ) {
featureId = aFeatureIds[nJ];
result[featureId] = {};
result[featureId].BBox = this.mFeatureBBox[featureId];
result[featureId].Midpoint = [
(this.mFeatureBBox[featureId][0] + this.mFeatureBBox[featureId][1]) / 2, (this.mFeatureBBox[featureId][2] + this.mFeatureBBox[featureId][3]) / 2
];
result[featureId].Name = this.mNames[featureId];
result[featureId].Properties = this.mFeatureProps[featureId];
}
return result;
};
FeatureCollection.prototype.handleEvent = function(event) {
var s = event.Action.name;
var funcname = "fire" + s[0].toUpperCase() + s.slice(1);
// first we try to get the event on a FeatureCollection instance......................//
var oOverlay, sInstance = event.Action.instance;
if ((oOverlay = this.findInstance(sInstance))) {
if (oOverlay.mEventRegistry[s]) {
if (s === "click") {
oOverlay.mClickGeoPos = event.Action.AddActionProperties.AddActionProperty[0]['#'];
}
if (s === "contextMenu") {
oOverlay.mClickPos = [
event.Action.Params.Param[0]['#'], event.Action.Params.Param[1]['#']
];
// create an empty menu
jQuery.sap.require("sap.ui.unified.Menu");
if (this.oParent.mVBIContext.m_Menus) {
this.oParent.mVBIContext.m_Menus.deleteMenu("DynContextMenu");
}
var oMenuObject = new sap.ui.unified.Menu();
oMenuObject.vbi_data = {};
oMenuObject.vbi_data.menuRef = "CTM";
oMenuObject.vbi_data.VBIName = "DynContextMenu";
// fire the contextMenu..................................................//
oOverlay.fireContextMenu({
menu: oMenuObject
});
} else if (s === "handleMoved") {
oOverlay[funcname]({
data: event
});
} else {
oOverlay[funcname]({});
}
}
}
// check wether event is registered on Feature Collection and fire in case of
if (this.mEventRegistry[s]) {
this[funcname]({
featureId: sInstance.split(".")[1]
});
}
};
/**
* open a Detail Window
*
* @param {sap.ui.vbm.Feature} oFeature VO instance for which the Detail Window should be opened
* @param {object} oParams Parameter object
* @param {string} oParams.caption Text for Detail Window caption
* @param {string} oParams.offsetX position offset in x-direction from the anchor point
* @param {string} oParams.offsetY position offset in y-direction from the anchor point
* @returns {void}
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
FeatureCollection.prototype.openDetailWindow = function(oFeature, oParams) {
var oParent = this.getParent();
oParent.mDTWindowCxt.bUseClickPos = true;
oParent.mDTWindowCxt.open = true;
oParent.mDTWindowCxt.src = oFeature;
oParent.mDTWindowCxt.key = oFeature.getFeatureId();
oParent.mDTWindowCxt.params = oParams;
oParent.m_bWindowsDirty = true;
oParent.invalidate(this);
};
/**
* open the context menu
*
* @param {sap.ui.vbm.Feature} oFeature VO instance for which the Detail Window should be opened
* @param {object} oMenu the context menu to be opened
* @returns {void}
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
FeatureCollection.prototype.openContextMenu = function(oFeature, oMenu) {
this.oParent.openContextMenu("Area", oFeature, oMenu);
};
FeatureCollection.prototype.handleChangedData = function(aElements) {
if (aElements && aElements.length) {
for (var nI = 0, oElement, oInst; nI < aElements.length; ++nI) {
oElement = aElements[nI];
oInst = this.findInstance(oElement.K);
if (oInst) {
oInst.handleChangedData(oElement);
}
}
}
};
return FeatureCollection;
});
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
sap.ui.define([
"sap/ui/fl/Utils", "jquery.sap.global"
], function(Utils, $) {
"use strict";
/**
* Base class for all change handler subclasses which provides some reuse methods
* @constructor
* @alias sap.ui.fl.changeHandler.Base
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*
*/
var Base = function() {
};
/**
* @param {sap.ui.core.Control} oControl - the control for which the properties shall be returned
* @param {String} sName - name of property
* @returns {Object} property object
* @private
*/
Base.prototype._getProperty = function(oControl, sName) {
if (oControl) {
if (oControl.getMetadata) {
var oMetadata = oControl.getMetadata();
var oProperties = oMetadata.getProperties();
if (oProperties) {
var oProperty = oProperties[sName];
if (oProperty) {
return oProperty;
}
}
}
}
};
/**
* Changes a property of the control
*
* @param {sap.ui.core.Control} oControl - the control for which the changes should be fetched
* @param {string} sName - property name
* @param {object} oValue - new value of the property
*
* @public
*/
Base.prototype.changeProperty = function(oControl, sName, oValue) {
var oProperty = this._getProperty(oControl, sName);
if (oProperty) {
oControl.setProperty(sName, oValue);
}
};
/**
* Sets a property of the control back to its default value
*
* @param {sap.ui.core.Control} oControl - the control for which the changes should be fetched
* @param {string} sName - property name
*
* @public
*/
Base.prototype.clearProperty = function(oControl, sName) {
var oProperty = this._getProperty(oControl, sName);
if (oProperty) {
oControl.setProperty(sName, oProperty.defaultValue);
}
};
/**
* Adds an additional item of the aggregation or changes it in case it is not a multiple one
*
* @param {sap.ui.core.Control} oControl - the control for which the changes should be fetched
* @param {string} sName - aggregation name
* @param {string} oObject - aggregated object to be set
* @param {integer} iIndex <optional> - index to which it should be added/inserted
*
* @public
*/
Base.prototype.addAggregation = function(oControl, sName, oObject, iIndex) {
if (oControl) {
if (oControl.getMetadata) {
var oMetadata = oControl.getMetadata();
var oAggregations = oMetadata.getAllAggregations();
if (oAggregations) {
var oAggregation = oAggregations[sName];
if (oAggregation) {
// if(oAggregation.multiple === false) {
// oControl.destroyAggregation(sName);
// }
if (oAggregation.multiple) {
var iInsertIndex = iIndex || oAggregations.length || 0;
oControl[oAggregation._sInsertMutator](oObject, iInsertIndex);
} else {
oControl[oAggregation._sMutator](oObject);
}
}
}
}
}
};
Base.prototype.removeAggregation = function(oControl, sName, oObject) {
if (oControl) {
if (oControl.getMetadata) {
var oMetadata = oControl.getMetadata();
var oAggregations = oMetadata.getAllAggregations();
if (oAggregations) {
var oAggregation = oAggregations[sName];
if (oAggregation) {
oControl[oAggregation._sRemoveMutator](oObject);
}
}
}
}
};
/**
* Sets a text in a change.
*
* @param {object} oChange - change object
* @param {string} sKey - text key
* @param {string} sText - text value
* @param {string} sType - translation text type e.g. XBUT, XTIT, XTOL, XFLD
*
* @public
*/
Base.prototype.setTextInChange = function(oChange, sKey, sText, sType) {
if (!oChange.texts) {
oChange.texts = {};
}
if (!oChange.texts[sKey]) {
oChange.texts[sKey] = {};
}
oChange.texts[sKey].value = sText;
oChange.texts[sKey].type = sType;
};
return Base;
}, /* bExport= */true);
<file_sep>// This file has been generated by the SAPUI5 'AllInOne' Builder
(function () {
"use strict";
/*global sap, jQuery */
sap.ui.controller("sap.ovp.cards.charts.bubble.BubbleChart", {
onInit: function () {
sap.ovp.cards.charts.Utils.formatChartYaxis();
var vizFrame = this.getView().byId("bubbleChartCard");
if (vizFrame) {
vizFrame.attachBrowserEvent("click", this.onHeaderClick.bind(this));
}
this.delegate1 = {
onBeforeRendering: function(){
this.setBusy(true);
}
};
this.delegate2 = {
onAfterRendering: function(){
this.setBusy(false);
}
};
},
onBeforeRendering : function() {
sap.ovp.cards.charts.Utils.validateCardConfiguration(this);
var vizFrame = this.getView().byId("bubbleChartCard");
if (!vizFrame) {
jQuery.sap.log.error(sap.ovp.cards.charts.Utils.constants.ERROR_NO_CHART +
": (" + this.getView().getId() + ")");
} else {
vizFrame.addEventDelegate(this.delegate1, vizFrame);
var binding = vizFrame.getDataset().getBinding("data");
binding.attachDataReceived(jQuery.proxy(this.onDataReceived, this));
sap.ovp.cards.charts.Utils.validateMeasuresDimensions(vizFrame, "Bubble");
}
},
onDataReceived: function(oEvent) {
var vizFrame = this.getView().byId("bubbleChartCard");
vizFrame.addEventDelegate(this.delegate2, vizFrame);
sap.ovp.cards.charts.Utils.hideDateTimeAxis(vizFrame, "valueAxis");
sap.ovp.cards.charts.Utils.checkNoData(oEvent, this.getCardContentContainer(), vizFrame);
}
});
})();
(function () {
"use strict";
/*global sap, jQuery */
sap.ui.controller("sap.ovp.cards.charts.donut.DonutChart", {
onInit: function() {
var vizFrame = this.getView().byId("donutChartCard");
if (vizFrame) {
vizFrame.attachBrowserEvent("click", this.onHeaderClick.bind(this));
}
this.delegate1 = {
onBeforeRendering: function(){
this.setBusy(true);
}
};
this.delegate2 = {
onAfterRendering: function(){
this.setBusy(false);
}
};
},
onBeforeRendering: function () {
var utils = sap.ovp.cards.charts.Utils;
utils.validateCardConfiguration(this);
var measureArrNames = [];
var dimensionArrayNames = [];
var vizFrame = this.getView().byId("donutChartCard");
if (!vizFrame) {
jQuery.sap.log.error(utils.constants.ERROR_NO_CHART +
": (" + this.getView().getId() + ")");
} else {
vizFrame.addEventDelegate(this.delegate1, vizFrame);
var binding = vizFrame.getDataset().getBinding("data");
binding.attachDataReceived(jQuery.proxy(this.onDataReceived, this));
sap.ovp.cards.charts.Utils.validateMeasuresDimensions(vizFrame, "Donut");
var entityTypeObject = this.getCardPropertiesModel().getProperty("/entityType");
var columnLabels = utils.getAllColumnLabels(entityTypeObject);
var measuresArr = vizFrame.getDataset().getMeasures();
var dimensionsArr = vizFrame.getDataset().getDimensions();
measureArrNames.push(measuresArr[0].getName());
var dimensionName = columnLabels[dimensionsArr[0].getName()];
dimensionArrayNames.push(dimensionName ? dimensionName : dimensionsArr[0].getName());
vizFrame.removeAllFeeds();
vizFrame.addFeed(new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "size",
'type': "Measure",
'values': measureArrNames
}));
vizFrame.addFeed(new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "color",
'type': "Dimension",
'values': dimensionArrayNames
}));
vizFrame.setVizProperties({
size:{
title:{
visible:false
}
},
color:{
title:{
visible:false
}
},
legend: {
isScrollable: false
},
title: {
visible: false
},
interaction:{
noninteractiveMode: true,
selectability: {
legendSelection: false,
axisLabelSelection: false,
mode: "NONE",
plotLassoSelection: false,
plotStdSelection: false
}
}
});
utils.formatChartYaxis();
}
},
onDataReceived: function(oEvent) {
var vizFrame = this.getView().byId("donutChartCard");
vizFrame.addEventDelegate(this.delegate2, vizFrame);
sap.ovp.cards.charts.Utils.checkNoData(oEvent, this.getCardContentContainer(), vizFrame);
}
});
})();
(function () {
"use strict";
/*global sap, jQuery */
sap.ui.controller("sap.ovp.cards.charts.line.LineChart", {
onInit: function () {
sap.ovp.cards.charts.Utils.formatChartYaxis();
var vizFrame = this.getView().byId("lineChartCard");
if (vizFrame) {
vizFrame.attachBrowserEvent("click", this.onHeaderClick.bind(this));
}
this.delegate1 = {
onBeforeRendering: function(){
this.setBusy(true);
}
};
this.delegate2 = {
onAfterRendering: function(){
this.setBusy(false);
}
};
},
onBeforeRendering : function() {
sap.ovp.cards.charts.Utils.validateCardConfiguration(this);
var vizFrame = this.getView().byId("lineChartCard");
if (!vizFrame) {
jQuery.sap.log.error(sap.ovp.cards.charts.Utils.constants.ERROR_NO_CHART +
": (" + this.getView().getId() + ")");
} else {
vizFrame.addEventDelegate(this.delegate1, vizFrame);
var binding = vizFrame.getDataset().getBinding("data");
binding.attachDataReceived(jQuery.proxy(this.onDataReceived, this));
sap.ovp.cards.charts.Utils.validateMeasuresDimensions(vizFrame, "Line");
}
},
onDataReceived: function(oEvent) {
var vizFrame = this.getView().byId("lineChartCard");
sap.ovp.cards.charts.Utils.hideDateTimeAxis(vizFrame, "categoryAxis");
sap.ovp.cards.charts.Utils.checkNoData(oEvent, this.getCardContentContainer(), vizFrame);
vizFrame.addEventDelegate(this.delegate2, vizFrame);
}
});
})();
(function () {
"use strict";
/*global sap, jQuery */
sap.ui.controller("sap.ovp.cards.image.Image", {
onInit: function () {
},
onImagePress: function (oEvent) {
this.doNavigation(oEvent.getSource().getBindingContext());
}
});
})();
(function () {
"use strict";
/*global sap, jQuery */
sap.ui.controller("sap.ovp.cards.list.List", {
maxValue: -1,
counter: 0,
arrayLength: 0,
onInit: function () {
this.counter = 0;
},
onListItemPress: function (oEvent) {
var aNavigationFields = this.getEntityNavigationEntries(oEvent.getSource().getBindingContext(), this.getCardPropertiesModel().getProperty("/annotationPath"));
this.doNavigation(oEvent.getSource().getBindingContext(), aNavigationFields[0]);
},
normalizeValueToPercentage: function (value) {
var oEntityType = this.getEntityType(),
sAnnotationPath = this.getCardPropertiesModel().getProperty("/annotationPath"),
aRecords = oEntityType[sAnnotationPath],
context = this.getMetaModel().createBindingContext(oEntityType.$path + "/" + sAnnotationPath);
if (sap.ovp.cards.AnnotationHelper.isFirstDataPointPercentageUnit(context, aRecords)) {
var iPercent = parseInt(value, 10);
return iPercent <= 100 ? iPercent : 100;
}
var maxV = this._getMaxValue();
if (this.counter == this.arrayLength) {
this.counter = 0;
this.maxValue = -1;
}
if (value > maxV) {
return 100;
} else {
var iValue = (parseInt(value, 10) * 100) / maxV;
if (iValue != 0) {
return iValue;
} else { //if the value is 0 we want to show some minimal value in the bar
return 0.5;
}
}
},
_getMaxValue: function () {
this.counter++;
if (this.maxValue != -1) {
return this.maxValue;
}
var oEntityType = this.getEntityType(),
sAnnotationPath = this.getCardPropertiesModel().getProperty("/annotationPath"),
aRecords = oEntityType[sAnnotationPath],
context = this.getMetaModel().createBindingContext(oEntityType.$path + "/" + sAnnotationPath);
var dataPointValue = sap.ovp.cards.AnnotationHelper.getFirstDataPointValue(context, aRecords);
var barList = this.getView().byId("ovpList"),
listItems = barList.getBinding("items"),
itemsContextsArray = listItems.getCurrentContexts();
this.arrayLength = itemsContextsArray.length;
for (var i = 0; i < itemsContextsArray.length; i++) {
if (parseInt(itemsContextsArray[i].getObject()[dataPointValue], 10) > this.maxValue) {
this.maxValue = parseInt(itemsContextsArray[i].getObject()[dataPointValue], 10);
}
}
return this.maxValue;
},
/**
* Gets the card items binding object for the count footer
*/
getCardItemsBinding: function() {
var list = this.getView().byId("ovpList");
return list.getBinding("items");
}
});
})();
(function () {
"use strict";
/*global sap, jQuery */
sap.ui.controller("sap.ovp.cards.loading.Loading", {
onInit: function () {
},
onAfterRendering: function(){
var oView = this.getView();
oView.addStyleClass("sapOvpLoadingCard");
var loadingFooter = oView.byId("ovpLoadingFooter");
var sState = this.getCardPropertiesModel().getProperty("/state");
if (sState === sap.ovp.cards.loading.State.ERROR){
loadingFooter.setText(sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("cannotLoadCard"));
} else {
//sState === sap.ovp.cards.loading.State.LOADING
setTimeout(function () {
loadingFooter.setBusy(true);
}, 6000);
setTimeout(function(){
loadingFooter.setBusy(false);
loadingFooter.setText(sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("cannotLoadCard"));
}, 9000);
}
}
});
})();
(function () {
"use strict";
/*global sap, jQuery */
sap.ui.controller("sap.ovp.cards.table.Table", {
onInit: function () {
},
onColumnListItemPress: function (oEvent) {
var aNavigationFields = this.getEntityNavigationEntries(oEvent.getSource().getBindingContext(), this.getCardPropertiesModel().getProperty("/annotationPath"));
this.doNavigation(oEvent.getSource().getBindingContext(), aNavigationFields[0]);
},
/**
* Gets the card items binding object for the count footer
*/
getCardItemsBinding: function() {
var table = this.getView().byId("ovpTable");
return table.getBinding("items");
}
});
})();
jQuery.sap.declare('sap.ovp.library-all');
jQuery.sap.declare('sap.ovp.cards.charts.bubble.BubbleChart.controller'); // raw module, declared by SAPUI5 'AllInOne' Builder
jQuery.sap.declare('sap.ovp.cards.charts.donut.DonutChart.controller'); // raw module, declared by SAPUI5 'AllInOne' Builder
jQuery.sap.declare('sap.ovp.cards.charts.line.LineChart.controller'); // raw module, declared by SAPUI5 'AllInOne' Builder
jQuery.sap.declare('sap.ovp.cards.image.Image.controller'); // raw module, declared by SAPUI5 'AllInOne' Builder
jQuery.sap.declare('sap.ovp.cards.list.List.controller'); // raw module, declared by SAPUI5 'AllInOne' Builder
jQuery.sap.declare('sap.ovp.cards.loading.Loading.controller'); // raw module, declared by SAPUI5 'AllInOne' Builder
jQuery.sap.declare('sap.ovp.cards.table.Table.controller'); // raw module, declared by SAPUI5 'AllInOne' Builder
if ( !jQuery.sap.isDeclared('sap.ovp.app.Component') ) {
(function () {
"use strict";
/*global sap, jQuery */
/**
* @fileOverview Application component to display information on entities from the GWSAMPLE_BASIC
* OData service.
* @version 1.36.12
*/
jQuery.sap.declare("sap.ovp.app.Component");
jQuery.sap.require('sap.ui.model.odata.AnnotationHelper'); // unlisted dependency retained
sap.ui.core.UIComponent.extend("sap.ovp.app.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
routing : {
config: {
routerClass : sap.ui.core.routing.Router
},
targets: {},
routes : []
},
properties: {
"cardContainerFragment": {
"type": "string",
"defaultValue": "sap.ovp.app.CardContainer"
}
},
version: "1.36.12",
library: "sap.ovp.app",
dependencies: {
libs: [ "sap.m",
"sap.ui.comp",
"sap.uxap"
],
components: []
},
config: {
fullWidth: true,
hideLightBackground: true
}
},
_addModelsMeasurements: function(){
var oModels = this.oModels;
var oModel, sModel;
for (sModel in oModels){
oModel = this.getModel(sModel);
if (oModel.getMetaModel()){
this._addModelMeasurements(oModel, sModel);
}
}
},
_addModelMeasurements: function(oModel, sModel) {
var sId = "ovp:ModelLoading-" + sModel;
var sIdBatch = "ovp:ModelBatchCall-" + sModel + ":";
jQuery.sap.measure.start(sId, "Component createContent -> MetaData loaded", "ovp");
oModel.getMetaModel().loaded().then(function(){
jQuery.sap.measure.end(sId);
}
);
oModel.attachBatchRequestSent(function(oEvent){
jQuery.sap.measure.start(sIdBatch + oEvent.getParameter("ID"), "BatchRequestSent -> BatchRequestCompleted", "ovp");
});
oModel.attachBatchRequestCompleted(function(oEvent){
jQuery.sap.measure.end(sIdBatch + oEvent.getParameter("ID"));
});
},
/**
* get the merged sap.ovp section from all component hierarchy
* @returns merged sap.ovp section from manifes files
*/
getOvpConfig: function(){
var oOvpConfig;
var aExtendArgs = [];
var oManifest = this.getMetadata();
//loop over the manifest hierarchy till we reach the current generic component
while (oManifest && oManifest.getComponentName() !== "sap.ovp.app"){
oOvpConfig = oManifest.getManifestEntry("sap.ovp");
if (oOvpConfig){
//as the last object is the dominant one we use unshift and not push
aExtendArgs.unshift(oOvpConfig);
}
oManifest = oManifest.getParent();
}
//add an empty object for the merged config as we don't whant to change the actual manifest objects
aExtendArgs.unshift({});
//add deep flag so the merge would be recurcive
aExtendArgs.unshift(true);
oOvpConfig = jQuery.extend.apply(jQuery, aExtendArgs);
return oOvpConfig;
},
createXMLView: function (ovpConfig) {
jQuery.sap.measure.start("ovp:AppCreateContent", "OVP app Component createContent", "ovp");
this._addModelsMeasurements();
this.getRouter().initialize();
var appConfig = this.getMetadata().getManifestEntry("sap.app");
var uiConfig = this.getMetadata().getManifestEntry("sap.ui");
var sIcon = jQuery.sap.getObject("icons.icon", undefined, uiConfig);
var sComponentName = this.getMetadata().getComponentName();
ovpConfig.baseUrl = jQuery.sap.getModulePath(sComponentName);
var uiModel = new sap.ui.model.json.JSONModel(ovpConfig);
uiModel.setProperty("/title", jQuery.sap.getObject("title", undefined, appConfig));
uiModel.setProperty("/description", jQuery.sap.getObject("description", undefined, appConfig));
uiModel.setProperty("/cardContainerFragment", this.getCardContainerFragment());
if (sIcon){
if (sIcon.indexOf("sap-icon") < 0 && sIcon.charAt(0) !== '/'){
sIcon = ovpConfig.baseUrl + "/" + sIcon;
}
uiModel.setProperty("/icon", sIcon);
}
//convert cards object into sorted array
var oCards = ovpConfig.cards;
var aCards = [];
var oCard;
for (var cardKey in oCards){
if (oCards.hasOwnProperty(cardKey) && oCards[cardKey]) {
oCard = oCards[cardKey];
oCard.id = cardKey;
aCards.push(oCard);
}
}
aCards.sort(function(card1, card2){
if (card1.id < card2.id){
return -1;
} else if (card1.id > card2.id){
return 1;
} else {
return 0;
}
});
uiModel.setProperty("/cards", aCards);
this.setModel(uiModel, "ui");
var oFilterModel = this.getModel(ovpConfig.globalFilterModel);
this.setModel(oFilterModel);
var oEntityType = oFilterModel.getMetaModel().getODataEntityType(oFilterModel.getMetaModel().oModel.oData.dataServices.schema[0].namespace + "." + ovpConfig.globalFilterEntityType, true);
var oView = sap.ui.view({
height: "100%",
preprocessors: {
xml: {
bindingContexts: {ui: uiModel.createBindingContext("/"),
meta: oFilterModel.getMetaModel().createBindingContext(oEntityType)},
models: {ui: uiModel,
meta: oFilterModel.getMetaModel()}
}
},
type: sap.ui.core.mvc.ViewType.XML,
viewName: "sap.ovp.app.Main"
});
jQuery.sap.measure.end("ovp:AppCreateContent");
return oView;
},
setContainer: function () {
var ovpConfig = this.getOvpConfig();
var oFilterModel = this.getModel(ovpConfig.globalFilterModel);
// call overwritten setContainer (sets this.oContainer)
sap.ui.core.UIComponent.prototype.setContainer.apply(this, arguments);
if (oFilterModel) {
oFilterModel.getMetaModel().loaded().then(function () {
// Do the templating once the metamodel is loaded
this.runAsOwner(function () {
var oView = this.createXMLView(ovpConfig);
this.setAggregation("rootControl", oView);
this.getUIArea().invalidate();
}.bind(this));
}.bind(this));
}
}
});
}());
}; // end of sap/ovp/app/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.ActionUtils') ) {
(function () {
"use strict";
/*global dispatchEvent, document, jQuery, localStorage, sap */
jQuery.sap.declare("sap.ovp.cards.ActionUtils");
sap.ovp.cards.ActionUtils = {};
sap.ovp.cards.ActionUtils.getActionInfo = function(oContext, action, oEntityType) {
var metaModel = oContext.getModel().getMetaModel();
var sFunctionName = action.action.split('/')[1];
var oContextObject = oContext.getObject();
var actionData = {
oContext: oContext,
sFunctionImportPath: action.action,
sFunctionLabel: action.label,
oFunctionImport: metaModel.getODataFunctionImport(sFunctionName),
parameterData: {},
allParameters: []
};
var oParameterValue;
if (actionData.oFunctionImport.parameter) {
var keyMap = this._getKeyProperties(oEntityType);
for (var i = 0; i < actionData.oFunctionImport.parameter.length; i++) {
var oParameter = actionData.oFunctionImport.parameter[i];
this._addParamLabel(oParameter, oEntityType, metaModel);
if (keyMap[oParameter.name]) {
oParameter.isKey = true;
}
if (typeof oParameter.nullable === 'undefined') {
oParameter.nullable = true;// default is not mandatory parameter == could be null
}
if (oContextObject.hasOwnProperty(oParameter.name)) {
oParameterValue = oContextObject[oParameter.name];
} else {
oParameterValue = "";
}
actionData.parameterData[oParameter.name] = oParameterValue;
actionData.allParameters.push(oParameter);
}
}
return actionData;
};
sap.ovp.cards.ActionUtils._getKeyProperties = function(oEntityType){
var oKeyMap = {};
if (oEntityType && oEntityType.key && oEntityType.key.propertyRef){
for (var i = 0; i < oEntityType.key.propertyRef.length; i++) {
var sKeyName = oEntityType.key.propertyRef[i].name;
oKeyMap[sKeyName] = true;
}
}
return oKeyMap;
};
sap.ovp.cards.ActionUtils._addParamLabel = function (oParameter, oEntityType, metaModel){
if (oEntityType && oParameter && !oParameter["com.sap.vocabularies.Common.v1.Label"]) {
var oProperty = metaModel.getODataProperty(oEntityType, oParameter.name, false);
if (oProperty && oProperty["com.sap.vocabularies.Common.v1.Label"]) {
// copy label from property to parameter with same name as default if no label is set for function import parameter
oParameter["com.sap.vocabularies.Common.v1.Label"] = oProperty["com.sap.vocabularies.Common.v1.Label"];
} else if (oProperty && oProperty["sap:label"]) {
oParameter["sap:label"] = oProperty["sap:label"];
}
}
};
sap.ovp.cards.ActionUtils.buildParametersForm = function(actionData, onFieldChangeCB) {
function getParamLabel(oParameter){
var sLabel = "";
if (oParameter["com.sap.vocabularies.Common.v1.Label"]) {
sLabel = oParameter["com.sap.vocabularies.Common.v1.Label"].String;
} else if (oParameter["sap:label"]) {
sLabel = oParameter["sap:label"];
} else {
sLabel = oParameter.name;
}
return sLabel;
}
jQuery.sap.require("sap.ui.layout.form.SimpleForm");
jQuery.sap.require("sap.ui.comp.smartfield.SmartField");
var oForm = new sap.ui.layout.form.SimpleForm({
editable: true
});
var aFields = [];
for (var i = 0; i < actionData.allParameters.length; i++) {
var oParameter = actionData.allParameters[i];
var sParameterLabel = getParamLabel(oParameter);
var sBinding = '{/' + oParameter.name + '}';
var sJSONType = null;
var sEdmType = oParameter.type;
// max length - default undefined if not set in OData metadata
var iMaxLength = oParameter.maxLength ? parseInt(oParameter.maxLength, 10) : undefined;
// covers Edm.Byte, Edm.SByte, Edm.Boolean, Edm.Int16, Edm.Int32, Edm.Time
if (sEdmType === 'Edm.Boolean') {
sJSONType = sap.ui.comp.smartfield.JSONType.Boolean;
} else if (sEdmType === 'Edm.Byte' || sEdmType === 'Edm.SByte' || sEdmType === 'Edm.Int16' || sEdmType === 'Edm.Int32') {
sJSONType = sap.ui.comp.smartfield.JSONType.Integer;
} else {
sJSONType = sap.ui.comp.smartfield.JSONType.String;
}
var isMandatory = sap.ovp.cards.ActionUtils._isMandatoryParameter(oParameter);
var oField = new sap.ui.comp.smartfield.SmartField({
value: sBinding,
mandatory: isMandatory,
jsontype: sJSONType,
maxLength: iMaxLength,
editable:!oParameter.isKey
});
oField.attachChange(onFieldChangeCB);
aFields.push(oField);
var oLabel = new sap.ui.comp.smartfield.SmartLabel();
oLabel.setRequired(isMandatory && !oParameter.isKey);
oLabel.setText(sParameterLabel);
oLabel.setLabelFor(oField);
oForm.addContent(oLabel);
oForm.addContent(oField);
}
return oForm;
};
sap.ovp.cards.ActionUtils.getParameters = function (oParameterModel, functionImport){
var paramObject = sap.ovp.cards.ActionUtils._validateParametersValue(oParameterModel, functionImport);
return paramObject.preparedParameterData;
};
sap.ovp.cards.ActionUtils.mandatoryParamsMissing = function(oParameterModel, functionImport) {
var oValidatedParams = sap.ovp.cards.ActionUtils._validateParametersValue(oParameterModel, functionImport);
return oValidatedParams.missingMandatoryParameters && oValidatedParams.missingMandatoryParameters.length > 0;
};
sap.ovp.cards.ActionUtils._validateParametersValue = function(oParameterModel, functionImport) {
var aMissingMandatoryParameters = [];
var oModelParameterData = oParameterModel.getObject('/');
var oPreparedParameterData = {};
var oValue, isMandatory;
for (var i = 0; i < functionImport.parameter.length; i++) {
var oParameter = functionImport.parameter[i];
var sParameterName = oParameter.name;
if (oModelParameterData.hasOwnProperty(sParameterName)) {
oValue = oModelParameterData[sParameterName];
isMandatory = sap.ovp.cards.ActionUtils._isMandatoryParameter(oParameter);
if (oValue === undefined || oValue === "") {
if (isMandatory) {
if (oParameter.type === 'Edm.Boolean'){
oPreparedParameterData[sParameterName] = false;
} else {
aMissingMandatoryParameters.push(oParameter);
}
}
} else {
oPreparedParameterData[sParameterName] = oValue;
}
} else {
throw new Error("Unknown parameter: " + sParameterName);
}
}
return {
preparedParameterData: oPreparedParameterData,
missingMandatoryParameters: aMissingMandatoryParameters
};
};
sap.ovp.cards.ActionUtils._isMandatoryParameter = function(oParameter) {
return !sap.ovp.cards.ActionUtils._toBoolean(oParameter.nullable);
};
sap.ovp.cards.ActionUtils._toBoolean = function(oParameterValue) {
if (typeof oParameterValue === "string"){
var oValue = oParameterValue.toLowerCase();
return !(oValue == "false" || oValue == "" || oValue == " ");
}
return !!oParameterValue;
};
}());
}; // end of sap/ovp/cards/ActionUtils.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.AnnotationHelper') ) {
// Copyright (c) 2009-2014 SAP SE, All Rights Reserved
/**
* @fileOverview This file contains miscellaneous utility functions.
*/
(function () {
"use strict";
/*global dispatchEvent, document, jQuery, localStorage, sap */
// ensure that sap.ushell exists
jQuery.sap.declare("sap.ovp.cards.AnnotationHelper");
sap.ovp.cards.AnnotationHelper = {};
sap.ovp.cards.AnnotationHelper.formatFunctions = {count: 0};
sap.ovp.cards.AnnotationHelper.NumberFormatFunctions = {};
sap.ovp.cards.AnnotationHelper.criticalityConstants = {
StateValues : {
None : "None",
Negative : "Error",
Critical : "Warning",
Positive : "Success"
},
ColorValues : {
None : "Neutral",
Negative : "Error",
Critical : "Critical",
Positive : "Good"
}
};
function getCacheEntry(iContext, sKey) {
if (iContext.getSetting) {
var oCache = iContext.getSetting("_ovpCache");
return oCache[sKey];
}
return undefined;
}
function setCacheEntry(iContext, sKey, oValue) {
if (iContext.getSetting) {
var oCache = iContext.getSetting("_ovpCache");
oCache[sKey] = oValue;
}
}
function criticality2state(criticality, oCriticalityConfigValues) {
var sState = oCriticalityConfigValues.None;
if (criticality && criticality.EnumMember) {
var val = criticality.EnumMember;
if (endsWith(val, 'Negative')) {
sState = oCriticalityConfigValues.Negative;
} else if (endsWith(val, 'Critical')) {
sState = oCriticalityConfigValues.Critical;
} else if (endsWith(val, 'Positive')) {
sState = oCriticalityConfigValues.Positive;
}
}
return sState;
}
function endsWith(sString, sSuffix) {
return sString && sString.indexOf(sSuffix, sString.length - sSuffix.length) !== -1;
}
function generateCriticalityCalculationStateFunction(criticalityCalculation, oCriticalityConfigValues) {
return function (value) {
value = Number(value);
var sDirection = criticalityCalculation.ImprovementDirection.EnumMember;
var oCriticality = {};
var deviationLow = getNumberValue(criticalityCalculation.DeviationRangeLowValue);
var deviationHigh = getNumberValue(criticalityCalculation.DeviationRangeHighValue);
var toleranceLow = getNumberValue(criticalityCalculation.ToleranceRangeLowValue);
var toleranceHigh = getNumberValue(criticalityCalculation.ToleranceRangeHighValue);
if (endsWith(sDirection, "Minimize") || endsWith(sDirection, "Minimizing")) {
if (value <= toleranceHigh) {
oCriticality.EnumMember = "Positive";
} else if (value > deviationHigh) {
oCriticality.EnumMember = "Negative";
} else {
oCriticality.EnumMember = "Critical";
}
} else if (endsWith(sDirection, "Maximize") || endsWith(sDirection, "Maximizing")) {
if (value >= toleranceLow) {
oCriticality.EnumMember = "Positive";
} else if (value < deviationLow) {
oCriticality.EnumMember = "Negative";
} else {
oCriticality.EnumMember = "Critical";
}
} else if (endsWith(sDirection, "Target")) {
if (value >= toleranceLow && value <= toleranceHigh) {
oCriticality.EnumMember = "Positive";
} else if (value < deviationLow || value > deviationHigh) {
oCriticality.EnumMember = "Negative";
} else {
oCriticality.EnumMember = "Critical";
}
}
return criticality2state(oCriticality, oCriticalityConfigValues);
};
}
function getSortedDataFields(iContext, aCollection) {
var sCacheKey = iContext.getPath() + "-DataFields-Sorted";
var aSortedFields = getCacheEntry(iContext, sCacheKey);
if (!aSortedFields) {
var aDataPoints = getSortedDataPoints(iContext, aCollection);
var aDataPointsValues = aDataPoints.map(function (oDataPoint) {
return oDataPoint.Value.Path;
});
aDataPointsValues = aDataPointsValues.filter(function (element) {
return !!element;
});
aSortedFields = aCollection.filter(function (item) {
if (item.RecordType === "com.sap.vocabularies.UI.v1.DataField" && aDataPointsValues.indexOf(item.Value.Path) === -1) {
return true;
}
return false;
});
sortCollectionByImportance(aSortedFields);
setCacheEntry(iContext, sCacheKey, aSortedFields);
}
return aSortedFields;
}
function getSortedDataPoints(iContext, aCollection) {
var sCacheKey = iContext.getPath() + "-DataPoints-Sorted";
var aSortedFields = getCacheEntry(iContext, sCacheKey);
if (!aSortedFields) {
aSortedFields = aCollection.filter(isDataFieldForAnnotation);
sortCollectionByImportance(aSortedFields);
var sEntityTypePath;
for (var i = 0; i < aSortedFields.length; i++) {
sEntityTypePath = iContext.getPath().substr(0, iContext.getPath().lastIndexOf("/") + 1);
aSortedFields[i] = iContext.getModel().getProperty(getTargetPathForDataFieldForAnnotation(sEntityTypePath,aSortedFields[i]));
sEntityTypePath = "";
}
setCacheEntry(iContext, sCacheKey, aSortedFields);
}
return aSortedFields;
}
function isDataFieldForAnnotation(oItem) {
if (oItem.RecordType === "com.sap.vocabularies.UI.v1.DataFieldForAnnotation"
&&
oItem.Target.AnnotationPath.match(/@com.sap.vocabularies.UI.v1.DataPoint.*/)) {
return true;
}
return false;
}
function getTargetPathForDataFieldForAnnotation(sEntityTypePath, oDataFieldForAnnotation) {
if (sEntityTypePath && !endsWith(sEntityTypePath,'/')) {
sEntityTypePath += '/';
}
return sEntityTypePath + oDataFieldForAnnotation.Target.AnnotationPath.slice(1);
}
function getImportance(oDataField) {
var sImportance;
if (oDataField["com.sap.vocabularies.UI.v1.Importance"]) {
sImportance = oDataField["com.sap.vocabularies.UI.v1.Importance"].EnumMember;
}
return sImportance;
}
function sortCollectionByImportance(aCollection) {
aCollection.sort(function (a, b) {
var aImportance = getImportance(a),
bImportance = getImportance(b);
if (aImportance === bImportance) {
return 0;
}
if (aImportance === "com.sap.vocabularies.UI.v1.ImportanceType/High") {
return -1;
} else if (bImportance === "com.sap.vocabularies.UI.v1.ImportanceType/High") {
return 1;
} else if (aImportance === "com.sap.vocabularies.UI.v1.ImportanceType/Medium") {
return -1;
} else if (bImportance === "com.sap.vocabularies.UI.v1.ImportanceType/Medium") {
return 1;
} else if (aImportance === "com.sap.vocabularies.UI.v1.ImportanceType/Low") {
return -1;
} else if (bImportance === "com.sap.vocabularies.UI.v1.ImportanceType/Low") {
return 1;
}
return -1;
});
return aCollection;
}
function formatDataField(iContext, aCollection, index) {
var item = getSortedDataFields(iContext, aCollection)[index];
if (item) {
return formatField(iContext, item);
}
return "";
}
function getDataFieldName(iContext, aCollection, index) {
var item = getSortedDataFields(iContext, aCollection)[index];
if (item) {
return item.Label.String;
}
return "";
}
function getDataPointName(iContext, aCollection, index) {
var item = getSortedDataPoints(iContext, aCollection)[index];
if (item && item.Title) {
return item.Title.String;
}
return "";
}
function formatDataPoint(iContext, aCollection, index) {
var item = getSortedDataPoints(iContext, aCollection)[index];
if (!item) {
return "";
}
var oModel = iContext.getSetting('ovpCardProperties');
var oEntityType = oModel.getProperty("/entityType");
var oMetaModel = oModel.getProperty("/metaModel");
return _formatDataPoint(iContext, item, oEntityType, oMetaModel);
}
function _formatDataPoint(iContext, oItem, oEntityType, oMetaModel) {
if (!oItem || !oItem.Value) {
return "";
}
var oEntityTypeProperty = oMetaModel.getODataProperty(oEntityType, oItem.Value.Path);
//Support sap:text attribute
if (oEntityTypeProperty && oEntityTypeProperty["sap:text"]) {
oEntityTypeProperty = oMetaModel.getODataProperty(oEntityType, oEntityTypeProperty["sap:text"]);
oItem = {Value: {Path: oEntityTypeProperty.name}};
}
return formatField(iContext, oItem);
}
function formatField(iContext, item, bDontIncludeUOM, bIncludeOnlyUOM) {
if (item.Value.Apply) {
return sap.ui.model.odata.AnnotationHelper.format(iContext, item.Value);
}
var oModel = iContext.getSetting('ovpCardProperties');
var oEntityType = oModel.getProperty("/entityType");
var oMetaModel = oModel.getProperty("/metaModel");
return _formatField(iContext, item, oEntityType, oMetaModel, bDontIncludeUOM, bIncludeOnlyUOM);
}
function _formatField(iContext, oItem, oEntityType, oMetaModel, bDontIncludeUOM, bIncludeOnlyUOM) {
if (oItem.Value.Apply) {
return sap.ui.model.odata.AnnotationHelper.format(iContext, oItem.Value);
}
var oEntityTypeProperty = oMetaModel.getODataProperty(oEntityType, oItem.Value.Path);
var result = "";
var functionName;
if (!bIncludeOnlyUOM) {
//Support association
if (oItem.Value.Path.split("/").length > 1) {
oEntityTypeProperty = getNavigationSuffix(oMetaModel, oEntityType, oItem.Value.Path);
}
if (!oEntityTypeProperty) {
return "";
}
//Item has ValueFormat annotation
if (oItem.ValueFormat && oItem.ValueFormat.NumberOfFractionalDigits) {
functionName = getNumberFormatFunctionName(oItem.ValueFormat.NumberOfFractionalDigits.Int);
result = "{path:'" + oItem.Value.Path + "', formatter: '" + functionName + "'}";
} else if (oEntityTypeProperty["scale"]) {
//If there is no value format annotation, we will use the metadata scale property
functionName = getNumberFormatFunctionName(oEntityTypeProperty["scale"]);
result = "{path:'" + oEntityTypeProperty.name + "', formatter: '" + functionName + "'}";
} else {
result = sap.ui.model.odata.AnnotationHelper.format(iContext, oItem.Value);
}
}
if (!bDontIncludeUOM) {
//Add currency using path or string
if (oEntityTypeProperty["Org.OData.Measures.V1.ISOCurrency"]) {
var oCurrency = oEntityTypeProperty["Org.OData.Measures.V1.ISOCurrency"];
if (oCurrency.Path) {
result = result + " {path: '" + oCurrency.Path + "'}";
} else if (oCurrency.String) {
result = result + " " + oCurrency.String;
}
}
//Add unit using path or string
if (oEntityTypeProperty["Org.OData.Measures.V1.Unit"]) {
var oUnit = oEntityTypeProperty["Org.OData.Measures.V1.Unit"];
if (oUnit.Path) {
result = result + " {path: '" + oUnit.Path + "'}";
} else if (oUnit.String) {
result = result + " " + oUnit.String;
}
}
}
if (result[0] === " "){
result = result.substring(1);
}
return result;
}
function getNumberFormatFunctionName(numberOfFractionalDigits) {
var functionName = "formatNumberCalculation" + numberOfFractionalDigits;
if (!sap.ovp.cards.AnnotationHelper.NumberFormatFunctions[functionName]) {
sap.ovp.cards.AnnotationHelper.NumberFormatFunctions[functionName] = generateNumberFormatFunc(Number(numberOfFractionalDigits));
}
return "sap.ovp.cards.AnnotationHelper.NumberFormatFunctions." + functionName;
}
function generateNumberFormatFunc(numOfFragmentDigit) {
return function (value) {
jQuery.sap.require("sap.ui.core.format.NumberFormat");
var formatNumber = sap.ui.core.format.NumberFormat.getFloatInstance({
style: 'short',
showMeasure: false,
minFractionDigits: numOfFragmentDigit,
maxFractionDigits: numOfFragmentDigit
});
return formatNumber.format(Number(value));
};
}
function getNavigationSuffix(oMetaModel, oEntityType, sProperty) {
var aParts = sProperty.split("/");
if (aParts.length > 1) {
for (var i = 0; i < (aParts.length - 1); i++) {
var oAssociationEnd = oMetaModel.getODataAssociationEnd(oEntityType, aParts[i]);
if (oAssociationEnd) {
oEntityType = oMetaModel.getODataEntityType(oAssociationEnd.type);
}
}
return oMetaModel.getODataProperty(oEntityType, aParts[aParts.length - 1]);
}
}
function formatDataPointState(iContext, aCollection, index) {
var aDataPoints = getSortedDataPoints(iContext, aCollection);
var sState = "None";
if (aDataPoints.length > index) {
var item = aDataPoints[index];
sState = formatDataPointToValue(iContext, item, sap.ovp.cards.AnnotationHelper.criticalityConstants.StateValues);
}
return sState;
}
function formatDataPointToValue(iContext, oDataPoint, oCriticalityConfigValues) {
var sState = oCriticalityConfigValues.None;
if (oDataPoint.Criticality) {
sState = criticality2state(oDataPoint.Criticality, oCriticalityConfigValues);
} else if (oDataPoint.CriticalityCalculation) {
var sFormattedPath = sap.ui.model.odata.AnnotationHelper.format(iContext, oDataPoint.Value);
var sPath = sFormattedPath.match(/path *: *'.*?',/g);
if (sPath) {
var fFormatFunc = generateCriticalityCalculationStateFunction(oDataPoint.CriticalityCalculation, oCriticalityConfigValues);
sap.ovp.cards.AnnotationHelper.formatFunctions.count++;
var fName = "formatCriticalityCalculation" + sap.ovp.cards.AnnotationHelper.formatFunctions.count;
sap.ovp.cards.AnnotationHelper.formatFunctions[fName] = fFormatFunc;
sState = "{" + sPath + " formatter: 'sap.ovp.cards.AnnotationHelper.formatFunctions." + fName + "'}";
}
}
return sState;
}
function getNavigationPrefix(oMetaModel, oEntityType, sProperty) {
var sExpand = "";
var aParts = sProperty.split("/");
if (aParts.length > 1) {
for (var i = 0; i < (aParts.length - 1); i++) {
var oAssociationEnd = oMetaModel.getODataAssociationEnd(oEntityType, aParts[i]);
if (oAssociationEnd) {
oEntityType = oMetaModel.getODataEntityType(oAssociationEnd.type);
if (sExpand) {
sExpand = sExpand + "/";
}
sExpand = sExpand + aParts[i];
} else {
return sExpand;
}
}
}
return sExpand;
}
sap.ovp.cards.AnnotationHelper.formatField = function (iContext, oItem) {
return formatField(iContext,oItem);
};
/*
* This formatter method parses the List-Card List's items aggregation path in the Model.
* The returned path may contain also sorter definition (for the List) sorting is defined
* appropriately via respected Annotations.
*
* @param iContext
* @param itemsPath
* @returns List-Card List's items aggregation path in the Model
*/
sap.ovp.cards.AnnotationHelper.formatItems = function (iContext, oEntitySet) {
var oModel = iContext.getSetting('ovpCardProperties');
var bAddODataSelect = oModel.getProperty("/addODataSelect");
var oMetaModel = oModel.getProperty("/metaModel");
var oEntityType = oMetaModel.getODataEntityType(oEntitySet.entityType);
var oSelectionVariant = oEntityType[oModel.getProperty('/selectionAnnotationPath')];
var oPresentationVariant = oEntityType[oModel.getProperty('/presentationAnnotationPath')];
var sEntitySetPath = "/" + oEntitySet.name;
var aAnnotationsPath = Array.prototype.slice.call(arguments, 2);
//check if entity set needs parameters
// if selection-annotations path is supplied - we need to resolve it in order to resolve the full entity-set path
if (oSelectionVariant) {
if (oSelectionVariant && oSelectionVariant.Parameters) {
// in case we have UI.SelectionVariant annotation defined on the entityType including Parameters - we need to resolve the entity-set path to include it
sEntitySetPath = sap.ovp.cards.AnnotationHelper.resolveParameterizedEntitySet(iContext.getSetting('dataModel'), oEntitySet, oSelectionVariant);
}
}
var result = "{path: '" + sEntitySetPath + "', length: " + getItemsLength(oModel);
//prepare the select fields in case flag is on
var aSelectFields = [];
if (bAddODataSelect) {
aSelectFields = getSelectFields(iContext, oMetaModel, oEntityType, aAnnotationsPath);
}
//prepare the expand list if navigation properties are used
var aExpand = getExpandList(oMetaModel, oEntityType, aAnnotationsPath);
//add select and expand parameters to the binding info string if needed
if (aSelectFields.length > 0 || aExpand.length > 0) {
result = result + ", parameters: {";
if (aSelectFields.length > 0) {
result = result + "select: '" + aSelectFields.join(',') + "'";
}
if (aExpand.length > 0) {
if (aSelectFields.length > 0) {
result = result + ", ";
}
result = result + "expand: '" + aExpand.join(',') + "'";
}
result = result + "}";
}
//apply sorters information
var aSorters = getSorters(oModel, oPresentationVariant);
if (aSorters.length > 0) {
result = result + ", sorter:" + JSON.stringify(aSorters);
}
//apply filters information
var aFilters = getFilters(oModel, oSelectionVariant);
if (aFilters.length > 0) {
result = result + ", filters:" + JSON.stringify(aFilters);
}
result = result + "}";
// returning the parsed path for the Card's items-aggregation binding
return result;
};
/**
* returns an array of navigation properties prefixes to be used in an odata $expand parameter
*
* @param oMetaModel - metamodel to get the annotations to query
* @param oEntityType - the relevant entityType
* @param aAnnotationsPath - an array of annotation path to check
* @returns {Array} of navigation properties prefixes to be used in an odata $expand parameter
*/
function getExpandList(oMetaModel, oEntityType, aAnnotationsPath) {
var aExpand = [];
var sAnnotationPath, oBindingContext, aColl, sExpand;
//loop over the annotation paths
for (var i = 0; i < aAnnotationsPath.length; i++) {
if (!aAnnotationsPath[i]) {
continue;
}
sAnnotationPath = oEntityType.$path + "/" + aAnnotationsPath[i];
oBindingContext = oMetaModel.createBindingContext(sAnnotationPath);
aColl = oBindingContext.getObject();
//if the annotationPath does not exists there is no BindingContext
aColl = aColl ? aColl : [];
for (var j = 0; j < aColl.length; j++) {
if (aColl[j].Value && aColl[j].Value.Path) {
sExpand = getNavigationPrefix(oMetaModel, oEntityType, aColl[j].Value.Path);
if (sExpand && aExpand.indexOf(sExpand) === -1) {
aExpand.push(sExpand);
}
}
}
}
return aExpand;
}
/**
* returns an array of properties paths to be used in an odata $select parameter
*
* @param oMetaModel - metamodel to get the annotations to query
* @param oEntityType - the relevant entityType
* @param aAnnotationsPath - an array of annotation path to check
* @returns {Array} of properties paths to be used in an odata $select parameter
*/
function getSelectFields(iContext, oMetaModel, oEntityType, aAnnotationsPath) {
var aSelectFields = [];
var sAnnotationPath, oBindingContext, aColl;
//loop over the annotation paths
for (var i = 0; i < aAnnotationsPath.length; i++) {
if (!aAnnotationsPath[i]) {
continue;
}
sAnnotationPath = oEntityType.$path + "/" + aAnnotationsPath[i];
oBindingContext = oMetaModel.createBindingContext(sAnnotationPath);
aColl = oBindingContext.getObject();
//if the annotationPath does not exists there is no BindingContext
aColl = aColl ? aColl : [];
var oItem;
var aItemValue;
var sFormattedField;
var sRecordType;
for (var j = 0; j < aColl.length; j++) {
aItemValue = [];
oItem = aColl[j];
sFormattedField = "";
sRecordType = oItem.RecordType;
if (sRecordType === "com.sap.vocabularies.UI.v1.DataField") {
// in case of a DataField we format the field to get biding string
sFormattedField = _formatField(iContext,oItem,oEntityType,oMetaModel);
} else if (sRecordType === "com.sap.vocabularies.UI.v1.DataFieldForAnnotation") {
// in case of DataFieldForAnnotation we resolve the DataPoint target path of the DataField and format the field to get biding string
var sTargetPath = getTargetPathForDataFieldForAnnotation(oEntityType.$path, oItem);
sFormattedField = _formatDataPoint(iContext, oMetaModel.getProperty(sTargetPath), oEntityType, oMetaModel);
} else if (sRecordType === "com.sap.vocabularies.UI.v1.DataFieldWithUrl" && oItem.Url) {
// format the URL ONLY IN CASE NO UrlRef member resides under it
var sFormattedUrl;
if (!oItem.Url.UrlRef) {
sFormattedUrl = sap.ui.model.odata.AnnotationHelper.format(iContext, oItem.Url);
}
// meaning binding which needs to be evaluated at runtime
if (sFormattedUrl && sFormattedUrl.substring(0,2) === "{=") {
sFormattedField = sFormattedUrl;
}
}
// if we have found a relevant binding-info-string this iteration then parse it to get binded properties
if (sFormattedField) {
aItemValue = getPropertiesFromBindingString(sFormattedField);
}
if (aItemValue && aItemValue.length > 0) {
// for each property found we check if has sap:unit and sap:text
var sItemValue;
for (var k = 0; k < aItemValue.length; k++) {
sItemValue = aItemValue[k];
// if this property is found for the first time - look for its unit and text properties as well
if (!aSelectFields[sItemValue]) {
aSelectFields[sItemValue] = true;
// checking if we need to add also the sap:unit property of the field's value
var sUnitPropName = getUnitColumn(sItemValue, oEntityType);
if (sUnitPropName && sUnitPropName !== sItemValue) {
aSelectFields[sUnitPropName] = true;
}
// checking if we need to add also the sap:text property of the field's value
var sTextPropName = getTextPropertyForEntityProperty(oMetaModel, oEntityType, sItemValue);
if (sTextPropName && sTextPropName !== sItemValue) {
aSelectFields[sTextPropName] = true;
}
}
}
}
}
}
// return all relevant property names
return Object.keys(aSelectFields);
}
function getPropertiesFromBindingString(sBinding) {
var regexBindingEvaluation = /\${([a-zA-Z0-9|\/]*)/g;
var regexBindingNoPath = /[^[{]*[a-zA-Z0-9]/g;
var regexBindingPath = /path *\: *\'([a-zA-Z0-9]+)*\'/g;
var regex, index, matches = [];
if (sBinding.substring(0, 2) === "{=") {
/*
meaning binding string looks like "{= <rest of the binding string>}"
which is a binding which needs to be evaluated using some supported function
properties appear as ${propertyName} inside the string
*/
regex = regexBindingEvaluation;
/* index is 1 as each match found by this regular expression (by invoking regex.exec(string) below) */
/* is an array of 2 items, for example ["${Address}", "Address"] so we need the 2nd result each match found */
index = 1;
} else if (sBinding.indexOf("path") !== -1) {
/* In a scenario where binding contains string like "{propertyName} {path:'propertyName'}" */
/* Here we get the properties without path and add it to array matches*/
var matchWithNoPath = regexBindingNoPath.exec(sBinding);
while (matchWithNoPath) {
if (matchWithNoPath[0].indexOf("path") === -1) {
matches.push(matchWithNoPath[0]);
}
matchWithNoPath = regexBindingNoPath.exec(sBinding);
}
/* meaning binding contains string like "{path:'propertyName'}" */
regex = regexBindingPath;
/* index is 1 as each match found by this regular expression (by invoking regex.exec(string) below) */
/* is an array of 2 items, for example ["{path: 'Address'}", "Address"] so we need the 2nd result each match found */
index = 1;
} else {
/* meaning binding contains string like "{'propertyName'}" */
regex = regexBindingNoPath;
/* index is 0 as each match found by this regular expression (by invoking regex.exec(string) below) */
/* is an array of one item, for example ["Address"] so we need the 1st result each match found */
index = 0;
}
var match = regex.exec(sBinding);
while (match) {
if (match[index]) {
matches.push(match[index]);
}
match = regex.exec(sBinding);
}
return matches;
}
/**
* return the sorters that need to be applyed on an aggregation
*
* @param ovpCardProperties - card properties model which might contains sort configurations
* @param oPresentationVariant - optional presentation variant annotation with SortOrder configuration
* @returns {Array} of model sorters
*/
function getSorters(ovpCardProperties, oPresentationVariant) {
var aSorters = [];
var oSorter, bDescending;
//get the configured sorter if exist and append them to the sorters array
var sPropertyPath = ovpCardProperties.getProperty("/sortBy");
if (sPropertyPath) {
// If sorting is enabled by card configuration
var sSortOrder = ovpCardProperties.getProperty('/sortOrder');
if (sSortOrder && sSortOrder.toLowerCase() !== 'descending') {
bDescending = false;
} else {
bDescending = true;
}
oSorter = {
path: sPropertyPath,
descending: bDescending
};
aSorters.push(oSorter);
}
//get the sorters from the presentation variant annotations if exists
var aSortOrder = oPresentationVariant && oPresentationVariant.SortOrder || undefined;
var oSortOrder, sPropertyPath;
if (aSortOrder) {
for (var i = 0; i < aSortOrder.length; i++) {
oSortOrder = aSortOrder[i];
sPropertyPath = oSortOrder.Property.PropertyPath;
bDescending = getBooleanValue(oSortOrder.Descending, true);
oSorter = {
path: sPropertyPath,
descending: bDescending
};
aSorters.push(oSorter);
}
}
return aSorters;
}
sap.ovp.cards.AnnotationHelper.getCardFilters = function (ovpCardProperties) {
var oEntityType = ovpCardProperties.getProperty('/entityType');
var oSelectionVariant = oEntityType[ovpCardProperties.getProperty('/selectionAnnotationPath')];
return getFilters(ovpCardProperties, oSelectionVariant);
};
/**
* return the filters that need to be applyed on an aggregation
*
* @param ovpCardProperties - card properties model which might contains filters configurations
* @param oSelectionVariant - optional selection variant annotation with SelectOptions configuration
* @returns {Array} of model filters
*/
function getFilters(ovpCardProperties, oSelectionVariant) {
var aFilters = [];
//get the configured filters if exist and append them to the filter array
var aConfigFilters = ovpCardProperties.getProperty("/filters");
if (aConfigFilters) {
aFilters = aFilters.concat(aConfigFilters);
}
//get the filters from the selection variant annotations if exists
var aSelectOptions = oSelectionVariant && oSelectionVariant.SelectOptions;
var oSelectOption, sPropertyPath, oRange;
if (aSelectOptions) {
for (var i = 0; i < aSelectOptions.length; i++) {
oSelectOption = aSelectOptions[i];
sPropertyPath = oSelectOption.PropertyName.PropertyPath;
//a select option might contains more then one filter in the Ranges array
for (var j = 0; j < oSelectOption.Ranges.length; j++) {
oRange = oSelectOption.Ranges[j];
if (oRange.Sign.EnumMember === "com.sap.vocabularies.UI.v1.SelectionRangeSignType/I") {
//create the filter. the Low value is mandatory
var oFilter = {
path: sPropertyPath,
operator: oRange.Option.EnumMember.split("/")[1],
value1: getPrimitiveValue(oRange.Low),
value2: getPrimitiveValue(oRange.High)
};
//append the filter to the filters array
aFilters.push(oFilter);
}
}
}
}
return aFilters;
}
function getBooleanValue(oValue, bDefault) {
if (oValue && oValue.Boolean) {
if (oValue.Boolean.toLowerCase() === "true") {
return true;
} else if (oValue.Boolean.toLowerCase() === "false") {
return false;
}
}
return bDefault;
}
function getNumberValue(oValue) {
var value;
if (oValue) {
if (oValue.String) {
value = Number(oValue.String);
} else if (oValue.Int) {
value = Number(oValue.Int);
} else if (oValue.Decimal) {
value = Number(oValue.Decimal);
} else if (oValue.Double) {
value = Number(oValue.Double);
} else if (oValue.Single) {
value = Number(oValue.Single);
}
}
return value;
}
function getPrimitiveValue(oValue) {
var value;
if (oValue) {
if (oValue.String) {
value = oValue.String;
} else if (oValue.Boolean) {
value = getBooleanValue(oValue);
} else {
value = getNumberValue(oValue);
}
}
return value;
}
//This object is responsive for devices
//the id build by Type-ListType-flavor
var ITEM_LENGTH = {
"List_condensed": {phone: 5, tablet: 5, desktop: 5},
"List_extended": {phone: 3, tablet: 3, desktop: 3},
"List_condensed_bar": {phone: 5, tablet: 5, desktop: 5},
"List_extended_bar": {phone: 3, tablet: 3, desktop: 3},
"Table": {phone: 5, tablet: 5, desktop: 5},
"Stack_simple": {phone: 20, tablet: 20, desktop: 20},
"Stack_complex": {phone: 5, tablet: 5, desktop: 5}
};
function getItemsLength(oOvpCardPropertiesModel) {
var type = oOvpCardPropertiesModel.getProperty('/contentFragment');
var listType = oOvpCardPropertiesModel.getProperty('/listType');
var flavor = oOvpCardPropertiesModel.getProperty('/listFlavor');
var oItemSizes;
var device = "desktop";
//get current device
if (sap.ui.Device.system.phone) {
device = "phone";
} else if (sap.ui.Device.system.tablet) {
device = "tablet";
}
//check the current card type and get the sizes objects
if (type == "sap.ovp.cards.list.List") {
if (listType == "extended") {
if (flavor == "bar") {
oItemSizes = ITEM_LENGTH["List_extended_bar"];
} else {
oItemSizes = ITEM_LENGTH["List_extended"];
}
} else if (flavor == "bar") {
oItemSizes = ITEM_LENGTH["List_condensed_bar"];
} else {
oItemSizes = ITEM_LENGTH["List_condensed"];
}
} else if (type == "sap.ovp.cards.table.Table") {
oItemSizes = ITEM_LENGTH["Table"];
} else if (type == "sap.ovp.cards.stack.Stack") {
if (oOvpCardPropertiesModel.getProperty('/objectStreamCardsNavigationProperty')) {
oItemSizes = ITEM_LENGTH["Stack_complex"];
} else {
oItemSizes = ITEM_LENGTH["Stack_simple"];
}
}
if (oItemSizes) {
return oItemSizes[device];
}
return 5;
}
sap.ovp.cards.AnnotationHelper.formatUrl = function (iContext, sUrl) {
if (sUrl.charAt(0) === '/' || sUrl.indexOf("http") === 0) {
return sUrl;
}
var sBaseUrl = iContext.getModel().getProperty("/baseUrl");
if (sBaseUrl) {
return sBaseUrl + "/" + sUrl;
}
return sUrl;
};
sap.ovp.cards.AnnotationHelper.getDataPointsCount = function (iContext, aCollection) {
var aDataPoints = getSortedDataPoints(iContext, aCollection);
return aDataPoints.length;
};
sap.ovp.cards.AnnotationHelper.getFirstDataPointValue = function (iContext, aCollection) {
return sap.ovp.cards.AnnotationHelper.getDataPointValue(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.getSecondDataPointValue = function (iContext, aCollection) {
return sap.ovp.cards.AnnotationHelper.getDataPointValue(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.getDataPointValue = function (iContext, aCollection, index) {
var aDataPoints = getSortedDataPoints(iContext, aCollection),
oDataPoint = aDataPoints[index];
if (oDataPoint && oDataPoint.Value && oDataPoint.Value.Path) {
return oDataPoint.Value.Path;
}
return "";
};
sap.ovp.cards.AnnotationHelper.getFirstDataFieldName = function (iContext, aCollection) {
return getDataFieldName(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.getSecondDataFieldName = function (iContext, aCollection) {
return getDataFieldName(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.getThirdDataFieldName = function (iContext, aCollection) {
return getDataFieldName(iContext, aCollection, 2);
};
sap.ovp.cards.AnnotationHelper.formatFirstDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.formatSecondDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.formatThirdDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 2);
};
sap.ovp.cards.AnnotationHelper.formatFourthDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 3);
};
sap.ovp.cards.AnnotationHelper.formatFifthDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 4);
};
sap.ovp.cards.AnnotationHelper.formatSixthDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 5);
};
sap.ovp.cards.AnnotationHelper.getFirstDataPointName = function (iContext, aCollection) {
return getDataPointName(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.getSecondDataPointName = function (iContext, aCollection) {
return getDataPointName(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.getThirdDataPointName = function (iContext, aCollection) {
return getDataPointName(iContext, aCollection, 2);
};
sap.ovp.cards.AnnotationHelper.formatFirstDataPointValue = function (iContext, aCollection) {
return formatDataPoint(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.formatSecondDataPointValue = function (iContext, aCollection) {
return formatDataPoint(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.formatThirdDataPointValue = function (iContext, aCollection) {
return formatDataPoint(iContext, aCollection, 2);
};
sap.ovp.cards.AnnotationHelper.formatFirstDataPointState = function (iContext, aCollection) {
return formatDataPointState(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.formatSecondDataPointState = function (iContext, aCollection) {
return formatDataPointState(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.formatThirdDataPointState = function (iContext, aCollection) {
return formatDataPointState(iContext, aCollection, 2);
};
sap.ovp.cards.AnnotationHelper.formatKPIHeaderState = function (iContext, oDataPoint) {
return formatDataPointToValue(iContext, oDataPoint, sap.ovp.cards.AnnotationHelper.criticalityConstants.ColorValues);
};
/*
* @param iContext
* @returns 0 for false - there are no actions for this context
* 1 for true - there are actions for this context
* does not return actual boolean - so we won't need to parse the result in the xml
*/
sap.ovp.cards.AnnotationHelper.hasActions = function (iContext, aCollection) {
var oItem;
for (var i = 0; i < aCollection.length; i++){
oItem = aCollection[i];
if (oItem.RecordType === "com.sap.vocabularies.UI.v1.DataFieldForIntentBasedNavigation" ||
oItem.RecordType === "com.sap.vocabularies.UI.v1.DataFieldForAction" ||
oItem.RecordType === "com.sap.vocabularies.UI.v1.DataFieldWithUrl"){
return 1;
}
}
return 0;
};
sap.ovp.cards.AnnotationHelper.isFirstDataPointPercentageUnit = function (iContext, aCollection) {
var oDataPoint = getSortedDataPoints(iContext, aCollection)[0];
if (oDataPoint && oDataPoint.Value && oDataPoint.Value.Path) {
var sEntityTypePath = iContext.getPath().substr(0, iContext.getPath().lastIndexOf("/") + 1);
var oModel = iContext.getModel();
var oEntityType = oModel.getProperty(sEntityTypePath);
var oProperty = oModel.getODataProperty(oEntityType, oDataPoint.Value.Path);
if (oProperty && oProperty["Org.OData.Measures.V1.Unit"]) {
return oProperty["Org.OData.Measures.V1.Unit"].String === "%";
}
}
return false;
};
sap.ovp.cards.AnnotationHelper.resolveEntityTypePath = function (oAnnotationPathContext) {
var sAnnotationPath = oAnnotationPathContext.getObject();
var oModel = oAnnotationPathContext.getModel();
var oMetaModel = oModel.getProperty("/metaModel");
var oEntitySet = oMetaModel.getODataEntitySet(oModel.getProperty("/entitySet"));
var oEntityType = oMetaModel.getODataEntityType(oEntitySet.entityType);
sAnnotationPath = oEntityType.$path + "/" + sAnnotationPath;
return oMetaModel.createBindingContext(sAnnotationPath);
};
sap.ovp.cards.AnnotationHelper.resolveParameterizedEntitySet = function (oDataModel, oEntitySet, oSelectionVariant) {
jQuery.sap.require("sap.ui.model.analytics.odata4analytics");
var path = "";
var o4a = new sap.ui.model.analytics.odata4analytics.Model(sap.ui.model.analytics.odata4analytics.Model.ReferenceByModel(oDataModel));
var queryResult = o4a.findQueryResultByName(oEntitySet.name);
var queryResultRequest = new sap.ui.model.analytics.odata4analytics.QueryResultRequest(queryResult);
var parameterization = queryResult.getParameterization();
if (parameterization) {
queryResultRequest.setParameterizationRequest(new sap.ui.model.analytics.odata4analytics.ParameterizationRequest(parameterization));
jQuery.each(oSelectionVariant.Parameters, function () {
if (this.RecordType === "com.sap.vocabularies.UI.v1.IntervalParameter") {
queryResultRequest.getParameterizationRequest().setParameterValue(
this.PropertyName.PropertyPath,
this.PropertyValueFrom.String,
this.PropertyValueTo.String
);
} else {
queryResultRequest.getParameterizationRequest().setParameterValue(
this.PropertyName.PropertyPath,
this.PropertyValue.String
);
}
});
}
try {
path = queryResultRequest.getURIToQueryResultEntitySet();
} catch (exception) {
queryResult = queryResultRequest.getQueryResult();
path = "/" + queryResult.getEntitySet().getQName();
jQuery.sap.log.error("getEntitySetPathWithParameters", "binding path with parameters failed - " + exception
|| exception.message);
}
return path;
};
sap.ovp.cards.AnnotationHelper.getAssociationObject = function (oModel, sAssociation, ns) {
// find a nicer way of getting association set entry in meta model
var aAssociations = oModel.getServiceMetadata().dataServices.schema[0].association;
for (var i = 0; i < aAssociations.length; i++) {
if (ns + "." + aAssociations[i].name === sAssociation) {
return aAssociations[i];
}
}
};
/**************************** Formatters & Helpers for KPI-Header logic ****************************/
/* Returns binding path for singleton */
sap.ovp.cards.AnnotationHelper.getAggregateNumber = function (iContext, oEntitySet, oDataPoint, oSelectionVariant) {
var measure = oDataPoint.Value.Path;
var ret = "";
var bParams = oSelectionVariant && oSelectionVariant.Parameters;
var filtersString = "";
if (bParams) {
var dataModel = iContext.getSetting("dataModel");
var path = sap.ovp.cards.AnnotationHelper.resolveParameterizedEntitySet(dataModel, oEntitySet, oSelectionVariant);
ret += "{path: '" + path + "'";
} else {
ret += "{path: '/" + oEntitySet.name + "'";
}
ret += ", length: 1";
var oOvpCardSettings = iContext.getSetting('ovpCardProperties');
var oEntityType = oOvpCardSettings.getProperty("/entityType");
var unitColumn = getUnitColumn(measure, oEntityType);
var aFilters = getFilters(oOvpCardSettings, oSelectionVariant);
if (aFilters.length > 0) {
filtersString += ", filters: " + JSON.stringify(aFilters);
}
var selectArr = [];
selectArr.push(measure);
if (unitColumn) {
selectArr.push(unitColumn);
}
if (oDataPoint.TrendCalculation && oDataPoint.TrendCalculation.ReferenceValue && oDataPoint.TrendCalculation.ReferenceValue.Path) {
selectArr.push(oDataPoint.TrendCalculation.ReferenceValue.Path);
}
return ret + ", parameters:{select:'" + selectArr.join(",") + "'}" + filtersString + "}";
};
/* Creates binding path for NumericContent value */
sap.ovp.cards.AnnotationHelper.formThePathForAggregateNumber = function (iContext, dataPoint) {
if (!dataPoint || !dataPoint.Value || !dataPoint.Value.Path) {
return "";
}
return formatField(iContext, dataPoint, true, false);
};
/* Creates binding path for trend icon */
sap.ovp.cards.AnnotationHelper.formThePathForTrendIcon = function (dataPoint) {
if (!dataPoint || !dataPoint.Value || !dataPoint.Value.Path || !dataPoint.TrendCalculation) {
return "";
}
if (dataPoint.TrendCalculation &&
dataPoint.TrendCalculation.ReferenceValue &&
dataPoint.TrendCalculation.ReferenceValue.Path) {
return "{parts: [{path:'" + dataPoint.Value.Path + "'}, {path:'" + dataPoint.TrendCalculation.ReferenceValue.Path + "'}], formatter: 'sap.ovp.cards.AnnotationHelper.returnTrendDirection'}";
} else {
return "{parts: [{path:'" + dataPoint.Value.Path + "'}], formatter: 'sap.ovp.cards.AnnotationHelper.returnTrendDirection'}";
}
};
/* Formatter for Trend Direction for Header */
sap.ovp.cards.AnnotationHelper.returnTrendDirection = function (aggregateValue, referenceValue) {
aggregateValue = Number(aggregateValue);
var ovpModel = this.getModel("ovpCardProperties");
if (!ovpModel) {
return;
}
var fullQualifier = ovpModel.getProperty("/dataPointAnnotationPath");
var dataPoint = ovpModel.getProperty("/entityType")[fullQualifier];
var finalReferenceValue, upDifference, downDifference;
if (dataPoint.TrendCalculation.ReferenceValue) {
if (dataPoint.TrendCalculation.ReferenceValue.Path) {
finalReferenceValue = Number(referenceValue);
} else {
finalReferenceValue = getNumberValue(dataPoint.TrendCalculation.ReferenceValue);
}
}
if (dataPoint.TrendCalculation.UpDifference) {
upDifference = getNumberValue(dataPoint.TrendCalculation.UpDifference);
}
if (dataPoint.TrendCalculation.DownDifference) {
downDifference = getNumberValue(dataPoint.TrendCalculation.DownDifference);
}
if (!dataPoint.TrendCalculation.UpDifference && (aggregateValue - finalReferenceValue >= 0)) {
return "Up";
}
if (!dataPoint.TrendCalculation.DownDifference && (aggregateValue - finalReferenceValue <= 0)) {
return "Down";
}
if (finalReferenceValue && upDifference && (aggregateValue - finalReferenceValue >= upDifference)) {
return "Up";
}
if (finalReferenceValue && downDifference && (aggregateValue - finalReferenceValue <= downDifference)) {
return "Down";
}
};
/* Creates binding path for UOM placeholder */
sap.ovp.cards.AnnotationHelper.formThePathForUOM = function (iContext, dataPoint) {
if (!dataPoint || !dataPoint.Value || !dataPoint.Value.Path) {
return "";
}
return formatField(iContext, dataPoint, false, true);
};
/* Creates binding path for % change */
sap.ovp.cards.AnnotationHelper.formPathForPercentageChange = function (dataPoint) {
if (!dataPoint || !dataPoint.TrendCalculation || !dataPoint.TrendCalculation.ReferenceValue) {
return "";
}
if (dataPoint.TrendCalculation.ReferenceValue.Path) {
return "{parts: [{path:'" + dataPoint.Value.Path + "'}, {path:'" + dataPoint.TrendCalculation.ReferenceValue.Path + "'}], formatter: 'sap.ovp.cards.AnnotationHelper.returnPercentageChange'}";
} else {
return "{parts: [{path:'" + dataPoint.Value.Path + "'}], formatter: 'sap.ovp.cards.AnnotationHelper.returnPercentageChange'}";
}
};
/* Formatter for % change for Header */
sap.ovp.cards.AnnotationHelper.returnPercentageChange = function (aggregateValue, referenceValuePath) {
jQuery.sap.require("sap.ui.core.format.NumberFormat");
var ret = "";
aggregateValue = Number(aggregateValue);
var ovpModel = this.getModel("ovpCardProperties");
if (!ovpModel) {
return ret;
}
var fullQualifier = ovpModel.getProperty("/dataPointAnnotationPath");
var dataPoint = ovpModel.getProperty("/entityType")[fullQualifier];
var referenceValue;
if (!dataPoint.TrendCalculation) {
return ret;
}
if (dataPoint.TrendCalculation.ReferenceValue) {
if (dataPoint.TrendCalculation.ReferenceValue.String) {
referenceValue = Number(dataPoint.TrendCalculation.ReferenceValue.String);
}
if (dataPoint.TrendCalculation.ReferenceValue.Path) {
referenceValue = Number(referenceValuePath);
}
if (!referenceValue || referenceValue == 0) {
return ret;
}
var percentNumber = ((Number(aggregateValue) - referenceValue) / referenceValue);
var percentFormatter = sap.ui.core.format.NumberFormat.getPercentInstance({
style: 'short',
minFractionDigits: 2,
maxFractionDigits: 2
});
return percentFormatter.format(percentNumber);
}
};
/*
* Reads groupBy from annotation and prepares comma separated list
*/
sap.ovp.cards.AnnotationHelper.listGroupBy = function (oPresentationVariant) {
var result = "";
var bPV = oPresentationVariant && oPresentationVariant.GroupBy;
if (!bPV) {
return result;
}
var metaModel = this.getModel('ovpCardProperties').getProperty("/metaModel");
var oEntityType = this.getModel('ovpCardProperties').getProperty("/entityType");
var groupByList;
if (oPresentationVariant.GroupBy.constructor === Array) {
groupByList = oPresentationVariant.GroupBy;
} else if (!oPresentationVariant.GroupBy.Collection) {
return result;
} else {
groupByList = oPresentationVariant.GroupBy.Collection;
}
var propVal;
jQuery.each(groupByList, function () {
propVal = getLabelForEntityProperty(metaModel, oEntityType, this.PropertyPath);
if (!propVal) {
return;
}
result += propVal;
result += ", ";
});
if (result[result.length - 1] === " " && result[result.length - 2] === ",") {
result = result.substring(0, result.length - 2);
}
return result == "" ? "" : sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("By", [result]);
};
/*
* returns the string for the filter-by values of the KPI Header
* */
sap.ovp.cards.AnnotationHelper.formTheFilterByString = function(iContext, oSelectionVariant) {
var oCardPropsModel = iContext.getSetting('ovpCardProperties');
var oEntityType = oCardPropsModel.getProperty("/entityType");
var oMetaModel = oCardPropsModel.getProperty("/metaModel");
var aFilters = getFilters(oCardPropsModel, oSelectionVariant);
var sProp;
var sTextPropKey;
//Clean from Filter array all the filters with sap-text that the filter array contains there sap-text
for (var i = 0; i < aFilters.length; i++ ) {
sProp = aFilters[i].path;
sTextPropKey = getTextPropertyForEntityProperty(oMetaModel, oEntityType, sProp);
//Check if there is sap-text, in case there is checks that the Filter array contains it
if (sTextPropKey !== sProp) {
for (var j = 0; j < aFilters.length; j++ ) {
// if there is sap test - we won't show the original filter (instead we will show the sap-text) and we clean it from the array
if ((aFilters[j].path == sTextPropKey)){
aFilters.splice(i, 1);
break;
}
}
}
}
// build the filter string
return generateStringForFilters(aFilters);
};
/************************ METADATA PARSERS ************************/
function generateStringForFilters(aFilters) {
var aFormatterFilters = [];
for (var i = 0; i < aFilters.length; i++ ) {
aFormatterFilters.push(generateSingleFilter(aFilters[i]));
}
return aFormatterFilters.join(', ');
}
function generateSingleFilter(oFilter) {
var bNotOperator = false;
var sFormattedFilter = oFilter.value1;
if (oFilter.operator[0] === "N") {
bNotOperator = true;
}
if (oFilter.value2) {
sFormattedFilter += " - " + oFilter.value2;
}
if (bNotOperator) {
sFormattedFilter = sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("kpiHeader_Filter_NotOperator", [sFormattedFilter]);
}
return sFormattedFilter;
}
/* Returns column name that contains the unit for the measure */
function getUnitColumn (measure, oEntityType) {
var properties = oEntityType.property;
for (var i = 0, len = properties.length; i < len; i++) {
if (properties[i].name == measure) {
if (properties[i].hasOwnProperty("sap:unit")) {
return properties[i]["sap:unit"];
}
break;
}
}
return null;
}
function getLabelForEntityProperty(oMetadata, oEntityType, sPropertyName) {
return getAttributeValueForEntityProperty(oMetadata, oEntityType,
sPropertyName, "com.sap.vocabularies.Common.v1.Label");
}
function getTextPropertyForEntityProperty(oMetamodel, oEntityType, sPropertyName) {
return getAttributeValueForEntityProperty(oMetamodel, oEntityType,
sPropertyName, "sap:text");
}
function getAttributeValueForEntityProperty(oMetamodel, oEntityType, sPropertyName, sAttributeName) {
var oProp = oMetamodel.getODataProperty(oEntityType, sPropertyName);
if (!oProp) {
jQuery.sap.log.error("No Property Found for with Name '" + sPropertyName
+ " For Entity-Type '" + oEntityType.name + "'");
return;
}
var oPropAttVal = oProp[sAttributeName];
if (oPropAttVal) {
if (sAttributeName === "com.sap.vocabularies.Common.v1.Label") {
return oPropAttVal.String;
}
return oPropAttVal;
}
return oProp.name;
}
sap.ovp.cards.AnnotationHelper._criticality2state = criticality2state;
sap.ovp.cards.AnnotationHelper._generateCriticalityCalculationStateFunction = generateCriticalityCalculationStateFunction;
sap.ovp.cards.AnnotationHelper._getPropertiesFromBindingString = getPropertiesFromBindingString;
sap.ovp.cards.AnnotationHelper.sortCollectionByImportance = sortCollectionByImportance;
sap.ovp.cards.AnnotationHelper.formatField.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formThePathForAggregateNumber.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formThePathForUOM.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formTheFilterByString.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getAggregateNumber.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getFirstDataFieldName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getSecondDataFieldName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getThirdDataFieldName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatFirstDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatSecondDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatThirdDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatFourthDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatFifthDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatSixthDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getDataPointsCount.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getFirstDataPointName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getSecondDataPointName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getThirdDataPointName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatFirstDataPointValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatSecondDataPointValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatThirdDataPointValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatFirstDataPointState.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatSecondDataPointState.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatThirdDataPointState.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatKPIHeaderState.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatItems.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatUrl.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.hasActions.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getFirstDataPointValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getSecondDataPointValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.isFirstDataPointPercentageUnit.requiresIContext = true;
}());
}; // end of sap/ovp/cards/AnnotationHelper.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.CommonUtils') ) {
(function () {
"use strict";
jQuery.sap.declare("sap.ovp.cards.CommonUtils");
sap.ovp.cards.CommonUtils = {
app : undefined,
navigationHandler : undefined,
enable : function(app, oNavHandler) {
this.app = app;
this.navigationHandler = oNavHandler;
},
getApp : function() {
return this.app;
},
getNavigationHandler : function() {
return this.navigationHandler;
}
};
}());
}; // end of sap/ovp/cards/CommonUtils.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.charts.Utils') ) {
/**
* @fileOverview This file contains miscellaneous utility functions.
*/
(function () {
"use strict";
jQuery.sap.declare("sap.ovp.cards.charts.Utils");
sap.ovp.cards.charts.Utils = sap.ovp.cards.charts.Utils || {};
/* All constants feature here */
sap.ovp.cards.charts.Utils.constants = {
/* qualifiers for annotation terms */
CHART_QUALIFIER_KEY: "chartAnnotationPath",
SELVAR_QUALIFIER_KEY: "selectionAnnotationPath",
PREVAR_QUALIFIER_KEY: "presentationAnnotationPath",
/* size of the collection to be rendered on chart */
CHART_DATA_SIZE: "4",
/* DEBUG MESSAGES */
ERROR_NO_CHART: "Analytic cards require valid \"chartAnnotationPath\" " +
"configured in manifest.json"
};
/* retrieve qualifier from iContext */
sap.ovp.cards.charts.Utils.getQualifier = function (iContext, annoTerm) {
/* see sap.ovp.cards.charts.Utils.constants for legal values of annoTerm */
if (!annoTerm) {
return "";
}
var settingsModel = iContext.getSetting('ovpCardProperties');
if (!settingsModel) {
return "";
}
var oSettings = settingsModel.oData;
if (!oSettings) {
return "";
}
var fullQualifier = oSettings && oSettings[annoTerm] ? oSettings[annoTerm] : "";
return fullQualifier === "" ? "" : fullQualifier.split("#")[1];
};
/************************ FORMATTERS ************************/
sap.ovp.cards.charts.Utils.wrapInBraces = function(whateverNeedsToBeInBraces) {
return "{" + whateverNeedsToBeInBraces + "}";
};
sap.ovp.cards.charts.Utils.getSapLabel = function(property) {
var entityTypeObject = this.getModel('ovpCardProperties').getProperty("/entityType");
var label = sap.ovp.cards.charts.Utils.getAllColumnLabels(entityTypeObject)[property];
return label ? label : property;
};
sap.ovp.cards.charts.Utils.formDimensionPath = function(dimension) {
var ret = "{" + dimension + "}";
var entityTypeObject = this.getModel('ovpCardProperties').getProperty("/entityType");
if (!entityTypeObject) {
return ret;
}
var edmTypes = sap.ovp.cards.charts.Utils.getEdmTypeOfAll(entityTypeObject);
if (!edmTypes || !edmTypes[dimension]) {
return ret;
}
var type = edmTypes[dimension];
if (type == "Edm.DateTime") {
return "{path:'" + dimension + "', formatter: 'sap.ovp.cards.charts.Utils.returnDateFormat'}";
}
var columnTexts = sap.ovp.cards.charts.Utils.getAllColumnTexts(entityTypeObject);
if (!columnTexts) {
return ret;
}
ret = "{" + (columnTexts[dimension] || dimension) + "}";
return ret;
};
sap.ovp.cards.charts.Utils.returnDateFormat = function(date) {
if (date) {
jQuery.sap.require("sap.ui.core.format.DateFormat");
var oDateFormat = sap.ui.core.format.DateFormat.getDateTimeInstance({pattern: "dd-MMM"});
return oDateFormat.format(new Date(date));
}
return "";
};
/*
* Reads filters from annotation and prepares data binding path
*/
sap.ovp.cards.charts.Utils.formatItems = function(iContext, oEntitySet, oSelectionVariant, oPresentationVariant, oDimensions, oMeasures) {
var ret = "";
var dimensionsList = [];
var measuresList = [];
var sorterList = [];
var bFilter = oSelectionVariant && oSelectionVariant.SelectOptions;
var bParams = oSelectionVariant && oSelectionVariant.Parameters;
var bSorter = oPresentationVariant && oPresentationVariant.SortOrder;
var maxItemTerm = oPresentationVariant && oPresentationVariant.MaxItems, maxItems = null;
var columnsWithText;
var tmp;
var aConfigFilters;
if (bParams) {
var dataModel = iContext.getSetting("dataModel");
var path = sap.ovp.cards.AnnotationHelper.resolveParameterizedEntitySet(dataModel, oEntitySet, oSelectionVariant);
ret += "{path: '" + path + "'";
} else {
ret += "{path: '/" + oEntitySet.name + "'";
}
var filters = [];
var entityTypeObject = null;
var edmTypes = null;
if (!iContext || !iContext.getSetting('ovpCardProperties')) {
jQuery.sap.log.error("Analytic card configuration error");
ret += "}";
return ret;
}
entityTypeObject = iContext.getSetting('ovpCardProperties').getProperty("/entityType");
edmTypes = sap.ovp.cards.charts.Utils.getEdmTypeOfAll(entityTypeObject);
columnsWithText = sap.ovp.cards.charts.Utils.getAllColumnTexts(entityTypeObject);
aConfigFilters = iContext.getSetting('ovpCardProperties').getProperty("/filters");
if (bFilter) {
jQuery.each(oSelectionVariant.SelectOptions, function() {
var prop = this.PropertyName.PropertyPath;
jQuery.each(this.Ranges, function() {
if (this.Sign.EnumMember === "com.sap.vocabularies.UI.v1.SelectionRangeSignType/I") {
var filtervalue = this.Low.String;
if (edmTypes &&
(edmTypes[prop].substring(0, 7) === "Edm.Int" ||
edmTypes[prop].substring(0, 11) === 'Edm.Decimal')) {
filtervalue = Number(filtervalue);
}
var filter = {
path : prop,
operator : this.Option.EnumMember.split("/")[1],
value1 : filtervalue
};
if (this.High) {
filter.value2 = this.High.String;
}
filters.push(filter);
}
});
});
}
/*
* code for ObjectStream
*/
if (aConfigFilters && aConfigFilters.length > 0){
filters = filters.concat(aConfigFilters);
}
if (filters.length > 0) {
ret += ", filters: " + JSON.stringify(filters);
}
if (bSorter) {
var oSortAnnotationCollection = oPresentationVariant.SortOrder;
if (oSortAnnotationCollection.length < 1) {
jQuery.sap.log.warning("OVP-AC: Analytic card: Warning: SortOrder is present in PresentationVariant, " +
"but it is empty or not well formed.");
} else {
var sSorterValue = "";
var oSortOrder;
var sSortOrder;
var sSortBy;
for (var i = 0; i < oSortAnnotationCollection.length; i++) {
oSortOrder = oSortAnnotationCollection[i];
sSortBy = oSortOrder.Property.PropertyPath;
sorterList.push(sSortBy);
if (typeof oSortOrder.Descending == "undefined") {
sSortOrder = 'true';
} else {
var checkFlag = oSortOrder.Descending.Bool || oSortOrder.Descending.Boolean;
if (!checkFlag) {
jQuery.sap.log.warning("OVP-AC: Analytic card: Warning: Boolean value is not present in PresentationVariant ");
sSortOrder = 'true';
} else {
sSortOrder = checkFlag.toLowerCase() == 'true' ? 'true' : 'false';
}
}
sSorterValue = sSorterValue + "{path: '" + sSortBy + "',descending: " + sSortOrder + "},";
}
/* trim the last ',' */
ret += ", sorter: [" + sSorterValue.substring(0, sSorterValue.length - 1) + "]";
}
}
if (maxItemTerm) {
maxItems = maxItemTerm.Int32 ? maxItemTerm.Int32 : maxItemTerm.Int;
}
jQuery.each(oMeasures, function(i, m){
tmp = m.Measure.PropertyPath;
measuresList.push(tmp);
if (columnsWithText && tmp != columnsWithText[tmp]) {
measuresList.push(columnsWithText[tmp] ? columnsWithText[tmp] : tmp);
}
});
jQuery.each(oDimensions, function(i, d){
tmp = d.Dimension.PropertyPath;
dimensionsList.push(tmp);
if (columnsWithText && tmp != columnsWithText[tmp]) {
dimensionsList.push(columnsWithText[tmp] ? columnsWithText[tmp] : tmp);
}
});
ret += ", parameters: {select:'" + [].concat(dimensionsList, measuresList).join(",");
if (sorterList.length > 0) {
ret += "," + sorterList.join(",");
}
/* close `parameters` */
ret += "'}";
if (maxItems) {
if (/^\d+$/.test(maxItems)) {
ret += ", length: " + maxItems;
} else {
jQuery.sap.log.error("OVP-AC: Analytic card Error: maxItems is Invalid. " +
"Please enter an Integer.");
}
}
ret += "}";
return ret;
};
sap.ovp.cards.charts.Utils.formatItems.requiresIContext = true;
/************************ METADATA PARSERS ************************/
/* Returns the set of all properties in the metadata */
sap.ovp.cards.charts.Utils.getAllColumnProperties = function(prop, entityTypeObject) {
var finalObject = {};
var properties = entityTypeObject.property;
for (var i = 0, len = properties.length; i < len; i++) {
if (properties[i].hasOwnProperty(prop) && prop == "com.sap.vocabularies.Common.v1.Label") {
finalObject[properties[i].name] = properties[i][prop].String;
} else if (properties[i].hasOwnProperty(prop)) {
finalObject[properties[i].name] = properties[i][prop];
} else {
finalObject[properties[i].name] = properties[i].name;
}
}
return finalObject;
};
/* Returns column name that contains the sap:label(s) for all properties in the metadata*/
sap.ovp.cards.charts.Utils.getAllColumnLabels = function(entityTypeObject) {
return sap.ovp.cards.charts.Utils.getAllColumnProperties("com.sap.vocabularies.Common.v1.Label", entityTypeObject);
};
/* Returns column name that contains the sap:text(s) for all properties in the metadata*/
sap.ovp.cards.charts.Utils.getAllColumnTexts = function(entityTypeObject) {
return sap.ovp.cards.charts.Utils.getAllColumnProperties("sap:text", entityTypeObject);
};
/* get EdmType of all properties from $metadata */
sap.ovp.cards.charts.Utils.getEdmTypeOfAll = function(entityTypeObject) {
return sap.ovp.cards.charts.Utils.getAllColumnProperties("type", entityTypeObject);
};
/************************ Format Chart Axis ************************/
sap.ovp.cards.charts.Utils.formatChartYaxis = function() {
jQuery.sap.require("sap.ui.core.format.NumberFormat");
var customFormatter = {
locale: function(){},
format: function(value, pattern) {
if (pattern == "yValueAxisFormatter") {
var numberFormat = sap.ui.core.format.NumberFormat.getFloatInstance(
{style: 'short',
minFractionDigits: 2,
maxFractionDigits: 2}
);
return numberFormat.format(Number(value));
}
}
};
jQuery.sap.require("sap.viz.ui5.api.env.Format");
sap.viz.ui5.api.env.Format.numericFormatter(customFormatter);
};
sap.ovp.cards.charts.Utils.hideDateTimeAxis = function(vizFrame, feedName) {
var entityTypeObject = vizFrame.getModel('ovpCardProperties').getProperty("/entityType");
var edmTypes = sap.ovp.cards.charts.Utils.getEdmTypeOfAll(entityTypeObject);
var feeds = vizFrame.getFeeds();
for (var i = 0; i < feeds.length; i++) {
if (feeds[i].getUid() == feedName) {
var feedValues = feeds[i].getValues();
if (!feedValues) {
return;
}
for (var j = 0; j < feedValues.length; j++) {
if (edmTypes[feedValues[j]] != "Edm.DateTime") {
return;
}
}
vizFrame.setVizProperties({categoryAxis:{
title:{
visible: false
}
}});
return;
}
}
};
/************************ Line Chart functions ************************/
sap.ovp.cards.charts.Utils.LineChart = sap.ovp.cards.charts.Utils.LineChart || {};
sap.ovp.cards.charts.Utils.LineChart.categoryAxisFeedList = {};
sap.ovp.cards.charts.Utils.LineChart.getVizProperties = function(iContext, dimensions, measures) {
var rawValueAxisTitles = sap.ovp.cards.charts.Utils.LineChart.getValueAxisFeed(iContext, measures).split(",");
var rawCategoryAxisTitles = sap.ovp.cards.charts.Utils.LineChart.getCategoryAxisFeed(iContext, dimensions).split(",");
var valueAxisTitles = [];
jQuery.each(rawValueAxisTitles, function(i, m){
valueAxisTitles.push(m);
});
var categoryAxisTitles = [];
jQuery.each(rawCategoryAxisTitles, function(i, d){
categoryAxisTitles.push(d);
});
/*
//Readable version for debugging
//eslint can't multiline strings
return "{\
valueAxis:{\
title:{\
visible:true,\
text: '" + valueAxisTitles.join(",") + "'\
},\
label:{\
formatString:'yValueAxisFormatter'\
}\
},\
categoryAxis:{\
title:{\
visible:true,\
text: '" + categoryAxisTitles.join(",") + "'\
},\
label:{\
formatString:'yValueAxisFormatter'\
}\
},\
legend: {\
isScrollable: false\
},\
title: {\
visible: false\
},\
interaction:{\
noninteractiveMode: true,\
selectability: {\
legendSelection: false,\
axisLabelSelection: false,\
mode: 'NONE',\
plotLassoSelection: false,\
plotStdSelection: false\
}\
}\
}";
*/
return "{ valueAxis:{ title:{ visible:true, text: '" + valueAxisTitles.join(",") + "' }, label:{ formatString:'yValueAxisFormatter' } }, categoryAxis:{ title:{ visible:true, text: '" + categoryAxisTitles.join(",") + "' }, label:{ formatString:'yValueAxisFormatter' } }, legend: { isScrollable: false }, title: { visible: false }, interaction:{ noninteractiveMode: true, selectability: { legendSelection: false, axisLabelSelection: false, mode: 'NONE', plotLassoSelection: false, plotStdSelection: false } } }";
};
sap.ovp.cards.charts.Utils.LineChart.getVizProperties.requiresIContext = true;
sap.ovp.cards.charts.Utils.LineChart.getValueAxisFeed = function(iContext, measures) {
var entityTypeObject = iContext.getSetting('ovpCardProperties').getProperty("/entityType");
if (!entityTypeObject) {
return "";
}
var columnLabels = sap.ovp.cards.charts.Utils.getAllColumnLabels(entityTypeObject);
var ret = [];
jQuery.each(measures, function(i, m){
ret.push(columnLabels[m.Measure.PropertyPath] || m.Measure.PropertyPath);
});
return ret.join(",");
};
sap.ovp.cards.charts.Utils.LineChart.getValueAxisFeed.requiresIContext = true;
sap.ovp.cards.charts.Utils.LineChart.getCategoryAxisFeed = function(iContext, dimensions) {
var entityTypeObject = iContext.getSetting('ovpCardProperties').getProperty("/entityType");
if (!entityTypeObject) {
return "";
}
var columnLabels = sap.ovp.cards.charts.Utils.getAllColumnLabels(entityTypeObject);
var ret = [];
var qualifier;
var feedValue;
jQuery.each(dimensions, function(i, d){
if (d.Role.EnumMember.split("/")[1] === "Category") {
feedValue = columnLabels[d.Dimension.PropertyPath];
ret.push(feedValue ? feedValue : d.Dimension.PropertyPath);
}
});
/*
* If no dimensions are given as category, pick first dimension as category
* (see Software Design Description UI5 Chart Control 3.1.2.2.1.1)
*/
if (ret.length < 1) {
feedValue = columnLabels[dimensions[0].Dimension.PropertyPath];
ret.push(feedValue ? feedValue : dimensions[0].Dimension.PropertyPath);
}
qualifier = sap.ovp.cards.charts.Utils.getQualifier(iContext,
sap.ovp.cards.charts.Utils.constants.CHART_QUALIFIER_KEY);
sap.ovp.cards.charts.Utils.LineChart.categoryAxisFeedList[qualifier] = ret;
return ret.join(",");
};
sap.ovp.cards.charts.Utils.LineChart.getCategoryAxisFeed.requiresIContext = true;
sap.ovp.cards.charts.Utils.LineChart.getColorFeed = function(iContext, dimensions) {
var ret = [];
var qualifier;
var entityTypeObject = iContext.getSetting('ovpCardProperties').getProperty("/entityType");
if (!entityTypeObject) {
return "";
}
var columnLabels = sap.ovp.cards.charts.Utils.getAllColumnLabels(entityTypeObject);
var feedValue;
jQuery.each(dimensions, function(i, d){
if (d.Role.EnumMember.split("/")[1] === "Series") {
feedValue = columnLabels[d.Dimension.PropertyPath];
ret.push(feedValue ? feedValue : d.Dimension.PropertyPath);
}
});
/*
* If the dimensions is picked up for category feed as no category is given in the annotation,
* remove it from color feed.
* (see Software Design Description UI5 Chart Control 3.1.2.2.1.1)
*/
qualifier = sap.ovp.cards.charts.Utils.getQualifier(iContext,
sap.ovp.cards.charts.Utils.constants.CHART_QUALIFIER_KEY);
ret = jQuery.grep(ret, function(value) {
if (!sap.ovp.cards.charts.Utils.LineChart.categoryAxisFeedList[qualifier]) {
return true;
}
return value != sap.ovp.cards.charts.Utils.LineChart.categoryAxisFeedList[qualifier][0];
});
return ret.join(",");
};
sap.ovp.cards.charts.Utils.LineChart.getColorFeed.requiresIContext = true;
sap.ovp.cards.charts.Utils.LineChart.testColorFeed = function(iContext, dimensions) {
return sap.ovp.cards.charts.Utils.LineChart.getColorFeed(iContext, dimensions) !== "";
};
sap.ovp.cards.charts.Utils.LineChart.testColorFeed.requiresIContext = true;
/************************ Bubble Chart Functions ************************/
sap.ovp.cards.charts.Utils.BubbleChart = sap.ovp.cards.charts.Utils.BubbleChart || {};
sap.ovp.cards.charts.Utils.BubbleChart.getVizProperties = function(iContext, dimensions, measures) {
var rawValueAxisTitles = sap.ovp.cards.charts.Utils.BubbleChart.getValueAxisFeed(iContext, measures).split(",");
var rawValueAxis2Titles = sap.ovp.cards.charts.Utils.BubbleChart.getValueAxis2Feed(iContext, measures).split(",");
var valueAxisTitles = [];
jQuery.each(rawValueAxisTitles, function(i, m){
valueAxisTitles.push(m);
});
var valueAxis2Titles = [];
jQuery.each(rawValueAxis2Titles, function(i, m){
valueAxis2Titles.push(m);
});
/*
//Readable version for debugging
//eslint can't multiline strings
return "{\
valueAxis:{\
title:{\
visible:true,\
text: '" + valueAxisTitles.join(",") + "'\
},\
label:{\
formatString:'yValueAxisFormatter'\
}\
},\
valueAxis2:{\
title:{\
visible:true,\
text: '" + valueAxis2Titles.join(",") + "'\
},\
label:{\
formatString:'yValueAxisFormatter'\
}\
},\
categoryAxis:{\
title:{\
visible:true\
},\
label:{\
formatString:'yValueAxisFormatter'\
}\
},\
legend: {\
isScrollable: false\
},\
title: {\
visible: false\
},\
interaction:{\
noninteractiveMode: true,\
selectability: {\
legendSelection: false,\
axisLabelSelection: false,\
mode: 'NONE',\
plotLassoSelection: false,\
plotStdSelection: false\
}\
}\
}";
*/
return "{ valueAxis:{ title:{ visible:true, text: '" + valueAxisTitles.join(",") + "' }, label:{ formatString:'yValueAxisFormatter' } }, valueAxis2:{ title:{ visible:true, text: '" + valueAxis2Titles.join(",") + "' }, label:{ formatString:'yValueAxisFormatter' } }, categoryAxis:{ title:{ visible:true }, label:{ formatString:'yValueAxisFormatter' } }, legend: { isScrollable: false }, title: { visible: false }, interaction:{ noninteractiveMode: true, selectability: { legendSelection: false, axisLabelSelection: false, mode: 'NONE', plotLassoSelection: false, plotStdSelection: false } } }";
};
sap.ovp.cards.charts.Utils.BubbleChart.getVizProperties.requiresIContext = true;
sap.ovp.cards.charts.Utils.BubbleChart.getMeasurePriorityList = function(iContext, measures) {
/* (see Software Design Description UI5 Chart Control - Bubble Chart) */
var ovpCardPropertiesModel;
if (!iContext ||
!iContext.getSetting ||
!(ovpCardPropertiesModel = iContext.getSetting('ovpCardProperties'))) {
return [""];
}
var entityTypeObject = ovpCardPropertiesModel.getProperty("/entityType");
if (!entityTypeObject) {
return [""];
}
var columnLabels = sap.ovp.cards.charts.Utils.getAllColumnLabels(entityTypeObject);
var ret = [null, null, null];
jQuery.each(measures, function(i, m){
if (m.Role.EnumMember.split("/")[1] === "Axis1") {
if (ret[0] === null) {
ret[0] = columnLabels[m.Measure.PropertyPath] || m.Measure.PropertyPath;
} else if (ret[1] === null) {
ret[1] = columnLabels[m.Measure.PropertyPath] || m.Measure.PropertyPath;
} else if (ret[2] == null) {
ret[2] = columnLabels[m.Measure.PropertyPath] || m.Measure.PropertyPath;
}
}
});
jQuery.each(measures, function(i, m){
if (m.Role.EnumMember.split("/")[1] === "Axis2") {
if (ret[0] === null) {
ret[0] = columnLabels[m.Measure.PropertyPath] || m.Measure.PropertyPath;
} else if (ret[1] === null) {
ret[1] = columnLabels[m.Measure.PropertyPath] || m.Measure.PropertyPath;
} else if (ret[2] == null) {
ret[2] = columnLabels[m.Measure.PropertyPath] || m.Measure.PropertyPath;
}
}
});
jQuery.each(measures, function(i, m){
if (m.Role.EnumMember.split("/")[1] === "Axis3") {
if (ret[0] === null) {
ret[0] = columnLabels[m.Measure.PropertyPath] || m.Measure.PropertyPath;
} else if (ret[1] === null) {
ret[1] = columnLabels[m.Measure.PropertyPath] || m.Measure.PropertyPath;
} else if (ret[2] == null) {
ret[2] = columnLabels[m.Measure.PropertyPath] || m.Measure.PropertyPath;
}
}
});
return ret;
};
sap.ovp.cards.charts.Utils.BubbleChart.getMeasurePriorityList.requiresIContext = true;
sap.ovp.cards.charts.Utils.BubbleChart.getValueAxisFeed = function(iContext, measures) {
return sap.ovp.cards.charts.Utils.BubbleChart.getMeasurePriorityList(iContext, measures)[0];
};
sap.ovp.cards.charts.Utils.BubbleChart.getValueAxisFeed.requiresIContext = true;
sap.ovp.cards.charts.Utils.BubbleChart.getValueAxis2Feed = function(iContext, measures) {
return sap.ovp.cards.charts.Utils.BubbleChart.getMeasurePriorityList(iContext, measures)[1];
};
sap.ovp.cards.charts.Utils.BubbleChart.getValueAxis2Feed.requiresIContext = true;
sap.ovp.cards.charts.Utils.BubbleChart.getBubbleWidthFeed = function(iContext, measures) {
return sap.ovp.cards.charts.Utils.BubbleChart.getMeasurePriorityList(iContext, measures)[2];
};
sap.ovp.cards.charts.Utils.BubbleChart.getBubbleWidthFeed.requiresIContext = true;
sap.ovp.cards.charts.Utils.BubbleChart.getColorFeed = function(iContext, dimensions) {
var entityTypeObject = iContext.getSetting('ovpCardProperties').getProperty("/entityType");
if (!entityTypeObject) {
return "";
}
var columnLabels = sap.ovp.cards.charts.Utils.getAllColumnLabels(entityTypeObject);
var ret = [];
var feedValue;
jQuery.each(dimensions, function(i, d){
if (d.Role.EnumMember.split("/")[1] === "Series") {
feedValue = columnLabels[d.Dimension.PropertyPath];
ret.push(feedValue ? feedValue : d.Dimension.PropertyPath);
}
});
return ret.join(",");
};
sap.ovp.cards.charts.Utils.BubbleChart.getColorFeed.requiresIContext = true;
sap.ovp.cards.charts.Utils.BubbleChart.getShapeFeed = function(iContext, dimensions) {
var entityTypeObject = iContext.getSetting('ovpCardProperties').getProperty("/entityType");
if (!entityTypeObject) {
return "";
}
var columnLabels = sap.ovp.cards.charts.Utils.getAllColumnLabels(entityTypeObject);
var ret = [];
var feedValue;
jQuery.each(dimensions, function(i, d){
if (d.Role.EnumMember.split("/")[1] === "Category") {
feedValue = columnLabels[d.Dimension.PropertyPath];
ret.push(feedValue ? feedValue : d.Dimension.PropertyPath);
}
});
return ret.join(",");
};
sap.ovp.cards.charts.Utils.BubbleChart.getShapeFeed.requiresIContext = true;
sap.ovp.cards.charts.Utils.BubbleChart.testColorFeed = function(iContext, dimensions) {
return sap.ovp.cards.charts.Utils.BubbleChart.getColorFeed(iContext, dimensions) !== "";
};
sap.ovp.cards.charts.Utils.BubbleChart.testColorFeed.requiresIContext = true;
sap.ovp.cards.charts.Utils.BubbleChart.testShapeFeed = function(iContext, dimensions) {
return sap.ovp.cards.charts.Utils.BubbleChart.getShapeFeed(iContext, dimensions) !== "";
};
sap.ovp.cards.charts.Utils.BubbleChart.testShapeFeed.requiresIContext = true;
sap.ovp.cards.charts.Utils.validateMeasuresDimensions = function(vizFrame, type) {
var measuresArr = null;
var dimensionsArr = null;
if (!vizFrame.getDataset()) {
jQuery.sap.log.error("OVP-AC: " + type + " Card Error: No Dataset defined for chart.");
return false;
}
measuresArr = vizFrame.getDataset().getMeasures();
dimensionsArr = vizFrame.getDataset().getDimensions();
switch (type) {
case "Bubble":
if (measuresArr.length !== 3 || dimensionsArr.length < 1 ||
!measuresArr[0].getName() || !measuresArr[1].getName() || !measuresArr[2].getName() ||
!dimensionsArr[0].getName()) {
jQuery.sap.log.error("OVP-AC: Bubble Card Error: Enter exactly 3 measures and at least 1 dimension.");
return false;
}
break;
case "Donut":
if (measuresArr.length !== 1 || dimensionsArr.length !== 1 ||
!measuresArr[0].getName() || !dimensionsArr[0].getName()) {
jQuery.sap.log.error("OVP-AC: Donut Card Error: Enter exactly 1 measure and 1 dimension.");
return false;
}
break;
case "Line":
if (measuresArr.length < 1 || dimensionsArr.length < 1 ||
!measuresArr[0].getName() || !dimensionsArr[0].getName()) {
jQuery.sap.log.error("OVP-AC: Line Card Error: Configure at least 1 dimensions and 1 measure.");
return false;
}
break;
}
return true;
};
/*
* Check if annotations exist vis-a-vis manifest
* @param {String} term - Annotation with Qualifier
* @param {Object} annotation - Annotation Data
* @param {String} type - Type of Annotation
* @param {Boolean} [bMandatory=false] - Whether the term is mandatory
* @returns {Boolean}
*/
sap.ovp.cards.charts.Utils.checkExists = function(term, annotation, type, bMandatory, logViewId) {
bMandatory = typeof bMandatory === "undefined" ? false : bMandatory;
var ret = false;
var annoTerm;
if (!term && bMandatory) {
jQuery.sap.log.error(logViewId + "OVP-AC: Analytic card: Error: " + type + " is mandatory.");
return ret;
}
if (!term) {
/* Optional parameters can be blank */
jQuery.sap.log.warning(logViewId + "OVP-AC: Analytic card: Warning: " + type + " is missing.");
ret = true;
return ret;
}
annoTerm = annotation[term];
if (!annoTerm || typeof annoTerm !== "object") {
var logger = bMandatory ? jQuery.sap.log.error : jQuery.sap.log.warning;
logger(logViewId + "OVP-AC: Analytic card: Error in " + type +
". (" + term + " is not found or not well formed)");
return ret;
}
ret = true;
return ret;
};
/*
* Check and log errors/warnings if any.
*/
sap.ovp.cards.charts.Utils.validateCardConfiguration = function(oController) {
var ret = false;
if (!oController) {
return ret;
}
var selVar;
var chartAnno;
var preVar;
var idAnno;
var dPAnno;
var entityTypeData;
var logViewId = "";
var oCardsModel;
var oView = oController.getView();
if (oView) {
logViewId = "[" + oView.getId() + "] ";
}
if (!(oCardsModel = oController.getCardPropertiesModel())) {
jQuery.sap.log.error(logViewId + "OVP-AC: Analytic card: Error in card configuration." +
"Could not obtain Cards model.");
return ret;
}
entityTypeData = oCardsModel.getProperty("/entityType");
if (!entityTypeData || jQuery.isEmptyObject(entityTypeData)) {
jQuery.sap.log.error(logViewId + "OVP-AC: Analytic card: Error in card annotation.");
return ret;
}
selVar = oCardsModel.getProperty("/selectionAnnotationPath");
chartAnno = oCardsModel.getProperty("/chartAnnotationPath");
preVar = oCardsModel.getProperty("/presentationAnnotationPath");
idAnno = oCardsModel.getProperty("/identificationAnnotationPath");
dPAnno = oCardsModel.getProperty("/dataPointAnnotationPath");
ret = this.checkExists(selVar, entityTypeData, "Selection Variant", false, logViewId);
ret = this.checkExists(chartAnno, entityTypeData, "Chart Annotation", true, logViewId) && ret;
ret = this.checkExists(preVar, entityTypeData, "Presentation Variant", false, logViewId) && ret;
ret = this.checkExists(idAnno, entityTypeData, "Identification Annotation", true, logViewId) && ret;
ret = this.checkExists(dPAnno, entityTypeData, "Data Point", false, logViewId) && ret;
return ret;
};
sap.ovp.cards.charts.Utils.checkNoData = function(oEvent, cardContainer, vizFrame) {
var data, noDataDiv;
if (!cardContainer) {
jQuery.sap.log.error("OVP-AC: Analytic card Error: Could not obtain card container. " +
"(" + vizFrame.getId() + ")");
return;
}
data = oEvent.getParameter("data");
if (!data || jQuery.isEmptyObject(data) ||
!data.results || !data.results.length) {
jQuery.sap.log.error("OVP-AC: Analytic card Error: No data available. " +
"(" + vizFrame.getId() + ")");
noDataDiv = sap.ui.xmlfragment("sap.ovp.cards.charts.generic.noData");
cardContainer.removeAllItems();
cardContainer.addItem(noDataDiv);
}
};
}());
}; // end of sap/ovp/cards/charts/Utils.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.generic.Card.controller') ) {
jQuery.sap.declare('sap.ovp.cards.generic.Card.controller');
(function () {
"use strict";
/*global sap, jQuery */
jQuery.sap.require('sap.ui.generic.app.navigation.service.NavigationHandler'); // unlisted dependency retained
var ActionUtils = sap.ovp.cards.ActionUtils;
sap.ui.controller("sap.ovp.cards.generic.Card", {
onInit: function () {
var oHeader = this.getView().byId("ovpCardHeader");
oHeader.attachBrowserEvent("click", this.onHeaderClick.bind(this));
oHeader.addEventDelegate({
onkeydown: function (oEvent) {
if (!oEvent.shiftKey && (oEvent.keyCode == 13 || oEvent.keyCode == 32)) {
oEvent.preventDefault();
this.onHeaderClick();
}
}.bind(this)
});
var oNumericControl = this.getView().byId("kpiNumberValue");
if (oNumericControl) {
oNumericControl.addEventDelegate({
onAfterRendering: function() {
var $numericControl = oNumericControl.$();
var $number = $numericControl.find(".sapMNCValueScr");
var $scale = $numericControl.find(".sapMNCScale");
$number.attr("aria-label", $number.text());
$scale.attr("aria-label", $scale.text());
}
});
}
},
onAfterRendering: function(){
var footer = this.getCardPropertiesModel().getProperty("/footerFragment");
if (footer){
this._handleActionFooter();
this._handleCountFooter();
}
},
onHeaderClick: function(){
//call the navigation with the binded context to support single object cards such as quickview card
this.doNavigation(this.getView().getBindingContext());
},
_handleActionFooter: function(footer){
var actionFooter = this.getView().byId("ovpActionFooter");
if (actionFooter) {
var aActions = actionFooter.getContent();
//remove the 'ToolbarSpacer'
aActions = aActions.splice(1, aActions.length);
var oLayoutData = aActions[0].getLayoutData();
oLayoutData.setMoveToOverflow(false);
oLayoutData.setStayInOverflow(false);
if (aActions.length === 2) {
oLayoutData = aActions[1].getLayoutData();
oLayoutData.setMoveToOverflow(false);
oLayoutData.setStayInOverflow(false);
}
}
},
_handleCountFooter: function(){
var countFooter = this.getView().byId("ovpCountFooter");
if (countFooter) {
//Gets the card items binding object
var oItemsBinding = this.getCardItemsBinding();
if (oItemsBinding) {
oItemsBinding.attachDataReceived(function () {
var iTotal = oItemsBinding.getLength();
var iCurrent = oItemsBinding.getCurrentContexts().length;
var countFooterText = sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("Count_Footer", [iCurrent, iTotal]);
countFooter.setText(countFooterText);
});
}
}
},
/**
* default empty implementation for the count footer
*/
getCardItemsBinding: function(){
},
onActionPress: function(oEvent) {
var sourceObject = oEvent.getSource(),
oCustomData = this._getActionObject(sourceObject),
context = sourceObject.getBindingContext();
if (oCustomData.type.indexOf("DataFieldForAction") !== -1) {
this.doAction(context, oCustomData);
} else {
this.doNavigation(context, oCustomData);
}
},
_getActionObject: function(sourceObject) {
var aCustomData = sourceObject.getCustomData();
var oCustomData = {};
for (var i = 0; i < aCustomData.length; i++) {
oCustomData[aCustomData[i].getKey()] = aCustomData[i].getValue();
}
return oCustomData;
},
doNavigation: function (oContext, oNavigationField) {
if (!oNavigationField) {
oNavigationField = this.getEntityNavigationEntries(oContext)[0];
}
if ( oNavigationField ){
switch ( oNavigationField.type ){
case "com.sap.vocabularies.UI.v1.DataFieldWithUrl":
this.doNavigationWithUrl(oContext,oNavigationField);
break;
case "com.sap.vocabularies.UI.v1.DataFieldForIntentBasedNavigation":
this.doIntentBasedNavigation(oContext, oNavigationField);
break;
}
}
},
doNavigationWithUrl: function (oContext, oNavigationField) {
var oParsingSerivce = sap.ushell.Container.getService("URLParsing");
//Checking if navigation is external or IntentBasedNav with paramters
//If Not a internal navigation, navigate in a new window
if (!(oParsingSerivce.isIntentUrl(oNavigationField.url))){
window.open(oNavigationField.url);
} else {
var oParsedShellHash = oParsingSerivce.parseShellHash(oNavigationField.url);
this.doIntentBasedNavigation(oContext, oParsedShellHash);
}
},
doIntentBasedNavigation: function (oContext, oIntent) {
var oParametersPromise,
oNavArguments,
oEntity = oContext ? oContext.getObject() : null;
var oNavigationHandler = sap.ovp.cards.CommonUtils.getNavigationHandler();
if (oNavigationHandler) {
if (oIntent) {
oParametersPromise = this._getEntityNavigationParameters(oEntity);
oParametersPromise.done(function (oParameters, oAppDataForSave) {
oNavArguments = {
target: {
semanticObject: oIntent.semanticObject,
action: oIntent.action
},
appSpecificRoute: oIntent.appSpecificRoute,
params: oParameters
};
var oAppInnerData = {};
if (oAppDataForSave) {
oAppInnerData = oAppDataForSave;
}
function fnHandleError(oError) {
if (oError instanceof Error) {
oError.showMessageBox();
}
}
oNavigationHandler.navigate(oNavArguments.target.semanticObject, oNavArguments.target.action, oNavArguments.params,
oAppInnerData, fnHandleError);
});
}
}
},
doAction: function (oContext, action) {
this.actionData = ActionUtils.getActionInfo(oContext, action, this.getEntityType());
if (this.actionData.allParameters.length > 0) {
this._loadParametersForm();
} else {
this._callFunction();
}
},
getEntityNavigationEntries: function (oContext, sAnnotationPath) {
var aNavigationFields = [];
var oEntityType = this.getEntityType();
if (!sAnnotationPath){
var oCardPropsModel = this.getCardPropertiesModel();
var sIdentificationAnnotationPath = oCardPropsModel.getProperty("/identificationAnnotationPath");
sAnnotationPath = sIdentificationAnnotationPath;
}
// if we have an array object e.g. we have records
var aRecords = oEntityType[sAnnotationPath];
if (Array.isArray(aRecords)) {
// sort the records by Importance - before we initialize the navigation-actions of the card
aRecords = sap.ovp.cards.AnnotationHelper.sortCollectionByImportance(aRecords);
for (var i = 0; i < aRecords.length; i++) {
if (aRecords[i].RecordType === "com.sap.vocabularies.UI.v1.DataFieldForIntentBasedNavigation") {
aNavigationFields.push({
type: aRecords[i].RecordType,
semanticObject: aRecords[i].SemanticObject.String,
action: aRecords[i].Action.String,
label: aRecords[i].Label.String
});
}
if (aRecords[i].RecordType === "com.sap.vocabularies.UI.v1.DataFieldWithUrl" && !aRecords[i].Url.UrlRef) {
var oModel = this.getView().getModel();
var oMetaData = oModel.oMetaModel;
var oEntityBindingContext = oMetaData.createBindingContext(oEntityType.$path);
var sBindingString = sap.ui.model.odata.AnnotationHelper.format(oEntityBindingContext, aRecords[i].Url);
var oCustomData = new sap.ui.core.CustomData({key: "url", value: sBindingString});
oCustomData.setModel(oModel);
oCustomData.setBindingContext(oContext);
var oUrl = oCustomData.getValue();
aNavigationFields.push({
type: aRecords[i].RecordType,
url: oUrl,
value: aRecords[i].Value.String,
label: aRecords[i].Label.String
});
}
}
}
return aNavigationFields;
},
getModel: function () {
return this.getView().getModel();
},
getMetaModel: function () {
return this.getModel().getMetaModel();
},
getCardPropertiesModel: function () {
return this.getView().getModel("ovpCardProperties");
},
getEntitySet: function () {
if (!this.entitySet) {
var sEntitySet = this.getCardPropertiesModel().getProperty("/entitySet");
this.entitySet = this.getMetaModel().getODataEntitySet(sEntitySet);
}
return this.entitySet;
},
getEntityType: function () {
if (!this.entityType) {
this.entityType = this.getMetaModel().getODataEntityType(this.getEntitySet().entityType);
}
return this.entityType;
},
getCardContentContainer: function(){
if (!this.cardContentContainer){
this.cardContentContainer = this.getView().byId("ovpCardContentContainer");
}
return this.cardContentContainer;
},
_saveAppState : function(sFilterDataSuiteFormat) {
var oDeferred = jQuery.Deferred();
var oAppState = sap.ushell.Container.getService("CrossApplicationNavigation").createEmptyAppState(this.getOwnerComponent());
var sAppStateKey = oAppState.getKey();
var oAppDataForSave = {
selectionVariant: sFilterDataSuiteFormat
};
oAppState.setData(oAppDataForSave);
var oSavePromise = oAppState.save();
oSavePromise.done(function () {
oDeferred.resolve(sAppStateKey, oAppDataForSave);
});
return oDeferred.promise();
},
/**
* Retrieve entity parameters (if exists) and add xAppState from oComponentData.appStateKeyFunc function (if exists)
* @param oEntity
* @returns {*}
* @private
*/
_getEntityNavigationParameters: function (oEntity) {
var oDeferred = jQuery.Deferred();
var oUrlParameters = {};
var oEntityType;
var oComponentData = this.getOwnerComponent().getComponentData();
var oGlobalFilter = oComponentData ? oComponentData.globalFilter : undefined;
var oSaveAppStatePromise;
var oCardFilters = sap.ovp.cards.AnnotationHelper.getCardFilters(this.getCardPropertiesModel());
var oSelectionVariant;
// Build result object of card parameters
if (oEntity) {
oEntityType = this.getEntityType();
var key;
for (var i = 0; oEntityType.property && i < oEntityType.property.length; i++) {
key = oEntityType.property[i].name;
if (oEntity.hasOwnProperty(key)) {
if (window.Array.isArray(oEntity[key]) && oEntity[key].length === 1) {
oUrlParameters[key] = oEntity[key][0].toString();
} else if (oEntity[key]) {
oUrlParameters[key] = oEntity[key].toString();
}
}
}
}
//Build selection variant object from global filter, card filter and card parameters
oSelectionVariant = this._buildSelectionVariant(oGlobalFilter, oCardFilters, oUrlParameters);
//Get all filters with EQ option and add it to parameters result
// in order for it will to be shown on the URL
var aSelectOptionsNames = oSelectionVariant.getSelectOptionsPropertyNames();
for (var i = 0; i < aSelectOptionsNames.length; i++) {
var sSelectOptions = aSelectOptionsNames[i];
var oValue = oSelectionVariant.getSelectOption(sSelectOptions);
if ((oValue)[0] && (oValue)[0].Option === "EQ"){
var value = (oValue)[0].Low;
if (value) {
oUrlParameters[sSelectOptions] = value;
}
}
}
//Save parameters and filters on app-state in case selection variant not empty
if (!oSelectionVariant.isEmpty()) {
oSaveAppStatePromise = this._saveAppState(oSelectionVariant.toJSONString());
oSaveAppStatePromise.done(function(sAppStateKey, oAppDataForSave) {
oUrlParameters["sap-xapp-state"] = sAppStateKey;
oDeferred.resolve(oUrlParameters, oAppDataForSave);
});
oSaveAppStatePromise.fail(function () {
jQuery.sap.log.error("appStateKey is not saved for OVP Application");
oDeferred.resolve(oUrlParameters);
});
} else {
oDeferred.resolve(oUrlParameters);
}
return oDeferred.promise();
},
_buildSelectionVariant: function(oGlobalFilter, oCardFilters, oUrlParameters) {
var sGlobalFilter = oGlobalFilter ? oGlobalFilter.getFilterDataAsString() : "{}";
var oSelectionVariant = new sap.ui.generic.app.navigation.service.SelectionVariant(sGlobalFilter);
// Add card filters to selection variant
for (var i = 0; i < oCardFilters.length; i++) {
var entry = oCardFilters[i];
//value1 might be typeof number, hence we check not typeof undefined
if (entry.path && entry.operator && typeof entry.value1 !== "undefined") {
//value2 is optional, hence we check it separately
var sValue2 = (typeof entry.value2 === "number") ? entry.value2.toString() : undefined;
oSelectionVariant.addSelectOption(entry.path, "I", entry.operator, entry.value1.toString(), sValue2);
}
}
// Add card parameters to selection variant
// in case key exist from filters do not add it!
if (oUrlParameters) {
var value;
for (var key in oUrlParameters) {
value = oUrlParameters[key];
//Check that current parameter is not already exist on filters
if (!oSelectionVariant.getSelectOption(key)) {
oSelectionVariant.addParameter(key, value);
}
}
}
return oSelectionVariant;
},
_loadParametersForm: function() {
var oParameterModel = new sap.ui.model.json.JSONModel();
oParameterModel.setData(this.actionData.parameterData);
var that = this;
// first create dialog
var oParameterDialog = new sap.m.Dialog('ovpCardActionDialog', {
title: this.actionData.sFunctionLabel,
afterClose: function() {
oParameterDialog.destroy();
}
}).addStyleClass("sapUiNoContentPadding");
// action button (e.g. BeginButton)
var actionButton = new sap.m.Button({
text: this.actionData.sFunctionLabel,
press: function(oEvent) {
var mParameters = ActionUtils.getParameters(oEvent.getSource().getModel(), that.actionData.oFunctionImport);
oParameterDialog.close();
that._callFunction(mParameters);
}
});
// cancel button (e.g. EndButton)
var cancelButton = new sap.m.Button({
text: "Cancel",
press: function() {
oParameterDialog.close();
}
});
// assign the buttons to the dialog
oParameterDialog.setBeginButton(actionButton);
oParameterDialog.setEndButton(cancelButton);
// preparing a callback function which will be invoked on the Form's Fields-change
var onFieldChangeCB = function(oEvent) {
var missingMandatory = ActionUtils.mandatoryParamsMissing(oEvent.getSource().getModel(),that.actionData.oFunctionImport);
actionButton.setEnabled(!missingMandatory);
};
// get the form assign it the Dialog and open it
var oForm = ActionUtils.buildParametersForm(this.actionData,onFieldChangeCB);
oParameterDialog.addContent(oForm);
oParameterDialog.setModel(oParameterModel);
oParameterDialog.open();
},
_callFunction: function(mUrlParameters) {
var mParameters = {
batchGroupId: "Changes",
changeSetId: "Changes",
urlParameters: mUrlParameters,
forceSubmit: true,
context: this.actionData.oContext,
functionImport: this.actionData.oFunctionImport
};
var that = this;
var oPromise = new Promise(function(resolve, reject) {
var model = that.actionData.oContext.getModel();
var sFunctionImport;
sFunctionImport = "/" + mParameters.functionImport.name;
model.callFunction(sFunctionImport, {
method: mParameters.functionImport.httpMethod,
urlParameters: mParameters.urlParameters,
batchGroupId: mParameters.batchGroupId,
changeSetId: mParameters.changeSetId,
headers: mParameters.headers,
success: function(oData, oResponse) {
resolve(oResponse);
},
error : function(oResponse) {
reject(oResponse);
}
});
});
//Todo: call translation on message toast
oPromise.then(function(oResponse) {
return sap.m.MessageToast.show(sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("Toast_Action_Success"), { duration: 1000});
}, function(oError) {
return sap.m.MessageToast.show(sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("Toast_Action_Error"), { duration: 1000});
});
},
/**
* In case of error card implementation can call this method to display
* card error state.
* Current instance of the card will be destroied and instead loading card
* will be presenetd with the 'Cannot load card' meassage
*/
setErrorState: function(){
//get the current card component
var oCurrentCard = this.getOwnerComponent();
//get the component container
var oComponentContainer = oCurrentCard.oContainer;
//prepare card configuration, i.e. category, title, description and entitySet
//which are required for the loading card. in addition set the card state to error
//so no loading indicator will be presented
var oCardPropertiesModel = this.getCardPropertiesModel();
var oComponentConfig = {
name: "sap.ovp.cards.loading",
componentData: {
model: this.getView().getModel(),
settings: {
category: oCardPropertiesModel.getProperty("/category"),
title: oCardPropertiesModel.getProperty("/title"),
description: oCardPropertiesModel.getProperty("/description"),
entitySet: oCardPropertiesModel.getProperty("/entitySet"),
state: sap.ovp.cards.loading.State.ERROR
}
}
};
//create the loading card
var oLoadingCard = sap.ui.component(oComponentConfig);
//set the loading card in the container
oComponentContainer.setComponent(oLoadingCard);
//destroy the current card
setTimeout(function(){
oCurrentCard.destroy();
}, 0);
}
});
})();
}; // end of sap/ovp/cards/generic/Card.controller.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.generic.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.generic.Component");
jQuery.sap.require('sap.ui.core.UIComponent'); // unlisted dependency retained
sap.ui.core.UIComponent.extend("sap.ovp.cards.generic.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"contentFragment": {
"type": "string"
},
"headerExtensionFragment": {
"type": "string"
},
"contentPosition": {
"type": "string",
"defaultValue": "Middle"
},
"footerFragment": {
"type": "string"
},
"identificationAnnotationPath":{
"type": "string",
"defaultValue": "com.sap.vocabularies.UI.v1.Identification"
},
"selectionAnnotationPath":{
"type": "string"
},
"filters": {
"type": "object"
},
"addODataSelect": {
"type": "boolean",
"defaultValue": false
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m" ],
components: []
},
config: {}
},
/**
* Default "abstract" empty function.
* In case there is a need to enrich the default preprocessor which provided by OVP, the extended Component should provide this function and return a preprocessor object.
* @public
* @returns {Object} SAPUI5 preprocessor object
*/
getCustomPreprocessor: function () {},
getPreprocessors : function(ovplibResourceBundle) {
var oComponentData = this.getComponentData(),
oSettings = oComponentData.settings,
oModel = oComponentData.model,
oMetaModel,
oEntityTypeContext,
oEntitySetContext;
//Backwards compatibility to support "description" property
if (oSettings.description && !oSettings.subTitle) {
oSettings.subTitle = oSettings.description;
}
if (oModel){
var oMetaModel = oModel.getMetaModel();
var oEntitySet = oMetaModel.getODataEntitySet(oSettings.entitySet);
var sEntitySetPath = oMetaModel.getODataEntitySet(oSettings.entitySet, true);
var oEntityType = oMetaModel.getODataEntityType(oEntitySet.entityType);
oEntitySetContext = oMetaModel.createBindingContext(sEntitySetPath);
oEntityTypeContext = oMetaModel.createBindingContext(oEntityType.$path);
}
var oCardProperties = this._getCardPropertyDefaults();
oCardProperties = jQuery.extend(true, {metaModel: oMetaModel, entityType: oEntityType}, oCardProperties, oSettings);
var oOvpCardPropertiesModel = new sap.ui.model.json.JSONModel(oCardProperties);
var ovplibResourceBundle = this.getOvplibResourceBundle();
var oDefaultPreprocessors = {
xml: {
bindingContexts: {entityType: oEntityTypeContext, entitySet: oEntitySetContext},
models: {entityType: oMetaModel, entitySet:oMetaModel, ovpMeta: oMetaModel, ovpCardProperties: oOvpCardPropertiesModel, ovplibResourceBundle: ovplibResourceBundle},
ovpCardProperties: oOvpCardPropertiesModel,
dataModel: oModel,
_ovpCache: {}
}
};
return jQuery.extend(true, {}, this.getCustomPreprocessor(), oDefaultPreprocessors);
},
_getCardPropertyDefaults: function(){
var oCardProperties = {};
var oPropsDef = this.getMetadata().getAllProperties();
var oPropDef;
for (var propName in oPropsDef){
oPropDef = oPropsDef[propName];
if (oPropDef.defaultValue !== undefined){
oCardProperties[oPropDef.name] = oPropDef.defaultValue;
}
}
return oCardProperties;
},
getOvplibResourceBundle: function(){
if (!this.ovplibResourceBundle){
var oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ovp");
this.ovplibResourceBundle = oResourceBundle ? new sap.ui.model.resource.ResourceModel({bundleUrl: oResourceBundle.oUrlInfo.url}) : null;
}
return this.ovplibResourceBundle;
},
createContent: function () {
var oComponentData = this.getComponentData && this.getComponentData();
var oModel = oComponentData.model;
var oPreprocessors = this.getPreprocessors();
var oView;
oView = sap.ui.view({
preprocessors: oPreprocessors,
type: sap.ui.core.mvc.ViewType.XML,
viewName: "sap.ovp.cards.generic.Card"
});
oView.setModel(oModel);
// check if i18n model is available and then add it to card view
if (oComponentData.i18n) {
oView.setModel(oComponentData.i18n, "@i18n");
}
oView.setModel(oPreprocessors.xml.ovpCardProperties, "ovpCardProperties");
oView.setModel(this.getOvplibResourceBundle(), "ovplibResourceBundle");
return oView;
}
});
})();
}; // end of sap/ovp/cards/generic/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.image.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.image.Component");
sap.ovp.cards.generic.Component.extend("sap.ovp.cards.image.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"contentFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.image.Image"
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m" ],
components: []
},
config: {},
customizing: {
"sap.ui.controllerExtensions": {
"sap.ovp.cards.generic.Card": {
controllerName: "sap.ovp.cards.image.Image"
}
}
}
}
});
})();
}; // end of sap/ovp/cards/image/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.list.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.list.Component");
sap.ovp.cards.generic.Component.extend("sap.ovp.cards.list.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"contentFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.list.List"
},
"annotationPath": {
"type": "string",
"defaultValue": "com.sap.vocabularies.UI.v1.LineItem"
},
"footerFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.generic.CountFooter"
},
"headerExtensionFragment":{
"type": "string",
"defaultValue": "sap.ovp.cards.generic.KPIHeader"
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m" ],
components: []
},
config: {},
customizing: {
"sap.ui.controllerExtensions": {
"sap.ovp.cards.generic.Card": {
controllerName: "sap.ovp.cards.list.List"
}
}
}
}
});
})();
}; // end of sap/ovp/cards/list/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.loading.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.loading.Component");
sap.ovp.cards.loading.State = {
ERROR: "Error",
LOADING: "Loading"
};
sap.ovp.cards.generic.Component.extend("sap.ovp.cards.loading.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"footerFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.loading.LoadingFooter"
},
"state": {
"type": "string",
"defaultValue": sap.ovp.cards.loading.State.LOADING
}
},
version: "1.36.12",
library: "sap.ovp",
customizing: {
"sap.ui.controllerExtensions": {
"sap.ovp.cards.generic.Card": {
controllerName: "sap.ovp.cards.loading.Loading"
}
}
}
}
});
})();
}; // end of sap/ovp/cards/loading/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.quickview.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.quickview.Component");
sap.ovp.cards.generic.Component.extend("sap.ovp.cards.quickview.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"contentFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.quickview.Quickview"
},
"annotationPath": {
"type": "string",
"defaultValue": "com.sap.vocabularies.UI.v1.Facets"
},
"footerFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.generic.ActionsFooter"
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m" ],
components: []
},
config: {},
customizing: {
"sap.ui.controllerExtensions": {
"sap.ovp.cards.generic.Card": {
controllerName: "sap.ovp.cards.quickview.Quickview"
}
}
}
}
});
})();
}; // end of sap/ovp/cards/quickview/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.quickview.Quickview.controller') ) {
jQuery.sap.declare('sap.ovp.cards.quickview.Quickview.controller');
(function () {
"use strict";
/*global sap, jQuery */
sap.ui.controller("sap.ovp.cards.quickview.Quickview", {
onInit: function () {
},
onAfterRendering: function(){
}
});
})();
}; // end of sap/ovp/cards/quickview/Quickview.controller.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.stack.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.stack.Component");
sap.ovp.cards.generic.Component.extend("sap.ovp.cards.stack.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"contentFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.stack.Stack"
},
"contentPosition": {
"type": "string",
"defaultValue": "Right"
},
"objectStreamCardsSettings" : {
"type": "object",
"defaultValue": {
}
},
"objectStreamCardsTemplate" : {
"type": "string",
"defaultValue": "sap.ovp.cards.quickview"
},
"objectStreamCardsNavigationProperty" : {
"type": "string"
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m" ],
components: []
},
config: {},
customizing: {
"sap.ui.controllerExtensions": {
"sap.ovp.cards.generic.Card": {
controllerName: "sap.ovp.cards.stack.Stack"
}
}
}
}
});
})();
}; // end of sap/ovp/cards/stack/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.table.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.table.Component");
sap.ovp.cards.generic.Component.extend("sap.ovp.cards.table.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"contentFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.table.Table"
},
"annotationPath": {
"type": "string",
"defaultValue": "com.sap.vocabularies.UI.v1.LineItem"
},
"footerFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.generic.CountFooter"
},
"headerExtensionFragment":{
"type": "string",
"defaultValue": "sap.ovp.cards.generic.KPIHeader"
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m" ],
components: []
},
config: {},
customizing: {
"sap.ui.controllerExtensions": {
"sap.ovp.cards.generic.Card": {
controllerName: "sap.ovp.cards.table.Table"
}
}
}
}
});
})();
}; // end of sap/ovp/cards/table/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.library') ) {
/*!
* Copyright (c) 2009-2014 SAP SE, All Rights Reserved
*/
/* -----------------------------------------------------------------------------------
* Hint: This is a derived (generated) file. Changes should be done in the underlying
* source files only (*.type, *.js) or they will be lost after the next generation.
* ----------------------------------------------------------------------------------- */
/**
* Initialization Code and shared classes of library sap.ovp (1.36.12)
*/
jQuery.sap.declare("sap.ovp.library");
jQuery.sap.require('sap.ui.core.Core'); // unlisted dependency retained
/**
* SAP library: sap.ovp
*
* @namespace
* @name sap.ovp
* @public
*/
// library dependencies
jQuery.sap.require('sap.ui.core.library'); // unlisted dependency retained
jQuery.sap.require('sap.ui.layout.library'); // unlisted dependency retained
jQuery.sap.require('sap.ui.generic.app.library'); // unlisted dependency retained
jQuery.sap.require('sap.m.library'); // unlisted dependency retained
jQuery.sap.require('sap.ui.comp.library'); // unlisted dependency retained
// delegate further initialization of this library to the Core
sap.ui.getCore().initLibrary({
name : "sap.ovp",
dependencies : ["sap.ui.core","sap.ui.layout","sap.ui.generic.app","sap.m","sap.ui.comp"],
types: [],
interfaces: [],
controls: [],
elements: [],
version: "1.36.12"
});
}; // end of sap/ovp/library.js
if ( !jQuery.sap.isDeclared('sap.ovp.ui.CardContentContainer') ) {
/*!
* ${copyright}
*/
/*global sap window*/
jQuery.sap.declare('sap.ovp.ui.CardContentContainer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ovp/ui/CardContentContainer",["jquery.sap.global", "sap/ovp/library"],
function(jQuery) {
"use strict";
var CardContentContainer = sap.m.FlexBox.extend("sap.ovp.ui.CardContentContainer", {
metadata: {
library: "sap.ovp"
},
renderer: {
render: function (oRm, oControl) {
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapOvpCardContentContainer");
oRm.writeClasses();
oRm.write(">");
var items = oControl.getItems();
for (var i = 0; i < items.length; i++) {
oRm.renderControl(items[i]);
}
oRm.write("</div>");
}
}
});
return CardContentContainer;
}, /* bExport= */ true);
}; // end of sap/ovp/ui/CardContentContainer.js
if ( !jQuery.sap.isDeclared('sap.ovp.ui.CustomData') ) {
/*!
* ${copyright}
*/
jQuery.sap.declare('sap.ovp.ui.CustomData'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.CustomData'); // unlisted dependency retained
jQuery.sap.require('sap.ushell.library'); // unlisted dependency retained
sap.ui.define("sap/ovp/ui/CustomData",['jquery.sap.global', 'sap/ui/core/CustomData', 'sap/ushell/library'],
function (jQuery, CustomData, library) {
"use strict";
var CustomData = CustomData.extend("sap.ovp.ui.CustomData");
// fnOrigcheckWriteToDom = CustomData.prototype._checkWriteToDom;
CustomData.prototype._checkWriteToDom = function (oRelated) {
var sKey = this.getKey().toLowerCase(),
bIsAccessibilityOn = sap.ui.getCore().getConfiguration().getAccessibility();
if (!bIsAccessibilityOn) {
return;
}
if (!this.getWriteToDom()) {
return null;
}
var value = this.getValue();
if (typeof value != "string") {
jQuery.sap.log.error("CustomData with key " + sKey + " should be written to HTML of " + oRelated + " but the value is not a string.");
return null;
}
if (!(sap.ui.core.ID.isValid(sKey)) || (sKey.indexOf(":") != -1)) {
jQuery.sap.log.error("CustomData with key " + sKey + " should be written to HTML of " + oRelated + " but the key is not valid (must be a valid sap.ui.core.ID without any colon).");
return null;
}
if (sKey == jQuery.sap._FASTNAVIGATIONKEY) {
value = /^\s*(x|true)\s*$/i.test(value) ? "true" : "false"; // normalize values
} else if (sKey.indexOf("sap-ui") == 0) {
jQuery.sap.log.error("CustomData with key " + sKey + " should be written to HTML of " + oRelated + " but the key is not valid (may not start with 'sap-ui').");
return null;
}
return {key: sKey, value: value};
};
return CustomData;
}, /* bExport= */ true);
}; // end of sap/ovp/ui/CustomData.js
if ( !jQuery.sap.isDeclared('sap.ovp.ui.EasyScanLayout') ) {
/*!
* ${copyright}
*/
/*global sap window*/
jQuery.sap.declare('sap.ovp.ui.EasyScanLayout'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ovp/ui/EasyScanLayout",["jquery.sap.global", "sap/ovp/library"],
function (jQuery) {
"use strict";
jQuery.sap.require('sap.ovp.ui.UIActions');
var ReplaceItems = function (settings) {
this.init(settings);
};
ReplaceItems.prototype.init = function (settings) {
settings.beforeDragCallback = this._beforeDragHandler.bind(this);
settings.dragStartCallback = this._dragStartHandler.bind(this);
settings.dragMoveCallback = this._dragMoveHandler.bind(this);
settings.dragEndCallback = this._dragEndHandler.bind(this);
settings.endCallback = this._endHandler.bind(this);
this.layout = settings.layout;
this.afterReplaceElements = settings.afterReplaceElements || function () {};
this.settings = settings;
delete settings.afterReplaceElements;
this.destroy(); //destroy the previous instance of UIActions
this.uiActions = new sap.ovp.ui.UIActions(this.settings).enable();
this.aCardsOrder = null; //DOM elements array
this.verticalMargin = null; //space vertical between items
this.horizontalMargin = null; //horizontal space vertical between items
this.columnCount = null; //number of layout columns
this.top = null; //space between layout top and first card
this.left = null; //space between layout left and first card
this.width = null; //item width
this.layoutOffset = null; //layout coordinates on screen, needed to normalize mouse position to layout
this.jqLayout = null; //layout jQuery reference
this.jqLayoutInner = null; //layout inner wrapper jQuery reference
this.isRTLEnabled = null; //RTL flag
this.lastCollidedEl = null; //last collided element
this.lastCollisionTop = null; //last element collision top or bottom true/false
};
//search collision with elements,
//moveX - normalized X cord.
//moveY - normalized Y cord.
//itemList array of elements with posDnD property {top: , left: , height:, width: }
//returns found element or undefined
ReplaceItems.prototype.findCollision = function (moveX, moveY, itemList) {
var colliedItem;
for (var i = 0; i < itemList.length; i++) {
var item = itemList[i];
var isHorizontalIntersection = !(item.posDnD.right < moveX || item.posDnD.left > moveX);
var isVerticalIntersection = !(item.posDnD.bottom < moveY || item.posDnD.top > moveY);
if (isHorizontalIntersection && isVerticalIntersection) {
colliedItem = item;
break;
}
}
return colliedItem;
};
//returns which part of element has collision - true for top, false for bottom
ReplaceItems.prototype.isCollisionTop = function (moveX, moveY, item) {
var halfBottom = ((item.posDnD.bottom - item.posDnD.top) / 2) + item.posDnD.top;
var isCollisionTop = !(halfBottom < moveY || item.posDnD.top > moveY);
return isCollisionTop;
};
//callback for UIActions, every time when mouse is moved in drag mode.
ReplaceItems.prototype._dragMoveHandler = function (actionObject) {
//{evt : evt, clone : this.clone, element: this.element, isScrolling: isScrolling, moveX : this.moveX, moveY : this.moveY}
var sourceElement = actionObject.element;
var moveX = actionObject.moveX - this.layoutOffset.left;
var moveY = actionObject.moveY - this.jqLayout.get(0).getBoundingClientRect().top + this.jqLayout.scrollTop();
var collidedItem = this.findCollision(moveX, moveY, this.aCardsOrder);
if (!collidedItem) {
return; //no collided item, no need to act
}
var collidedItemTopCollision = this.isCollisionTop(moveX, moveY, collidedItem); //get element collision part
if (collidedItem === sourceElement) {
this.lastCollidedEl = collidedItem; //collided is dragged element, save it as last collided, and exit.
return;
}
if (collidedItem === this.lastCollidedEl) {
//current collided element the same as it was last time
if (this.lastCollisionTop === collidedItemTopCollision) {
//mouse was not moved to another element part (from top to bottom or wise versa), so no need to act
return;
}
if (this.lastCollisionTop) {
this.lastCollisionTop = collidedItemTopCollision;
if (sourceElement.posDnD.top > collidedItem.posDnD.top) {
//mouse was moved from top to bottom, but sourceElement already on the bottom of collided element, no need to switch.
return;
}
} else {
this.lastCollisionTop = collidedItemTopCollision;
if (sourceElement.posDnD.top < collidedItem.posDnD.top) {
//mouse was moved from bottom to top, but sourceElement already on the top of collided element, no need to switch.
return;
}
}
}
if (this.lastCollidedEl && (this.lastCollidedEl !== collidedItem && this.lastCollidedEl !== sourceElement) &&
(this.lastCollidedEl.posDnD.left === collidedItem.posDnD.left && this.lastCollidedEl.posDnD.left === sourceElement.posDnD.left)){
//complicated situation, when lastCollided, currentCollided and sourceElement, it's 3 different items, and they all in the same column.
//it means that we don't want to switch with currentCollided element, becouse it dosn't look good.
//Instead we switch with lastCollided item, which is more logical behaviour for user.
collidedItem = this.lastCollidedEl;
}
//switch elements and recalculate new layout state.
this.dragAndDropElement(sourceElement, collidedItem);
//we want to know under which card mouse will be after cards change places.
//Because cards could be very high, it's possible that after change, mouse will appear under another card.
//So we need to prevent future collision with this card, else you could face endless loop, when two high card will change each other endlessly.
this.lastCollidedEl = this.findCollision(moveX, moveY, this.aCardsOrder);
if (this.lastCollidedEl) {
this.lastCollisionTop = this.isCollisionTop(moveX, moveY, this.lastCollidedEl);
}
};
//switch elements and apply new element positions
ReplaceItems.prototype.dragAndDropElement = function (sourceElement, targetElement) {
if (sourceElement && targetElement) {
this.aCardsOrder = this.dragAndDropSwapElement(sourceElement, targetElement, this.aCardsOrder);
this.drawLayout(this.aCardsOrder);
}
};
//switch two elements
ReplaceItems.prototype.dragAndDropSwapElement = function (sourceElement, targetElement, itemsList) {
var newOrder = itemsList.slice();
var sourceElementIndex = itemsList.indexOf(sourceElement);
var targetElementIndex = itemsList.indexOf(targetElement);
newOrder[targetElementIndex] = sourceElement;
newOrder[sourceElementIndex] = targetElement;
return newOrder;
};
//keyboard navigation
ReplaceItems.prototype.dragAndDropSwapElementForKeyboardNavigation = function (sourceElement, targetElement) {
if (sourceElement && targetElement) {
var aLayoutCards = this.layout.getVisibleLayoutItems().map(function (item) {
return item.$().parent()[0];
});
var changes = 0;
for (var i = 0; i < aLayoutCards.length; i++){
if (aLayoutCards[i] === sourceElement){
aLayoutCards[i] = targetElement;
changes++;
continue;
}
if (aLayoutCards[i] === targetElement){
aLayoutCards[i] = sourceElement;
changes++;
continue;
}
}
//callback afterSwapItems
if (changes === 2) {
this.afterReplaceElements(aLayoutCards);
}
}
};
//init function called when drag start
ReplaceItems.prototype.initCardsSettingsForDragAndDrop = function () {
this.jqLayout = this.layout.$();
this.jqLayoutInner = this.jqLayout.children().first();
var layoutScroll = this.jqLayout.scrollTop();
var layoutHeight = this.jqLayoutInner.height();
this.isRTLEnabled = sap.ui.getCore().getConfiguration().getRTL() ? 1 : -1;
this.aCardsOrder = [];
this.layoutOffset = this.jqLayout.offset();
var visibleLayoutItems = this.layout.getVisibleLayoutItems();
if (!visibleLayoutItems) {
return;
}
this.aCardsOrder = visibleLayoutItems.map(function (item) {
var element = item.$().parent()[0];
element.posDnD = {
width: element.offsetWidth,
height: element.offsetHeight
};
element.style.width = element.offsetWidth + "px";
return element;
});
var jqFirstColumn = this.jqLayoutInner.children().first();
var marginProp = (this.isRTLEnabled === 1) ? "margin-left" : "margin-right";
this.verticalMargin = parseInt(jqFirstColumn.css(marginProp), 10);
var firstItemEl = this.aCardsOrder[0];
this.horizontalMargin = parseInt(jQuery(firstItemEl).css("margin-bottom"), 10);
this.columnCount = this.layout.getColumnCount();
this.top = firstItemEl.getBoundingClientRect().top - this.jqLayoutInner[0].getBoundingClientRect().top;
this.left = firstItemEl.getBoundingClientRect().left - this.jqLayoutInner[0].getBoundingClientRect().left;
this.width = firstItemEl.offsetWidth;
jQuery(this.aCardsOrder).css("position", "absolute");
this.drawLayout(this.aCardsOrder);
//all elements are switched to position absolute to prevent layout from collapsing we put height on it like it was before change.
//and fix scroll, so user will not see position changes on the screen.
this.jqLayoutInner.height(layoutHeight);
this.jqLayout.scrollTop(layoutScroll);
};
//put all elements to new position.
ReplaceItems.prototype.drawLayout = function (aCardsLayout) {
var oCountColumnHeight = [];
for (var i = 0; i < this.columnCount; i++) {
oCountColumnHeight[i] = 0;
}
for (var naturalIndex = 0; naturalIndex < aCardsLayout.length; naturalIndex++) {
var currentColumn = naturalIndex % this.columnCount;
var currentHeight = oCountColumnHeight[currentColumn]++;
var currentLeft = this.left - this.isRTLEnabled * (currentColumn * this.verticalMargin + currentColumn * this.width);
var currentTop = this.top;
var domElement = aCardsLayout[naturalIndex];
for (var j = 0; j < currentHeight; j++) {
currentTop += this.horizontalMargin;
var parentIndex = naturalIndex - (j + 1) * this.columnCount;
currentTop += aCardsLayout[parentIndex].posDnD.height;
}
domElement.posDnD.top = currentTop;
domElement.posDnD.bottom = currentTop + domElement.posDnD.height;
domElement.posDnD.left = currentLeft;
domElement.posDnD.right = currentLeft + domElement.posDnD.width;
this.updateElementCSS(aCardsLayout[naturalIndex]);
}
};
ReplaceItems.prototype.updateElementCSS = function (element) {
jQuery(element).css({
top: element.posDnD.top,
left: element.posDnD.left
});
};
//callback when drag starts
ReplaceItems.prototype._dragStartHandler = function (evt, cardElement) {
//Prevent selection of text on tiles and groups
if (window.getSelection) {
var selection = window.getSelection();
selection.removeAllRanges();
}
this.initCardsSettingsForDragAndDrop();
};
//callback before clone created
ReplaceItems.prototype._beforeDragHandler = function (evt, ui) {
//Prevent the browser to mark any elements while dragging
if (sap.ui.Device.system.desktop) {
jQuery('body').addClass("sapOVPDisableUserSelect sapOVPDisableImageDrag");
}
//Prevent text selection menu and magnifier on mobile devices
if (sap.ui.Device.browser.mobile) {
this.selectableElemets = jQuery(ui).find('.sapUiSelectable');
this.selectableElemets.removeClass('sapUiSelectable');
}
jQuery(this.settings.wrapper).addClass("dragAndDropMode");
};
//model changes, and cleanup after drag and drop finished
ReplaceItems.prototype._dragEndHandler = function (evt, ui) {
this.lastCollidedEl = null;
if (this.aCardsOrder) {
this.afterReplaceElements(this.aCardsOrder);
}
//Cleanup added classes and styles before drag
if (sap.ui.Device.system.desktop) {
jQuery('body').removeClass("sapOVPDisableUserSelect sapOVPDisableImageDrag");
}
jQuery(this.settings.wrapper).removeClass("dragAndDropMode");
this.jqLayoutInner.removeAttr("style");
jQuery(this.aCardsOrder).removeAttr("style");
};
ReplaceItems.prototype._endHandler = function (evt, ui) {
//Prevent text selection menu and magnifier on mobile devices
if (sap.ui.Device.browser.mobile && this.selectableElemets) {
this.selectableElemets.addClass('sapUiSelectable');
}
};
ReplaceItems.prototype.getSwapItemsFunction = function () {
return this.dragAndDropSwapElementForKeyboardNavigation.bind(this);
};
ReplaceItems.prototype.destroy = function () {
if (this.uiActions) {
this.uiActions.disable();
this.uiActions = null;
}
};
var DragAndDropFactory = {
buildReplaceItemsInstance: function (settings) {
var defaultSettings = {
containerSelector: ".sapUshellEasyScanLayoutInner",
wrapper: ".sapUshellEasyScanLayout",
draggableSelector: ".easyScanLayoutItemWrapper",
placeHolderClass: "easyScanLayoutItemWrapper-placeHolder",
cloneClass: "easyScanLayoutItemWrapperClone",
moveTolerance: 10,
switchModeDelay: 800,
isTouch: !sap.ui.Device.system.desktop,
debug: false
};
settings = jQuery.extend(defaultSettings, settings);
return new ReplaceItems(settings);
}
};
var KeyboardNavigation = function (easyScanLayout, swapItemsFunction) {
this.init(easyScanLayout, swapItemsFunction);
};
KeyboardNavigation.prototype.init = function (easyScanLayout, swapItemFunction) {
this.easyScanLayout = easyScanLayout;
this.swapItemsFunction = (typeof swapItemFunction === "function") ? swapItemFunction : function () {
};
this.keyCodes = jQuery.sap.KeyCodes;
this.jqElement = easyScanLayout.$();
this.jqElement.on('keydown.keyboardNavigation', this.keydownHandler.bind(this));
this.jqElement.find(".after").on("focus.keyboardNavigation", this.afterFocusHandler.bind(this));
this.jqElement.find(".sapUshellEasyScanLayoutInner").on("focus.keyboardNavigation", this.layoutFocusHandler.bind(this));
this.jqElement.on("focus.keyboardNavigation", ".easyScanLayoutItemWrapper", this.layoutItemFocusHandler.bind(this));
this._ignoreSelfFocus = false;
this.swapSourceElement = null;
};
KeyboardNavigation.prototype.destroy = function () {
if (this.jqElement) {
this.jqElement.off(".keyboardNavigation");
this.jqElement.find(".after").off(".keyboardNavigation");
this.jqElement.find(".sapUshellEasyScanLayoutInner").off(".keyboardNavigation");
}
delete this.jqElement;
delete this.easyScanLayout;
};
KeyboardNavigation.prototype.getVisibleLayoutItems = function () {
//layout items could be hidden, so we filter them and receive only visible
var content = this.easyScanLayout.getContent();
var filteredItems = content.filter(function (item) {
return item.getVisible();
});
return filteredItems;
};
KeyboardNavigation.prototype.afterFocusHandler = function () {
//two options are possible, or focus came to us from outside, as a result of outside navigation (Shift+tab Shift+F6 etc...)
//or we put focus as a result of Tab button inside layout, to maintain Accessibility guide:
// If focus is on the last control inside a Item, move focus to the next control in the tab chain after the Item Container
if (this._ignoreSelfFocus) {
//focus was on the last control inside a Item, move focus to the next control in the tab chain after the Item Container
//so, this function was called from tabButtonHandler, we put focus on after element, so browser will move it outside of layout
this._ignoreSelfFocus = false;
return;
}
//focus came to us from outside, as a result of outside navigation (Shift+tab Shift+F6 etc...)
// On enter first time, move focus to the last control of the first Item.
// On enter any consecutive time, move focus to the last control of the Item which had the focus before
var jqItem = this.jqElement.find(".easyScanLayoutItemWrapper:sapTabbable").first();
var lastTabbable = jqItem.find(":sapTabbable").last();
if (!lastTabbable.length) {
lastTabbable = jqItem;
}
lastTabbable.focus();
};
KeyboardNavigation.prototype.layoutFocusHandler = function () {
//two options are possible, or focus came to us from outside, as a result of outside navigation (tab F6 etc...)
//or we put focus as a result of Shift+Tab button inside layout, to maintain Accessibility guide:
// If focus is on a Item, move focus to the previous control in the tab chain before the Item Container.
if (this._ignoreSelfFocus) {
//focus was on the Item, move focus to the previous control in the tab chain before the Item Container
//so this function was called from shiftTabButtonHandler, and we put focus on layout itself, so browser will move it outside of layout
this._ignoreSelfFocus = false;
return;
}
//focus was received from outside element
//On enter first time, move focus to the first Item (as a whole).
//On enter any consecutive time, move focus to the Item which had the focus before.
this.jqElement.find(".easyScanLayoutItemWrapper:sapTabbable").first().focus();
};
KeyboardNavigation.prototype.layoutItemFocusHandler = function () {
var jqFocused = jQuery(document.activeElement);
// Check that focus element exits, id this item exits it will be easyScanLayoutItemWrapper (because the jQuery definitions
// After we have the element we want to add to his aria-labelledby attribute all the IDs of his sub elements that have aria-label and role headind
if (jqFocused) {
// Select all sub elements with aria-label
var labelledElement = jqFocused.find("[aria-label]");
var i, strIdList = "";
// Add every element id with aria label and roll heading inside the LayoutItemWrapper to string list
for (i = 0; i < labelledElement.length; i++) {
if (labelledElement[i].getAttribute("role") == "heading") {
strIdList += labelledElement[i].id + " ";
}
}
// add the id string list to the focus element (warpper) aria-labelledby attribute
if (strIdList.length) {
jqFocused.attr("aria-labelledby", strIdList);
}
}
};
//return array index of visible items from layout content aggregation
KeyboardNavigation.prototype._getLayoutItemIndex = function (jqFocused) {
if (!jqFocused.hasClass("easyScanLayoutItemWrapper")) {
return false;
}
var currentItemId = jqFocused.children().attr("id");
var itemIndex = false;
this.getVisibleLayoutItems().forEach(function (item, index) {
if (currentItemId == item.getId()) {
itemIndex = index;
}
});
return itemIndex;
};
KeyboardNavigation.prototype._changeItemsFocus = function (jqItem) {
//to preserve last focusable item, we need to set all other items tabindex=-1
var jqTabbableElements = jQuery('.easyScanLayoutItemWrapper');
jqTabbableElements.attr("tabindex", "-1");
jqItem.attr("tabindex", 0);
jqItem.focus();
};
KeyboardNavigation.prototype._swapItemsFocus = function (e, jqItemFrom, jqItemTo) {
//to preserve last focusable item, first item received tabindex=-1, second tabindex=-1.
e.preventDefault();
jqItemFrom.attr("tabindex", "-1");
jqItemTo.attr("tabindex", "0").focus();
};
KeyboardNavigation.prototype.tabButtonHandler = function (e) {
//Forward navigation:
//On enter first time, move focus to the first Item (as a whole).
//On enter any consecutive time, move focus to the Item which had the focus before.
//If focus is on a Item, move focus to the first control in the tab chain inside the Item.
//If focus is on a control inside a Item, move focus to the next control in the tab chain inside the same Item.
//If focus is on the last control inside a Item, move focus to the next control in the tab chain after the Item Container
var jqFocusedElement = jQuery(document.activeElement);
if (jqFocusedElement.hasClass("easyScanLayoutItemWrapper")) {
return;
}
var jqItem = jqFocusedElement.closest(".easyScanLayoutItemWrapper");
//need to check if focus is inside layout item
if (!jqItem.length) {
return;
}
//we know that focus is inside item, so now we want to check if it is last focusable.
var jqTabbables = jqItem.find(":sapTabbable");
//need to filter elements which have `after` in id, becouse those are dummy focusable elements and they
// prevent us from finding real last element
jqTabbables = jqTabbables.filter(":not([id$=after])");
//if currently focused element is itm's last one, then we place focus outside of layout
if (jqTabbables.eq(jqTabbables.length - 1).is(jqFocusedElement)) {
e.stopPropagation();
e.stopImmediatePropagation();
var beforeScrollLocation = this.jqElement.scrollTop();
this._ignoreSelfFocus = true;
this.jqElement.find(".after").focus();
this.jqElement.scrollTop(beforeScrollLocation);
}
};
KeyboardNavigation.prototype.f7Handler = function (e) {
//If focus is on a Item, move focus to the control inside the Item. Default: first control in the tab chain inside the Item.
//If focus is on a control inside a Item, move focus to the Item.
var jqFocusedElement = jQuery(document.activeElement);
if (jqFocusedElement.hasClass("easyScanLayoutItemWrapper")) {
//focus on item we place on first element inside
jqFocusedElement.find(":sapTabbable").first().focus();
} else {
//focus inside item, we put it on item itself
jqFocusedElement.closest(".easyScanLayoutItemWrapper").focus();
}
e.preventDefault();
};
KeyboardNavigation.prototype.shiftTabButtonHandler = function (e) {
//Backward navigation:
//On enter first time, move focus to the last control of the first Item.
//If focus is on a control inside a Item, move focus to the previous control in the tab chain inside the same Item.
//If focus is on the first control inside a Item, move focus to the corresponding Item (as a whole).
//If focus is on a Item, move focus to the previous control in the tab chain before the Item Container.
var jqFocusedElement = jQuery(document.activeElement);
if (!jqFocusedElement.hasClass("easyScanLayoutItemWrapper")) {
return;
}
//focus was on the Item, move focus to the previous control in the tab chain before the Item Container
//we put focus on layout itself, so browser will move it outside of layout
this._ignoreSelfFocus = true;
this.jqElement.find(".sapUshellEasyScanLayoutInner").focus();
};
KeyboardNavigation.prototype.arrowUpDownHandler = function (e, isArrowUp) {
//UP - If focus is on a Item, move focus to the Item above. If focus is on the first Item of a column, do nothing.
//DOWN - If focus is on a Item, move focus to the Item below. If focus is on the last Item of a column, do nothing.
var fName = isArrowUp ? "prev" : "next";
var jqFocused = jQuery(document.activeElement);
var nextFocus = jQuery(jqFocused)[fName](".easyScanLayoutItemWrapper");
if (!nextFocus.is(jqFocused)) {
this._swapItemsFocus(e, jqFocused, nextFocus);
}
};
KeyboardNavigation.prototype.arrowRightLeftHandler = function (e, isArrowRight) {
//Left - If focus is on a Card, move focus one Card to the left.
// If focus is on the first Card of a row, move focus to the last Card of the previous row.
// If focus is on the first Card, do nothing.
//Right - If focus is on a Card, move focus one Card to the right.
// If focus is on the last Card of a row, move focus to the first Card of the next row.
// If focus is on the last Card, do nothing.
var indexDiff = isArrowRight ? 1 : -1;
var jqFocused = jQuery(document.activeElement);
var currentItemIndex = this._getLayoutItemIndex(jqFocused);
if (currentItemIndex === false) {
return;
}
var oItem = this.getVisibleLayoutItems()[currentItemIndex + indexDiff];
if (oItem) {
this._swapItemsFocus(e, jqFocused, oItem.$().parent());
}
};
KeyboardNavigation.prototype.homeHandler = function (e) {
//If focus is on a Card, move focus to the first Card of the same row.
//If focus is on the first Card of a row, move focus to the first item within the Card Container.
var jqFocused = jQuery(document.activeElement);
var focusedElementIndex = this._getLayoutItemIndex(jqFocused);
if (focusedElementIndex === false) {
return;
}
var colCount = this.easyScanLayout.getColumnCount();
var indexDelta = focusedElementIndex % colCount;
var item;
var layoutItems = this.getVisibleLayoutItems();
if (indexDelta == 0) {
//focus will be put to the first item in layout
item = layoutItems[0];
} else {
//focus will be put to the first element in row
item = layoutItems[focusedElementIndex - indexDelta];
}
this._swapItemsFocus(e, jqFocused, item.$().parent());
};
KeyboardNavigation.prototype.endHandler = function (e) {
//If focus is on a Card, move focus to the last Card of the same row.
//If focus is on the last Card of a row, move focus to the last item within the Card Container.
var jqFocused = jQuery(document.activeElement);
var focusedElementIndex = this._getLayoutItemIndex(jqFocused);
if (focusedElementIndex === false) {
return;
}
var colCount = this.easyScanLayout.getColumnCount();
var indexDelta = focusedElementIndex % colCount;
var item;
var layoutItems = this.getVisibleLayoutItems();
if ((indexDelta == (colCount - 1)) ||
((focusedElementIndex + (colCount - indexDelta)) > layoutItems.length)) {
//focus wil be put to last layout item
item = layoutItems[(layoutItems.length - 1)];
} else {
//focus will be put to last item in row
item = layoutItems[focusedElementIndex + (colCount - indexDelta - 1)];
}
this._swapItemsFocus(e, jqFocused, item.$().parent());
};
KeyboardNavigation.prototype.ctrlHomeHandler = function (e) {
//If focus is on a Card, move focus to the first Card of the same column.
//If focus is on the first Card of a column, move focus to the first Card within the Card Container.
var jqFocused = jQuery(document.activeElement);
var focusedElementIndex = this._getLayoutItemIndex(jqFocused);
if (focusedElementIndex === false) {
return;
}
var colCount = this.easyScanLayout.getColumnCount();
var indexDelta = focusedElementIndex % colCount;
var visibleItems = this.getVisibleLayoutItems();
var item = visibleItems[indexDelta];
var nextFocus = item.$().parent();
if (nextFocus.is(jqFocused)) {
nextFocus = visibleItems[0].$().parent();
}
this._swapItemsFocus(e, jqFocused, nextFocus);
};
KeyboardNavigation.prototype.ctrlEndHandler = function (e) {
//If focus is on a Card, move focus to the last Card of the same column.
//If focus is on the last Card of a column, move focus to the last Card within the Card Container.
var jqFocused = jQuery(document.activeElement);
var focusedElementIndex = this._getLayoutItemIndex(jqFocused);
if (focusedElementIndex < 0) {
return;
}
var colCount = this.easyScanLayout.getColumnCount();
var indexDelta = focusedElementIndex % colCount;
var item;
var visibleItems = this.getVisibleLayoutItems();
for (var i = visibleItems.length - 1; i >= 0; i--) {
if ((i % colCount) == indexDelta) {
item = visibleItems[i];
break;
}
}
var nextFocus = item.$().parent();
if (nextFocus.is(jqFocused)) {
nextFocus = visibleItems[visibleItems.length - 1].$().parent();
}
this._swapItemsFocus(e, jqFocused, nextFocus);
};
KeyboardNavigation.prototype.altPageUpHandler = function (e) {
//If focus is on a Card, move focus left by page size. Page size can be set by apps, default page size is 5 Cards.
//If there are less Cards available than page size, move focus to the first Card of the row.
//If focus is on the first Card of the row, do nothing.
var jqFocused = jQuery(document.activeElement);
var focusedElementIndex = this._getLayoutItemIndex(jqFocused);
if (!focusedElementIndex) {
return;
}
var colCount = this.easyScanLayout.getColumnCount();
var indexDelta = focusedElementIndex % colCount;
var item = this.getVisibleLayoutItems()[focusedElementIndex - indexDelta];
this._swapItemsFocus(e, jqFocused, item.$().parent());
};
KeyboardNavigation.prototype.altPageDownHandler = function (e) {
//If focus is on a Card, move focus right by page size. Page size can be set by apps, default page size is 5 Cards.
//If there are less Cards available than page size, move focus to the last Card of the row.
//If focus is on the last Card of the row, do nothing.
var jqFocused = jQuery(document.activeElement);
var focusedElementIndex = this._getLayoutItemIndex(jqFocused);
if (focusedElementIndex < 0) {
return;
}
var colCount = this.easyScanLayout.getColumnCount();
var indexDelta = focusedElementIndex % colCount;
var item;
var layoutItems = this.getVisibleLayoutItems();
if (indexDelta != (colCount - 1)) {
item = layoutItems[focusedElementIndex + (colCount - indexDelta - 1)];
if (!item) {
item = layoutItems[layoutItems.length - 1];
}
this._swapItemsFocus(e, jqFocused, item.$().parent());
}
};
KeyboardNavigation.prototype.pageUpDownHandler = function (e, isPageUp) {
//move focus Up/Down to the first not visible (outside of viewport).
//if all items (on direction) are visible, then to first/last
var fName = isPageUp ? "prev" : "next";
var jqFocused = jQuery(document.activeElement);
if (!jqFocused.hasClass("easyScanLayoutItemWrapper")) {
return;
}
if (!jqFocused[fName]().length) {
return;
}
var nextFocusEl = false;
var currentEl = jqFocused;
var windowHeight = jQuery(window).height();
var layoutTop = this.jqElement.offset().top;
//find first "outside of viewport" item
while (!nextFocusEl) {
var next = currentEl[fName]();
if (!next.length) {
nextFocusEl = currentEl;
break;
}
if (!isPageUp && next.offset().top > windowHeight) {
nextFocusEl = next;
break;
}
if (isPageUp && (next.offset().top + next.outerHeight()) <= layoutTop) {
nextFocusEl = next;
break;
}
currentEl = next;
}
this._swapItemsFocus(e, jqFocused, nextFocusEl);
};
KeyboardNavigation.prototype.ctrlArrowHandler = function (e) {
//Check that we are not in Drag mode already
//then we need to start the DragMode if it's possible
if (this.swapSourceElement == null) {
this.swapSourceElement = jQuery(document.activeElement);
if (!this.swapSourceElement.hasClass("easyScanLayoutItemWrapper")) {
this.endSwap();
} else {
this.jqElement.on('keyup.keyboardNavigation', this.keyupHandler.bind(this));
//change css of the current element
this.jqElement.addClass('dragAndDropMode');
this.swapSourceElement.addClass('dragHovered');
}
}
};
KeyboardNavigation.prototype.keyupHandler = function (e) {
//This is the case when we finished our Drag and Drop actions, and we want to swap items
if (this.swapSourceElement != null && e.keyCode === this.keyCodes.CONTROL) {
var jqFocused = jQuery(document.activeElement);
if (jqFocused.hasClass("easyScanLayoutItemWrapper")) {
this.swapItemsFunction(this.swapSourceElement[0], jqFocused[0]);
this._changeItemsFocus(this.swapSourceElement);
}
this.endSwap();
}
};
KeyboardNavigation.prototype.endSwap = function (e) {
this.swapSourceElement.removeClass('dragHovered');
this.jqElement.removeClass('dragAndDropMode');
this.swapSourceElement = null;
this.jqElement.off('keyup.keyboardNavigation');
};
KeyboardNavigation.prototype.checkIfSwapInterrupted = function (e) {
//When Drag&Drop mode is enabled, any other button except arrowKey will stop Drag&Drop action
if (this.swapSourceElement != null &&
e.keyCode != this.keyCodes.ARROW_LEFT &&
e.keyCode != this.keyCodes.ARROW_RIGHT &&
e.keyCode != this.keyCodes.ARROW_UP &&
e.keyCode != this.keyCodes.ARROW_DOWN) {
this.endSwap();
}
};
KeyboardNavigation.prototype.keydownHandler = function (e) {
//in case swap was interrupted call end swap
this.checkIfSwapInterrupted(e);
switch (e.keyCode) {
case this.keyCodes.TAB:
(e.shiftKey) ? this.shiftTabButtonHandler(e) : this.tabButtonHandler(e);
break;
case this.keyCodes.F6:
if (e.shiftKey) {
this._ignoreSelfFocus = true;
this.jqElement.find(".sapUshellEasyScanLayoutInner").focus();
jQuery.sap.handleF6GroupNavigation(e);
} else {
this._ignoreSelfFocus = true;
var beforeScrollLocation = this.jqElement.scrollTop();
this.jqElement.find(".after").focus();
jQuery.sap.handleF6GroupNavigation(e);
this.jqElement.scrollTop(beforeScrollLocation);
}
break;
case this.keyCodes.F7:
this.f7Handler(e);
break;
case this.keyCodes.ARROW_UP:
if (e.ctrlKey == true) {
this.ctrlArrowHandler(e);
}
this.arrowUpDownHandler(e, true);
break;
case this.keyCodes.ARROW_DOWN:
if (e.ctrlKey == true) {
this.ctrlArrowHandler(e);
}
this.arrowUpDownHandler(e, false);
break;
case this.keyCodes.ARROW_RIGHT:
if (e.ctrlKey == true) {
this.ctrlArrowHandler(e);
}
this.arrowRightLeftHandler(e, true);
break;
case this.keyCodes.ARROW_LEFT:
if (e.ctrlKey == true) {
this.ctrlArrowHandler(e);
}
this.arrowRightLeftHandler(e, false);
break;
case this.keyCodes.HOME:
(e.ctrlKey == true) ? this.ctrlHomeHandler(e) : this.homeHandler(e);
break;
case this.keyCodes.END:
(e.ctrlKey == true) ? this.ctrlEndHandler(e) : this.endHandler(e);
break;
case this.keyCodes.PAGE_UP:
(e.altKey == true) ? this.altPageUpHandler(e) : this.pageUpDownHandler(e, true);
break;
case this.keyCodes.PAGE_DOWN:
(e.altKey == true) ? this.altPageDownHandler(e) : this.pageUpDownHandler(e, false);
break;
}
};
var EasyScanLayout = sap.ui.core.Control.extend("sap.ovp.ui.EasyScanLayout", {
metadata: {
library: "sap.ovp",
aggregations: {
content: {type: "sap.ui.core.Control", multiple: true, singularName: "content"}
},
defaultAggregation: "content",
events: {
afterRendering: {},
afterDragEnds: {}
},
properties: {
useMediaQueries: {group: "Misc", type: "boolean", defaultValue: false},
dragAndDropRootSelector: {group: "Misc", type: "string"},
dragAndDropEnabled: {group: "Misc", type: "boolean", defaultValue: true},
debounceTime: {group: "Misc", type: "sap.ui.core/int", defaultValue: 150}
}
},
renderer: {
render: function (oRm, oControl) {
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapUshellEasyScanLayout");
oRm.writeClasses();
oRm.write(">");
oRm.write("<div class='sapUshellEasyScanLayoutInner' tabindex='0'>");
var columnCount = oControl.columnCount;
var columnList = Array.apply(null, new Array(columnCount)).map(function () {
return [];
});
var filteredItems = oControl.getContent().filter(function (item) {
return item.getVisible();
});
for (var i = 0; i < filteredItems.length; i++) {
columnList[i % columnCount].push(filteredItems[i]);
}
var itemCounter = 1;
columnList.forEach(function (column) {
oRm.write("<div");
oRm.addClass("easyScanLayoutColumn");
oRm.writeAccessibilityState(undefined, {role: "list"});
oRm.writeClasses();
oRm.write(">");
column.forEach(function (item, index) {
oRm.write("<div ");
(itemCounter === 1) ? oRm.write("tabindex='0' ") : oRm.write("tabindex='-1' ");
oRm.addClass("easyScanLayoutItemWrapper");
oRm.writeAccessibilityState(undefined, {role: "listitem"});
oRm.write("aria-setsize=" + filteredItems.length + " aria-posinset=" + itemCounter);
itemCounter++;
oRm.writeClasses();
oRm.write(">");
oRm.renderControl(item);
oRm.write("</div>");
});
oRm.write("</div>");
});
oRm.write("</div>");
// dummy after focusable area
oRm.write("<div class='after' tabindex='0'></div>");
oRm.write("</div>");
}
}
});
var getColumnResolutionList = function () {
return [
{minWidth: 0, styleClass: "columns-blank", columnCount: 1},
{minWidth: 240, styleClass: "columns-block", columnCount: 1},
{minWidth: 352, styleClass: "columns-narrow", columnCount: 1},
{minWidth: 433, styleClass: "columns-wide", columnCount: 1},
{minWidth: 704, styleClass: "columns-narrow", columnCount: 2},
{minWidth: 864, styleClass: "columns-wide", columnCount: 2},
{minWidth: 1024, styleClass: "columns-narrow", columnCount: 3},
{minWidth: 1280, styleClass: "columns-wide", columnCount: 3},
{minWidth: 1440, styleClass: "columns-narrow", columnCount: 4},
{minWidth: 1920, styleClass: "columns-wide", columnCount: 4},
{minWidth: 2560, styleClass: "columns-narrow", columnCount: 5},
{minWidth: 3008, styleClass: "columns-wide", columnCount: 5},
//This is for 8K and 4K Screens (on 3600px flp make 1rem - 32px)
{minWidth: 3600, styleClass: "columns-narrow", columnCount: 4},
{minWidth: 3840, styleClass: "columns-wide", columnCount: 4},
{minWidth: 5120, styleClass: "columns-wide", columnCount: 5},
{minWidth: 6016, styleClass: "columns-wide", columnCount: 5}
];
};
EasyScanLayout.prototype.init = function () {
this.data("sap-ui-fastnavgroup", "true", true);
this.columnResolutionList = getColumnResolutionList();
this.columnCount = this.columnResolutionList[0].columnCount;
this.columnStyle = "";
this.updateColumnClass(this.columnResolutionList[0].styleClass);
var matchMediaSupported = sap.ui.Device.browser.msie && sap.ui.Device.browser.version > 9;
if (matchMediaSupported && this.getUseMediaQueries()) { //if matchMedia supported and full page --> use media queries
this.mediaQueryList = this.initMediaListeners(this.columnResolutionList);
} else { //if not full page --> use resize handler
this.resizeHandlerId = this.initResizeHandler(this.columnResolutionList);
}
};
var mediaListenerHandlerTimerId;
var mediaListenersDebounce = function (columnCount, columnStyle, mq) {
var mediaListenerHandler = function (cols, className) {
this.updateColumnClass(className);
this.refreshColumnCount(cols, this.getContent());
};
if (mq.matches) {
window.clearTimeout(mediaListenerHandlerTimerId);
mediaListenerHandlerTimerId = window.setTimeout(mediaListenerHandler.bind(this, columnCount, columnStyle), this.getDebounceTime());
}
};
var buildQuery = function (bottomRes, topRes) {
var min = bottomRes.minWidth;
var max = topRes && topRes.minWidth;
return "(min-width: " + min + "px)" + (max ? " and (max-width: " + (max - 1) + "px)" : "");
};
EasyScanLayout.prototype.initMediaListeners = function (colResList) {
var mediaQueryList = [];
for (var i = 0; i < colResList.length; i++) {
var query = buildQuery(colResList[i], colResList[i + 1]);
var mediaQuery = window.matchMedia(query);
var boundedListener = mediaListenersDebounce.bind(this, colResList[i].columnCount, colResList[i].styleClass);
mediaQuery.addListener(boundedListener);
mediaQuery.bindedListener = boundedListener;
boundedListener(mediaQuery);
mediaQueryList.push(mediaQuery);
}
return mediaQueryList;
};
EasyScanLayout.prototype.initResizeHandler = function (colResList) {
var resizeHandlerTimerId;
var debounceTime = this.getDebounceTime();
var resizeHandlerDebounce = function () {
window.clearTimeout(resizeHandlerTimerId);
resizeHandlerTimerId = window.setTimeout(this.oControl.resizeHandler.bind(this, colResList), debounceTime);
};
return sap.ui.core.ResizeHandler.register(this, resizeHandlerDebounce);
};
EasyScanLayout.prototype.resizeHandler = function (colResList) {
var width = this.iWidth;
var oControl = this.oControl;
var resObject;
for (var i = 0; i < colResList.length; i++) {
if (!colResList[i + 1]) {
resObject = colResList[i];
break;
}
if (colResList[i].minWidth <= width && colResList[i + 1].minWidth > width) {
resObject = colResList[i];
break;
}
}
oControl.refreshColumnCount(resObject.columnCount, oControl.getContent());
oControl.updateColumnClass(resObject.styleClass);
};
EasyScanLayout.prototype.refreshColumnCount = function (columnCount, content) {
this.columnCount = columnCount;
var jqColumnsNew = jQuery();
for (var i = 0; i < columnCount; i++) {
jqColumnsNew = jqColumnsNew.add("<div class='easyScanLayoutColumn' role = 'list'/>");
}
var filteredItems = content.filter(function (item) {
return item.getVisible();
});
for (var j = 0; j < filteredItems.length; j++) {
jqColumnsNew.get(j % columnCount).appendChild(filteredItems[j].getDomRef().parentNode);
}
this.$().children(".sapUshellEasyScanLayoutInner").empty().append(jqColumnsNew);
};
EasyScanLayout.prototype.getColumnCount = function () {
return this.columnCount;
};
EasyScanLayout.prototype.getVisibleLayoutItems = function () {
//layout items could be hidden, so we filter them and receive only visible
var content = this.getContent();
var filteredItems = content.filter(function (item) {
return item.getVisible();
});
return filteredItems;
};
EasyScanLayout.prototype.updateColumnClass = function (columnClass) {
if (this.columnStyle === columnClass) {
return;
}
this.removeStyleClass(this.columnStyle);
this.addStyleClass(columnClass);
this.columnStyle = columnClass;
};
EasyScanLayout.prototype.afterDragAndDropHandler = function (aElements) {
var aAllControls = this.removeAllAggregation("content", true);
var aVisibleControls = [];
var iVizibleIndex = 0;
//receive contols list from wrapperDOM list
aElements.forEach(function (el) {
var elementId = el.children[0].getAttribute("id");
var oControl = sap.ui.getCore().byId(elementId);
aVisibleControls.push(oControl);
});
// We need to keep all controls in the content aggregation, keep
// the original order and change the order only for the visible controls
for (var i = 0; i < aAllControls.length; i++){
if (aAllControls[i].getVisible()){
this.addAggregation("content", aVisibleControls[iVizibleIndex], true);
iVizibleIndex++;
} else {
this.addAggregation("content", aAllControls[i], true);
}
}
this.fireAfterDragEnds();
this.refreshColumnCount(this.getColumnCount(), this.getContent());
};
EasyScanLayout.prototype.onAfterRendering = function () {
if (!this.getDragAndDropRootSelector()) {
this.setDragAndDropRootSelector("#" + this.getId());
}
if (this.layoutDragAndDrop) {
this.layoutDragAndDrop.destroy();
}
if (this.getDragAndDropEnabled()) {
this.layoutDragAndDrop = DragAndDropFactory.buildReplaceItemsInstance({
afterReplaceElements: this.afterDragAndDropHandler.bind(this),
rootSelector: this.getDragAndDropRootSelector(),
layout: this
});
}
if (this.keyboardNavigation) {
this.keyboardNavigation.destroy();
}
var swapItemsFunc = this.layoutDragAndDrop ? this.layoutDragAndDrop.getSwapItemsFunction() : null;
this.keyboardNavigation = new KeyboardNavigation(this, swapItemsFunc);
this.fireAfterRendering();
};
EasyScanLayout.prototype.exit = function () {
if (this.mediaQueryList) {
this.mediaQueryList.forEach(function (mediaQuery) {
mediaQuery.removeListener(mediaQuery.bindedListener);
});
delete this.mediaQueryList;
}
if (this.resizeHandlerId) {
sap.ui.core.ResizeHandler.deregister(this.resizeHandlerId);
}
if (this.layoutDragAndDrop) {
this.layoutDragAndDrop.destroy();
delete this.layoutDragAndDrop;
}
};
return EasyScanLayout;
}, /* bExport= */ true);
}; // end of sap/ovp/ui/EasyScanLayout.js
if ( !jQuery.sap.isDeclared('sap.ovp.ui.ObjectStream') ) {
/**
* Created by i060586 on 11/25/14.
*/
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2014 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.require('sap.ui.core.delegate.ScrollEnablement'); // unlisted dependency retained
jQuery.sap.declare('sap.ovp.ui.ObjectStream'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ovp/ui/ObjectStream",['jquery.sap.global'],
function(jQuery) {
"use strict";
var KeyboardNavigation = function (objectStream) {
this.init(objectStream);
};
KeyboardNavigation.prototype.init = function(objectStream) {
this.objectStream = objectStream;
this.keyCodes = jQuery.sap.KeyCodes;
this.jqElement = objectStream.$();
this.jqElement.on('keydown.keyboardNavigation', this.keydownHandler.bind(this));
this.jqElement.on("focus.keyboardNavigation",".sapOvpObjectStreamItem", this.ObjectStreamFocusAccessabilityHandler.bind(this));
};
KeyboardNavigation.prototype.destroy = function () {
if (this.jqElement) {
this.jqElement.off(".keyboardNavigation");
}
delete this.jqElement;
delete this.objectStream;
};
KeyboardNavigation.prototype._swapItemsFocus = function (e, jqItemFrom, jqItemTo) {
//to preserve last focusable item, first item received tabindex=-1, second tabindex=-1.
e.preventDefault();
jqItemFrom.attr("tabindex", "-1");
jqItemTo.attr("tabindex", "0").focus();
};
//Handle focus on object stream item
KeyboardNavigation.prototype.ObjectStreamFocusAccessabilityHandler = function () {
var focusedDomElement = document.activeElement;
focusedDomElement = jQuery(focusedDomElement);
//Check that we got a focused item, after that will add to aria-labelledby every id
// of items inside the object stream item that have role=heading and aria-label
if (focusedDomElement){
// get all elements inside that have aria-label
var labelledElement = focusedDomElement.find("[aria-label]");
var i, strIdList = "";
// add every item that also have role heading to id list string
for (i = 0; i < labelledElement.length; i++ ){
if (labelledElement[i].getAttribute("role") == "heading"){
strIdList += labelledElement[i].id + " ";
}
}
//add the object stream item the aria-labelledby attribute with list of relevants IDs
if (strIdList.length) {
focusedDomElement.attr("aria-labelledby", strIdList);
}
}
};
KeyboardNavigation.prototype.tabButtonHandler = function (e) {
//Forward navigation:
//On enter first time, move focus to the first Item (as a whole).
//If focus is on a Item, move focus to the first control in the tab chain inside the Item.
//If focus is on a control inside a Item, move focus to the next control in the tab chain inside the same Item.
//If focus is on the last control inside a Item, move focus to the next control in the tab chain after the Object Stream, usually it's Close button
var jqFocused = jQuery(document.activeElement);
if (jqFocused.hasClass("sapOvpObjectStreamItem")) {
return;
}
if (jqFocused.hasClass("sapOvpObjectStreamClose")) {
//focus on the close button, move focus to last focused item.
e.preventDefault();
this.jqElement.find(".sapOvpObjectStreamItem:sapTabbable").focus();
return;
}
var jqCard = jqFocused.closest(".sapOvpObjectStreamItem");
if (!jqCard.length) {
return;
}
var jqTabbables = jqCard.find(":sapTabbable");
//If focus is on the last control inside a Item, move focus to the next control in the tab chain after the Object Stream, usually it's Close button
if (jqTabbables.eq(jqTabbables.length - 1).is(jqFocused)) {
e.preventDefault();
this.jqElement.find(".sapOvpObjectStreamClose").focus();
}
};
KeyboardNavigation.prototype.shiftTabButtonHandler = function (e) {
//Backward navigation:
//On enter first time, move focus to the last control of the first Card.
//On enter any consecutive time, move focus to the last control of the Card which had the focus before.
//If focus is on a control inside a Card, move focus to the previous control in the tab chain inside the same Card. usually it's Close button
var jqFocused = jQuery(document.activeElement);
if (jqFocused.hasClass("sapOvpObjectStreamItem")) {
e.preventDefault();
this.jqElement.find(".sapOvpObjectStreamClose").focus();
}
if (jqFocused.hasClass("sapOvpObjectStreamClose")) {
e.preventDefault();
this.jqElement.find(".sapOvpObjectStreamItem:sapTabbable *:sapTabbable").last().focus();
return;
}
};
KeyboardNavigation.prototype.enterHandler = function (e) {
var jqFocused = jQuery(document.activeElement);
//if Space/Enter was on Close button, close dialog
if (jqFocused.hasClass("sapOvpObjectStreamClose")) {
e.preventDefault();
this.objectStream.getParent().close();
return;
}
//if Space/Enter was last item (it is a Placeholder), trigger click
if (jqFocused.hasClass("sapOvpObjectStreamItem") && !jqFocused.next().length) {
jqFocused.children().click();
return;
}
};
KeyboardNavigation.prototype.f6Handler = function (e) {
//No matter where the focus resides inside the Object Stream, move it to the first element in the tab chain of the next F6-group. (It's Close button)
var jqFocused = jQuery(document.activeElement);
if (jqFocused.hasClass("sapOvpObjectStreamClose")) {
this.jqElement.find('.sapOvpObjectStreamItem').attr("tabindex", "-1").first().attr("tabindex", "0").focus();
} else {
this.jqElement.find('.sapOvpObjectStreamClose').focus();
}
};
KeyboardNavigation.prototype.f7Handler = function (e) {
//If focus is on a Card, move focus to the control inside the Default: first control in the tab chain inside the Card.
//If focus is on a control inside a Card, move focus to the Card.
var jqFocused = jQuery(document.activeElement);
if (jqFocused.hasClass("sapOvpObjectStreamItem")) {
jqFocused.find(':sapTabbable').first().focus();
} else {
jqFocused.closest('.sapOvpObjectStreamItem').focus();
}
e.preventDefault();
};
KeyboardNavigation.prototype.leftRightHandler = function (e, isRight) {
//Left - If focus is on a Card, move focus to the previous Card. If focus is on the first Card, do nothing.
//Right - If focus is on a Card, move focus to the next Card. If focus is on the last Card, do nothing.
var fName = isRight ? "next" : "prev";
var jqFocused = jQuery(document.activeElement);
if (!jqFocused.hasClass("sapOvpObjectStreamItem")) {
return false;
}
var nextFocus = jqFocused[fName]();
if (!nextFocus.length) {
return;
}
this._swapItemsFocus(e, jqFocused, nextFocus);
};
KeyboardNavigation.prototype.homeEndHandler = function (e, isHome) {
//Home - If focus is on a Card, move focus to the first Card.
//End - If focus is on a Card, move focus to the last Card. This is usually the Placeholder Card.
var fName = isHome ? "first" : "last";
var jqFocused = jQuery(document.activeElement);
if (!jqFocused.hasClass("sapOvpObjectStreamItem")) {
return false;
}
e.preventDefault();
var nextFocus = this.jqElement.find(".sapOvpObjectStreamItem")[fName]();
this._swapItemsFocus(e, jqFocused, nextFocus);
};
KeyboardNavigation.prototype.pageUpDownHandler = function (e, isPageUp) {
//move focus Left/Right to the first not visible (outside of viewport) item.
//if all items (on direction) are visible, then to first/last
var fName = isPageUp ? "prev" : "next";
var jqFocused = jQuery(document.activeElement);
if (!jqFocused.hasClass("sapOvpObjectStreamItem")) {
return;
}
if (!jqFocused[fName]().length) {
return;
}
var nextFocusEl = false;
var currentEl = jqFocused;
var windowWidth = jQuery(window).width();
while (!nextFocusEl) {
var next = currentEl[fName]();
if (!next.length) {
nextFocusEl = currentEl;
break;
}
if (!isPageUp && next.offset().left > windowWidth) {
nextFocusEl = next;
break;
}
if (isPageUp && (next.offset().left + next.outerHeight()) <= 0) {
nextFocusEl = next;
break;
}
currentEl = next;
}
this._swapItemsFocus(e, jqFocused, nextFocusEl);
};
KeyboardNavigation.prototype.keydownHandler = function(e) {
switch (e.keyCode) {
case this.keyCodes.TAB:
(e.shiftKey) ? this.shiftTabButtonHandler(e) : this.tabButtonHandler(e);
break;
case this.keyCodes.ENTER:
case this.keyCodes.SPACE:
this.enterHandler(e);
break;
case this.keyCodes.F6:
this.f6Handler(e);
break;
case this.keyCodes.F7:
this.f7Handler(e);
break;
case this.keyCodes.ARROW_UP:
case this.keyCodes.ARROW_LEFT:
this.leftRightHandler(e, false);
break;
case this.keyCodes.ARROW_DOWN:
case this.keyCodes.ARROW_RIGHT:
this.leftRightHandler(e, true);
break;
case this.keyCodes.HOME:
this.homeEndHandler(e, true);
break;
case this.keyCodes.END:
this.homeEndHandler(e, false);
break;
case this.keyCodes.PAGE_UP:
this.pageUpDownHandler(e, true);
break;
case this.keyCodes.PAGE_DOWN:
this.pageUpDownHandler(e, false);
break;
}
};
var ObjectStream = sap.ui.core.Control.extend("sap.ovp.ui.ObjectStream", { metadata : {
library : "sap.ovp",
properties : {
title: {type : "string", defaultValue: ""}
},
aggregations : {
content: {type: "sap.ui.core.Control", multiple: true},
placeHolder: {type: "sap.ui.core.Control", multiple: false}
}
}});
ObjectStream.prototype.init = function() {
var that = this;
this._closeIcon = new sap.ui.core.Icon({
src: "sap-icon://decline",
tooltip: "close"
});
this._closeIcon.addEventDelegate({
onclick: function () {
that.getParent().close();
}
});
};
ObjectStream.prototype._startScroll = function(direction) {
this._direction = direction;
var scrollDiff = this.wrapper.scrollWidth - this.wrapper.offsetWidth - Math.abs(this.wrapper.scrollLeft);
var leftToScroll;
if (direction == "left" ) {
leftToScroll = (this.rtl && !this.scrollReverse) ? scrollDiff : this.wrapper.scrollLeft;
if (leftToScroll <= 0) {
return;
}
this.jqRightEdge.css("opacity", 1);
} else {
leftToScroll = (this.rtl && !this.scrollReverse) ? Math.abs(this.wrapper.scrollLeft) : scrollDiff;
if (leftToScroll <= 0) {
return;
}
this.jqLeftEdge.css("opacity", 1);
}
var scrollTime = leftToScroll * 3;
var translateX = (direction == "left") ? leftToScroll : ~leftToScroll + 1;
jQuery(this.container).one("transitionend", function () {
this._mouseLeave({data: this});
}.bind(this));
this.container.style.transition = 'transform ' + scrollTime + 'ms linear';
this.container.style.transform = 'translate(' + translateX + 'px, 0px) scale(1) translateZ(0px) ';
};
ObjectStream.prototype._mouseLeave = function (e) {
var containerTransform = window.getComputedStyle(e.data.container).transform;
e.data.container.style.transform = containerTransform;
e.data.container.style.transition = '';
var transformX;
var transformParamsArr = containerTransform.split(",");
if (containerTransform.substr(0, 8) == "matrix3d") {
transformX = parseInt(transformParamsArr[12], 10);
} else if (containerTransform.substr(0, 6) == "matrix") {
transformX = parseInt(transformParamsArr[4], 10);
}
if (isNaN(transformX)) {
return;
}
e.data.container.style.transform = "none";
e.data.wrapper.scrollLeft += ~transformX + (e.data._direction == "left" ? -5 : 5);
e.data._checkEdgesVisibility();
};
var scrollHandlerTimerId;
ObjectStream.prototype.debounceScrollHandler = function () {
window.clearTimeout(scrollHandlerTimerId);
scrollHandlerTimerId = window.setTimeout(this._checkEdgesVisibility.bind(this), 150);
};
ObjectStream.prototype._initScrollVariables = function () {
var jqObjectStream = this.$();
this.container = jqObjectStream.find(".sapOvpObjectStreamScroll").get(0);
this.rtl = sap.ui.getCore().getConfiguration().getRTL();
this.wrapper = jqObjectStream.find(".sapOvpObjectStreamCont").get(0);
this.scrollReverse = this.scrollReverse || this.wrapper.scrollLeft > 0;
this.shouldShowScrollButton = (!sap.ui.Device.system.phone && !sap.ui.Device.system.tablet) || sap.ui.Device.system.combi; //should be shown only in desktop (and combi)
this.jqRightEdge = jqObjectStream.find(".sapOvpOSEdgeRight");
this.jqLeftEdge = jqObjectStream.find(".sapOvpOSEdgeLeft");
if (this.shouldShowScrollButton) {
this.jqRightEdge.add(this.jqLeftEdge).on("mouseenter.objectStream", this, this._mouseEnter).
on("mouseleave.objectStream", this, this._mouseLeave);
jQuery(this.wrapper).on("scroll.objectStream", this.debounceScrollHandler.bind(this));
}else {
this.jqLeftEdge.css("display", "none");
this.jqRightEdge.css("display", "none");
}
this._checkEdgesVisibility();
};
ObjectStream.prototype._afterOpen = function () {
if (sap.ui.Device.os.ios && this.$().length) {
//prevent sap.m.Dialog from stop scroll by cancelling "touchmove" on iOS
this.$().on("touchmove.scrollFix", function (e) {e.stopPropagation(); });
}
this.$().find('.sapOvpObjectStreamItem').first().focus();
if (this.keyboardNavigation) {
this.keyboardNavigation.destroy();
}
this.keyboardNavigation = new KeyboardNavigation(this);
this._initScrollVariables();
this.jqBackground = jQuery("<div id='objectStreamBackgroundId' class='objectStreamNoBackground'></div>");
jQuery.sap.byId("sap-ui-static").prepend(this.jqBackground);
this.jqBackground.on('click.closePopup', function () {
this._oPopup.close();
}.bind(this));
jQuery(".sapUshellEasyScanLayout").addClass("bluredLayout");
};
ObjectStream.prototype._beforeClose = function () {
if (sap.ui.Device.os.ios && this.$().length) {
this.$().off(".scrollFix");
}
this.keyboardNavigation.destroy();
this.jqBackground.remove();
this.jqLeftEdge.add(this.jqRightEdge).add(this.wrapper).off(".objectStream");
jQuery(".sapUshellEasyScanLayout").removeClass("bluredLayout");
};
ObjectStream.prototype._mouseEnter = function (evt) {
var scrollDirection = 'right';
if ((evt.target == evt.data.jqRightEdge.get(0)) ||
(evt.currentTarget == evt.data.jqRightEdge.get(0))){
scrollDirection = sap.ui.getCore().getConfiguration().getRTL() ? 'left' : 'right';
}
if ((evt.target == evt.data.jqLeftEdge.get(0)) ||
(evt.currentTarget == evt.data.jqLeftEdge.get(0))){
scrollDirection = sap.ui.getCore().getConfiguration().getRTL() ? 'right' : 'left';
}
evt.data._startScroll(scrollDirection);
};
ObjectStream.prototype._checkEdgesVisibility = function () {
var scrollPosition = this.wrapper.scrollLeft;
var leftToScroll = this.wrapper.scrollWidth - this.wrapper.offsetWidth - this.wrapper.scrollLeft;
var leftEdgeOpacity = (scrollPosition == 0) ? 0 : 1;
var rightEdgeOpacity = (leftToScroll == 0) ? 0 : 1;
if (sap.ui.getCore().getConfiguration().getRTL() && this.scrollReverse) {
this.jqLeftEdge.css("opacity", rightEdgeOpacity);
this.jqRightEdge.css("opacity", leftEdgeOpacity);
} else {
this.jqLeftEdge.css("opacity", leftEdgeOpacity);
this.jqRightEdge.css("opacity", rightEdgeOpacity);
}
};
ObjectStream.prototype._createPopup = function () {
this._oPopup = new sap.m.Dialog({
showHeader: false,
afterOpen: this._afterOpen.bind(this),
beforeClose: this._beforeClose.bind(this),
content: [this],
stretch: sap.ui.Device.system.phone
}).removeStyleClass("sapUiPopupWithPadding").addStyleClass("sapOvpStackedCardPopup");
this._oPopup.oPopup.setModal(false);
};
ObjectStream.prototype.open = function (cardWidth) {
if (!this._oPopup) {
this._createPopup();
}
//save card width for after rendering
this._cardWidth = cardWidth;
//set height and width of each card on object stream
this.setCardsSize(this._cardWidth);
this._oPopup.open();
};
ObjectStream.prototype.onBeforeRendering = function() {
};
ObjectStream.prototype.onAfterRendering = function() {
if (!this._oPopup || !this._oPopup.isOpen() || !this.getContent().length ) {
return;
}
//set height and width of each card on object stream
this.setCardsSize(this._cardWidth);
setTimeout(function () {
this._initScrollVariables();
}.bind(this));
};
ObjectStream.prototype.exit = function() {
if (this._oPopup){
this._oPopup.destroy();
}
this._closeIcon.destroy();
if (this._oScroller) {
this._oScroller.destroy();
this._oScroller = null;
}
};
ObjectStream.prototype.setCardsSize = function(cardWidth) {
var remSize = parseInt(window.getComputedStyle(document.documentElement).fontSize, 10);
var cardHeight = sap.ui.Device.system.phone ? document.body.clientHeight / remSize - 4.5 : 28.75;
var cardList = this.getContent();
cardList.map(function (oCard) {
oCard.setWidth(cardWidth + "px");
oCard.setHeight(cardHeight + "rem");
});
var oPlaceHolder = this.getPlaceHolder();
if (oPlaceHolder) {
oPlaceHolder.setWidth(cardWidth + "px");
oPlaceHolder.setHeight(cardHeight + "rem");
}
};
ObjectStream.prototype.updateContent = function(reason){
/* We are updaing the content only data was change and not by refresh
* This is done due to the fact that UI5 is calling the updateContent
* twice, one with reason = 'refresh' with no data in the model and second
* with reason = 'change' with the data.
* In order to be able to have rendering optimization we are updating only when
* we have the data in the model and therefore we can reuse most of the items
* Ticket was open on this # 1570807520
*/
// in any case we need to call the oBinding.getContexts().
// it seams that this will trigger the second call with the change reason
var oBindingInfo = this.mBindingInfos["content"],
oBinding = oBindingInfo.binding,
aBindingContexts = oBinding.getContexts(oBindingInfo.startIndex, oBindingInfo.length);
if (reason === "change"){
var fnFactory = oBindingInfo.factory,
i = 0,
aItems = this.getContent(),
addNewItem = jQuery.proxy(function (oContext) {
var sId = this.getId() + "-" + jQuery.sap.uid(),
oClone = fnFactory(sId, oContext);
oClone.setBindingContext(oContext, oBindingInfo.model);
this.addContent(oClone);
}, this);
// Bind as many context as possible to existing elements. Create new ones if necessary.
for (i = 0; i < aBindingContexts.length; ++i) {
if (i < aItems.length) {
aItems[i].setBindingContext(aBindingContexts[i], oBindingInfo.model);
} else {
addNewItem(aBindingContexts[i]);
}
}
if (aItems.length > aBindingContexts.length){
// Delete unused elements.
for (; i < aItems.length; ++i) {
aItems[i].destroy();
}
// Update the array length.
aItems.length = aBindingContexts.length;
}
}
};
return ObjectStream;
}, /* bExport= */ true);
}; // end of sap/ovp/ui/ObjectStream.js
if ( !jQuery.sap.isDeclared('sap.ovp.ui.ObjectStreamRenderer') ) {
/**
* Created by i060586 on 11/25/14.
*/
jQuery.sap.declare('sap.ovp.ui.ObjectStreamRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ovp/ui/ObjectStreamRenderer",['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* Button renderer.
* @namespace
*/
var ObjectStreamRenderer = {
};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm
* the RenderManager that can be used for writing to
* the Render-Output-Buffer
* @param {sap.ui.core.Control} oButton
* the button to be rendered
*/
ObjectStreamRenderer.render = function(oRm, oControl) {
if (!oControl.getVisible()) {
return;
}
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.writeAccessibilityState(undefined, {role: "dialog"});
oRm.writeAccessibilityState(oControl, {label: oControl.getTitle()});
oRm.addClass("sapOvpObjectStream");
oRm.writeClasses();
oRm.write(">");
/*header*/
oRm.write("<div");
oRm.addClass("sapOvpObjectStreamHeader");
oRm.writeAccessibilityState(undefined, {role: "heading"});
oRm.writeClasses();
oRm.write(">" + oControl.getTitle() + "</div>");
oRm.write('<div tabindex="0" ');
oRm.addClass("sapOvpObjectStreamClose");
oRm.writeAccessibilityState(undefined, {role: "button"});
oRm.writeAccessibilityState(oControl, {label: "close"});
oRm.writeClasses();
oRm.write(">");
oRm.renderControl(oControl._closeIcon);
oRm.write("</div>");
/*header*/
oRm.write('<div id="' + oControl.getId() + '-cont" class="sapOvpObjectStreamCont"');
oRm.write(">");
oRm.write('<div id="' + oControl.getId() + '-scroll"');
oRm.writeAccessibilityState(undefined, {role: "list"});
oRm.addClass("sapOvpObjectStreamScroll");
oRm.writeClasses();
oRm.write(">");
var aContent = oControl.getContent();
aContent.forEach(function(control, i) {
oRm.write("<div class='sapOvpObjectStreamItem' ");
if (i == 0) {
oRm.write("tabindex='0' ");
} else {
oRm.write("tabindex='-1' ");
}
oRm.writeAccessibilityState(undefined, {role: "listitem"});
oRm.write("aria-setsize = " + (aContent.length + 1) + " aria-posinset = " + (i + 1));
oRm.write(">");
oRm.renderControl(control);
oRm.write("</div>");
});
var placeHolder = oControl.getPlaceHolder();
if (placeHolder){
oRm.write("<div class='sapOvpObjectStreamItem' ");
if (!aContent.length) {
oRm.write("tabindex='0'");
} else {
oRm.write("tabindex='-1'");
}
oRm.writeAccessibilityState(undefined, {role: "listitem"});
oRm.write("aria-setsize = " + (aContent.length + 1) + " aria-posinset = " + (aContent.length + 1));
oRm.write(">");
oRm.renderControl(placeHolder);
oRm.write("</div>");
}
oRm.write("</div>"); // scroll
oRm.write('<div id="' + oControl.getId() + '-leftedge" class="sapOvpOSEdgeLeft">');
oRm.renderControl(new sap.ui.core.Icon({src: "sap-icon://slim-arrow-left", useIconTooltip:false}));
oRm.write('</div>');
oRm.write('<div id="' + oControl.getId() + '-rightedge" class="sapOvpOSEdgeRight">');
oRm.renderControl(new sap.ui.core.Icon({src: "sap-icon://slim-arrow-right", useIconTooltip:false}));
oRm.write('</div>');
oRm.write("</div>"); // cont
oRm.write("</div>"); // root
};
ObjectStreamRenderer.renderFooterContent = function(oRm, oControl) {
// overrides this function
};
return ObjectStreamRenderer;
}, /* bExport= */ true);
}; // end of sap/ovp/ui/ObjectStreamRenderer.js
if ( !jQuery.sap.isDeclared('sap.ovp.ui.SmartphoneHeaderToggle') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.ui.SmartphoneHeaderToggle");
sap.ovp.ui.SmartphoneHeaderToggle = {
threshold : 10,
headerVisible : true,
startY : undefined,
app : undefined,
jqView : undefined,
startHandler : function(e) {
if (this.app.getGlobalFilter().getVisible()) {
return;
}
this.startY = e.touches[0].pageY;
},
resizeHandler : function() {
if (!this.headerVisible) {
this.animateHeader.call(this, this.headerVisible);
}
},
animateHeader : function(setVisible) {
var jqHeaderVbox = this.jqView.find('.ovpApplication > .sapUiFixFlexFixed > .sapMVBox');
var jqFlexContainerParent = this.jqView.find('.ovpApplication > .sapUiFixFlexFlexible');
var jqFlexContainer = jqFlexContainerParent.children();
var translate;
if (setVisible) {
translate = "translateY(0px)";
jqHeaderVbox.add(jqFlexContainerParent).css({"transform": translate, "-webkit-transform": translate});
jqFlexContainerParent.one('transitionend', function(e) {
if (this.headerVisible) {
jqFlexContainer.css({bottom: "0px"});
}
}.bind(this));
} else {
var headerHeight = this.view.byId('ovpPageHeader').$().height();
jqFlexContainer.css({bottom: "-" + headerHeight + "px"});
translate = "translateY(-" + headerHeight + "px)";
jqFlexContainerParent.add(jqHeaderVbox).css({"transform": translate, "-webkit-transform": translate});
}
},
moveHandler : function(e) {
var moveY = e.touches[0].pageY;
if (typeof this.startY == "undefined") {
if (this.app.getGlobalFilter().getVisible()) {
return;
}
this.startY = moveY;
}
if (Math.abs(this.startY - moveY) < this.threshold) {
return;
}
if (this.startY > moveY && this.headerVisible) {
this.headerVisible = false;
this.startY = moveY;
this.animateHeader.call(this, this.headerVisible);
}
if (this.startY < moveY && !this.headerVisible) {
this.headerVisible = true;
this.startY = moveY;
this.animateHeader.call(this, this.headerVisible);
}
},
endHandler : function() {
this.startY = undefined;
return;
},
enable : function(app) {
this.app = app;
this.view = this.app.getView();
this.jqView = this.view.$();
this.jqView.on('touchstart.headerHiding', this.startHandler.bind(this));
this.jqView.on('touchmove.headerHiding', this.moveHandler.bind(this));
this.jqView.on('touchend.headerHiding touchcancel.headerHiding touchleave.headerHiding', this.endHandler.bind(this));
jQuery(window).on("resize.headerHiding", this.resizeHandler.bind(this));
},
disable : function() {
this.jqView.off('touchstart.headerHiding touchmove.headerHiding touchend.headerHiding touchcancel.headerHiding touchleave.headerHiding');
jQuery(window).off("resize.headerHiding");
}
};
}());
}; // end of sap/ovp/ui/SmartphoneHeaderToggle.js
if ( !jQuery.sap.isDeclared('sap.ovp.ui.UIActions') ) {
/*global jQuery, sap, clearTimeout, console, window */
(function () {
"use strict";
jQuery.sap.declare("sap.ovp.ui.UIActions");
sap.ovp.ui.UIActions = function(cfg) {
if (!cfg || !cfg.rootSelector || !cfg.containerSelector || !cfg.draggableSelector) {
throw new Error("No configuration object to initialize User Interaction module.");
}
/* PRIVATE MEMBERS */
this.captureStart = null; // {Function} capture start event X and Y position
this.captureMove = null; // {Function} capture move event X and Y position
this.captureEnd = null; // {Function} capture end event X and Y position
this.clickCallback = null; // {Function} Callback function execute after capture `click` event
this.clickEvent = null; // {String} `click` event
this.clickHandler = null; // {Function} capture click event and prevent the default behaviour on IOS
this.clone = null; // {Element} cloned draggable element
this.cloneClass = null; // {String} clone CSS Class
this.container = null; // {Element} content container to be scrolled
this.contextMenuEvent = null; // {String} `contextmenu` event for Windows 8 Chrome
this.debug = false; // {Boolean} for debug mode
this.dragMoveCallback = null; // {Function} Callback function executes while drag mode is active
this.dragAndScrollDuration = null; // {Number} Scroll timer duration in ms
this.dragAndScrollTimer = null; // {Number} timer ID. Used in drag & scroll animation
this.draggable = null; // {Array<Element>|NodeList<Element>} list of draggable elements
this.placeHolderClass = null; // {String} placeholder CSS Class
this.draggableSelector = null; // {String} CSS Selector String which specifies the draggable elements
this.doubleTapCallback = null; // {Function} Callback function execute when double tap
this.doubleTapDelay = null; // {Number} number of milliseconds to recognize double tap
this.element = null; // {Element} draggable element
this.swapTargetElement = null; // {Element} draggable element to swap the current element with
this.endX = null; // {Number} X coordinate of end event
this.endY = null; // {Number} Y coordinate of end event
this.isTouch = null; // {Boolean} does browser supports touch events
this.lastElement = null; // {Element} last tapped element
this.lastTapTime = null; // {Number} number of milliseconds elapsed since last touchstart or mousedown
this.lockMode = null; // {Boolean} if the value is true, preventing change element mode
this.log = null; // {Function} logs to console in debug mode
this.mode = null; // {String} current feature mode `normal`, `scroll`, `drag`, `move`
this.mouseDownEvent = null; // {String} 'mousedown'
this.mouseMoveEvent = null; // {String} 'mousemove'
this.mouseUpEvent = null; // {String} 'mouseup'
this.moveTolerance = null; // {Number} tolerance in pixels between touchStart/mousedwon and touchMove/mousemove
this.moveX = null; // {Number} X coordinate of move event
this.moveY = null; // {Number} Y coordinate of move event
this.noop = null; // {Function} empty function
this.preventClickFlag; // {Boolean} flag indicates if prevent default click behaviour
this.preventClickTimeoutId; // {Number} timer ID. Used to clear click preventing
this.scrollContainer = null; // {Element} the element we would like to transition while drag and scroll
this.scrollContainerSelector = null; // {String} CSS Selector String which specifies the element we would like to transition while drag and scroll
this.scrollEvent = null; // {String} `scroll` event
this.scrollTimer = null; // {Number} number of milliseconds elapsed since the last scroll event
this.startX = null; // {Number} X coordinate of start event
this.startY = null; // {Number} Y coordinate of start event
this.switchModeDelay = null; // {Number} switch mode delay in ms
this.tapsNumber = null; // {Number} the number of taps. could be 0 / 1 / 2
this.timer = null; // {Number} timer ID. Used to decide mode
this.scrollHandler = null; // {Function} scroll event handler
this.touchCancelEvent = null; // {String} `touchcancel` event
this.dragStartCallback = null; // {Function} Callback function execute when drag mode is active
this.dragEndCallback = null; // {Function} Callback function execute after capture `touchend` or `mouseup` event and mode is 'drag' or 'drag-and-scroll'
this.endCallback = null; // {Function} Callback function execute after capture `touchend` or `mouseup` event
this.touchEndEvent = null; // {String} `touchend`
this.touchMoveEvent = null; // {String} `touchmove`
this.beforeDragCallback = null; // {Function} Callback function execute after capture `touchstart` or `mousedown` event
this.touchStartEvent = null; // {String} `touchstart`
this.wrapper = null; // {Element} content container parent
this.wrapperRect = null; // {Object} wrapper Bounding Rect
this.scrollEdge = 100; // {Number} edge in pixels top and bottom when scroll is starting
/**
* Initialize state using configuration
*
* @private
*/
this.init = function (cfg) {
this.startX = -1;
this.startY = -1;
this.moveX = -1;
this.moveY = -1;
this.endX = -1;
this.endY = -1;
this.noop = function() {};
this.isTouch = cfg.isTouch ? !!cfg.isTouch : false;
this.container = document.querySelector(cfg.containerSelector);
this.scrollContainerSelector = cfg.scrollContainerSelector || cfg.containerSelector;
this.switchModeDelay = cfg.switchModeDelay || 1500;
this.dragAndScrollDuration = cfg.dragAndScrollDuration || 230;
this.moveTolerance = cfg.moveTolerance === 0 ? 0 : cfg.moveTolerance || 10;
this.draggableSelector = cfg.draggableSelector;
this.mode = 'normal';
this.debug = cfg.debug || false;
this.root = document.querySelector(cfg.rootSelector);
this.tapsNumber = 0;
this.lastTapTime = 0;
this.log = this.debug ? this.logToConsole : this.noop;
this.lockMode = false;
this.placeHolderClass = cfg.placeHolderClass || "";
this.cloneClass = cfg.cloneClass || "";
this.wrapper = cfg.wrapperSelector ? document.querySelector(cfg.wrapperSelector) : this.container.parentNode;
this.clickCallback = typeof cfg.clickCallback === 'function' ? cfg.clickCallback : this.noop;
this.beforeDragCallback = typeof cfg.beforeDragCallback === 'function' ? cfg.beforeDragCallback : this.noop;
this.doubleTapCallback = typeof cfg.doubleTapCallback === 'function' ? cfg.doubleTapCallback : this.noop;
this.dragEndCallback = typeof cfg.dragEndCallback === 'function' ? cfg.dragEndCallback : this.noop;
this.endCallback = typeof cfg.endCallback === 'function' ? cfg.endCallback : this.noop;
this.dragStartCallback = typeof cfg.dragStartCallback === 'function' ? cfg.dragStartCallback : this.noop;
this.dragMoveCallback = typeof cfg.dragMoveCallback === 'function' ? cfg.dragMoveCallback : this.noop;
this.doubleTapDelay = cfg.doubleTapDelay || 500;
this.wrapperRect = this.wrapper.getBoundingClientRect();
this.scrollEvent = 'scroll';
this.touchStartEvent = 'touchstart';
this.touchMoveEvent = 'touchmove';
this.touchEndEvent = 'touchend';
this.mouseDownEvent = 'mousedown';
this.mouseMoveEvent = 'mousemove';
this.mouseUpEvent = 'mouseup';
this.contextMenuEvent = 'contextmenu';
this.touchCancelEvent = 'touchcancel';
this.clickEvent = 'click';
if (this.wrapper) {
jQuery(this.wrapper).css({"position": "absolute",
"top": 0,
"left": 0,
"right": 0,
"bottom": 0,
"-webkit-transform": "translateZ(0)",
"transform": "translateZ(0)"});
}
};
/* PRIVATE METHODS */
/**
* Iterates over array-like object and calls callback function
* for each item
*
* @param {Array|NodeList|Arguments} scope - array-like object
* @param {Function} callback - function to be called for each element in scope
* @returns {Array|NodeList|Arguments} scope
*/
this.forEach = function (scope, callback) {
/*
* NodeList and Arguments don't have forEach,
* therefore borrow it from Array.prototype
*/
return Array.prototype.forEach.call(scope, callback);
};
/**
* Returns index of item in array-like object
*
* @param {Array|NodeList|Arguments} scope - array-like object
* @param {*} item - item which index to be found
* @returns {Number} index of item in the array-like object
*/
this.indexOf = function (scope, item) {
/*
* NodeList and Arguments don't have indexOf,
* therefore borrow it from Array.prototype
*/
return Array.prototype.indexOf.call(scope, item);
};
/**
* Cuts item from array-like object and pastes before reference item
*
* @param {Array|NodeList|Arguments} scope
* @param {*} item
* @param {*} referenceItem
*/
this.insertBefore = function (scope, item, referenceItem) {
var itemIndex,
referenceItemIndex,
splice;
splice = Array.prototype.splice;
itemIndex = this.indexOf(scope, item);
referenceItemIndex = this.indexOf(scope, referenceItem);
splice.call(
scope,
referenceItemIndex - (itemIndex < referenceItemIndex ? 1 : 0),
0,
splice.call(scope, itemIndex, 1)[0]
);
};
/**
* Log to console
*
* @private
*/
this.logToConsole = function () {
window.console.log.apply(console, arguments);
};
this.getDraggableElement = function (currentElement) {
var element;
this.draggable = jQuery(this.draggableSelector, this.container);
//Since we are listening on the root element,
//we would like to identify when a draggable element is being touched.
//The target element of the event is the lowest element in the DOM hierarchy
//where the user touched the screen.
//We need to climb in the DOM tree from the target element until we identify the draggable element,
//or getting out of container scope.
while (typeof element === 'undefined' && currentElement !== this.root) {
//Only draggable tiles
if (this.indexOf(this.draggable, currentElement) >= 0) {
element = currentElement;
}
currentElement = currentElement.parentNode;
}
return element;
};
/**
* Capture X and Y coordinates of touchstart or mousedown event
*
* @param {Event} evt - touchstart or mousedowm event
* @private
*/
this.captureStart = function (evt) {
var eventObj;
if (evt.type === 'touchstart' && evt.touches.length === 1) {
eventObj = evt.touches[0];
} else if (evt.type === 'mousedown') {
eventObj = evt;
if (evt.which != 1) {//Only LEFT click operation is enabled. Otherwise do nothing.
return;
}
}
if (eventObj) {
this.element = this.getDraggableElement(eventObj.target);
this.startX = eventObj.pageX;
this.startY = eventObj.pageY;
this.lastMoveX = 0;
this.lastMoveY = 0;
//Check if it is a doubletap flow or single tap
if (this.lastTapTime && this.lastElement && this.element && (this.lastElement === this.element)
&& Math.abs(Date.now() - this.lastTapTime) < this.doubleTapDelay) {
this.lastTapTime = 0;
this.tapsNumber = 2;
} else {
this.lastTapTime = Date.now();
this.tapsNumber = 1;
this.lastElement = this.element;
}
this.log('captureStart(' + this.startX + ', ' + this.startY + ')');
}
};
/**
* Handler for `mousedown` or `touchstart`
*
* @private
*/
this.startHandler = function (evt) {
this.log('startHandler');
clearTimeout(this.timer);
delete this.timer;
this.captureStart(evt);
if (this.element) {
this.beforeDragCallback(evt, this.element);
if (this.lockMode === false) {
if (this.tapsNumber === 2) {
this.mode = 'double-tap';
return;
}
if (this.isTouch) {
this.timer = setTimeout(function () {
this.log('mode switched to drag');
this.mode = 'drag';
this.createClone();
this.dragStartCallback(evt, this.element);
}.bind(this), this.switchModeDelay);
}
}
}
}.bind(this);
/**
* Capture X and Y coordinates of touchmove or mousemove event
*
* @param {Event} evt - touchmove or mousemove event
* @private
*/
this.captureMove = function (evt) {
var eventObj;
if (evt.type === 'touchmove' && evt.touches.length === 1) {
eventObj = evt.touches[0];
} else if (evt.type === 'mousemove') {
eventObj = evt;
}
if (eventObj) {
this.moveX = eventObj.pageX;
this.moveY = eventObj.pageY;
this.log('captureMove(' + this.moveX + ', ' + this.moveY + ')');
}
};
/**
* Handler for `mousemove` or `touchmove`
*
* @private
*/
this.moveHandler = function(evt) {
var isScrolling;
this.log('moveHandler');
this.captureMove(evt);
switch (this.mode) {
case 'normal':
if ((Math.abs(this.startX - this.moveX) > this.moveTolerance || Math.abs(this.startY - this.moveY) > this.moveTolerance)) {
if (this.isTouch) {
this.log('-> normal');
clearTimeout(this.timer);
delete this.timer;
} else if (this.element) { //In desktop start dragging immediately
this.log('mode switched to drag');
this.mode = 'drag';
this.createClone();
}
}
break;
case 'drag':
evt.preventDefault();
this.log('-> drag');
this.mode = 'drag-and-scroll';
window.addEventListener(this.mouseUpEvent, this.endHandler, true);
this.translateClone();
this.scrollContainer = document.querySelector(this.scrollContainerSelector);
this.dragAndScroll();
if (!this.isTouch) {
this.dragStartCallback(evt, this.element);
}
break;
case 'drag-and-scroll':
evt.stopPropagation();
evt.preventDefault();
this.log('-> drag-and-scroll');
isScrolling = this.dragAndScroll();
this.translateClone();
this.dragMoveCallback({evt : evt, clone : this.clone, element: this.element, draggable: this.draggable, isScrolling: isScrolling, moveX : this.moveX, moveY : this.moveY});
break;
default:
break;
}
}.bind(this);
/**
* Capture X and Y coordinates of touchend or mouseup event
*
* @param {Event} evt - touchmove or mouseup event
* @private
*/
this.captureEnd = function (evt) {
var eventObj;
if ((evt.type === 'touchend' || evt.type === 'touchcancel') && (evt.changedTouches.length === 1)) {
eventObj = evt.changedTouches[0];
} else if (evt.type === 'mouseup') {
eventObj = evt;
}
if (eventObj) {
this.endX = eventObj.pageX;
this.endY = eventObj.pageY;
this.log('captureEnd(' + this.endX + ', ' + this.endY + ')');
}
};
/**
* Handler for `contextmenu` event. Disable right click on Chrome
*
* @private
*/
this.contextMenuHandler = function (evt) {
if (this.isTouch) {
evt.preventDefault();
}
}.bind(this);
/**
*
* @param event
*/
this.clickHandler = function (event) {
if (this.preventClickFlag) {
this.preventClickFlag = false;
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
clearTimeout(this.preventClickTimeoutId);
}
this.clickCallback();
}.bind(this);
/**
* This function solves a bug which causes the tile to be launched after D&D.
*/
this.preventClick = function () {
this.preventClickFlag = true;
this.preventClickTimeoutId = setTimeout(function () {
this.preventClickFlag = false;
}.bind(this), 100);
};
/**
* Handler for `mouseup` or `touchend`
*
* @private
*/
this.endHandler = function (evt) {
this.log('endHandler');
this.captureEnd(evt);
switch (this.mode) {
case 'normal':
this.log('-> normal');
break;
case 'drag':
this.log('-> drag');
this.removeClone();
this.dragEndCallback(evt, this.element);
this.preventClick();
break;
case 'drag-and-scroll':
this.log('-> drag-and-scroll');
window.removeEventListener(this.mouseUpEvent, this.endHandler, true);
this.removeClone();
this.dragEndCallback(evt, this.element);
this.preventClick();
evt.stopPropagation();
evt.preventDefault();
break;
case 'double-tap':
this.log('-> double-tap');
this.doubleTapCallback(evt, this.element);
break;
default:
break;
}
if (this.element) {
this.endCallback(evt, this.element);
}
clearTimeout(this.timer);
delete this.timer;
this.lastMoveX = 0;
this.lastMoveY = 0;
this.swapTargetElement = null;
this.element = null;
this.mode = 'normal';
}.bind(this);
this.defaultDragStartHandler = function (evt) {
//prevent the Native Drag behavior of the browser
evt.preventDefault();
};
this.scrollHandler = function() {
clearTimeout(this.scrollTimer);
this.lockMode = true;
//release the scroll lock after 100 ms
this.scrollTimer = setTimeout(function(){
this.lockMode = false;
}.bind(this), 500);
}.bind(this);
/**
* Create clone of draggable element
*
* @private
*/
this.createClone = function () {
var style,
rect;
rect = this.element.getBoundingClientRect();
this.clone = this.element.cloneNode(true);
this.clone.className += (' ' + this.cloneClass);
this.element.className += (' ' + this.placeHolderClass);
style = this.clone.style;
style.position = 'absolute';
style.display = 'block';
style.top = ( rect.top - this.root.getBoundingClientRect().top ) + 'px';
style.left = ( rect.left - this.root.getBoundingClientRect().left ) + 'px';
style.width = rect.width + 'px';
style.zIndex = '100';
style.webkitTransition = '-webkit-transform 0ms cubic-bezier(0.33, 0.66, 0.66, 1)';
style.mozTransition = '-moz-transform 0ms cubic-bezier(0.33, 0.66, 0.66, 1)';
style.msTransition = '-ms-transform 0ms cubic-bezier(0.33, 0.66, 0.66, 1)';
style.transition = 'transform 0ms cubic-bezier(0.33, 0.66, 0.66, 1)';
style.webkitTransform = 'translate3d(0px, 0px, 0px) ';
style.mozTransform = 'translate3d(0px, 0px, 0px) ';
style.msTransform = 'translate3d(0px, 0px, 0px) ';
style.transform = 'translate3d(0px, 0px, 0px) ';
this.root.appendChild(this.clone);
this.log('createClone');
};
/**
* Remove clone of draggable element
*
* @private
*/
this.removeClone = function () {
this.element.className = this.element.className.split(' ' + this.placeHolderClass).join('');
this.clone.parentElement.removeChild(this.clone);
// unset reference to DOM element of the clone, otherwise it will remain DOM fragment
this.clone = null;
this.log('removeClone');
};
/**
* Translate clone of draggable element
*
* @private
*/
this.translateClone = function () {
var deltaX,
deltaY;
deltaX = this.moveX - this.startX;
deltaY = this.moveY - this.startY;
this.clone.style.webkitTransform = 'translate3d(' + deltaX + 'px, ' + deltaY + 'px, 0px)';
this.clone.style.mozTransform = 'translate3d(' + deltaX + 'px, ' + deltaY + 'px, 0px)';
//IE9 contains only 2-D transform
this.clone.style.msTransform = 'translate(' + deltaX + 'px, ' + deltaY + 'px)';
this.clone.style.transform = 'translate3d(' + deltaX + 'px, ' + deltaY + 'px, 0px)';
this.log('translateClone (' + deltaX + ', ' + deltaY + ')');
};
/**
* Scroll while dragging if needed
*
* @private
*/
this.dragAndScroll = function () {
var
/*
* Duration of scrolling animation in milliseconds.
* Greater value makes scroll faster, lower values - smoother
*/
duration = this.dragAndScrollDuration,
style,
that = this;
function startAnimation(transitionY) {
style.webkitTransition = '-webkit-transform ' + duration + 'ms linear';
style.transition = 'transform ' + duration + 'ms linear';
style.mozTransition = '-moz-transform ' + duration + 'ms linear';
style.msTransition = '-ms-transform ' + duration + 'ms linear';
style.webkitTransform = 'translate(0px, ' + transitionY + 'px) scale(1) translateZ(0px)';
style.mozTransform = 'translate(0px, ' + transitionY + 'px) scale(1) translateZ(0px)';
style.msTransform = 'translate(0px, ' + transitionY + 'px) scale(1) translateZ(0px)';
style.transform = 'translate(0px, ' + transitionY + 'px) scale(1) translateZ(0px)';
}
function clearAnimation(transitionY) {
style.webkitTransition = '';
style.mozTransition = '';
style.msTransition = '';
style.transition = '';
style.webkitTransform = '';
style.mozTransform = '';
style.msTransform = '';
style.transform = '';
that.wrapper.scrollTop -= transitionY;
}
/*
* Indicates how much pixels of draggable element are overflowing in a vertical axis.
* When deltaY is negative - content should be scrolled down,
* when deltaY is positive - content should be scrolled up,
* when deltaY is zero - content should not be scrolled
*/
function getDeltaY() {
var wrapperRect = that.wrapper.getBoundingClientRect();
//Up
var topDiff = that.moveY - wrapperRect.top - that.scrollEdge;
if (topDiff < 0) {
return Math.abs(topDiff);
}
//Down
var bottomDiff = wrapperRect.bottom - that.moveY - that.scrollEdge;
if (bottomDiff < 0) {
return bottomDiff;
}
return 0;
}
function getNextTransitionY(deltaY) {
var possibleScroll;
var nextTransitionY = deltaY * 2;
if (deltaY < 0) {
//Down
possibleScroll = (that.wrapper.offsetHeight + that.wrapper.scrollTop) - that.wrapper.scrollHeight;
return nextTransitionY < possibleScroll ? possibleScroll : nextTransitionY;
} else if (deltaY > 0) {
//Up
possibleScroll = that.wrapper.scrollTop;
return nextTransitionY < possibleScroll ? nextTransitionY : possibleScroll;
}
return 0;
}
function start(transitionY) {
startAnimation(transitionY);
that.dragAndScrollTimer = setTimeout(function(oldTransitionY) {
clearAnimation(oldTransitionY);
that.dragAndScrollTimer = undefined;
var nextTransitionY = getNextTransitionY(getDeltaY());
if (nextTransitionY) {
start(nextTransitionY);
}
}.bind(that, transitionY), duration);
}
var nextTransitionY = getNextTransitionY(getDeltaY());
if (nextTransitionY && !this.dragAndScrollTimer) {
//in IE when reaching the drag and scroll we lose the ref to this.scrollContainer
this.scrollContainer = this.scrollContainer || document.querySelector(this.scrollContainerSelector);
style = this.scrollContainer.style;
start(nextTransitionY);
}
this.log('dragAndScroll (' + nextTransitionY + ')');
return !!nextTransitionY;
};
/* PUBLIC METHODS */
/**
* Enable feature
*
* @public
*/
this.enable = function () {
this.log('enable');
//Touch Events
this.root.addEventListener(this.touchStartEvent, this.startHandler, false);
this.root.addEventListener(this.touchMoveEvent, this.moveHandler, true);
this.root.addEventListener(this.touchEndEvent, this.endHandler, false);
this.root.addEventListener(this.touchCancelEvent, this.endHandler, false);
//Mouse Events
this.root.addEventListener(this.mouseMoveEvent, this.moveHandler, true);
this.root.addEventListener(this.mouseDownEvent, this.startHandler, false);
this.root.addEventListener(this.mouseUpEvent, this.endHandler, false);
//Additional Events
this.root.addEventListener(this.contextMenuEvent, this.contextMenuHandler, false);
this.root.addEventListener(this.clickEvent, this.clickHandler, true);
this.wrapper.addEventListener(this.scrollEvent, this.scrollHandler, false);
return this;
};
/**
* Disable feature
*
* @public
*/
this.disable = function () {
this.log('disable');
this.root.removeEventListener(this.touchStartEvent, this.startHandler, false);
this.root.removeEventListener(this.touchMoveEvent, this.moveHandler, true);
this.root.removeEventListener(this.touchEndEvent, this.endHandler, false);
this.root.removeEventListener(this.mouseDownEvent, this.startHandler, false);
this.root.removeEventListener(this.mouseMoveEvent, this.moveHandler, true);
this.root.removeEventListener(this.mouseUpEvent, this.endHandler, false);
this.root.removeEventListener(this.contextMenuEvent, this.contextMenuHandler, false);
this.root.removeEventListener(this.clickEvent, this.clickHandler, true);
this.root.removeEventListener(this.touchCancelEvent, this.endHandler, false);
this.wrapper.removeEventListener(this.scrollEvent, this.scrollHandler, false);
return this;
};
/*
* Initialize dynamic feature state
* and behaviour using configuration
*/
this.init(cfg);
/**
* @public
* @returns {{x: moveX, y: moveY}}
*/
this.getMove = function () {
return {x: this.moveX, y: this.moveY};
};
};
})();
}; // end of sap/ovp/ui/UIActions.js
if ( !jQuery.sap.isDeclared('sap.ovp.app.Main.controller') ) {
jQuery.sap.declare('sap.ovp.app.Main.controller');
(function () {
"use strict";
/*global sap, jQuery */
jQuery.sap.require('sap.ui.model.odata.ODataUtils'); // unlisted dependency retained
jQuery.sap.require('sap.ui.generic.app.navigation.service.NavigationHandler'); // unlisted dependency retained
sap.ui.controller("sap.ovp.app.Main", {
onInit: function () {
this.oCardsModels = {};
this.oLoadedComponents = {};
jQuery.sap.measure.start("ovp:GlobalFilter", "Main Controller init -> Global Filter loaded", "ovp");
jQuery.sap.measure.start("ovp:Personalization", "Main Controller init -> Personalization loaded", "ovp");
this.isInitialLoading = true;
this._initSmartVariantManagement();
this.getLayout().addStyleClass("ovpLayoutElement");
/* Appstate*/
this.oState = {};
this.oState.oSmartFilterbar = this.byId("ovpGlobalFilter");
/* Appstate */
this._initGlobalFilter();
},
//clarify with UI5 Core: why can view models not be accessed in onInit?
onBeforeRendering: function () {
},
onAfterRendering: function() {
//make sure we will not initialize more then ones
if (this.initialized){
return;
}
this.initialized = true;
this.oPersistencyVariantPromise.then(function(oVariant) {
jQuery.sap.measure.end("ovp:Personalization");
this.persistencyVariantLoaded = true;
var oCard;
this.aManifestOrderedCards = this._getCardArrayAsVariantFormat(this.getLayout().getContent());
this.aOrderedCards = this._mergeCards(this.aManifestOrderedCards, oVariant);
this._updateLayoutWithOrderedCards();
if (this.isDragAndDropEnabled()) {
this._initShowHideCardsButton();
}
jQuery.sap.measure.start("ovp:CreateLoadingCards", "Create Loading cards", "ovp");
//First create the loading card
for (var i = 0; i < this.aOrderedCards.length; i++) {
if (this.aOrderedCards[i].visibility) {
oCard = this._getCardFromManifest(this.aOrderedCards[i].id);
if (oCard) {
this.createLoadingCard(oCard);
}
}
}
jQuery.sap.measure.end("ovp:CreateLoadingCards");
//In order to add the below css class after second layout rendering which caused by this._updateLayoutWithOrderedCards()
setTimeout(function () {
this.getLayout().addStyleClass("ovpLayoutElementShow");
}.bind(this), 0);
//Second load each card component and create the card
//We would like to wait for the loading cards invocation
setTimeout(function () {
jQuery.sap.measure.start("ovp:CreateCards", "Create cards loop", "ovp");
for (var i = 0; i < this.aOrderedCards.length; i++) {
if (this.aOrderedCards[i].visibility) {
oCard = this._getCardFromManifest(this.aOrderedCards[i].id);
if (oCard) {
oCard.settings.baseUrl = this._getBaseUrl();
this._initCardModel(oCard.model);
this._loadCardComponent(oCard.template);
this.createCard(oCard);
}
}
}
jQuery.sap.measure.end("ovp:CreateCards");
}.bind(this), 10);
if (this.busyDialog) {
this.busyDialog.close();
}
}.bind(this), function(err) {
jQuery.sap.log.error("Could not load information from LREP Persistency");
jQuery.sap.log.error(err);
});
if (sap.ui.Device.system.phone) {
jQuery.sap.require("sap.ovp.ui.SmartphoneHeaderToggle");
sap.ovp.ui.SmartphoneHeaderToggle.enable(this);
}
setTimeout(function () {
if (!this.persistencyVariantLoaded) {
this.busyDialog = new sap.m.BusyDialog({text: this._getLibraryResourceBundle().getText("loading_dialog_text")});
this.busyDialog.open();
this.busyDialog.addStyleClass('sapOVPBusyDialog');
}
}.bind(this), 500);
},
_getLibraryResourceBundle : function () {
if (!this.oLibraryResourceBundle) {
this.oLibraryResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ovp");
}
return this.oLibraryResourceBundle;
},
_getCardsModel : function() {
var oUIModel = this.getView().getModel("ui");
if (!this.oCards) {
this.oCards = oUIModel.getProperty("/cards");
}
return this.oCards;
},
_getBaseUrl : function() {
var oUIModel = this.getView().getModel("ui");
if (!this.sBaseUrl) {
this.sBaseUrl = oUIModel.getProperty("/baseUrl");
}
return this.sBaseUrl;
},
_getCardFromManifest : function (sCardId) {
var aCards = this._getCardsModel();
for (var i = 0; i < aCards.length; i++) {
if (aCards[i].id === sCardId) {
return aCards[i];
}
}
return null;
},
_getCardArrayAsVariantFormat: function(aComponentContainerArray) {
var aCards = [];
for (var i = 0; i < aComponentContainerArray.length; i++) {
aCards.push({id: this._getCardId(aComponentContainerArray[i].getId()) , visibility: aComponentContainerArray[i].getVisible()});
}
return aCards;
},
_mergeCards: function (aLayoutCardsArray, oVariant) {
var variantCardsArray = (oVariant && oVariant.cards) ? oVariant.cards : [];
var oResult = [];
var sCardId;
var bCardVisibility;
var aLayoutCardsArr = (aLayoutCardsArray && aLayoutCardsArray.length) ? aLayoutCardsArray : [];
//First, we insert into the oResult the cards from the variant which exist in the oLayoutCard:
for (var i = 0; i < variantCardsArray.length; i++) {
bCardVisibility = variantCardsArray[i].visibility;
for (var j = 0; j < aLayoutCardsArr.length; j++) {
sCardId = aLayoutCardsArr[j].id;
if (variantCardsArray[i].id === sCardId) {
oResult.push({id: sCardId, visibility: bCardVisibility});
break;
}
}
}
//Second, we add additional cards from the current layout (fragment + manifest) into the end of the oResult
for (var j = 0; j < aLayoutCardsArr.length; j++) {
var isFound = false;
sCardId = aLayoutCardsArr[j].id;
bCardVisibility = aLayoutCardsArr[j].visibility;
for (var i = 0; !isFound && i < oResult.length; i++) {
if (oResult[i].id === sCardId) {
isFound = true;
}
}
if (!isFound) {
oResult.push({id: sCardId, visibility: bCardVisibility});
}
}
return oResult;
},
_updateLayoutWithOrderedCards: function() {
var oLayout = this.getLayout();
var aOrderedCards = this.aOrderedCards;
oLayout.removeAllContent();
for (var i = 0; i < aOrderedCards.length; i++) {
var oComponentContainer = this.getView().byId(aOrderedCards[i].id);
oComponentContainer.setVisible(aOrderedCards[i].visibility);
oLayout.addContent(oComponentContainer);
}
},
verifyGlobalFilterLoaded: function(){
if (this.getGlobalFilter().search()) {
return true;
}
//else make sure filter is open so user will see the required field
return false;
},
/**
* Register to the filterChange event of the filter bar in order to mark that
* one or more of the filters were changed
*/
onGlobalFilterChange: function(){
this.filterChanged = true;
},
/**
* Register to the search event of the filter bar in order to refresh all models
* with the changes in the filter bar (if there are changes) when "go" is clicked
*/
onGlobalFilterSearch: function(){
if (this.filterChanged){
var sBatchGroupId = "ovp-" + new Date().getTime();
for (var modelKey in this.oCardsModels){
if (this.oCardsModels.hasOwnProperty(modelKey)){
this.oCardsModels[modelKey].refresh(false, false, sBatchGroupId);
}
}
this.filterChanged = false;
}
},
_initGlobalFilter: function(){
var oGlobalFilter = this.getGlobalFilter();
if (!oGlobalFilter){
jQuery.sap.measure.end("ovp:GlobalFilter");
return;
}
this.oGlobalFilterLodedPromise = new Promise(function (resolve, reject){
oGlobalFilter.attachAfterVariantLoad(function(){
this.oParseNavigationPromise.done(function (oAppData, oURLParameters, sNavType) {
this._setNavigationVariantToGlobalFilter(oAppData, oURLParameters, sNavType);
}.bind(this));
this.oParseNavigationPromise.fail(function () {
jQuery.sap.log.error("Could not parse navigation variant from URL");
});
this.oParseNavigationPromise.always(function () {
if (this.verifyGlobalFilterLoaded()){
resolve();
}
}.bind(this));
}, this);
oGlobalFilter.attachInitialise(function(){
//Parse navigation variant from the URL (if exists)
this._parseNavigationVariant();
// in case no variant is selected by user then the attachAfterVariantLoad
//event is not fired, therefore we check if there is no variant we
//call the verification here
if (!oGlobalFilter.getCurrentVariantId()) {
if (this.verifyGlobalFilterLoaded()){
resolve();
}
}
}, this);
oGlobalFilter.attachSearch(function(){
//If user pressed GO, it means that the required field varification
//was allredy done by the globalFilter, therefore we can resolve the promise.
//This is needed in case some required field was empty and therefore the promise
//object was not resolved in the initial flow, we have to do it now after user
//set the filter
resolve();
this.onGlobalFilterSearch();
}, this);
oGlobalFilter.attachFilterChange(this.onGlobalFilterChange, this);
}.bind(this));
this.oGlobalFilterLodedPromise.then(function(oVariant) {
jQuery.sap.measure.end("ovp:GlobalFilter");
});
},
_loadCardComponent: function(sComponentName){
if (!this.oLoadedComponents[sComponentName]) {
jQuery.sap.measure.start("ovp:CardComponentLoad:" + sComponentName, "Card Component load", "ovp");
this.oLoadedComponents[sComponentName] = sap.ui.component.load({
name: sComponentName,
url: jQuery.sap.getModulePath(sComponentName),
async: true
});
this.oLoadedComponents[sComponentName].then(function(){
jQuery.sap.measure.end("ovp:CardComponentLoad:" + sComponentName);
});
}
},
_initCardModel: function(sCardModel){
if (this.oCardsModels[sCardModel]){
return;
}
this.oCardsModels[sCardModel] = this.getView().getModel(sCardModel);
this.oCardsModels[sCardModel].setUseBatch(true);
if (this.getGlobalFilter()){
this._overrideCardModelRead(this.oCardsModels[sCardModel]);
}
},
toggleFilterBar: function toggleFilterBar() {
var oGlobalFilter = this.getGlobalFilter();
function toOpenState(jqGlobalFilter, jqGlobalFilterWrapper, height) {
jqGlobalFilterWrapper.height(height);
jqGlobalFilter.css('top', 0);
}
function toCloseState(jqGlobalFilter, jqGlobalFilterWrapper, height) {
jqGlobalFilterWrapper.height(0);
jqGlobalFilter.css("top", "-" + height + "px");
}
var isVisible = oGlobalFilter.getVisible();
if ((sap.ui.Device.system.phone) || (sap.ui.Device.system.tablet)) {
oGlobalFilter.setVisible(!isVisible);
return;
}
if (toggleFilterBar.animationInProcess) {
return;
}
toggleFilterBar.animationInProcess = true;
if (isVisible) {
var jqGlobalFilter = jQuery(oGlobalFilter.getDomRef());
var jqGlobalFilterWrapper = jQuery(this.getView().byId("ovpGlobalFilterWrapper").getDomRef());
var height = jqGlobalFilterWrapper.height();
toOpenState(jqGlobalFilter, jqGlobalFilterWrapper, height);
jqGlobalFilterWrapper.height(); //make browser render css change
jqGlobalFilterWrapper.one('transitionend', function(e) {
oGlobalFilter.setVisible(false); //set filterbar invisible in case shell wants to reRender it
toggleFilterBar.animationInProcess = false;
});
toCloseState(jqGlobalFilter, jqGlobalFilterWrapper, height);
} else {
oGlobalFilter.setVisible(true);
setTimeout(function () { //we need this to wait for globalFilter renderer
var jqGlobalFilter = jQuery(oGlobalFilter.getDomRef());
var jqGlobalFilterWrapper = jQuery(this.getView().byId("ovpGlobalFilterWrapper").getDomRef());
var height = jqGlobalFilter.outerHeight();
toCloseState(jqGlobalFilter, jqGlobalFilterWrapper, height);
jqGlobalFilterWrapper.height(); //make browser render css change
jqGlobalFilterWrapper.one('transitionend', function(e) {
jqGlobalFilterWrapper.css("height", "auto");
toggleFilterBar.animationInProcess = false;
});
toOpenState(jqGlobalFilter, jqGlobalFilterWrapper, height);
}.bind(this));
}
},
/**
* This function is overriding the read function of the oDataModel with a function that will
* first find the relevant filters from the filter bar and then will call the original
* read function with the relevant filters as parameters.
* @param oModel
* @private
*/
_overrideCardModelRead: function(oModel){
var fOrigRead = oModel.read;
var that = this;
oModel.read = function(){
var aFilters = that.getGlobalFilter().getFilters();
var oParameters = arguments[1];
if (!oParameters) {
oParameters = {};
Array.prototype.push.call(arguments, oParameters);
}
var oEntityType = that._getEntityTypeFromPath(oModel, arguments[0], oParameters.context);
if (oEntityType){
var aRelevantFIlters = that._getEntityRelevantFilters(oEntityType, aFilters);
if (aRelevantFIlters.length > 0){
var foundIndex = -1;
var aUrlParams = oParameters.urlParameters;
if (aUrlParams){
for (var index = 0; index < aUrlParams.length; index++){
// We use here lastIndexOf instead of startsWith because it doesn't work on safari (ios devices)
if ((aUrlParams[index]).lastIndexOf("$filter=", 0) === 0){
foundIndex = index;
break;
}
}
}
if (foundIndex >= 0) {
aUrlParams[foundIndex] =
aUrlParams[foundIndex] + "%20and%20" +
sap.ui.model.odata.ODataUtils.createFilterParams(aRelevantFIlters, oModel.oMetadata, oEntityType).substr(8);
} else {
oParameters.filters = aRelevantFIlters;
}
}
}
fOrigRead.apply(oModel, arguments);
};
},
/**
* This is a temporary function used to retrieve the EntityType from a given path to an entity.
* This function is required due to fact that the function _getEntityTypeByPath of the ODataMetadata is not public.
* @param oModel
* @param sPath
* @param oContext
* @returns {object}
* @private
*/
_getEntityTypeFromPath: function(oModel, sPath, oContext){
//TODO need to request UI5 to have this a public API!!!!
var sNormPath = sap.ui.model.odata.v2.ODataModel.prototype._normalizePath.apply(oModel, [sPath, oContext]);
var oEntityType = sap.ui.model.odata.ODataMetadata.prototype._getEntityTypeByPath.apply(oModel.oMetadata, [sNormPath]);
return oEntityType;
},
/**
* This function goes over the provided list of filters and checks which filter appears as a field
* in the EntityType provided. The fields that appears in both lists (filters and EntityType fields)
* will be returned in an array.
* @param oEntityType
* @param aFilters
* @returns {array}
* @private
*/
_getEntityRelevantFilters: function(oEntityType, aFilters){
var aRelevantFiltes = [];
if (aFilters.length) {
var allFilters = aFilters[0].aFilters;
var entityProperties = oEntityType.property;
for (var i = 0; i < allFilters.length; i++) {
var currentFilterName;
if (allFilters[i].aFilters) {
currentFilterName = allFilters[i].aFilters[0].sPath;
} else {
currentFilterName = allFilters[i].sPath;
}
for (var j = 0; j < entityProperties.length; j++) {
if (entityProperties[j].name === currentFilterName) {
aRelevantFiltes.push(allFilters[i]);
break;
}
}
}
}
// Retaining the default OR/AND operation
if (aRelevantFiltes.length != 0) {
var aRelevantFilWrap = [];
aRelevantFilWrap.push(new sap.ui.model.Filter(aRelevantFiltes, aFilters[0].bAnd));
return aRelevantFilWrap;
}
return aRelevantFiltes;
},
/*
Check derived Card Component is implemented with respect to the below restrictions:
Custom card must be instance of sap.ovp.cards.generic.Component. In other words, custom card must extend sap.ovp.cards.generic.Component.
If sap.ovp.cards.generic.Card view is replaced by another custom View it means the custom card is not valid.
[If the extended Component has customization (under the component metadata) and the sap.ovp.cards.generic.Card is replaced by another view (using sap.ui.viewReplacements)]
If the extended Component overrides the createContent function of the base sap.ovp.cards.generic.Component class, the custom card is not valid.
If the extended Component overrides the getPreprocessors function of the base sap.ovp.cards.generic.Component class, the custom card is not valid.
*/
_checkIsCardValid: function (sCardTemplate) {
var sComponentClassName = sCardTemplate + ".Component";
var oComponentMetadata, oCustomizations;
jQuery.sap.require(sComponentClassName);
var oComponentClass = jQuery.sap.getObject(sComponentClassName);
if (!oComponentClass) {
return false;
}
if ((oComponentClass !== sap.ovp.cards.generic.Component) && !(oComponentClass.prototype instanceof sap.ovp.cards.generic.Component)) {
return false;
}
if ((oComponentMetadata = oComponentClass.getMetadata()) && (oCustomizations = oComponentMetadata.getCustomizing())) {
//if OVP Card view was replaced
if (oCustomizations["sap.ui.viewReplacements"] && oCustomizations["sap.ui.viewReplacements"]["sap.ovp.cards.generic.Card"]) {
return false;
}
}
if (oComponentClass.prototype.createContent != sap.ovp.cards.generic.Component.prototype.createContent) {
return false;
}
if (oComponentClass.prototype.getPreprocessors != sap.ovp.cards.generic.Component.prototype.getPreprocessors) {
return false;
}
return true;
},
_createCardComponent: function (oView, oModel, card) {
var sId = "ovp:CreateCard-" + card.template + ":" + card.id;
jQuery.sap.measure.start(sId, "Create Card", "ovp");
var oi18nModel = this.getView().getModel("@i18n");
if (card.template && this._checkIsCardValid(card.template)) {
var oComponentConfig = {
name: card.template,
componentData: {
model: oModel,
i18n: oi18nModel,
settings: card.settings,
appComponent: this.getOwnerComponent()
}
};
var oGlobalFilter = this.getGlobalFilter();
if (oGlobalFilter) {
oComponentConfig.componentData.globalFilter = {
getFilterDataAsString : oGlobalFilter.getDataSuiteFormat.bind(oGlobalFilter)
};
}
var oComponent = sap.ui.component(oComponentConfig);
var oComponentContainer = oView.byId(card.id);
var oOldCard = oComponentContainer.getComponentInstance();
oComponentContainer.setComponent(oComponent);
if (oOldCard){
//currently the old component is not destroyed when setting a different component
//so we need to do that in timeout to make sure that it will not be destoroyed
//too early, before real card will be rendered on the screen.
setTimeout(function(){
oOldCard.destroy();
}, 0);
}
} else {
// TODO: define the proper behavior indicating a card loading failure
jQuery.sap.log.error("Could not create Card from '" + card.template + "' template. Card is not valid.");
}
jQuery.sap.measure.end(sId);
},
createLoadingCard: function(card, opacityDelay){
/*
* we have to make sure metadata and filter are loaded before we create the card
* so we first create loading card and once all promises will be resulved
* we will create the real card and replace the loading card
*/
var loadingCard = jQuery.extend(true, {}, card, {template: "sap.ovp.cards.loading", settings: {opacityDelay: opacityDelay}});
this._createCardComponent(this.getView(), undefined, loadingCard);
},
createCard: function(card){
var oView = this.getView();
var oModel = oView.getModel(card.model);
///*
// * we have to make sure metadata and filter are loaded before we create the card
// * so we first create loading card and once all promises will be resulved
// * we will create the real card and replace the loading card
// */
Promise.all([
oModel.getMetaModel().loaded(),
this.oGlobalFilterLodedPromise,
this.oLoadedComponents[card.template]]
).then(
function() {
this._createCardComponent(oView, oModel, card);
}.bind(this),
function(reason) {
jQuery.sap.log.error("Can't load card with id:'" + card.id + "' and type:'" + card.template + "', reason:" + reason);
}
);
},
/**
* The function gets an UI5 generated id and returns the element original Id
*
* @param {string} generatedId - the UI5 generated id
* @param {string} elementId - the element original id
*/
_getCardId: function(generatedId) {
var appIdString = this.getView().getId() + "--";
if (generatedId.indexOf(appIdString) != -1) {
var start = generatedId.indexOf(appIdString) + appIdString.length;
return generatedId.substr(start);
}
return generatedId;
},
_initSmartVariantManagement: function () {
var oPersistencyControl = this._createPersistencyControlForSmartVariantManagement();
var oOVPVariantInfo = new sap.ui.comp.smartvariants.PersonalizableInfo({
type: "OVPVariant",
keyName: "persistencyKey",
control: oPersistencyControl
});
this.oPersistencyVariantPromise = new Promise(function(resolve, reject) {
this.smartVariandManagement = new sap.ui.comp.smartvariants.SmartVariantManagement({
personalizableControls: oOVPVariantInfo,
initialise: function(oEvent) {
var aKeys = oEvent.getParameters().variantKeys;
if (aKeys.length) { //the user has already a variant
resolve(this.smartVariandManagement.getVariantContent(oPersistencyControl, aKeys[0]));
} else { //the user do not have have any variant
resolve(null);
}
}.bind(this)
});
this.smartVariandManagement.initialise();
}.bind(this));
},
layoutChanged: function() {
var aContent = this.getLayout().getContent();
this.aOrderedCards = this._getCardArrayAsVariantFormat(aContent);
this.saveVariant();
},
saveVariant: function(oEvent) {
var that = this;
this.smartVariandManagement.getVariantsInfo(function(aVariants) {
var oPersonalisationVariantKey = null;
if (aVariants && aVariants.length > 0) {
oPersonalisationVariantKey = aVariants[0].key;
}
var bOverwrite = oPersonalisationVariantKey !== null;
var oParams = {
name: "Personalisation",
global: false,
overwrite: bOverwrite,
key: oPersonalisationVariantKey,
def: true
};
that.smartVariandManagement.fireSave(oParams);
});
},
getLayout: function() {
return this.getView().byId("ovpLayout");
},
_createPersistencyControlForSmartVariantManagement: function() {
var that = this;
sap.ui.core.Control.extend("sap.ovp.app.PersistencyControl", {
metadata: {
properties: {
persistencyKey : {type : "string", group : "Misc", defaultValue : null}
}
}
});
var oPersistencyControl = new sap.ovp.app.PersistencyControl({persistencyKey:"ovpVariant"});
/**
* Interface function for SmartVariantManagment control, returns the current used variant data
*
* @public
* @returns {json} The currently set variant
*/
oPersistencyControl.fetchVariant = function () {
//in the initial loading the variant is not saved
if (that.isInitialLoading) {
that.isInitialLoading = false;
return {};
}
var oLayout = this.getLayout();
if (!oLayout) {
jQuery.sap.log.error("Could not save persistency variant - 'ovpLayout' does not exists");
return;
}
var aLayoutContent = oLayout.getContent();
var aContentForSave = this._getCardArrayAsVariantFormat(aLayoutContent);
this.oOrderedCards = aContentForSave;
return {cards: aContentForSave};
}.bind(this);
return oPersistencyControl;
},
_initShowHideCardsButton: function() {
var srvc, oCardMenuButton;
var srvc = sap.ushell.services.AppConfiguration;
var oCardMenuButton = new sap.m.Button().addStyleClass("ovpManageCardsBtn");
oCardMenuButton.setIcon('sap-icon://dimension');
oCardMenuButton.setTooltip(this._getLibraryResourceBundle().getText("hideCardsBtn_tooltip"));
oCardMenuButton.setText(this._getLibraryResourceBundle().getText("hideCardsBtn_title"));
oCardMenuButton.attachPress((this._onCardMenuButtonPress).bind(this));
srvc.addApplicationSettingsButtons([oCardMenuButton]);
},
_onCardMenuButtonPress : function() {
var oModel;
function getCardIndexInArray(aCardsArr, cardId) {
for (var i = 0; i < aCardsArr.length; i++) {
if (aCardsArr[i].id == cardId) {
return i;
}
}
return -1;
}
function createOrDestroyCards(aOldContent, aNewContent) {
var oldIndex = -1;
for (var i = 0; i < aNewContent.length ; i++) {
//In case the card position has been changed, we need to get the card index in the old array.
//Otherwise, the new and the old position are the same
if (aOldContent[i].id == aNewContent[i].id) {
oldIndex = i;
} else {
oldIndex = getCardIndexInArray(aOldContent, aNewContent[i].id);
}
if (aNewContent[i].visibility != aOldContent[oldIndex].visibility) {
if (aNewContent[i].visibility === true) {
var oCard = this._getCardFromManifest(aNewContent[i].id);
if (oCard) {
this.createLoadingCard(oCard);
oCard.settings.baseUrl = this._getBaseUrl();
this._initCardModel(oCard.model);
this._loadCardComponent(oCard.template);
this.createCard(oCard);
}
} else {
var oOldComponentContainer = this.getView().byId(aNewContent[i].id);
var oOldCard = oOldComponentContainer.getComponentInstance();
if (oOldCard) {
oOldCard.destroy();
}
}
}
}
}
function cardTitleFormatter(id) {
var oCard = this._getCardFromManifest(id);
var cardSettings = oCard.settings;
if (cardSettings.title) {
return cardSettings.title;
} else if (cardSettings.category) {
return (cardSettings.category);
} else if (cardSettings.description) {
return cardSettings.description;
}
return id;
}
var oCardsTableTemplate = new sap.m.ColumnListItem({
cells: [
new sap.m.Text({text: {path: "id", formatter: cardTitleFormatter.bind(this) }}),
new sap.m.Switch({
state: "{visibility}",
customTextOff: " ",
customTextOn: " ",
change: function (event) {
var parent = event.oSource.getParent();
parent.toggleStyleClass('sapOVPHideCardsTableItem');
parent.getCells()[0].toggleStyleClass('sapOVPHideCardsDisabledCell');
},
tooltip: this._getLibraryResourceBundle().getText("hideCards_switchTooltip")
})
]
});
var oCardsTable = new sap.m.Table("sapOVPHideCardsTable", {
backgroundDesign: sap.m.BackgroundDesign.Transparent,
showSeparators: sap.m.ListSeparators.Inner,
columns: [
new sap.m.Column({
vAlign: "Middle"
}),
new sap.m.Column({
hAlign: sap.ui.core.TextAlign.Right,
vAlign: "Middle",
width: "4.94rem"
})
]
});
oCardsTable.addStyleClass('sapOVPHideCardsTable');
oCardsTable.bindItems({
path: "/cards",
template: oCardsTableTemplate
});
var oOrigOnAfterRendering = oCardsTable.onAfterRendering;
oCardsTable.onAfterRendering = function (event) {
oOrigOnAfterRendering.apply(oCardsTable, arguments);
var items = event.srcControl.mAggregations.items;
if (items) {
for (var i = 0; i < items.length; i++) {
if (!items[i].getCells()[1].getState()) {
items[i].addStyleClass('sapOVPHideCardsTableItem');
items[i].getCells()[0].addStyleClass('sapOVPHideCardsDisabledCell');
}
}
}
setTimeout(function () {
jQuery('.sapMListTblRow').first().focus();
}, 200);
};
var oSaveButton = new sap.m.Button("manageCardsokBtn", {
text: this._getLibraryResourceBundle().getText("okBtn"),
press: function () {
var aDialogCards = this.oDialog.getModel().getProperty('/cards');
createOrDestroyCards.apply(this, [this.aOrderedCards, aDialogCards]);
this.aOrderedCards = aDialogCards;
this._updateLayoutWithOrderedCards();
this.saveVariant();
this.oDialog.close();
}.bind(this)
});
var oCancelButton = new sap.m.Button("manageCardsCancelBtn", {
text: this._getLibraryResourceBundle().getText("cancelBtn"),
press: function () {
this.oDialog.close();
}.bind(this)
});
var oResetButton = new sap.m.Button("manageCardsResetBtn", {
text: this._getLibraryResourceBundle().getText("resetBtn"),
press: function () {
sap.m.MessageBox.show(this._getLibraryResourceBundle().getText("reset_cards_confirmation_msg"), {
id: "resetCardsConfirmation",
icon: sap.m.MessageBox.Icon.QUESTION,
title: this._getLibraryResourceBundle().getText("reset_cards_confirmation_title"),
actions: [sap.m.MessageBox.Action.OK, sap.m.MessageBox.Action.CANCEL],
onClose : function (oAction) {
if (oAction === sap.m.MessageBox.Action.OK) {
this.smartVariandManagement.getVariantsInfo(function(aVariants) {
var oPersonalisationVariantKeys = null;
if (aVariants && aVariants.length > 0) {
oPersonalisationVariantKeys = aVariants[0].key;
this.smartVariandManagement.fireManage({
deleted: [oPersonalisationVariantKeys]
});
}
createOrDestroyCards.apply(this,[this.aOrderedCards,this.aManifestOrderedCards]);
this.aOrderedCards = this.aManifestOrderedCards;
this._updateLayoutWithOrderedCards();
this.oDialog.close();
}.bind(this));
}
}.bind(this)
});
}.bind(this)
});
this.oDialog = new sap.m.Dialog({
title: this._getLibraryResourceBundle().getText("hideCardsBtn_title"),
contentWidth : "29.6rem",
contentHeight : "50%",
stretch: sap.ui.Device.system.phone,
content : oCardsTable,
buttons: [oResetButton, oSaveButton,oCancelButton],
afterClose: function () {
this.oDialog.destroy();
}.bind(this)
}).addStyleClass("sapOVPCardsVisibilityDialog");
var oDialogCardsModel = jQuery.extend(true, [], this.aOrderedCards);
oModel = new sap.ui.model.json.JSONModel({cards : oDialogCardsModel});
this.oDialog.setModel(oModel);
this.oDialog.open();
},
isDragAndDropEnabled : function () {
return !sap.ui.Device.system.phone;
},
getGlobalFilter : function () {
if (!this.oGlobalFilter) {
this.oGlobalFilter = this.getView().byId("ovpGlobalFilter");
}
return this.oGlobalFilter;
},
_parseNavigationVariant : function () {
var oGlobalFilter = this.getGlobalFilter();
if (oGlobalFilter) {
this.oNavigationHandler = this.oNavigationHandler || new sap.ui.generic.app.navigation.service.NavigationHandler(this);
this.oParseNavigationPromise = this.oNavigationHandler.parseNavigation();
jQuery.sap.require("sap.ovp.cards.CommonUtils");
sap.ovp.cards.CommonUtils.enable(this,this.oNavigationHandler);
} else {
// still initialize the global nav handler
jQuery.sap.require("sap.ovp.cards.CommonUtils");
this.oNavigationHandler = this.oNavigationHandler || new sap.ui.generic.app.navigation.service.NavigationHandler(this);
sap.ovp.cards.CommonUtils.enable(this,this.oNavigationHandler);
}
},
_setNavigationVariantToGlobalFilter: function (oAppData, oURLParameters, sNavType) {
if (sNavType !== sap.ui.generic.app.navigation.service.NavType.initial) {
var oGlobalFilter = this.getGlobalFilter();
var bHasOnlyDefaults = oAppData && oAppData.bNavSelVarHasDefaultsOnly;
var oSelectionVariant = new sap.ui.generic.app.navigation.service.SelectionVariant(oAppData.selectionVariant);
var aSelectionVariantProperties = oSelectionVariant.getParameterNames().concat(oSelectionVariant.getSelectOptionsPropertyNames());
for (var i = 0; i < aSelectionVariantProperties.length; i++) {
oGlobalFilter.addFieldToAdvancedArea(aSelectionVariantProperties[i]);
}
if (!bHasOnlyDefaults || oGlobalFilter.getCurrentVariantId() === "") {
// A default variant could be loaded. We have to clear the variant and we have to clear all the selections
// in the Smart Filter Bar.
oGlobalFilter.clearVariantSelection();
oGlobalFilter.clear();
oGlobalFilter.setDataSuiteFormat(oAppData.selectionVariant, true);
}
}
}
/* Appstate *//*
getCurrentAppState: function() {
var oSelectionVariant = new sap.ui.generic.app.navigation.service.SelectionVariant(this.oState.oSmartFilterbar.getDataSuiteFormat());
return {
selectionVariant: oSelectionVariant.toJSONString()
};
},
storeCurrentAppStateAndAdjustURL: function(oCurrentAppState) {
// oCurrentAppState is optional
// - nothing, if NavigationHandler not available
// - adjusts URL immediately
// - stores appState for this URL (asynchronously)
oCurrentAppState = oCurrentAppState || this.getCurrentAppState();
try {
var oNavigationHandler = new sap.ui.generic.app.navigation.service.NavigationHandler(this);
oNavigationHandler.storeInnerAppState(oCurrentAppState);
} catch (err) {
jQuery.sap.log.error("OVP.storeCurrentAppStateAndAdjustURL: " + err);
}
},
onSearchButtonPressed: function() {
//store navigation context
this.storeCurrentAppStateAndAdjustURL();
}
*//* Appstate */
});
}());
}; // end of sap/ovp/app/Main.controller.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.charts.generic.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.charts.generic.Component");
sap.ovp.cards.generic.Component.extend("sap.ovp.cards.charts.generic.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"headerExtensionFragment":{
"type": "string",
"defaultValue": "sap.ovp.cards.generic.KPIHeader"
},
"selectionAnnotationPath":{
"type": "string",
"defaultValue": "com.sap.vocabularies.UI.v1.SelectionVariant"
},
"chartAnnotationPath":{
"type": "string",
"defaultValue": "com.sap.vocabularies.UI.v1.Chart"
},
"presentationAnnotationPath":{
"type": "string",
"defaultValue": "com.sap.vocabularies.UI.v1.PresentationVariant"
},
"identificationAnnotationPath":{
"type": "string",
"defaultValue": "com.sap.vocabularies.UI.v1.Identification"
},
"dataPointAnnotationPath":{
"type": "string",
"defaultValue": "com.sap.vocabularies.UI.v1.DataPoint"
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m" ],
components: []
},
config: {}
},
addTabindex: function() {
jQuery(".tabindex0").attr("tabindex", 0);
},
onAfterRendering: function() {
this.addTabindex();
}
});
})();
}; // end of sap/ovp/cards/charts/generic/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.charts.line.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.charts.line.Component");
sap.ovp.cards.charts.generic.Component.extend("sap.ovp.cards.charts.line.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"contentFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.charts.line.LineChart"
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m","sap.viz" ],
components: []
},
config: {},
customizing: {
"sap.ui.controllerExtensions": {
"sap.ovp.cards.generic.Card": {
controllerName: "sap.ovp.cards.charts.line.LineChart"
}
}
}
}
});
})();
}; // end of sap/ovp/cards/charts/line/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.stack.Stack.controller') ) {
jQuery.sap.declare('sap.ovp.cards.stack.Stack.controller');
(function () {
"use strict";
/*global sap, jQuery */
sap.ui.controller("sap.ovp.cards.stack.Stack", {
onInit: function () {
var oVbox = this.getView().byId("stackContent");
oVbox.addEventDelegate({
onclick: this.openStack.bind(this),
//when space or enter is pressed on stack card, we open ObjectStream
onkeydown: function (oEvent) {
if (!oEvent.shiftKey && (oEvent.keyCode == 13 || oEvent.keyCode == 32)) {
oEvent.preventDefault();
this.openStack();
}
}.bind(this)
});
},
onExit: function() {
if (this.oObjectStream) {
this.oObjectStream.destroy();
}
},
onAfterRendering: function () {
var oView = this.getView();
var oModel = oView.getModel();
var oCardPropsModel = oView.getModel("ovpCardProperties");
var sEntitySet = oCardPropsModel.getProperty("/entitySet");
var oObjectStreamCardsSettings = oCardPropsModel.getProperty("/objectStreamCardsSettings");
var oMetaModel = oModel.getMetaModel();
var oEntitySet = oMetaModel.getODataEntitySet(sEntitySet);
var oEntityType = oMetaModel.getODataEntityType(oEntitySet.entityType);
//in order to support auto expand, the annotationPath property contains a "hint" to the
//annotaionPath of the stack card content. There might be more then 1 annotationPath value due to support of Facets
var sAnnotationPath = oCardPropsModel.getProperty("/annotationPath");
var aAnotationPath = (sAnnotationPath) ? sAnnotationPath.split(",") : [];
function getSetting(sKey){
if (sKey === "ovpCardProperties"){
return oCardPropsModel;
} else if (sKey === "dataModel"){
return oModel;
} else if (sKey === "_ovpCache"){
return {};
}
}
var aFormatItemsArguments = [{getSetting: getSetting}, oEntitySet].concat(aAnotationPath);
var sBindingInfo = sap.ovp.cards.AnnotationHelper.formatItems.apply(this,aFormatItemsArguments);
var oBindingInfo = sap.ui.base.BindingParser.complexParser(sBindingInfo);
var sObjectStreamCardsNavigationProperty = oCardPropsModel.getProperty("/objectStreamCardsNavigationProperty");
var bStackFlavorAssociation = sObjectStreamCardsNavigationProperty ? true : false;
var oStackFilterMapping;
var sObjectStreamCardsTemplate = oCardPropsModel.getProperty("/objectStreamCardsTemplate");
// if we are in the association-flavor scenario we need to determine bot filter AND entity set for the object stream cards
if (bStackFlavorAssociation) {
if (sObjectStreamCardsTemplate === "sap.ovp.cards.quickview"){
jQuery.sap.log.error("objectStreamCardsTemplate cannot be 'sap.ovp.cards.quickview' when objectStreamCardsNavigationProperty is provided");
this.setErrorState();
return;
}
oStackFilterMapping = this._determineFilterPropertyId(oModel, oEntitySet, oEntityType, sObjectStreamCardsNavigationProperty);
oObjectStreamCardsSettings.entitySet = oModel.getMetaModel().getODataAssociationSetEnd(oEntityType, sObjectStreamCardsNavigationProperty).entitySet;
} else {
if (sObjectStreamCardsTemplate !== "sap.ovp.cards.quickview"){
jQuery.sap.log.error("objectStreamCardsTemplate must be 'sap.ovp.cards.quickview' when objectStreamCardsNavigationProperty is not provided");
this.setErrorState();
return;
}
// we are in the regular scenario (QuickView cards for collection entities)
if (!oObjectStreamCardsSettings.category){
if (oEntityType["com.sap.vocabularies.UI.v1.HeaderInfo"] &&
oEntityType["com.sap.vocabularies.UI.v1.HeaderInfo"].TypeName &&
oEntityType["com.sap.vocabularies.UI.v1.HeaderInfo"].TypeName.String ) {
oObjectStreamCardsSettings.category = oEntityType["com.sap.vocabularies.UI.v1.HeaderInfo"].TypeName.String;
} else {
oObjectStreamCardsSettings.category = oEntityType.name;
}
}
oObjectStreamCardsSettings.entitySet = sEntitySet;
}
oBindingInfo.factory = function (sId, oContext) {
var oSettings = oObjectStreamCardsSettings, oFilters;
if (bStackFlavorAssociation) {
oFilters = {
filters : [{
path : oStackFilterMapping.foreignKey,
operator: "EQ",
value1: oContext.getProperty(oStackFilterMapping.key)
}]};
oSettings = jQuery.extend(oFilters, oObjectStreamCardsSettings);
}
var oComponent = sap.ui.component({
name: oCardPropsModel.getProperty("/objectStreamCardsTemplate"),
componentData: {
model: oModel,
settings: oSettings
}
});
var oCardComp = new sap.ui.core.ComponentContainer({component: oComponent});
/* we need to override the setBindingContext method as from some reason
* when calling it on the container its not set on the inner component
*/
oCardComp.setBindingContext = function(oContext){
oComponent.setBindingContext(oContext);
};
return oCardComp;
};
this.oObjectStream = new sap.ovp.ui.ObjectStream({
title: oCardPropsModel.getObject("/category"),
content: oBindingInfo
});
this.oObjectStream.setModel(oModel);
// place holder card is relevant only for the regular Stack-Card flavor (not the AssociationSet flavor)
if (!bStackFlavorAssociation) {
//Check if we have navigate target, if there is create placeHolder card and set it
var aNavigationFields = this.getEntityNavigationEntries();
if (aNavigationFields.length > 0) {
var sAppName = aNavigationFields[0].label;
var oPlaceHolder = this._createPlaceHolder(sAppName);
var that = this;
oPlaceHolder.addEventDelegate({
onclick: function () {
that.doNavigation(null);
}
});
this.oObjectStream.setPlaceHolder(oPlaceHolder);
}
}
var oListBinding = this.oObjectStream.getBinding("content");
oListBinding.attachDataReceived(function () {
var nCardCount = oListBinding.getCurrentContexts().length;
oView.byId("stackSize").setText(nCardCount);
var stackContentDomRef = this.getView().byId("stackContent").getDomRef();
jQuery(stackContentDomRef).attr("aria-label", sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("stackCardContent", [nCardCount]));
var stackSizeDomRef = this.getView().byId("stackSize").getDomRef();
jQuery(stackSizeDomRef).attr("aria-label", sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("stackCard", [nCardCount]));
}, this);
},
_determineFilterPropertyId : function(oModel, oEntitySet, oEntityType, sNavigationProperty) {
var oNavigationProperty, ns = oEntityType.namespace, sRelationshipName, oAssociation;
// find the relevant navigation property on the entity type
for (var i = 0; i < oEntityType.navigationProperty.length; i++) {
if (oEntityType.navigationProperty[i].name === sNavigationProperty) {
oNavigationProperty = oEntityType.navigationProperty[i];
break;
}
}
// find the Association ID / object which is the navigation property relationship member
sRelationshipName = oNavigationProperty.relationship;
oAssociation = sap.ovp.cards.AnnotationHelper.getAssociationObject(oModel, sRelationshipName, ns);
// find the filter value for stack card - by looking at the Association Object
var oRefs = oAssociation.referentialConstraint, filterMapping = {};
if (oRefs) {
filterMapping.foreignKey = oRefs.dependent.propertyRef[0].name;
filterMapping.key = oRefs.principal.propertyRef[0].name;
return filterMapping;
}
},
_createPlaceHolder: function (sAppName) {
var iIcon = new sap.ui.core.Icon({
src: "sap-icon://offsite-work",
useIconTooltip: false,
layoutData: new sap.m.FlexItemData({growFactor : 1, alignSelf: sap.m.FlexAlignSelf.Center})
});
iIcon.addStyleClass("sapOvpStackPlaceHolderIcon");
var lbAppName = new sap.m.Label({text: sAppName});
var strText = sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("ForMoreContentAppName", [sAppName]);
var txtText = new sap.m.Text({text: strText});
txtText.addCustomData(new sap.ovp.ui.CustomData({
key: "role",
value: "heading",
writeToDom: true
}));
txtText.addCustomData(new sap.ovp.ui.CustomData({
key: "aria-label",
value: strText,
writeToDom: true
}));
lbAppName.addStyleClass("sapOvpStackPlaceHolderAppName");
txtText.addStyleClass("sapOvpStackPlaceHolderTextLine");
var oDivVbox = new sap.m.VBox({items: [lbAppName, txtText]});
oDivVbox.addStyleClass("sapOvpStackPlaceHolderLabelsContainer");
oDivVbox.addCustomData(new sap.ovp.ui.CustomData({
key: "tabindex",
value: "0",
writeToDom: true
}));
oDivVbox.addCustomData(new sap.ovp.ui.CustomData({
key: "role",
value: "button",
writeToDom: true
}));
var oVbox = new sap.m.VBox({items: [iIcon, oDivVbox]});
oVbox.addStyleClass("sapOvpStackPlaceHolder");
oVbox.addEventDelegate({
//when space or enter is pressed on Placeholder, we trigger click
onkeydown: function (oEvent) {
if (!oEvent.shiftKey && (oEvent.keyCode == 13 || oEvent.keyCode == 32)) {
oEvent.preventDefault();
oEvent.srcControl.$().click();
}
}
});
return oVbox;
},
openStack: function () {
if (this.oObjectStream){
var oListBinding = this.oObjectStream.getBinding("content");
if (oListBinding.getCurrentContexts().length > 0){
var cardWidth = this.getView().$().width();
this.oObjectStream.open(cardWidth);
}
}
}
});
})();
}; // end of sap/ovp/cards/stack/Stack.controller.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.charts.bubble.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.charts.bubble.Component");
sap.ovp.cards.charts.generic.Component.extend("sap.ovp.cards.charts.bubble.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"contentFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.charts.bubble.BubbleChart"
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m","sap.viz" ],
components: []
},
config: {},
customizing: {
"sap.ui.controllerExtensions": {
"sap.ovp.cards.generic.Card": {
controllerName: "sap.ovp.cards.charts.bubble.BubbleChart"
}
}
}
}
});
})();
}; // end of sap/ovp/cards/charts/bubble/Component.js
if ( !jQuery.sap.isDeclared('sap.ovp.cards.charts.donut.Component') ) {
(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.charts.donut.Component");
sap.ovp.cards.charts.generic.Component.extend("sap.ovp.cards.charts.donut.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"contentFragment": {
"type": "string",
"defaultValue": "sap.ovp.cards.charts.donut.DonutChart"
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m","sap.viz" ],
components: []
},
config: {},
customizing: {
"sap.ui.controllerExtensions": {
"sap.ovp.cards.generic.Card": {
controllerName: "sap.ovp.cards.charts.donut.DonutChart"
}
}
}
}
});
})();
}; // end of sap/ovp/cards/charts/donut/Component.js
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2015 SAP SE. All rights reserved
*/
sap.ui.define(['sap/ui/core/theming/Parameters'], function (Parameters) {
"use strict";
/**
* Gantt Chart with table renderer.
*
* @namespace
*/
var GanttChartWithTable = {};
GanttChartWithTable.render = function (oRenderManager, oGanttChartWithTable) {
oRenderManager.write("<div");
oRenderManager.writeControlData(oGanttChartWithTable);
oRenderManager.addClass("sapUiTableHScr"); //force horizontal scroll bar to show
oRenderManager.addClass("sapGanttChartWithTable");
oRenderManager.writeClasses();
oRenderManager.addStyle("width", oGanttChartWithTable.getWidth());
oRenderManager.addStyle("height", oGanttChartWithTable.getHeight());
oRenderManager.writeStyles();
oRenderManager.write(">");
if (oGanttChartWithTable._oToolbar.getAllToolbarItems().length == 0) {
oGanttChartWithTable._oTT.addStyleClass("sapGanttChartColumnHeight");
} else if (oGanttChartWithTable._oTT.hasStyleClass("sapGanttChartColumnHeight")){
oGanttChartWithTable._oTT.removeStyleClass("sapGanttChartColumnHeight");
}
oRenderManager.renderControl(oGanttChartWithTable._oSplitter);
oRenderManager.write("</div>");
};
return GanttChartWithTable;
}, /* bExport= */ true);
<file_sep>/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define(['jquery.sap.global','sap/ui/fl/changeHandler/Base'],function(q,B){"use strict";var R=function(){};R.prototype=q.sap.newObject(B.prototype);R.prototype.applyChange=function(c,g){var i=null;if(g.getParent){i=g.getParent();if(i){if(i.removeFormContainer){i.removeFormContainer(g);}}}else{throw new Error("no Group control provided for removing the group");}};R.prototype.completeChangeContent=function(c,s){var C=c.getDefinition();if(!C.content){C.content={};}};return R;},true);
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
jQuery.sap.declare("sap.apf.modeler.core.messageDefinition");
sap.apf.modeler.core.messageDefinition = [ {
code : "11005",
severity : "technError",
text : "Bad HTTP request returned status code {0} with status text {1}."
}, {
code : "11006",
severity : "technError",
text : "Unknown identifier: {0}"
}, {
code : "11007",
severity : "technError",
text : "Cannot export unsaved configuration. Configuration ID: {0}"
}, {
code : "11008",
severity : "error",
description : "Format information is missing at least for text element {0} - please edit the exported text property file manually",
key : "11008"
}, {
code : "11009",
severity : "error",
description : "Application id {0} cannot be used as translation uuid in text property file - please edit the exported text property file manually",
key : "11009"
}, {
code : "11010",
severity : "error",
description : "Imported text property file does not contain the APF application id - expected an entry like #ApfApplicationId=543EC63F05550175E10000000A445B6D.",
key : "11010"
}, {
code : "11011",
severity : "error",
description : "Expected a valid text entry <key>=<value> in line {0}, but could not find - key must be in valid guid format.",
key : 11011
}, {
code : "11012",
severity : "error",
description : "No valid text entry <key>=<value> in line {0}, key is not in valid guid format like 543EC63F05550175E10000000A445B6D.",
key : 11012
}, {
code : "11013",
severity : "technError",
text : "Metadata request {3} to server failed with http status code {0}, http error message {1}, and server response {2}",
key : "11013"
}, {
code : "11014",
severity : "error",
description : "ApfApplicationId in line {0} has invalid format - a valid application id looks like 543EC63F05550175E10000000A445B6D.",
key : "11014"
}, {
code : "11015",
severity : "error",
description : "Date in line {0} has invalid format.",
key : "11015"
}, {
code : "11016",
severity : "error",
description : "Sorting options must be supplied when setting top n",
key : "11016"
},{
code : "11020",
severity : "error",
description : "Text property has invalid format and cannot be imported - see previous messages for details",
key : "11020"
}, {
code : "11021",
severity : "error",
description : "ApfApplicationId {0} referenced in the text property is not yet existing - please load one configuration of the application before importing the texts.",
key : "11021"
},
{
code : "11030",
severity : "error",
description : "Label {0} is not valid",
key : "11030"
},
{
code : "11031",
severity : "error",
description : "Category {0} is not valid",
key : "11031"
},
{
code : "11032",
severity : "error",
description : "Request {0} is not valid",
key : "11032"
},
{
code : "11033",
severity : "error",
description : "Binding {0} is not valid",
key : "11033"
},
{
code : "11034",
severity : "error",
description : "Facet filter {0} is not valid",
key : "11034"
},
{
code : "11035",
severity : "error",
description : "Step {0} is not valid",
key : "11035"
},
{
code : "11036",
severity : "error",
description : "Configuration is not valid",
key : "11036"
},
{
code : "11037",
severity : "error",
description : "Invalid application guid {0}",
key : "11037"
},
{
code : "11038",
severity : "error",
description : "Invalid configuration guid {0}",
key : "11038"
},
{
code : "11039",
severity : "error",
description : "Invalid text guid {0}",
key : "11039"
},
{
code : "11040",
severity : "error",
description : "Navigation target {0} is not valid",
key : "11040"
},{
code : "11041",
severity : "technError",
text : "Network service for retrieving semantic objects failed - see console."
},{
code : "11042",
severity : "technError",
text : "Error occurred when retrieving actions for semantic object - see console."
},{
code : "11500",
severity : "error",
description : "An error occurred while attempting to save the application.",
key : "11500"
},{
code : "11501",
severity : "error",
description : "An error occurred while attempting to delete the application.",
key : "11501"
},{
code : "11502",
severity : "error",
description : "An error occurred while importing the configuration.",
key : "11502"
},{
code : "11503",
severity : "error",
description : "An error occurred while importing the text properties file.",
key : "11503"
},{
code : "11504",
severity : "error",
description : "An error occurred while retrieving the semantic objects available.",
key : "11504"
},{
code : "11505",
severity : "error",
description : "An error occurred while retrieving the actions for the given semantic object.",
key : "11505"
}
];<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define(['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* @class FieldListNode renderer.
* @static
*/
var FieldListNodeRenderer = {};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
* @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
*/
FieldListNodeRenderer.render = function(oRm, oControl) {
// write the HTML into the render manager
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapUiCompFieldListNode");
if (!oControl.getIsVisible()) {
oRm.addClass("sapUiCompFieldListNodeIsHidden");
} else {
oRm.addClass("sapUiCompFieldListNodeIsVisible");
}
if (oControl.getIsSelected()) {
oRm.addClass("sapUiCompFieldListNodeIsSelected");
}
oRm.writeClasses();
oRm.write(">"); // span element
FieldListNodeRenderer.renderLayout(oRm, oControl);
FieldListNodeRenderer.renderChildren(oRm, oControl);
oRm.write("</div>");
};
/**
* Renders the layout control
*
* @param {sap.ui.core.RenderManager} oRm RenderManager
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oControl field list node
* @private
*/
FieldListNodeRenderer.renderLayout = function(oRm, oControl) {
oRm.renderControl(oControl._oLayout);
};
/**
* Renders the child nodes
*
* @param {sap.ui.core.RenderManager} oRm RenderManager
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oControl field list node
* @private
*/
FieldListNodeRenderer.renderChildren = function(oRm, oControl) {
var length, i, aChildren;
aChildren = oControl.getNodes();
length = aChildren.length;
oRm.write('<div class="sapUiCompFieldListNodeBorder">');
for (i = 0; i < length; i++) {
oRm.renderControl(aChildren[i]);
}
oRm.write("</div>");
};
return FieldListNodeRenderer;
}, /* bExport= */ true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define([],function(){"use strict";return{aggregations:{customToolbar:{ignore:true},semanticObjectController:{ignore:true},noData:{ignore:true}}};},false);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// This file defines behavior for the control.
sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* The configuration of the graphic element on the chart.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Displays parts of a whole as highlighted sectors in a pie chart.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.HarveyBallMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var HarveyBallMicroChart = Control.extend("sap.suite.ui.microchart.HarveyBallMicroChart", /** @lends sap.suite.ui.microchart.HarveyBallMicroChart.prototype */ {
metadata : {
library: "sap.suite.ui.microchart",
properties: {
/**
* The total value. This is taken as 360 degrees value on the chart.
*/
total: {group:"Misc", type:"float", defaultValue: null},
/**
* The total label. If specified, it is displayed instead of the total value.
*/
totalLabel: {group:"Misc", type:"string"},
/**
The scaling factor that is displayed next to the total value.
*/
totalScale: {group:"Misc", type:"string"},
/**
If set to true, the totalLabel parameter is considered as the combination of the total value and its scaling factor. The default value is false. It means that the total value and the scaling factor are defined separately by the total and the totalScale properties accordingly.
*/
formattedLabel: {group:"Misc", type:"boolean", defaultValue:false},
/**
If it is set to true, the total value is displayed next to the chart. The default setting is true.
*/
showTotal: {group:"Misc", type:"boolean", defaultValue:true},
/**
If it is set to true, the fraction values are displayed next to the chart. The default setting is true.
*/
showFractions: {group:"Misc", type:"boolean", defaultValue:true},
/**
The size of the chart. If it is not set, the default size is applied based on the device type.
*/
size: {group:"Misc", type:"sap.m.Size", defaultValue:"Auto"},
/**
The color palette for the chart. If this property is set, semantic colors defined in HarveyBallMicroChart are ignored. Colors from the palette are assigned to each slice consequentially. When all the palette colors are used, assignment of the colors begins from the first palette color.
*/
colorPalette: {type: "string[]", group : "Appearance", defaultValue : [] },
/**
The width of the chart. If it is not set, the size of the control is defined by the size property.
*/
width: {group:"Misc", type:"sap.ui.core.CSSSize"}
},
events: {
/**
* The event is fired when the user chooses the control.
*/
press: {}
},
aggregations: {
/**
* The set of points for this graphic element.
*/
"items": { multiple: true, type: "sap.suite.ui.microchart.HarveyBallMicroChartItem" }
}
}
});
///**
// * This file defines behavior for the control,
// */
HarveyBallMicroChart.prototype.getAltText = function() {
var sAltText = "";
var bIsFirst = true;
var aItems = this.getItems();
for (var i = 0; i < aItems.length; i++) {
var oItem = aItems[i];
var sColor = (this.getColorPalette().length === 0) ? this._rb.getText(("SEMANTIC_COLOR_" + oItem.getColor()).toUpperCase()) : "";
var sLabel = oItem.getFractionLabel();
var sScale = oItem.getFractionScale();
if (!sLabel && sScale) {
sLabel = oItem.getFormattedLabel() ? oItem.getFraction() : oItem.getFraction() + oItem.getFractionScale().substring(0,3);
} else if (!oItem.getFormattedLabel() && oItem.getFractionLabel()) {
sLabel += oItem.getFractionScale().substring(0,3);
}
sAltText += (bIsFirst ? "" : "\n") + sLabel + " " + sColor;
bIsFirst = false;
}
if (this.getTotal()) {
var sTLabel = this.getTotalLabel();
if (!sTLabel) {
sTLabel = this.getFormattedLabel() ? this.getTotal() : this.getTotal() + this.getTotalScale().substring(0,3);
} else if (!this.getFormattedLabel()) {
sTLabel += this.getTotalScale().substring(0,3);
}
sAltText += (bIsFirst ? "" : "\n") + this._rb.getText("HARVEYBALLMICROCHART_TOTAL_TOOLTIP") + " " + sTLabel;
}
return sAltText;
};
HarveyBallMicroChart.prototype.getTooltip_AsString = function() {
var oTooltip = this.getTooltip();
var sTooltip = this.getAltText();
if (typeof oTooltip === "string" || oTooltip instanceof String) {
sTooltip = oTooltip.split("{AltText}").join(sTooltip).split("((AltText))").join(sTooltip);
return sTooltip;
}
return oTooltip ? oTooltip : "";
};
HarveyBallMicroChart.prototype.init = function() {
this._rb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this.setTooltip("{AltText}");
sap.ui.Device.media.attachHandler(this.rerender, this, sap.ui.Device.media.RANGESETS.SAP_STANDARD);
};
HarveyBallMicroChart.prototype._calculatePath = function() {
var oSize = this.getSize();
var fTot = this.getTotal();
var fFrac = 0;
if (this.getItems().length) {
fFrac = this.getItems()[0].getFraction();
}
var bIsPhone = false;
if (oSize == "Auto") {
bIsPhone = jQuery("html").hasClass("sapUiMedia-Std-Phone");
}
if (oSize == "S" || oSize == "XS") {
bIsPhone = true;
}
var iMeadiaSize = bIsPhone ? 56 : 72;
var iCenter = iMeadiaSize / 2;
// var iBorder = bIsPhone? 3 : 4;
var iBorder = 4;
this._oPath = {
initial : {
x : iCenter,
y : iCenter,
x1 : iCenter,
y1 : iCenter
},
lineTo : {
x : iCenter,
y : iBorder
},
arc : {
x1 : iCenter - iBorder,
y1 : iCenter - iBorder,
xArc : 0,
largeArc : 0,
sweep : 1,
x2 : "",
y2 : ""
},
size : iMeadiaSize,
border : iBorder,
center : iCenter
};
var fAngle = fFrac / fTot * 360;
if (fAngle < 10) {
this._oPath.initial.x -= 1.5;
this._oPath.initial.x1 += 1.5;
this._oPath.arc.x2 = this._oPath.initial.x1;
this._oPath.arc.y2 = this._oPath.lineTo.y;
} else if (fAngle > 350 && fAngle < 360) {
this._oPath.initial.x += 1.5;
this._oPath.initial.x1 -= 1.5;
this._oPath.arc.x2 = this._oPath.initial.x1;
this._oPath.arc.y2 = this._oPath.lineTo.y;
} else {
var fRad = Math.PI / 180.0;
var fRadius = this._oPath.center - this._oPath.border;
var ix = fRadius * Math.cos((fAngle - 90) * fRad) + this._oPath.center;
var iy = this._oPath.size - (fRadius * Math.sin((fAngle + 90) * fRad) + this._oPath.center);
this._oPath.arc.x2 = ix.toFixed(2);
this._oPath.arc.y2 = iy.toFixed(2);
}
var iLargeArc = fTot / fFrac < 2 ? 1 : 0;
this._oPath.arc.largeArc = iLargeArc;
};
HarveyBallMicroChart.prototype.onBeforeRendering = function() {
this._calculatePath();
};
HarveyBallMicroChart.prototype.serializePieChart = function() {
var p = this._oPath;
return ["M", p.initial.x, ",", p.initial.y, " L", p.initial.x, ",", p.lineTo.y, " A", p.arc.x1, ",", p.arc.y1,
" ", p.arc.xArc, " ", p.arc.largeArc, ",", p.arc.sweep, " ", p.arc.x2, ",", p.arc.y2, " L", p.initial.x1,
",", p.initial.y1, " z"].join("");
};
HarveyBallMicroChart.prototype._parseFormattedValue = function(
sValue) {
return {
scale: sValue.replace(/.*?([^+-.,\d]*)$/g, "$1").trim(),
value: sValue.replace(/(.*?)[^+-.,\d]*$/g, "$1").trim()
};
};
HarveyBallMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.internet_explorer) {
this.$().focus();
}
this.firePress();
};
HarveyBallMicroChart.prototype.onkeydown = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.SPACE) {
oEvent.preventDefault();
}
};
HarveyBallMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.ENTER
|| oEvent.which == jQuery.sap.KeyCodes.SPACE) {
this.firePress();
oEvent.preventDefault();
}
};
HarveyBallMicroChart.prototype.attachEvent = function(
sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData,
fnFunction, oListener);
if (this.hasListeners("press")) {
this.$().attr("tabindex", 0).addClass("sapSuiteUiMicroChartPointer");
}
return this;
};
HarveyBallMicroChart.prototype.detachEvent = function(
sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction,
oListener);
if (!this.hasListeners("press")) {
this.$().removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer");
}
return this;
};
HarveyBallMicroChart.prototype.exit = function(oEvent) {
sap.ui.Device.media.detachHandler(this.rerender, this, sap.ui.Device.media.RANGESETS.SAP_STANDARD);
};
return HarveyBallMicroChart;
});
<file_sep>// This file has been generated by the SAPUI5 'AllInOne' Builder
jQuery.sap.declare('sap.ui.fl.library-all');
if ( !jQuery.sap.isDeclared('sap.ui.fl.Utils') ) {
/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.Utils'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Component'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/Utils",[
"jquery.sap.global", "sap/ui/core/Component"
], function(jQuery, Component) {
"use strict";
/**
* Provides utility functions for the flexibility library
*
* @namespace
* @alias sap.ui.fl.Utils
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.25.0
*/
var Utils = {
/**
* log object exposes available log functions
*
* @name sap.ui.fl.Utils.log
* @public
*/
log: {
error: function(sMessage, sDetails, sComponent) {
jQuery.sap.log.error(sMessage, sDetails, sComponent);
},
warning: function(sMessage, sDetails, sComponent) {
jQuery.sap.log.warning(sMessage, sDetails, sComponent);
}
},
/**
* Tries to retrieve the xsrf token from the controls OData Model. Returns empty string if retrieval failed.
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {String} XSRF Token
* @public
* @function
* @name sap.ui.fl.Utils.getXSRFTokenFromControl
*/
getXSRFTokenFromControl: function(oControl) {
var oModel;
if (!oControl) {
return "";
}
// Get Model
if (oControl && typeof oControl.getModel === "function") {
oModel = oControl.getModel();
return Utils._getXSRFTokenFromModel(oModel);
}
return "";
},
/**
* Returns XSRF Token from the Odata Model. Returns empty string if retrieval failed
*
* @param {sap.ui.model.odata.ODataModel} oModel - OData Model
* @returns {String} XSRF Token
* @private
*/
_getXSRFTokenFromModel: function(oModel) {
var mHeaders;
if (!oModel) {
return "";
}
if (typeof oModel.getHeaders === "function") {
mHeaders = oModel.getHeaders();
if (mHeaders) {
return mHeaders["x-csrf-token"];
}
}
return "";
},
/**
* Returns the class name of the component the given control belongs to.
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {String} The component class name, ending with ".Component"
* @see sap.ui.base.Component.getOwnerIdFor
* @public
* @function
* @name sap.ui.fl.Utils.getComponentClassName
*/
getComponentClassName: function(oControl) {
var oComponent = null, sVariantId = null;
// determine UI5 component out of given control
if (oControl) {
oComponent = this._getAppComponentForControl(oControl);
// check if the component is an application variant and assigned an application descriptor then use this as reference
if (oComponent) {
sVariantId = this._getComponentStartUpParameter(oComponent, "sap-app-id");
if (sVariantId) {
return sVariantId;
}
}
}
return Utils._getComponentName(oComponent);
},
/**
* Returns the appDescriptor of the component for the given control
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {object} that represent the appDescriptor
* @public
* @function
* @name sap.ui.fl.Utils.getAppDescriptor
*/
getAppDescriptor: function(oControl) {
var oManifest = null, oComponent = null, oComponentMetaData = null;
// determine UI5 component out of given control
if (oControl) {
oComponent = this._getAppComponentForControl(oControl);
// determine manifest out of found component
if (oComponent && oComponent.getMetadata) {
oComponentMetaData = oComponent.getMetadata();
if (oComponentMetaData && oComponentMetaData.getManifest) {
oManifest = oComponentMetaData.getManifest();
}
}
}
return oManifest;
},
/**
* Returns the siteId of a component
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {string} siteId - that represent the found sietId
* @public
* @function
* @name sap.ui.fl.Utils.getSiteId
*/
getSiteId: function(oControl) {
var sSiteId = null, oComponent = null;
// determine UI5 component out of given control
if (oControl) {
oComponent = this._getAppComponentForControl(oControl);
// determine siteId from ComponentData
if (oComponent) {
//Workaround for backend check: isApplicationPermitted
//As long as FLP does not know about appDescriptorId we have to pass siteID and applicationID.
//With startUpParameter hcpApplicationId we will get a concatenation of “siteId:applicationId”
//sSiteId = this._getComponentStartUpParameter(oComponent, "scopeId");
sSiteId = this._getComponentStartUpParameter(oComponent, "hcpApplicationId");
}
}
return sSiteId;
},
/**
* Indicates if the current application is a variant of an existing one and the VENDOR layer is selected
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {boolean} true if application is a variant and the VENDOR layer selected
* @public
* @function
* @name sap.ui.fl.Utils.isAppVariantMode
*/
isAppVariantMode: function(oControl) {
return (Utils.isVendorLayer() && Utils.isApplicationVariant(oControl));
},
/**
* Indicates if the VENDOR is selected
*
* @returns {boolean} true if it's an application variant
* @public
* @function
* @name sap.ui.fl.Utils.isVendorLayer
*/
isVendorLayer: function() {
// variant mode only supported for vendor other types are not allowed to change standard control variants
if (Utils.getCurrentLayer(false) === "VENDOR") {
return true;
}
return false;
},
/**
* Indicates if the current application is a variant of an existing one
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {boolean} true if it's an application variant
* @public
* @function
* @name sap.ui.fl.Utils.isApplicationVariant
*/
isApplicationVariant: function(oControl) {
var bIsApplicationVariant = false, oComponent = null, sVariantId = null;
if (oControl) {
oComponent = this._getAppComponentForControl(oControl);
// check if the component is an application variant and assigned an application descriptor then use this as reference
if (oComponent) {
sVariantId = this._getComponentStartUpParameter(oComponent, "sap-app-id");
if (sVariantId) {
bIsApplicationVariant = true;
}
}
}
return bIsApplicationVariant;
},
/**
* Determines the content for a given startUpParameter name
*
* @param {sap.ui.core.Component} oComponent - component instance
* @param {String} sParameterName - startUpParameterName that shall be determined
* @returns {String} content of found startUpParameter
* @private
*/
_getComponentStartUpParameter: function(oComponent, sParameterName) {
var startUpParameterContent = null, oComponentData = null;
if (sParameterName) {
if (oComponent && oComponent.getComponentData) {
oComponentData = oComponent.getComponentData();
if (oComponentData && oComponentData.startupParameters) {
if (jQuery.isArray(oComponentData.startupParameters[sParameterName])) {
startUpParameterContent = oComponentData.startupParameters[sParameterName][0];
}
}
}
}
return startUpParameterContent;
},
/**
* Gets the component name for a component instance.
*
* @param {sap.ui.core.Component} oComponent component instance
* @returns {String} component name
* @private
*/
_getComponentName: function(oComponent) {
var sComponentName = "";
if (oComponent) {
sComponentName = oComponent.getMetadata().getName();
}
if (sComponentName.length > 0 && sComponentName.indexOf(".Component") < 0) {
sComponentName += ".Component";
}
return sComponentName;
},
/**
* Gets the component instance for a component ID.
*
* @param {String} sComponentId component ID
* @returns {sap.ui.core.Component} component for the component ID
* @private
*/
_getComponent: function(sComponentId) {
var oComponent;
if (sComponentId) {
oComponent = sap.ui.getCore().getComponent(sComponentId);
}
return oComponent;
},
/**
* Returns ComponentId of the control. If the control has no component, it walks up the control tree in order to find a control having one
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {String} The component id
* @see sap.ui.base.Component.getOwnerIdFor
* @private
*/
_getComponentIdForControl: function(oControl) {
var sComponentId = "", i = 0;
do {
i++;
sComponentId = Utils._getOwnerIdForControl(oControl);
if (sComponentId) {
return sComponentId;
}
if (oControl && typeof oControl.getParent === "function") { // Walk up control tree
oControl = oControl.getParent();
} else {
return "";
}
} while (oControl && i < 100);
return "";
},
/**
* Returns the Component that belongs to given control. If the control has no component, it walks up the control tree in order to find a
* control having one.
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {sap.ui.base.Component} found component
* @public
*/
getComponentForControl: function(oControl) {
return Utils._getComponentForControl(oControl);
},
/**
* Returns the Component that belongs to given control whose type is "application". If the control has no component, it walks up the control tree in order to find a
* control having one.
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {sap.ui.base.Component} found component
* @private
*/
_getAppComponentForControl: function(oControl) {
var oComponent = null;
var oSapApp = null;
oComponent = this._getComponentForControl(oControl);
// special case for SmartTemplating to reach the real appComponent
if (oComponent && oComponent.getAppComponent) {
return oComponent.getAppComponent();
}
if (oComponent && oComponent.getManifestEntry) {
oSapApp = oComponent.getManifestEntry("sap.app");
} else {
return oComponent;
}
if (oSapApp && oSapApp.type && oSapApp.type !== "application") {
return this._getAppComponentForControl(oComponent);
}
return oComponent;
},
/**
* Returns the Component that belongs to given control. If the control has no component, it walks up the control tree in order to find a
* control having one.
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {sap.ui.base.Component} found component
* @private
*/
_getComponentForControl: function(oControl) {
var oComponent = null;
var sComponentId = null;
// determine UI5 component out of given control
if (oControl) {
sComponentId = Utils._getComponentIdForControl(oControl);
if (sComponentId) {
oComponent = Utils._getComponent(sComponentId);
}
}
return oComponent;
},
/**
* Returns the parent view of the control. If there are nested views, only the one closest to the control will be returned. If no view can be
* found, undefiend will be returned.
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {sap.ui.core.mvc.View} The view
* @see sap.ui.base.Component.getOwnerIdFor
* @public
*/
getViewForControl: function(oControl) {
return Utils.getFirstAncestorOfControlWithControlType(oControl, sap.ui.core.mvc.View);
},
getFirstAncestorOfControlWithControlType: function(oControl, controlType) {
if (oControl instanceof controlType) {
return oControl;
}
if (oControl && typeof oControl.getParent === "function") {
oControl = oControl.getParent();
return Utils.getFirstAncestorOfControlWithControlType(oControl, controlType);
}
},
hasControlAncestorWithId: function(sControlId, sAncestorControlId) {
var oControl;
if (sControlId === sAncestorControlId) {
return true;
}
oControl = sap.ui.getCore().byId(sControlId);
while (oControl) {
if (oControl.getId() === sAncestorControlId) {
return true;
}
if (typeof oControl.getParent === "function") {
oControl = oControl.getParent();
} else {
return false;
}
}
return false;
},
/**
* Checks whether the provided control is a view
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {Boolean} Flag
* @see sap.ui.base.Component.getOwnerIdFor
* @private
*/
_isView: function(oControl) {
return oControl instanceof sap.ui.core.mvc.View;
},
/**
* Returns OwnerId of the control
*
* @param {sap.ui.core.Control} oControl - SAPUI5 control
* @returns {String} The owner id
* @see sap.ui.base.Component.getOwnerIdFor
* @private
*/
_getOwnerIdForControl: function(oControl) {
return Component.getOwnerIdFor(oControl);
},
/**
* Returns the current layer as defined by the url parameter. If the end user flag is set, it always returns "USER".
*
* @param {boolean} bIsEndUser - the end user flag
* @returns {string} the current layer
* @public
* @function
* @name sap.ui.fl.Utils.getCurrentLayer
*/
getCurrentLayer: function(bIsEndUser) {
var oUriParams, layer;
if (bIsEndUser) {
return "USER";
}
oUriParams = this._getUriParameters();
layer = oUriParams.mParams["sap-ui-layer"];
if (layer && layer.length > 0) {
return layer[0];
}
return "CUSTOMER";
},
/**
* Checks if a shared newly created variant requires an ABAP package
*
* @returns {boolean} - Indicates whether a new variant needs an ABAP package
* @public
* @function
* @name sap.ui.fl.Utils.doesSharedVariantRequirePackage
*/
doesSharedVariantRequirePackage: function() {
var sCurrentLayer;
sCurrentLayer = Utils.getCurrentLayer(false);
if ((sCurrentLayer === "VENDOR") || (sCurrentLayer === "PARTNER")) {
return true;
}
if (sCurrentLayer === "USER") {
return false;
}
if (sCurrentLayer === "CUSTOMER") {
return false; // Variants in CUSTOMER layer might either be transported or stored as local objects ($TMP) as they are client
// dependent content. A variant which will be transported must not be assigned to a package.
}
return false;
},
/**
* Returns the tenant number for the communication with the ABAP backend.
*
* @public
* @function
* @returns {string} the current client
* @name sap.ui.fl.Utils.getClient
*/
getClient: function() {
var oUriParams, client;
oUriParams = this._getUriParameters();
client = oUriParams.mParams["sap-client"];
if (client && client.length > 0) {
return client[0];
}
return undefined;
},
_getUriParameters: function() {
return jQuery.sap.getUriParameters();
},
/**
* Returns whether the hot fix mode is active (url parameter hotfix=true)
*
* @public
* @returns {bool} is hotfix mode active, or not
*/
isHotfixMode: function() {
var oUriParams, aIsHotfixMode, sIsHotfixMode;
oUriParams = this._getUriParameters();
aIsHotfixMode = oUriParams.mParams["hotfix"];
if (aIsHotfixMode && aIsHotfixMode.length > 0) {
sIsHotfixMode = aIsHotfixMode[0];
}
return (sIsHotfixMode === "true");
},
/**
* Converts the browser language into a 2-character ISO 639-1 language. If the browser language is in format RFC4646, the first part will be
* used: For example en-us will be converted to EN. If the browser language already is in ISO 639-1, it will be returned after an upper case
* conversion: For example de will be converted to DE.
*
* @param {String} sBrowserLanguage - Language in RFC4646
* @returns {String} Language in ISO 639-1. Empty string if conversion was not successful
* @public
* @function
* @name sap.ui.fl.Utils.convertBrowserLanguageToISO639_1
*/
convertBrowserLanguageToISO639_1: function(sBrowserLanguage) {
if (!sBrowserLanguage || typeof sBrowserLanguage !== "string") {
return "";
}
var nIndex = sBrowserLanguage.indexOf("-");
if ((nIndex < 0) && (sBrowserLanguage.length <= 2)) {
return sBrowserLanguage.toUpperCase();
}
if (nIndex > 0 && nIndex <= 2) {
return sBrowserLanguage.substring(0, nIndex).toUpperCase();
}
return "";
},
/**
* Returns the current language in ISO 639-1 format.
*
* @returns {String} Language in ISO 639-1. Empty string if language cannot be determined
* @public
*/
getCurrentLanguage: function() {
var sLanguage = sap.ui.getCore().getConfiguration().getLanguage();
return Utils.convertBrowserLanguageToISO639_1(sLanguage);
},
/**
* Retrieves the controlType of the control
*
* @param {sap.ui.core.Control} oControl Control instance
* @returns {string} control type of the control - undefined if controlType cannot be determined
* @private
*/
getControlType: function(oControl) {
var oMetadata;
if (oControl && typeof oControl.getMetadata === "function") {
oMetadata = oControl.getMetadata();
if (oMetadata && typeof oMetadata.getElementName === "function") {
return oMetadata.getElementName();
}
}
},
/**
* Converts ASCII coding into a string. Required for restoring stored code extinsions
*
* @param {String} ascii string containing ascii code valid numbers seperated by ','
* @returns {String} parsedString parsed string
*/
asciiToString: function (ascii) {
var asciiArray = ascii.split(",");
var parsedString = "";
jQuery.each(asciiArray, function (index, asciiChar) {
parsedString += String.fromCharCode(asciiChar);
});
return parsedString;
},
/**
* Converts ASCII coding into a string. Required for restoring stored code extinsions
*
* @param {String} string string which has to be encoded
* @returns {String} ascii imput parsed to ascii numbers seperated by ','
*/
stringToAscii: function (string) {
var ascii = "";
for ( var i = 0; i < string.length; i++ ) {
ascii += string.charCodeAt(i) + ",";
}
// remove last ","
ascii = ascii.substring( 0 , ascii.length - 1 );
return ascii;
},
/**
* Check if the control id is generated or maintained by the application
*
* @param {sap.ui.core.Control} oControl Control instance
* @returns {boolean} Returns true if the id is maintained by the application
*/
checkControlId: function(oControl) {
var bIsGenerated = sap.ui.base.ManagedObjectMetadata.isGeneratedId(oControl.getId());
// get the information if the control id was generated or not
if (bIsGenerated === true) {
jQuery.sap.log.error("Generated id attribute found", "to offer flexibility a stable control id is needed to assign the changes to, but for this control the id was generated by SAPUI5", oControl.getId());
}
return !bIsGenerated;
},
/**
* Returns the a string containing all url parameters of the current window.location
*
* @returns {string} Substring of url containing the url query parameters
* @private
*/
_getAllUrlParameters: function() {
return window.location.search.substring(1);
},
/**
* Returns the value of the specified url parameter of the current url
*
* @param {String} sParameterName - Name of the url parameter
* @returns {string} url parameter
* @private
*/
getUrlParameter: function(sParameterName) {
return jQuery.sap.getUriParameters().get(sParameterName);
}
};
return Utils;
}, true);
}; // end of sap/ui/fl/Utils.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.changeHandler.Base') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.changeHandler.Base'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/changeHandler/Base",[
"sap/ui/fl/Utils", "jquery.sap.global"
], function(Utils, $) {
"use strict";
/**
* Base class for all change handler subclasses which provides some reuse methods
* @constructor
* @alias sap.ui.fl.changeHandler.Base
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*
*/
var Base = function() {
};
/**
* @param {sap.ui.core.Control} oControl - the control for which the properties shall be returned
* @param {String} sName - name of property
* @returns {Object} property object
* @private
*/
Base.prototype._getProperty = function(oControl, sName) {
if (oControl) {
if (oControl.getMetadata) {
var oMetadata = oControl.getMetadata();
var oProperties = oMetadata.getProperties();
if (oProperties) {
var oProperty = oProperties[sName];
if (oProperty) {
return oProperty;
}
}
}
}
};
/**
* Changes a property of the control
*
* @param {sap.ui.core.Control} oControl - the control for which the changes should be fetched
* @param {string} sName - property name
* @param {object} oValue - new value of the property
*
* @public
*/
Base.prototype.changeProperty = function(oControl, sName, oValue) {
var oProperty = this._getProperty(oControl, sName);
if (oProperty) {
oControl.setProperty(sName, oValue);
}
};
/**
* Sets a property of the control back to its default value
*
* @param {sap.ui.core.Control} oControl - the control for which the changes should be fetched
* @param {string} sName - property name
*
* @public
*/
Base.prototype.clearProperty = function(oControl, sName) {
var oProperty = this._getProperty(oControl, sName);
if (oProperty) {
oControl.setProperty(sName, oProperty.defaultValue);
}
};
/**
* Adds an additional item of the aggregation or changes it in case it is not a multiple one
*
* @param {sap.ui.core.Control} oControl - the control for which the changes should be fetched
* @param {string} sName - aggregation name
* @param {string} oObject - aggregated object to be set
* @param {integer} iIndex <optional> - index to which it should be added/inserted
*
* @public
*/
Base.prototype.addAggregation = function(oControl, sName, oObject, iIndex) {
if (oControl) {
if (oControl.getMetadata) {
var oMetadata = oControl.getMetadata();
var oAggregations = oMetadata.getAllAggregations();
if (oAggregations) {
var oAggregation = oAggregations[sName];
if (oAggregation) {
// if(oAggregation.multiple === false) {
// oControl.destroyAggregation(sName);
// }
if (oAggregation.multiple) {
var iInsertIndex = iIndex || oAggregations.length || 0;
oControl[oAggregation._sInsertMutator](oObject, iInsertIndex);
} else {
oControl[oAggregation._sMutator](oObject);
}
}
}
}
}
};
Base.prototype.removeAggregation = function(oControl, sName, oObject) {
if (oControl) {
if (oControl.getMetadata) {
var oMetadata = oControl.getMetadata();
var oAggregations = oMetadata.getAllAggregations();
if (oAggregations) {
var oAggregation = oAggregations[sName];
if (oAggregation) {
oControl[oAggregation._sRemoveMutator](oObject);
}
}
}
}
};
/**
* Sets a text in a change.
*
* @param {object} oChange - change object
* @param {string} sKey - text key
* @param {string} sText - text value
* @param {string} sType - translation text type e.g. XBUT, XTIT, XTOL, XFLD
*
* @public
*/
Base.prototype.setTextInChange = function(oChange, sKey, sText, sType) {
if (!oChange.texts) {
oChange.texts = {};
}
if (!oChange.texts[sKey]) {
oChange.texts[sKey] = {};
}
oChange.texts[sKey].value = sText;
oChange.texts[sKey].type = sType;
};
return Base;
}, /* bExport= */true);
}; // end of sap/ui/fl/changeHandler/Base.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.changeHandler.HideControl') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.changeHandler.HideControl'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/changeHandler/HideControl",[
'jquery.sap.global', './Base'
], function(jQuery, Base) {
"use strict";
/**
* Change handler for hiding of a control.
* @constructor
* @alias sap.ui.fl.changeHandler.HideControl
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*/
var HideControl = function() {
};
HideControl.prototype = jQuery.sap.newObject(Base.prototype);
/**
* Hides a control.
*
* @param {sap.ui.fl.Change} oChange change object with instructions to be applied on the control map
* @param {sap.ui.core.Control} oControl control that matches the change selector for applying the change
* @public
*/
HideControl.prototype.applyChange = function(oChange, oControl) {
if (oControl.setVisible) {
oControl.setVisible(false);
} else {
throw new Error("Provided control instance has no setVisible method");
}
};
/**
* Completes the change by adding change handler specific content
*
* @param {sap.ui.fl.Change} oChange change object to be completed
* @param {object} oSpecificChangeInfo as an empty object since no additional attributes are required for this operation
* @public
*/
HideControl.prototype.completeChangeContent = function(oChange, oSpecificChangeInfo) {
var oChangeJson = oChange.getDefinition();
if (!oChangeJson.content) {
oChangeJson.content = {};
}
};
return HideControl;
},
/* bExport= */true);
}; // end of sap/ui/fl/changeHandler/HideControl.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.changeHandler.MoveElements') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.changeHandler.MoveElements'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/changeHandler/MoveElements",['jquery.sap.global', './Base'], function(jQuery, Base) {
"use strict";
/**
* Change handler for moving of a elements.
*
* @constructor
* @alias sap.ui.fl.changeHandler.MoveElements
* @author <NAME>
* @version 1.36.12
* @experimental Since 1.34.0
*/
var MoveElements = function() {
};
MoveElements.prototype = jQuery.sap.newObject(Base.prototype);
MoveElements.CHANGE_TYPE = "moveElements";
/**
* Moves an element from one aggregation to another.
*
* @param {sap.ui.fl.Change}
* oChange change object with instructions to be applied on the control map
* @param {sap.ui.core.Control}
* oSourceParent control that matches the change selector for applying the change, which is the source of the
* move
* @public
*/
MoveElements.prototype.applyChange = function(oChange, oSourceParent) {
var that = this;
var mContent = oChange.getContent();
if (oSourceParent.getId() !== oChange.getSelector().id) {
throw new Error("Source parent id (selector) doesn't match the control on which to apply the change");
}
var sSourceAggregation = oChange.getSelector().aggregation;
if (!sSourceAggregation) {
throw new Error("No source aggregation supplied via selector for move");
}
if (!mContent.target || !mContent.target.selector) {
throw new Error("No target supplied for move");
}
var oTargetParent = this._byId(mContent.target.selector.id);
if (!oTargetParent) {
throw new Error("Move target parent not found");
}
var sTargetAggregation = mContent.target.selector.aggregation;
if (!sTargetAggregation) {
throw new Error("No target aggregation supplied for move");
}
if (!mContent.movedElements) {
throw new Error("No moveElements supplied");
}
mContent.movedElements.forEach(function(mMovedElement) {
var oMovedElement = that._byId(mMovedElement.selector.id);
if (!oMovedElement) {
throw new Error("Unkown element with id '" + mMovedElement.selector.id + "' in moveElements supplied");
}
if ( typeof mMovedElement.targetIndex !== "number") {
throw new Error("Missing targetIndex for element with id '" + mMovedElement.selector.id
+ "' in moveElements supplied");
}
that.removeAggregation(oSourceParent, sSourceAggregation, oMovedElement);
that.addAggregation(oTargetParent, sTargetAggregation, oMovedElement, mMovedElement.targetIndex);
});
};
/**
* Completes the change by adding change handler specific content
*
* @param {sap.ui.fl.Change}
* oChange change object to be completed
* @param {object}
* mSpecificChangeInfo as an empty object since no additional attributes are required for this operation
* @public
*/
MoveElements.prototype.completeChangeContent = function(oChange, mSpecificChangeInfo) {
var that = this;
var mSpecificInfo = this.getSpecificChangeInfo(mSpecificChangeInfo);
var mChangeData = oChange.getDefinition();
mChangeData.changeType = MoveElements.CHANGE_TYPE;
mChangeData.selector = mSpecificInfo.source;
mChangeData.content = {
movedElements : [],
target : {
selector : mSpecificInfo.target
}
};
mSpecificInfo.movedElements.forEach(function(mElement) {
var oElement = mElement.element || that._byId(mElement.id);
mChangeData.content.movedElements.push({
selector : {
id : oElement.getId(),
type : that._getType(oElement)
},
sourceIndex : mElement.sourceIndex,
targetIndex : mElement.targetIndex
});
});
};
/**
* Enrich the incoming change info with the change info from the setter, to get the complete data in one format
*/
MoveElements.prototype.getSpecificChangeInfo = function(mSpecificChangeInfo) {
var oSourceParent = this._getParentElement(this._mSource || mSpecificChangeInfo.source);
var oTargetParent = this._getParentElement(this._mTarget || mSpecificChangeInfo.target);
var sSourceAggregation = this._mSource && this._mSource.aggregation || mSpecificChangeInfo.source.aggregation;
var sTargetAggregation = this._mTarget && this._mTarget.aggregation || mSpecificChangeInfo.target.aggregation;
var mSpecificInfo = {
source : {
id : oSourceParent.getId(),
aggregation : sSourceAggregation,
type : this._getType(oSourceParent)
},
target : {
id : oTargetParent.getId(),
aggregation : sTargetAggregation,
type : this._getType(oTargetParent)
},
movedElements : this._aMovedElements || mSpecificChangeInfo.movedElements
};
return mSpecificInfo;
};
/**
* @param {array}
* aElements
* @param {string}
* aElements.elementId id of the moved element, can be omitted if element is passed
* @param {sap.ui.core.Element}
* aElements.element moved element, optional fallback for elementId
* @param {number}
* aElements.sourceIndex index of the moved elements in the source aggregation
* @param {number}
* aElements.targetIndex index of the moved elements in the target aggregation
*/
MoveElements.prototype.setMovedElements = function(aElements) {
this._aMovedElements = aElements;
};
/**
* @param {object}
* mSource
* @param {string}
* mSource.id id of the source parent, can be omitted if element is passed
* @param {sap.ui.core.Element}
* mSource.parent optional fallback for id
* @param {string}
* mSource.aggregation original aggregation of the moved elements
*/
MoveElements.prototype.setSource = function(mSource) {
this._mSource = mSource;
};
/**
* @param {object}
* mTarget
* @param {string}
* mTarget.id id of the target parent
* @param {sap.ui.core.Element}
* mTarget.parent optional fallback for id, can be omitted if parent is passed
* @param {string}
* mTarget.aggregation target aggregation of the moved elements in the target element
*/
MoveElements.prototype.setTarget = function(mTarget) {
this._mTarget = mTarget;
};
MoveElements.prototype._byId = function(sId) {
return sap.ui.getCore().byId(sId);
};
MoveElements.prototype._getType = function(oElement) {
return oElement.getMetadata().getName();
};
MoveElements.prototype._getParentElement = function(mData) {
var oElement = mData.parent;
if (!oElement) {
oElement = this._byId(mData.id);
}
return oElement;
};
return MoveElements;
},
/* bExport= */true);
}; // end of sap/ui/fl/changeHandler/MoveElements.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.changeHandler.PropertyChange') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/*global sap */
jQuery.sap.declare('sap.ui.fl.changeHandler.PropertyChange'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/changeHandler/PropertyChange",["jquery.sap.global", "sap/ui/fl/changeHandler/Base", "sap/ui/fl/Utils"], function(jQuery, Base, FlexUtils) {
"use strict";
/**
* Change handler for setting properties on controls
*
* @constructor
* @alias sap.ui.fl.changeHandler.PropertyChange
* @author SAP SE
* @version 1.36.12
* @since 1.36
* @private
* @experimental Since 1.36. This class is experimental and provides only limited functionality. Also the API might be changed in future.
*/
var PropertyChange = function() {
};
PropertyChange.prototype = jQuery.sap.newObject(Base.prototype);
/**
* Changes the properties on the given control
*
* @param {object} oChange - change object with instructions to be applied on the control
* @param {object} oControl - the control which has been determined by the selector id
* @public
* @name sap.ui.fl.changeHandler.PropertyChange#applyChange
*/
PropertyChange.prototype.applyChange = function(oChange, oControl) {
try {
var oDef = oChange.getDefinition();
var propertyName = oDef.content.property;
var propertyMetadata = oControl.getMetadata().getAllProperties()[propertyName];
var propertySetter = propertyMetadata._sMutator;
oControl[propertySetter](oDef.content.newValue);
} catch (ex) {
throw new Error("Applying property changes failed: " + ex);
}
};
/**
* Completes the change by adding change handler specific content
*
* @param {object} oChange change object to be completed
* @param {object} oSpecificChangeInfo with attribute property which contains an array which holds objects which have attributes
* id and index - id is the id of the field to property and index the new position of the field in the smart form group
* @public
* @name sap.ui.fl.changeHandler.PropertyChange#completeChangeContent
*/
PropertyChange.prototype.completeChangeContent = function(oChange, oSpecificChangeInfo) {
var oChangeJson = oChange.getDefinition();
if (oSpecificChangeInfo.content) {
oChangeJson.content = oSpecificChangeInfo.content;
} else {
throw new Error("oSpecificChangeInfo attribute required");
}
};
return PropertyChange;
}, /* bExport= */true);
}; // end of sap/ui/fl/changeHandler/PropertyChange.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.changeHandler.UnhideControl') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.changeHandler.UnhideControl'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/changeHandler/UnhideControl",[
'jquery.sap.global', './Base'
], function(jQuery, Base) {
"use strict";
/**
* Change handler for unhiding of a control.
* @constructor
* @alias sap.ui.fl.changeHandler.UnhideControl
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*/
var UnhideControl = function() {
};
UnhideControl.prototype = jQuery.sap.newObject(Base.prototype);
/**
* Unhides a control.
*
* @param {sap.ui.fl.Change} oChange change object with instructions to be applied on the control map
* @param {sap.ui.core.Control} oControl control that matches the change selector for applying the change
* @public
*/
UnhideControl.prototype.applyChange = function(oChange, oControl) {
if (oControl.setVisible) {
oControl.setVisible(true);
} else {
throw new Error("Provided control instance has no setVisible method");
}
};
/**
* Completes the change by adding change handler specific content
*
* @param {sap.ui.fl.Change} oChange change object to be completed
* @param {object} oSpecificChangeInfo as an empty object since no additional attributes are required for this operation
* @public
*/
UnhideControl.prototype.completeChangeContent = function(oChange, oSpecificChangeInfo) {
var oChangeJson = oChange.getDefinition();
if (!oChangeJson.content) {
oChangeJson.content = {};
}
};
return UnhideControl;
},
/* bExport= */true);
}; // end of sap/ui/fl/changeHandler/UnhideControl.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.core.FlexVisualizer') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.core.FlexVisualizer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/core/FlexVisualizer",[
"jquery.sap.global"
], function(jQuery) {
"use strict";
/**
*
* @constructor
* @alias sap.ui.fl.core.FlexVisualizer
*
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*
*/
var FlexVisualizer = function() {
};
/**
* Show a dialog providing detailed options to do a change
* @param {Object} oAffectedRegistryItems Relevant registry items required by the dialog to display itself correctly
* @param {Boolean} bIsKeyUser Is the current user in key user mode
*
* @public
*/
FlexVisualizer.showDialog = function(oAffectedRegistryItems, bIsKeyUser) {
};
/**
* Close an open dialog explicitly
*
* @public
*/
FlexVisualizer.closeDialog = function() {
};
return FlexVisualizer;
}, true);
}; // end of sap/ui/fl/core/FlexVisualizer.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.fieldExt.Access') ) {
/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/* global Promise */
jQuery.sap.declare('sap.ui.fl.fieldExt.Access'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
sap.ui.define("sap/ui/fl/fieldExt/Access",[], function() {
"use strict";
/**
* @namespace
* @alias sap.ui.fl.fieldExt.Access
* @experimental Since 1.25.0
* @author <NAME>
* @version 1.36.12
*/
var Access = {};
/**
* Returns all Business Contexts for given service and EntityTypeName/EntitySetName. Not that only EntityTypeName or EntitySetName can be
* supplied. Providing both results in an exception
*
* @param {string} sServiceUri
* @param {string} sEntityTypeName
* @param {string} sEntitySetName
* @returns {array} aBusinessContexts
* @public
*/
Access.getBusinessContexts = function(sServiceUri, sEntityTypeName, sEntitySetName) {
// Determine ServiceName and ServiceVersion from Service URI
var sServiceName = this._parseServiceName(sServiceUri);
var sServiceVersion = this._parseServiceVersion(sServiceUri, sServiceName);
// Build URL for BusinessContextRetrievalService based on ServiceName, ServiceVersion, EntityName
var sBusinessContextRetrievalUri = this._buildBusinessContextRetrievalUri(sServiceName, sServiceVersion, sEntityTypeName, sEntitySetName);
// Execute Ajax call
var mAjaxSettings = this._getAjaxSettings();
var promise = this._executeAjaxCall(sBusinessContextRetrievalUri, mAjaxSettings, sServiceName, sServiceVersion, sEntityTypeName, sEntitySetName);
return promise;
};
/**
* Extracts ServiceName out of Service URI
*
* @private
* @param {string} sServiceUri
* @returns {string} sVersionName
*/
Access._parseServiceName = function(sServiceUri) {
var sServiceName, sServiceNameWithVersion;
var sODataPath = "sap/opu/odata";
var iIndexOfODataPath = sServiceUri.indexOf(sODataPath);
if (iIndexOfODataPath !== -1) {
// Remove service path prefix
var iEndOfsODataPath = iIndexOfODataPath + sODataPath.length;
sServiceNameWithVersion = sServiceUri.substring(iEndOfsODataPath);
var sSapPrefix = "/SAP";
var bHasSapPrefix = jQuery.sap.startsWith(sServiceNameWithVersion, sSapPrefix);
if (bHasSapPrefix) {
// case of sap specific namespace for the service
sServiceNameWithVersion = sServiceNameWithVersion.substring(sSapPrefix.length);
}
} else {
// Remove all stuff before and including the first slash
var iStartPositionOfServiceName = sServiceUri.lastIndexOf("/") + 1;
sServiceNameWithVersion = sServiceUri.substring(iStartPositionOfServiceName);
}
if (sServiceNameWithVersion.indexOf(";v=") != -1) {
// Cut away all URI stuff that comes before the serviceName
sServiceName = sServiceNameWithVersion.substring(0, sServiceNameWithVersion.indexOf(";v="));
} else {
sServiceName = sServiceNameWithVersion;
}
return sServiceName;
};
/**
* Extracts ServiceVersion out of Service URI
*
* @private
* @param {string} sServiceUri
* @param {string} sServiceName
* @returns {string} sVersionNumber
*/
Access._parseServiceVersion = function(sServiceUri, sServiceName) {
if (sServiceUri.indexOf(sServiceName + ";v=") != -1) {
// Cut away all URI stuff that comes before the serviceName
var iPositionOfServiceWithVersionFragment = sServiceUri.indexOf(sServiceName + ";v=");
var sRemainingUri = sServiceUri.substring(iPositionOfServiceWithVersionFragment);
// Get String from ";v=" up to the next "/" --> this is the version
// number
var iPositionAfterVersionPrefix = sServiceName.length + 3;
var sVersionNumber = sRemainingUri.slice(iPositionAfterVersionPrefix, sRemainingUri.indexOf("/"));
return sVersionNumber;
} else {// In this case there is no version information and so it is
// version 1
return "0001";
}
};
/**
* Builds URI for BusinessContext Retrieval
*
* @private
* @param {string} sServiceUri
* @param {string} sServiceName
* @param {string} sEntityName
* @param {string} sEntitySetName
* @returns {string} sBusinessContextRetrievalUri
*/
Access._buildBusinessContextRetrievalUri = function(sServiceName, sServiceVersion, sEntityName, sEntitySetName) {
if (sEntityName == null) {
sEntityName = '';
}
if (sEntitySetName == null) {
sEntitySetName = '';
}
if (((sEntitySetName.length == 0) && (sEntityName.length == 0)) || (!(sEntitySetName.length == 0) && !(sEntityName.length == 0))) {
throw new Error("sap.ui.fl.fieldExt.Access._buildBusinessContextRetrievalUri()" + "Inconsistent input parameters EntityName: " + sEntityName + " EntitySet: " + sEntitySetName);
}
// Example call:
// sap/opu/odata/SAP/APS_CUSTOM_FIELD_MAINTENANCE_SRV/GetBusinessContextsByEntityType?EntitySetName=''&EntityTypeName='BusinessPartner'&ServiceName='CFD_TSM_BUPA_MAINT_SRV'&ServiceVersion='0001'&$format=json
var sBusinessContextRetrievalUri = "/sap/opu/odata/SAP/APS_CUSTOM_FIELD_MAINTENANCE_SRV/GetBusinessContextsByEntityType?" + "EntitySetName=\'" + sEntitySetName + "\'" + "&EntityTypeName=\'" + sEntityName + "\'" + "&ServiceName=\'" + sServiceName + "\'" + "&ServiceVersion=\'" + sServiceVersion + "\'" + "&$format=json";
return sBusinessContextRetrievalUri;
};
/**
* Executes Ajax Call for BusinessContext Retrieval
*
* @private
* @param {string} sBusinessContextRetrievalUri
* @param {map} mRequestSettings
* @param {string} sServiceName
* @param {string} sServiceVersion
* @param {string} sEntityName
* @returns {Object} oPromise
*/
Access._executeAjaxCall = function(sBusinessContextRetrievalUri, mRequestSettings, sServiceName, sServiceVersion, sEntityType, sEntitySetName) {
var that = this;
var oDeferred = jQuery.Deferred();
jQuery.ajax(sBusinessContextRetrievalUri, mRequestSettings).done(function(data, textStatus, jqXHR) {
var aBusinessContexts = [];
if (data) {
var aBusinessContexts = that._extractBusinessContexts(data);
}
var oResult = {
BusinessContexts: aBusinessContexts,
ServiceName: sServiceName,
ServiceVersion: sServiceVersion
};
oDeferred.resolve(oResult);
}).fail(function(jqXHR, textStatus, errorThrown) {
var aErrorMessages = that._getMessagesFromXHR(jqXHR);
var oError = {
errorOccured: true,
errorMessages: aErrorMessages,
serviceName: sServiceName,
serviceVersion: sServiceVersion,
entityType: sEntityType,
entitySet: sEntitySetName
};
oDeferred.reject(oError);
});
return oDeferred.promise();
};
/**
* @private
* @returns {map} mSettings
*/
Access._getAjaxSettings = function() {
var mSettings = {
type: "GET",
async: true,
dataType: 'json'
};
return mSettings;
};
/**
* Extracts BusinessContext out of Request response data
*
* @private
* @param {object} oData
* @returns {array} BusinessContexts
*/
Access._extractBusinessContexts = function(data) {
var aResults = null;
var aBusinessContexts = [];
if (data && data.d) {
aResults = data.d.results;
}
if (aResults !== null && aResults.length > 0) {
for (var i = 0; i < aResults.length; i++) {
if (aResults[i].BusinessContext !== null) {
aBusinessContexts.push(aResults[i].BusinessContext);
}
}
}
return aBusinessContexts;
};
/**
* Extracts error messages from request failure response
*
* @private
* @param {object} oXHR
* @returns {array} errorMessages
*/
Access._getMessagesFromXHR = function(oXHR) {
var aMessages = [];
try {
var oErrorResponse = JSON.parse(oXHR.responseText);
if (oErrorResponse && oErrorResponse.error && oErrorResponse.error.message && oErrorResponse.error.message.value && oErrorResponse.error.message.value !== '') {
aMessages.push({
severity: "error",
text: oErrorResponse.error.message.value
});
} else {
aMessages.push({
severity: "error",
text: oXHR.responseText
});
}
} catch (e) {
// ignore
}
return aMessages;
};
return Access;
}, /* bExport= */true);
}; // end of sap/ui/fl/fieldExt/Access.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.registry.ChangeRegistryItem') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.registry.ChangeRegistryItem'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/registry/ChangeRegistryItem",[
"sap/ui/fl/Utils", "jquery.sap.global"
], function(Utils, jQuery) {
"use strict";
/**
* Object to define a change on a specific control type with it's permissions
* @constructor
* @param {Object} mParam Parameter description below
* @param {sap.ui.fl.registry.ChangeTypeMetadata} mParam.changeTypeMetadata Change type metadata this registry item is describing
* @param {String} mParam.controlType Control type this registry item is assigned to
* @param {Object} [mParam.permittedRoles] Permissions who is allowed to use this kind of change type on the assigned control
* @alias sap.ui.fl.registry.ChangeRegistryItem
*
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*
*/
var ChangeRegistryItem = function(mParam) {
if (!mParam.changeTypeMetadata) {
Utils.log.error("sap.ui.fl.registry.ChangeRegistryItem: ChangeTypeMetadata required");
}
if (!mParam.controlType) {
Utils.log.error("sap.ui.fl.registry.ChangeRegistryItem: ControlType required");
}
this._changeTypeMetadata = mParam.changeTypeMetadata;
this._controlType = mParam.controlType;
if (mParam.permittedRoles) {
this._permittedRoles = mParam.permittedRoles;
}
if (mParam.dragTargets) {
this._dragTargets = mParam.dragTargets;
}
};
ChangeRegistryItem.prototype._changeTypeMetadata = undefined;
ChangeRegistryItem.prototype._controlType = undefined;
ChangeRegistryItem.prototype._permittedRoles = {};
ChangeRegistryItem.prototype._dragTargets = [];
/**
* Get the metadata for a change type
*
* @returns {sap.ui.fl.registry.ChangeTypeMetadata} Returns the change type metadata of the item
*
* @public
*/
ChangeRegistryItem.prototype.getChangeTypeMetadata = function() {
return this._changeTypeMetadata;
};
/**
* Get the name of a change type
*
* @returns {String} Returns the name of the change type of the item
*
* @public
*/
ChangeRegistryItem.prototype.getChangeTypeName = function() {
return this._changeTypeMetadata.getName();
};
/**
* Get the control type
*
* @returns {String} Returns the control type the item is assigned to
*
* @public
*/
ChangeRegistryItem.prototype.getControlType = function() {
return this._controlType;
};
/**
* Get the roles the change type for the control is permitted to
*
* @returns {String} Returns a list of permitted roles
*
* @public
*/
ChangeRegistryItem.prototype.getPermittedRoles = function() {
return this._permittedRoles;
};
/**
* Get the targets the control type can be dragged on
*
* @returns {String} Returns a list of possible drag targets
*
* @public
*/
ChangeRegistryItem.prototype.getDragTargets = function() {
return this._dragTargets;
};
return ChangeRegistryItem;
}, true);
}; // end of sap/ui/fl/registry/ChangeRegistryItem.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.registry.ChangeTypeMetadata') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.registry.ChangeTypeMetadata'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/registry/ChangeTypeMetadata",[
"sap/ui/fl/Utils", "jquery.sap.global"
], function(Utils, jQuery) {
"use strict";
/**
* Object to define a change type with it's handlers and visual appearance options
* @constructor
* @param {Object} mParam Parameter description below
* @param {String} mParam.name Semantic name to identify the change type
* @param {String} mParam.changeHandler Full qualified name of the function which is executed when a change for this change type is merged or applied
* @param {String} [mParam.labelKey] Key of the translatable label
* @param {String} [mParam.tooltipKey] Key of the translatable tooltip
* @param {String} [mParam.iconKey] Key of the icon which should be displayed
* @param {Object} [mParam.sortIndex] Index to sort the change type on the visualization. (0 = default, lowest priority)
* @alias sap.ui.fl.registry.ChangeTypeMetadata
*
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*
*/
var ChangeTypeMetadata = function(mParam) {
if (!mParam.name) {
Utils.log.error("sap.ui.fl.registry.ChangeType: Name required");
}
if (!mParam.changeHandler) {
Utils.log.error("sap.ui.fl.registry.ChangeType: ChangeHandler required");
}
this._name = mParam.name;
this._changeHandler = mParam.changeHandler;
if (mParam.labelKey) {
this._labelKey = mParam.labelKey;
}
if (mParam.tooltipKey) {
this._tooltipKey = mParam.tooltipKey;
}
if (mParam.iconKey) {
this._iconKey = mParam.iconKey;
}
if (mParam.sortIndex) {
this._sortIndex = mParam.sortIndex;
}
};
ChangeTypeMetadata.prototype._name = "";
ChangeTypeMetadata.prototype._changeHandler = "";
ChangeTypeMetadata.prototype._sortIndex = 0;
ChangeTypeMetadata.prototype._labelKey = "";
ChangeTypeMetadata.prototype._tooltipKey = "";
ChangeTypeMetadata.prototype._iconKey = "";
/**
* Get the semantical name of the change type
* @returns {String} Returns the semantical name of the change type
* @public
*/
ChangeTypeMetadata.prototype.getName = function() {
return this._name;
};
/**
* Get the full qualified name of the change handler function
* @returns {String} Returns the full qualified name of the change handler function
* @public
*/
ChangeTypeMetadata.prototype.getChangeHandler = function() {
return this._changeHandler;
};
/**
* Get the translated label text for this type of change
* @returns {String} Returns the translated label text for this type of change
* @public
*/
ChangeTypeMetadata.prototype.getLabel = function() {
return this._labelKey; //TODO: Add call with translation
};
/**
* Get the translated tooltip text for this type of change
* @returns {String} Returns the translated tooltip text for this type of change
* @public
*/
ChangeTypeMetadata.prototype.getTooltip = function() {
//TODO: Add call with translation
return this._tooltipKey;
};
/**
* Get the path to the icon which should be displayed for this type of change
* @returns {String} Returns the path to the icon which should be displayed for this type of change
* @public
*/
ChangeTypeMetadata.prototype.getIcon = function() {
return this._iconKey; //TODO: Add call to get icon path
};
/**
* Get the sort index of this type of change
* @returns {String} Returns the sort index of this type of change
* @public
*/
ChangeTypeMetadata.prototype.getSortIndex = function() {
return this._sortIndex;
};
return ChangeTypeMetadata;
}, true);
}; // end of sap/ui/fl/registry/ChangeTypeMetadata.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.registry.SimpleChanges') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.registry.SimpleChanges'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/registry/SimpleChanges",[
"jquery.sap.global", "sap/ui/fl/changeHandler/HideControl", "sap/ui/fl/changeHandler/UnhideControl", "sap/ui/fl/changeHandler/MoveElements", "sap/ui/fl/changeHandler/PropertyChange"
], function(jQuery, HideControl, UnhideControl, MoveElements, PropertyChange) {
"use strict";
/**
* Object containing standard changes like labelChange. Structure is like this: <code> { "labelChange":{"changeType":"labelChange", "changeHandler":sap.ui.fl.changeHandler.LabelChange}} </code>
* @constructor
* @alias sap.ui.fl.registry.SimpleChanges
*
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*
*/
var SimpleChanges = {
hideControl: {
changeType: "hideControl",
changeHandler: HideControl
},
unhideControl: {
changeType: "unhideControl",
changeHandler: UnhideControl
},
moveElements: {
changeType: "moveElements",
changeHandler: MoveElements
},
propertyChange : {
changeType: "propertyChange",
changeHandler: PropertyChange
}
};
return SimpleChanges;
}, true);
}; // end of sap/ui/fl/registry/SimpleChanges.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.Cache') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.Cache'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
sap.ui.define("sap/ui/fl/Cache",["sap/ui/fl/Utils"], function(Utils) {
"use strict";
/**
* Helper object to access a change from the backend.
* Access helper object for each change (and variant) which was fetched from the backend
*
* @namespace
* @alias sap.ui.fl.Cache
* @experimental Since 1.25.0
* @author SAP SE
* @version 1.36.12
*/
var Cache = function() {
};
Cache._isOn = true;
Cache._entries = {};
/**
* Indicates if the cache is active or not (for testing)
*
* @returns {boolean} Is Cache currently active or not
*
* @public
*/
Cache.isActive = function() {
return Cache._isOn;
};
/**
* Sets the active state
*
* @param {boolean} bActive - cache active or not
*
* @public
*/
Cache.setActive = function(bActive) {
Cache._isOn = bActive;
};
/**
* This method retrieves the changes for a given
* component. It answers all subsequent calls with the same promise, which
* will resolve with the same result. In the success case, it will keep the
* promise to resolve all calls in future event loop execution paths with
* the same result. In case of an error, it will delete the initial promise
* to give calls from future execution paths the chance to re-request the
* changes from the backend.
*
* If the cache is not active, the method just delegates the call to the
* loadChanges method of the given LrepConnector.
*
* @param {sap.ui.fl.LrepConnector} oLrepConnector - LrepConnector instance to retrieve the changes with
* @param {string} sComponentName - the component name to retrieve the changes for
* @param {map} mPropertyBag - (optional) contains additional data that are needed for reading of changes
* - appDescriptor that belongs to actual component
* - siteId that belongs to actual component
* @returns {Promise} resolves with the change file for the given component, either from cache or backend
*
* @public
*/
Cache.getChangesFillingCache = function(oLrepConnector, sComponentName, mPropertyBag) {
if (!this.isActive()) {
return oLrepConnector.loadChanges(sComponentName, mPropertyBag);
}
var oCacheEntry = Cache._entries[sComponentName];
if (!oCacheEntry) {
oCacheEntry = Cache._entries[sComponentName] = {};
}
if (oCacheEntry.promise) {
return oCacheEntry.promise;
}
var currentLoadChanges = oLrepConnector.loadChanges(sComponentName, mPropertyBag).then(function(mChanges) {
if (oCacheEntry.file) {
Utils.log.error('sap.ui.fl.Cache: Cached changes for component ' + sComponentName + ' overwritten.');
}
oCacheEntry.file = mChanges;
return oCacheEntry.file;
}, function(err) {
delete oCacheEntry.promise;
throw err;
});
oCacheEntry.promise = currentLoadChanges;
return currentLoadChanges;
};
/**
* @private
*
* @param {string} sComponentName - name of the SAPUI5 component
* @returns {array} Array of changes
*/
Cache._getChangeArray = function(sComponentName) {
var oEntry = Cache._entries[sComponentName];
if (oEntry) {
if (oEntry.file) {
return oEntry.file.changes.changes;
}
}
};
/**
* Add a change for the given component to the cached changes.
*
* @param {string} sComponentName Name of the component
* @param {object} oChange The change in JSON format
* @public
*/
Cache.addChange = function(sComponentName, oChange) {
var aChanges = Cache._getChangeArray(sComponentName);
if (!aChanges) {
return;
}
aChanges.push(oChange);
};
/**
* Updates a change for the given component in the cached changes.
*
* @param {string} sComponentName Name of the component
* @param {object} oChange The change in JSON format
* @public
*/
Cache.updateChange = function(sComponentName, oChange) {
var aChanges = Cache._getChangeArray(sComponentName);
if (!aChanges) {
return;
}
for ( var i = 0; i < aChanges.length; i++) {
if (aChanges[i].fileName === oChange.fileName) {
aChanges.splice(i, 1, oChange);
break;
}
}
};
/**
* Delete a change for the given component from the cached changes.
*
* @param {string} sComponentName Name of the SAPUI5 component
* @param {object} oChangeDefinition The change in JSON format
* @public
*/
Cache.deleteChange = function(sComponentName, oChangeDefinition) {
var aChanges = Cache._getChangeArray(sComponentName);
if (!aChanges) {
return;
}
for ( var i = 0; i < aChanges.length; i++) {
if (aChanges[i].fileName === oChangeDefinition.fileName) {
aChanges.splice(i, 1);
break;
}
}
};
return Cache;
}, /* bExport= */true);
}; // end of sap/ui/fl/Cache.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.LrepConnector') ) {
/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/* global Promise */
jQuery.sap.declare('sap.ui.fl.LrepConnector'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.thirdparty.URI'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/LrepConnector",[
"jquery.sap.global", "sap/ui/thirdparty/URI", "sap/ui/fl/Utils"
], function(jQuery, uri, FlexUtils) {
"use strict";
/**
* Provides the connectivity to the ABAP based LRep REST-service
*
* @param {object} [mParameters] - map of parameters, see below
* @param {String} [mParameters.XsrfToken] - XSRF Token which can be reused for the backend connectivity. If no XSRF token is passed, a new one
* will be fetched from backend.
* @constructor
* @alias sap.ui.fl.LrepConnector
* @experimental Since 1.25.0
* @author SAP SE
* @version 1.36.12
*/
var Connector = function(mParameters) {
this._initClientParam();
this._initLanguageParam();
if (mParameters) {
this._sXsrfToken = mParameters.XsrfToken;
}
};
Connector.createConnector = function(mParameters) {
return new Connector(mParameters);
};
Connector.prototype.DEFAULT_CONTENT_TYPE = "application/json";
Connector.prototype._sClient = undefined;
Connector.prototype._sLanguage = undefined;
Connector.prototype._aSentRequestListeners = [];
/**
* Registers a callback for a sent request to the backend. The callback is called for each change done one time! Each call is done with an object
* similar to the resolve of the promises containing a <code>status</code> of the response from the backend i.e. <code>success</code>, a
* <code>response</code> containing the change processed in this request
*
* @param {function} fCallback function called after all related promises are resolved
* @public
*/
Connector.attachSentRequest = function(fCallback) {
if (typeof fCallback === "function" && Connector.prototype._aSentRequestListeners.indexOf(fCallback) === -1) {
Connector.prototype._aSentRequestListeners.push(fCallback);
}
};
/**
* Deregisters a callback for a sent request to the backend if the callback was registered
*
* @param {function} fCallback function called after all related promises are resolved
* @public
*/
Connector.detachSentRequest = function(fCallback) {
var iIndex = Connector.prototype._aSentRequestListeners.indexOf(fCallback);
if (iIndex !== -1) {
Connector.prototype._aSentRequestListeners.splice(iIndex, 1);
}
};
/**
* Extract client from current running instance
*
* @private
*/
Connector.prototype._initClientParam = function() {
var client = FlexUtils.getClient();
if (client) {
this._sClient = client;
}
};
/**
* Extract the sap-language url parameter from current url
*
* @private
*/
Connector.prototype._initLanguageParam = function() {
var sLanguage;
sLanguage = this._getUrlParameter('sap-language') || this._getUrlParameter('sap-ui-language');
if (sLanguage) {
this._sLanguage = sLanguage;
}
};
/**
* Returns the a string containing all url parameters of the current window.location
*
* @returns {string} Substring of url containing the url query parameters
* @private
*/
Connector.prototype._getAllUrlParameters = function() {
return window.location.search.substring(1);
};
/**
* Returns the value of the specified url parameter of the current url
*
* @param {String} sParameterName - Name of the url parameter
* @returns {string} url parameter
* @private
*/
Connector.prototype._getUrlParameter = function(sParameterName) {
var aURLVariables, sUrlParams, i, aCurrentParameter;
sUrlParams = this._getAllUrlParameters();
aURLVariables = sUrlParams.split('&');
for (i = 0; i < aURLVariables.length; i++) {
aCurrentParameter = aURLVariables[i].split('=');
if (aCurrentParameter[0] === sParameterName) {
return aCurrentParameter[1];
}
}
};
/**
* Resolve the complete url of a request by taking the backendUrl and the relative url from the request
*
* @param {String} sRelativeUrl - relative url of the current request
* @returns {sap.ui.core.URI} returns the complete uri for this request
* @private
*/
Connector.prototype._resolveUrl = function(sRelativeUrl) {
if (!jQuery.sap.startsWith(sRelativeUrl, "/")) {
sRelativeUrl = "/" + sRelativeUrl;
}
var oUri = uri(sRelativeUrl).absoluteTo("");
return oUri.toString();
};
/**
* Get the default header for a request
*
* @returns {Object} Returns an object containing all headers for each request
* @private
*/
Connector.prototype._getDefaultHeader = function() {
var mHeaders = {
headers: {
"X-CSRF-Token": this._sXsrfToken || "fetch"
}
};
return mHeaders;
};
/**
* Get the default options, required for the jQuery.ajax request
*
* @param {String} sMethod - HTTP-method (PUT, POST, GET (default)...) used for this request
* @param {String} sContentType - Set the content-type manually and overwrite the default (application/json)
* @param {Object} oData - Payload of the request
* @returns {Object} Returns an object containing the options and the default header for a jQuery.ajax request
* @private
*/
Connector.prototype._getDefaultOptions = function(sMethod, sContentType, oData) {
var mOptions;
if (!sContentType) {
sContentType = this.DEFAULT_CONTENT_TYPE;
}
mOptions = jQuery.extend(true, this._getDefaultHeader(), {
type: sMethod,
async: true,
contentType: sContentType,
processData: false,
//xhrFields: {
// withCredentials: true
//},
headers: {
"Content-Type": sContentType
}
});
if (oData && mOptions.contentType === 'application/json') {
mOptions.dataType = 'json';
if (typeof oData === 'object') {
mOptions.data = JSON.stringify(oData);
} else {
mOptions.data = oData;
}
} else if (oData) {
mOptions.data = oData;
}
if (sMethod === 'DELETE') {
delete mOptions.data;
delete mOptions.contentType;
}
return mOptions;
};
/**
* Send a request to the backend
*
* @param {String} sUri Relative url for this request
* @param {String} sMethod HTTP-method to be used by this request (default GET)
* @param {Object} oData Payload of the request
* @param {Object} mOptions Additional options which should be used in the request
* @returns {Promise} Returns a promise to the result of the request
* @public
*/
Connector.prototype.send = function(sUri, sMethod, oData, mOptions) {
sMethod = sMethod || "GET";
sMethod = sMethod.toUpperCase();
mOptions = mOptions || {};
sUri = this._resolveUrl(sUri);
if (mOptions.success || mOptions.error) {
var sErrorMessage = "Success and error handler are not allowed in mOptions";
throw new Error(sErrorMessage);
}
var sContentType = mOptions.contentType || this.DEFAULT_CONTENT_TYPE;
mOptions = jQuery.extend(true, this._getDefaultOptions(sMethod, sContentType, oData), mOptions);
return this._sendAjaxRequest(sUri, mOptions);
};
/**
* Extracts the messages from the backend reponse
*
* @param {Object} oXHR - ajax request object
* @returns {Array} Array of messages, for example <code>[ { "severity": "Error", "text": "content id must be non-initial" } ] </code>
* @private
*/
Connector.prototype._getMessagesFromXHR = function(oXHR) {
var errorResponse, aMessages, length, i;
aMessages = [];
try {
errorResponse = JSON.parse(oXHR.responseText);
if (errorResponse && errorResponse.messages && errorResponse.messages.length > 0) {
length = errorResponse.messages.length;
for (i = 0; i < length; i++) {
aMessages.push({
severity: errorResponse.messages[i].severity,
text: errorResponse.messages[i].text
});
}
}
} catch (e) {
// ignore
}
return aMessages;
};
/**
* @param {String} sUri - Complete request url
* @param {Object} mOptions - Options to be used by the request
* @returns {Promise} Returns a Promise with the status and response and messages
* @private
*/
Connector.prototype._sendAjaxRequest = function(sUri, mOptions) {
var that = this;
var sFetchXsrfTokenUrl = "/sap/bc/lrep/actions/getcsrftoken/";
var mFetchXsrfTokenOptions = {
headers: {
'X-CSRF-Token': 'fetch'
},
type: "HEAD"
};
if (this._sClient) {
mFetchXsrfTokenOptions.headers['sap-client'] = this._sClient;
}
return new Promise(function(resolve, reject) {
function handleValidRequest(oResponse, sStatus, oXhr) {
var sNewCsrfToken = oXhr.getResponseHeader("X-CSRF-Token");
that._sXsrfToken = sNewCsrfToken || that._sXsrfToken;
var oResult = {
status: sStatus,
response: oResponse
};
resolve(oResult);
jQuery.each(that._aSentRequestListeners, function(iIndex, fCallback) {
fCallback(oResult);
});
}
function fetchTokenAndHandleRequest(oResponse, sStatus, oXhr) {
that._sXsrfToken = oXhr.getResponseHeader("X-CSRF-Token");
mOptions.headers = mOptions.headers || {};
mOptions.headers["X-CSRF-Token"] = that._sXsrfToken;
// Re-send request after fetching token
jQuery.ajax(sUri, mOptions).done(handleValidRequest).fail(function(oXhr, sStatus, sErrorThrown) {
var oError = new Error(sErrorThrown);
oError.status = "error";
oError.code = oXhr.statusCode().status;
oError.messages = that._getMessagesFromXHR(oXhr);
reject(oError);
});
}
function refetchTokenAndRequestAgainOrHandleInvalidRequest(oXhr, sStatus, sErrorThrown) {
if (oXhr.status === 403) {
// Token seems to be invalid, refetch and then resend
jQuery.ajax(sFetchXsrfTokenUrl, mFetchXsrfTokenOptions).done(fetchTokenAndHandleRequest).fail(function(oXhr, sStatus, sErrorThrown) {
// Fetching XSRF Token failed
reject({
status: "error"
});
});
} else {
if (mOptions && mOptions.type === "DELETE" && oXhr.status === 404) {
// Do not reject, if a file was not found during deletion
// (can be the case if another user already triggered a restore meanwhile)
resolve();
} else {
var result;
result = {
status: "error"
};
result.code = oXhr.statusCode().status;
result.messages = that._getMessagesFromXHR(oXhr);
reject(result);
}
}
}
//Check, whether CSRF token has to be requested
var bRequestCSRFToken = true;
if (mOptions && mOptions.type) {
if (mOptions.type === 'GET' || mOptions.type === 'HEAD') {
bRequestCSRFToken = false;
}
} else {
if (that._sXsrfToken && that._sXsrfToken !== "fetch") {
bRequestCSRFToken = false;
}
}
if (bRequestCSRFToken) {
// Fetch XSRF Token
jQuery.ajax(sFetchXsrfTokenUrl, mFetchXsrfTokenOptions).done(fetchTokenAndHandleRequest).fail(function(oXhr, sStatus, sErrorThrown) {
// Fetching XSRF Token failed
reject({
status: "error"
});
});
} else {
// Send normal request
jQuery.ajax(sUri, mOptions).done(handleValidRequest).fail(refetchTokenAndRequestAgainOrHandleInvalidRequest);
}
});
};
/**
* Loads the changes for the given component class name.
*
* @see sap.ui.core.Component
* @param {String} sComponentClassName - Component class name
* @param {map} mPropertyBag - (optional) contains additional data that are needed for reading of changes - appDescriptor that belongs to actual
* component - siteId that belongs to actual component
* @returns {Promise} Returns a Promise with the changes and componentClassName
* @public
*/
Connector.prototype.loadChanges = function(sComponentClassName, mPropertyBag) {
var sUri, oPromise, mOptions;
var that = this;
if (!sComponentClassName) {
return Promise.reject(new Error('Component name not specified'));
}
sUri = '/sap/bc/lrep/flex/data/';
if (sComponentClassName) {
sUri += sComponentClassName;
}
if (this._sClient) {
sUri += '&sap-client=' + this._sClient;
}
// Replace first & with ?
sUri = sUri.replace('&', '?');
// fill header attribute: appDescriptor.id
if (mPropertyBag) {
if (mPropertyBag.appDescriptor) {
if (mPropertyBag.appDescriptor["sap.app"]) {
if (!mOptions) {
mOptions = {};
}
if (!mOptions.headers) {
mOptions.headers = {};
}
mOptions.headers = {
"X-LRep-AppDescriptor-Id": mPropertyBag.appDescriptor["sap.app"].id
};
}
}
// fill header attribute: siteId
if (mPropertyBag.siteId) {
if (!mOptions) {
mOptions = {};
}
if (!mOptions.headers) {
mOptions.headers = {};
}
mOptions.headers = {
"X-LRep-Site-Id": mPropertyBag.siteId
};
}
}
oPromise = this.send(sUri, undefined, undefined, mOptions);
return oPromise.then(function(oResponse) {
if (oResponse.response) {
return {
changes: oResponse.response,
messagebundle: oResponse.response.messagebundle,
componentClassName: sComponentClassName
};
} else {
return Promise.reject('response is empty');
}
}, function(oError) {
if (oError.code === 404 || oError.code === 405) {
// load changes based old route, because new route is not implemented
return that._loadChangesBasedOnOldRoute(sComponentClassName);
} else {
throw (oError);
}
});
};
Connector.prototype._loadChangesBasedOnOldRoute = function(sComponentClassName) {
var resourceName, params;
try {
resourceName = jQuery.sap.getResourceName(sComponentClassName, "-changes.json");
} catch (e) {
return Promise.reject(e);
}
params = {
async: true,
dataType: "json",
failOnError: true,
headers: {
"X-UI5-Component": sComponentClassName
}
};
if (this._sClient) {
params.headers["sap-client"] = this._sClient;
}
return jQuery.sap.loadResource(resourceName, params).then(function(oResponse) {
return {
changes: oResponse,
componentClassName: sComponentClassName
};
});
};
/**
* @param {Array} aParams Array of parameter objects in format {name:<name>, value:<value>}
* @returns {String} Returns a String with all parameters concatenated
* @private
*/
Connector.prototype._buildParams = function(aParams) {
if (!aParams) {
aParams = [];
}
if (this._sClient) {
// Add mandatory 'sap-client' parameter
aParams.push({
name: "sap-client",
value: this._sClient
});
}
if (this._sLanguage) {
// Add mandatory 'sap-language' url parameter.
// sap-language shall be used only if there is a sap-language parameter in the original url.
// If sap-language is not added, the browser language might be used as backend login language instead of sap-language.
aParams.push({
name: "sap-language",
value: this._sLanguage
});
}
var result = "";
var len = aParams.length;
for (var i = 0; i < len; i++) {
if (i === 0) {
result += "?";
} else if (i > 0 && i < len) {
result += "&";
}
result += aParams[i].name + "=" + aParams[i].value;
}
return result;
};
/**
* The URL prefix of the REST API for example /sap/bc/lrep/changes/.
*
* @param {Boolean} bIsVariant Flag whether the change is of type variant
* @returns {String} url prefix
* @private
*/
Connector.prototype._getUrlPrefix = function(bIsVariant) {
if (bIsVariant) {
return "/sap/bc/lrep/variants/";
}
return "/sap/bc/lrep/changes/";
};
/**
* Creates a change or variant via REST call.
*
* @param {Object} oPayload The content which is send to the server
* @param {String} [sChangelist] The transport ID.
* @param {Boolean} bIsVariant - is variant?
* @returns {Object} Returns the result from the request
* @public
*/
Connector.prototype.create = function(oPayload, sChangelist, bIsVariant) {
var sRequestPath = this._getUrlPrefix(bIsVariant);
var aParams = [];
if (sChangelist) {
aParams.push({
name: "changelist",
value: sChangelist
});
}
sRequestPath += this._buildParams(aParams);
return this.send(sRequestPath, "POST", oPayload, null);
};
/**
* Update a change or variant via REST call.
*
* @param {Object} oPayload The content which is send to the server
* @param {String} sChangeName Name of the change
* @param {String} sChangelist (optional) The transport ID.
* @param {Boolean} bIsVariant - is variant?
* @returns {Object} Returns the result from the request
* @public
*/
Connector.prototype.update = function(oPayload, sChangeName, sChangelist, bIsVariant) {
var sRequestPath = this._getUrlPrefix(bIsVariant);
sRequestPath += sChangeName;
var aParams = [];
if (sChangelist) {
aParams.push({
name: "changelist",
value: sChangelist
});
}
sRequestPath += this._buildParams(aParams);
return this.send(sRequestPath, "PUT", oPayload, null);
};
/**
* Delete a change or variant via REST call.
*
* @param {String} mParameters property bag
* @param {String} mParameters.sChangeName - name of the change
* @param {String} [mParameters.sLayer='USER'] - other possible layers: VENDOR,PARTNER,CUSTOMER
* @param {String} mParameters.sNamespace - the namespace of the change file
* @param {String} mParameters.sChangelist - The transport ID.
* @param {Boolean} bIsVariant - is it a variant?
* @returns {Object} Returns the result from the request
* @public
*/
Connector.prototype.deleteChange = function(mParameters, bIsVariant) {
// REVISE rename to deleteFile
var sRequestPath = this._getUrlPrefix(bIsVariant);
sRequestPath += mParameters.sChangeName;
var aParams = [];
if (mParameters.sLayer) {
aParams.push({
name: "layer",
value: mParameters.sLayer
});
}
if (mParameters.sNamespace) {
aParams.push({
name: "namespace",
value: mParameters.sNamespace
});
}
if (mParameters.sChangelist) {
aParams.push({
name: "changelist",
value: mParameters.sChangelist
});
}
sRequestPath += this._buildParams(aParams);
return this.send(sRequestPath, "DELETE", {}, null);
};
/**
* Authenticated access to a resource in the Lrep
*
* @param {String} sNamespace The abap package goes here. It is needed to identify the change. Default LREP namespace is "localchange".
* @param {String} sName Name of the change
* @param {String} sType File type extension
* @param {Boolean} bIsRuntime The stored file content is handed over to the lrep provider that can dynamically adjust the content to the runtime
* context (e.g. do text replacement to the users' logon language) before
* @returns {Object} Returns the result from the request
* @public
*/
Connector.prototype.getStaticResource = function(sNamespace, sName, sType, bIsRuntime) {
var sApiPath = "/sap/bc/lrep/content/";
var sRequestPath = sApiPath;
sRequestPath += sNamespace + "/" + sName + "." + sType;
var aParams = [];
if (!bIsRuntime) {
aParams.push({
name: "dt",
value: "true"
});
}
sRequestPath += this._buildParams(aParams);
return this.send(sRequestPath, "GET", {}, null);
};
/**
* Retrieves the file attributes for a given resource in the LREP.
*
* @param {String} sNamespace The abap package goes here. It is needed to identify the change. Default LREP namespace is "localchange".
* @param {String} sName Name of the change
* @param {String} sType File type extension
* @param {String} sLayer File layer
* @returns {Object} Returns the result from the request
* @public
*/
Connector.prototype.getFileAttributes = function(sNamespace, sName, sType, sLayer) {
var sApiPath = "/sap/bc/lrep/content/";
var sRequestPath = sApiPath;
sRequestPath += sNamespace + "/" + sName + "." + sType;
var aParams = [];
aParams.push({
name: "metadata",
value: "true"
});
if (sLayer) {
aParams.push({
name: "layer",
value: sLayer
});
}
sRequestPath += this._buildParams(aParams);
return this.send(sRequestPath, "GET", {}, null);
};
/**
* Upserts a given change or variant via REST call.
*
* @param {String} sNamespace The abap package goes here. It is needed to identify the change.
* @param {String} sName Name of the change
* @param {String} sType File type extension
* @param {String} sLayer File layer
* @param {String} sContent File content to be saved as string
* @param {String} sContentType Content type (e.g. application/json, text/plain, ...), default: application/json
* @param {String} sChangelist The transport ID, optional
* @returns {Object} Returns the result from the request
* @public
*/
Connector.prototype.upsert = function(sNamespace, sName, sType, sLayer, sContent, sContentType, sChangelist) {
var that = this;
return Promise.resolve(that._fileAction("PUT", sNamespace, sName, sType, sLayer, sContent, sContentType, sChangelist));
};
/**
* Delete a file via REST call.
*
* @param {String} sNamespace The abap package goes here. It is needed to identify the change.
* @param {String} sName Name of the change
* @param {String} sType File type extension
* @param {String} sLayer File layer
* @param {String} sChangelist The transport ID, optional
* @returns {Object} Returns the result from the request
* @public
*/
Connector.prototype.deleteFile = function(sNamespace, sName, sType, sLayer, sChangelist) {
return this._fileAction("DELETE", sNamespace, sName, sType, sLayer, null, null, sChangelist);
};
Connector.prototype._fileAction = function(sMethod, sNamespace, sName, sType, sLayer, sContent, sContentType, sChangelist) {
var sApiPath = "/sap/bc/lrep/content/";
var sRequestPath = sApiPath;
sRequestPath += sNamespace + "/" + sName + "." + sType;
var aParams = [];
aParams.push({
name: "layer",
value: sLayer
});
if (sChangelist) {
aParams.push({
name: "changelist",
value: sChangelist
});
}
sRequestPath += this._buildParams(aParams);
var mOptions = {
contentType: sContentType || this.DEFAULT_CONTENT_TYPE
};
return this.send(sRequestPath, sMethod.toUpperCase(), sContent, mOptions);
};
/**
* @param {String} sOriginNamespace The abap package goes here. It is needed to identify the change. Default LREP namespace is "localchange".
* @param {String} sName Name of the change
* @param {String} sType File type extension
* @param {String} sOriginLayer File layer
* @param {String} sTargetLayer File where the new Target-Layer
* @param {String} sTargetNamespace target namespace
* @param {String} sChangelist The changelist where the file will be written to
* @returns {Object} Returns the result from the request
* @private Private for now, as is not in use.
*/
Connector.prototype.publish = function(sOriginNamespace, sName, sType, sOriginLayer, sTargetLayer, sTargetNamespace, sChangelist) {
var sApiPath = "/sap/bc/lrep/actions/publish/";
var sRequestPath = sApiPath;
sRequestPath += sOriginNamespace + "/" + sName + "." + sType;
var aParams = [];
if (sOriginLayer) {
aParams.push({
name: "layer",
value: sOriginLayer
});
}
if (sTargetLayer) {
aParams.push({
name: "target-layer",
value: sTargetLayer
});
}
if (sTargetNamespace) {
aParams.push({
name: "target-namespace",
value: sTargetNamespace
});
}
if (sChangelist) {
aParams.push({
name: "changelist",
value: sChangelist
});
}
sRequestPath += this._buildParams(aParams);
return this.send(sRequestPath, "POST", {}, null);
};
/**
* Retrieves the content for a given namespace and layer via REST call.
*
* @param {String} sNamespace - The file namespace goes here. It is needed to identify the change.
* @param {String} sLayer - File layer
* @returns {Object} Returns the result from the request
* @public
*/
Connector.prototype.listContent = function(sNamespace, sLayer) {
var sRequestPath = "/sap/bc/lrep/content/";
sRequestPath += sNamespace;
var aParams = [];
if (sLayer) {
aParams.push({
name: "layer",
value: sLayer
});
}
sRequestPath += this._buildParams(aParams);
return this.send(sRequestPath, "GET", {}, null);
};
return Connector;
}, true);
}; // end of sap/ui/fl/LrepConnector.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.Transports') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/*global Promise */
jQuery.sap.declare('sap.ui.fl.Transports'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
sap.ui.define("sap/ui/fl/Transports",[
"sap/ui/fl/LrepConnector", "sap/ui/fl/Utils"
], function(LrepConnector, FlexUtils) {
"use strict";
/**
* Entity that handles ABAP transport related information.
* @constructor
* @alias sap.ui.fl.Transports
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.25.0
*/
var Transports = function() {
};
/**
* Reads the transports of the current user from the backend.
* The "locked" attribute indicates that the provided file (package/name/type) is already locked on this transport.
*
* @param {object} mParameters map of parameters, see below
* @param {string} mParameters.package - abap package; only relevant for VENDOR layer
* @param {string} mParameters.name - name of the lrep document
* @param {string} mParameters.namespace - namespace of the lrep document
* @param {string} mParameters.type - file extension of the lrep document
* @returns {Promise} with parameter <code>oResult</code>
* which is an object that has the attributes "transports", "localonly" and "errorCode".
* "localonly" tells the consumer if only local development is valid and no transport selection should take place.
* "transports" is an array of objects with attributes "transportId", "owner", "description", "locked"(true/false).
* "errorCode" can have the values "INVALID_PACKAGE" or "NO_TRANSPORTS" or is an empty string if there is no error.
* @public
*/
Transports.prototype.getTransports = function(mParameters) {
var sUri, sClient, oLrepConnector, oPromise;
sUri = '/sap/bc/lrep/actions/gettransports/';
if (mParameters['package']) {
sUri += '&package=' + mParameters['package'];
}
if (mParameters.name) {
sUri += '&name=' + mParameters.name;
}
if (mParameters.namespace) {
sUri += '&namespace=' + mParameters.namespace;
}
if (mParameters.type) {
sUri += '&type=' + mParameters.type;
}
sClient = FlexUtils.getClient();
if (sClient) {
sUri += '&sap-client=' + sClient;
}
//Replace first & with ?
sUri = sUri.replace('&', '?');
oLrepConnector = LrepConnector.createConnector();
oPromise = oLrepConnector.send(sUri);
return oPromise.then(function(oResponse) {
if (oResponse.response) {
if (!oResponse.response.localonly) {
oResponse.response.localonly = false;
}
if (!oResponse.response.errorCode) {
oResponse.response.errorCode = "";
}
return Promise.resolve(oResponse.response);
} else {
return Promise.reject('response is empty');
}
});
};
/**
* Reads the transports of the current user from the backend.
* The "locked" attribute indicates that the provided file (package/name/type) is already locked on this transport.
*
* @param {object} mParameters map of parameters, see below
* @param {string} mParameters.transportId - ABAP transport ID
* @param {string} mParameters.changeIds - array of change ID objects with attributes "namespace", "fileName", "fileType"
* @returns {Promise} without parameters
* @public
*/
Transports.prototype.makeChangesTransportable = function(mParameters) {
var sUri, sClient, oLrepConnector;
sUri = '/sap/bc/lrep/actions/make_changes_transportable/';
sClient = FlexUtils.getClient();
if (sClient) {
sUri += '?sap-client=' + sClient;
}
if (!mParameters.transportId) {
return Promise.reject(new Error("no transportId provided as attribute of mParameters"));
}
if (!mParameters.changeIds) {
return Promise.reject(new Error("no changeIds provided as attribute of mParameters"));
}
oLrepConnector = LrepConnector.createConnector();
return oLrepConnector.send(sUri,'POST',mParameters);
};
return Transports;
}, /* bExport= */true);
}; // end of sap/ui/fl/Transports.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.registry.Settings') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/*global Error */
jQuery.sap.declare('sap.ui.fl.registry.Settings'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.base.EventProvider'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/registry/Settings",[
"jquery.sap.global", "sap/ui/fl/LrepConnector", "sap/ui/fl/Cache", "sap/ui/fl/Utils", "sap/ui/base/EventProvider"
], function(jQuery, LrepConnector, Cache, Utils, EventProvider) {
"use strict";
/**
* FlexSettings access
*
* @param {object} oSettings settings as JSON object
* @constructor
* @alias sap.ui.fl.registry.Settings
* @author SAP SE
* @experimental Since 1.27.0
* @private
*/
var Settings = function(oSettings) {
EventProvider.apply(this);
if (!oSettings) {
throw new Error("no flex settings provided");
}
if (!oSettings.features) {
// hardcoded list of flex features (change types) and their valid "writable layer"
oSettings.features = {
"addField": [
"CUSTOMER", "VENDOR"
],
"addGroup": [
"CUSTOMER", "VENDOR"
],
"removeField": [
"CUSTOMER", "VENDOR"
],
"removeGroup": [
"CUSTOMER", "VENDOR"
],
"hideControl": [
"CUSTOMER", "VENDOR"
],
"unhideControl": [
"CUSTOMER", "VENDOR"
],
"renameField": [
"CUSTOMER", "VENDOR"
],
"renameGroup": [
"CUSTOMER", "VENDOR"
],
"moveFields": [
"CUSTOMER", "VENDOR"
],
"moveGroups": [
"CUSTOMER", "VENDOR"
],
"moveElements": [
"CUSTOMER", "VENDOR"
],
"propertyChange": [
"VENDOR"
]
};
}
this._oSettings = oSettings;
this._hasMergeErrorOccured = false;
};
Settings.prototype = jQuery.sap.newObject(EventProvider.prototype);
Settings.events = {
flexibilityAdaptationButtonAllowedChanged: "flexibilityAdaptationButtonAllowedChanged",
changeModeUpdated: "changeModeUpdated"
};
Settings._instances = {};
Settings._bFlexChangeMode = true;
Settings._bFlexibilityAdaptationButtonAllowed = false;
Settings._oEventProvider = new EventProvider();
/**
* fires the passed event via its event provider
*
* @param {string} sEventId name of the event
* @param {object} mParameters
*
* @public
*/
Settings.fireEvent = function(sEventId, mParameters) {
Settings._oEventProvider.fireEvent(sEventId, mParameters);
};
/**
* attaches an callback to an event on the event provider of Settings
*
* @param {string} sEventId name of the event
* @param {function} oCallback
*
* @public
*/
Settings.attachEvent = function(sEventId, oCallback) {
Settings._oEventProvider.attachEvent(sEventId, oCallback);
};
/**
* detaches an callback to an event on the event provider of Settings
*
* @param {string} sEventId name of the event
* @param {function} oCallback
*
* @public
*/
Settings.detachEvent = function(sEventId, oCallback) {
Settings._oEventProvider.detachEvent(sEventId, oCallback);
};
/**
* Returns a settings instance after reading the settings from the backend if not already done. There is only one instance of settings during a
* session.
*
* @param {string} sComponentName current UI5 component name
* @param {map} mPropertyBag - (optional) contains additional data that are needed for reading of changes
* - appDescriptor that belongs to actual component
* - siteId that belongs to actual component
* @returns {Promise} with parameter <code>oInstance</code> of type {sap.ui.fl.registry.Settings}
* @public
*/
Settings.getInstance = function(sComponentName, mPropertyBag) {
return Cache.getChangesFillingCache(LrepConnector.createConnector(), sComponentName, mPropertyBag).then(function(oFileContent) {
var oSettings;
if (Settings._instances[sComponentName]) {
// if instance exists the backend settings are coming from the cache as well and can be ignored
oSettings = Settings._instances[sComponentName];
} else if (oFileContent.changes && oFileContent.changes.settings) {
oSettings = new Settings(oFileContent.changes.settings);
Settings._instances[sComponentName] = oSettings;
} else {
oSettings = new Settings({});
Settings._instances[sComponentName] = oSettings;
}
return oSettings;
});
};
/**
* Returns a settings instance from the local instance cache. There is only one instance of settings during a session. If no instance has been
* created before, undefined will be returned.
*
* @param {string} sComponentName current UI5 component name
* @returns {sap.ui.fl.registry.Settings} instance or undefined if no instance has been created so far.
* @public
*/
Settings.getInstanceOrUndef = function(sComponentName) {
var oSettings;
if (Settings._instances[sComponentName]) {
oSettings = Settings._instances[sComponentName];
}
return oSettings;
};
/**
* Checks if the flexibility change mode is enabled.
*
* @returns {boolean} true if the flexibility change mode is enabled
* @public
*/
Settings.isFlexChangeMode = function() {
var bFlexChangeModeUrl = this._isFlexChangeModeFromUrl();
if (bFlexChangeModeUrl !== undefined) {
return bFlexChangeModeUrl;
}
return Settings._bFlexChangeMode;
};
/**
* Checks if the flexibility change mode is enabled via URL query parameter
*
* @returns {boolean} bFlexChangeMode true if the flexibility change mode is enabled, false if not enabled, undefined if not set via url.
* @public
*/
Settings._isFlexChangeModeFromUrl = function() {
var bFlexChangeMode;
var oUriParams = jQuery.sap.getUriParameters();
if (oUriParams && oUriParams.mParams && oUriParams.mParams['sap-ui-fl-changeMode'] && oUriParams.mParams['sap-ui-fl-changeMode'][0]) {
if (oUriParams.mParams['sap-ui-fl-changeMode'][0] === 'true') {
bFlexChangeMode = true;
} else if (oUriParams.mParams['sap-ui-fl-changeMode'][0] === 'false') {
bFlexChangeMode = false;
}
}
return bFlexChangeMode;
};
/**
* Activates the flexibility change mode.
*
* @public
*/
Settings.activateFlexChangeMode = function() {
var bFlexChangeModeOn = true;
Settings._setFlexChangeMode(bFlexChangeModeOn);
};
/**
* Deactivates / leaves the flexibility change mode.
*
* @public
*/
Settings.leaveFlexChangeMode = function() {
var bFlexChangeModeOff = false;
Settings._setFlexChangeMode(bFlexChangeModeOff);
};
/**
* sets the flexChangeMode flag
* fires an event if the flag has been toggled
*
* @private
*/
Settings._setFlexChangeMode = function (bFlexChangeModeOn) {
if (Settings._bFlexChangeMode === bFlexChangeModeOn) {
return; // no change
}
Settings._bFlexChangeMode = bFlexChangeModeOn;
var mParameter = {
bFlexChangeMode: bFlexChangeModeOn
};
Settings.fireEvent(Settings.events.changeModeUpdated, mParameter);
};
/**
* Method to check for adaptation button allowance
*
* @returns {boolean} Settings._bFlexibilityAdaptationButtonAllowed
* @public
*/
Settings.isFlexibilityAdaptationButtonAllowed = function () {
return Settings._bFlexibilityAdaptationButtonAllowed;
};
/**
* Method to allow the adaptation button
*
* @public
*/
Settings.allowFlexibilityAdaptationButton = function () {
var bFlexibilityAdaptationButtonAllowed = true;
Settings.setFlexibilityAdaptationButtonAllowed(bFlexibilityAdaptationButtonAllowed);
};
/**
* Method to disallow the adaptation button
*
* @public
*/
Settings.disallowFlexibilityAdaptationButton = function () {
var bFlexibilityAdaptationButtonDisallowed = false;
Settings.setFlexibilityAdaptationButtonAllowed(bFlexibilityAdaptationButtonDisallowed);
};
/**
* Method to set the adaptation button allowance flag on or off depending on the passed parameter
* fires an event if the flag has been toggled
*
* @param {boolean} bFlexibilityAdaptationButtonAllowed
*
* @public
*/
Settings.setFlexibilityAdaptationButtonAllowed = function (bFlexibilityAdaptationButtonAllowed) {
if (Settings._bFlexibilityAdaptationButtonAllowed === bFlexibilityAdaptationButtonAllowed) {
return; // no change
}
Settings._bFlexibilityAdaptationButtonAllowed = bFlexibilityAdaptationButtonAllowed;
var mParameter = {
bFlexibilityAdaptationButtonAllowed: bFlexibilityAdaptationButtonAllowed
};
Settings.fireEvent(Settings.events.flexibilityAdaptationButtonAllowedChanged, mParameter);
};
/**
* Returns the key user status of the current user.
*
* @returns {boolean} true if the user is a flexibility key user, false if not supported.
* @public
*/
Settings.prototype.isKeyUser = function() {
var bIsKeyUser = false;
if (this._oSettings.isKeyUser) {
bIsKeyUser = this._oSettings.isKeyUser;
}
return bIsKeyUser;
};
/**
* Returns true if backend is ModelS backend.
*
* @returns {boolean} true if ATO coding exists in backend.
* @public
*/
Settings.prototype.isModelS = function() {
var bIsModelS = false;
if (this._oSettings.isAtoAvailable) {
bIsModelS = this._oSettings.isAtoAvailable;
}
return bIsModelS;
};
/**
* Returns true if ATO is enabled in the backend.
*
* @returns {boolean} true if ATO is enabled.
* @public
*/
Settings.prototype.isAtoEnabled = function() {
var bIsAtoEnabled = false;
if (this._oSettings.isAtoEnabled) {
bIsAtoEnabled = this._oSettings.isAtoEnabled;
}
return bIsAtoEnabled;
};
/**
* Checks if a change type is enabled for the current writable layer
*
* @param {string} sChangeType change type to be checked
* @param {string} sActiveLayer active layer name; if not provided "USER" is the default.
* @returns {boolean} true if the change type is enabled, false if not supported.
* @public
*/
Settings.prototype.isChangeTypeEnabled = function(sChangeType, sActiveLayer) {
if (!sActiveLayer) {
sActiveLayer = 'USER';
}
var bIsEnabled = false;
if (!this._oSettings.features[sChangeType]) {
// if the change type is not in the feature list, the change type is not check relevant and therefore always enabled.
// if a change type should be disabled for all layers, an entry in the feature map has to exist with an empty array.
bIsEnabled = true;
} else {
var iArrayPos = jQuery.inArray(sActiveLayer, this._oSettings.features[sChangeType]);
if (iArrayPos < 0) {
bIsEnabled = false;
} else {
bIsEnabled = true;
}
}
return bIsEnabled;
};
/**
* Is current back end system defined as productive system which can also transport changes
*
* @public
* @returns {boolean} true if system is productive system
*/
Settings.prototype.isProductiveSystem = function() {
var bIsProductiveSystem = false;
if (this._oSettings.isProductiveSystem) {
bIsProductiveSystem = this._oSettings.isProductiveSystem;
}
return bIsProductiveSystem;
};
Settings.prototype.setMergeErrorOccured = function(bErrorOccured) {
this._hasMergeErrorOccoured = bErrorOccured;
};
/**
* Checks if an merge error occured during merging changes into the view on startup
*/
Settings.prototype.hasMergeErrorOccured = function() {
return this._hasMergeErrorOccured;
};
return Settings;
}, /* bExport= */true);
}; // end of sap/ui/fl/registry/Settings.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.Change') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.Change'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('sap.ui.base.EventProvider'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/Change",[
"sap/ui/base/EventProvider", "sap/ui/fl/Utils", "sap/ui/fl/registry/Settings"
], function(EventProvider, Utils, Settings) {
"use strict";
/**
* A change object based on the json data with dirty handling.
* @constructor
* @alias sap.ui.fl.Change
* @param {object} oFile - file content and admin data
* @experimental Since 1.25.0
* @author SAP SE
* @version 1.36.12
*/
var Change = function(oFile) {
EventProvider.apply(this);
if (typeof (oFile) !== "object") {
Utils.log.error("Constructor : sap.ui.fl.Change : oFile is not defined");
}
this._oDefinition = oFile;
this._oOriginDefinition = JSON.parse(JSON.stringify(oFile));
this._sRequest = '';
this._bIsDeleted = false;
this._bUserDependent = (oFile.layer === "USER");
};
Change.events = {
markForDeletion: "markForDeletion"
};
Change.prototype = jQuery.sap.newObject(EventProvider.prototype);
/**
* Returns if the change protocol is valid
* @returns {boolean} Change is valid (mandatory fields are filled, etc)
*
* @public
*/
Change.prototype.isValid = function() {
var bIsValid = true;
if (typeof (this._oDefinition) !== "object") {
bIsValid = false;
}
if (!this._oDefinition.fileType) {
bIsValid = false;
}
if (!this._oDefinition.fileName) {
bIsValid = false;
}
if (!this._oDefinition.changeType) {
bIsValid = false;
}
if (!this._oDefinition.layer) {
bIsValid = false;
}
if (!this._oDefinition.originalLanguage) {
bIsValid = false;
}
return bIsValid;
};
/**
* Returns if the change is of type variant
* @returns {boolean} fileType of the change document is a variant
*
* @public
*/
Change.prototype.isVariant = function() {
return this._oDefinition.fileType === "variant";
};
/**
* Returns the change type
*
* @returns {String} Changetype of the file, for example LabelChange
* @public
*/
Change.prototype.getChangeType = function() {
if (this._oDefinition) {
return this._oDefinition.changeType;
}
};
/**
* Returns the the original language in ISO 639-1 format
*
* @returns {String} Original language
*
* @public
*/
Change.prototype.getOriginalLanguage = function() {
if (this._oDefinition && this._oDefinition.originalLanguage) {
return this._oDefinition.originalLanguage;
}
return "";
};
/**
* Returns the abap package name
* @returns {string} ABAP package where the change is assigned to
*
* @public
*/
Change.prototype.getPackage = function() {
return this._oDefinition.packageName;
};
/**
* Returns the namespace. The changes' namespace is
* also the namespace of the change file in the repository.
*
* @returns {String} Namespace of the change document
*
* @public
*/
Change.prototype.getNamespace = function() {
return this._oDefinition.namespace;
};
/**
* Returns the id of the change
* @returns {string} Id of the change document
*
* @public
*/
Change.prototype.getId = function() {
return this._oDefinition.fileName;
};
/**
* Returns the content section of the change
* @returns {string} Content of the change document. The content structure can be any JSON.
*
* @public
*/
Change.prototype.getContent = function() {
return this._oDefinition.content;
};
/**
* Sets the object of the content attribute
*
* @param {object} oContent The content of the change document. Can be any JSON object.
*
* @public
*/
Change.prototype.setContent = function(oContent) {
this._oDefinition.content = oContent;
};
/**
* Returns the selector from the file content
* @returns {object} selector in format selectorPropertyName:selectorPropertyValue
*
* @public
*/
Change.prototype.getSelector = function() {
return this._oDefinition.selector;
};
/**
* Returns the text in the current language for a given id
*
* @param {string} sTextId
* text id which was used as part of the <code>oTexts</code> object
* @returns {string} The text for the given text id
*
* @function
*/
Change.prototype.getText = function(sTextId) {
if (typeof (sTextId) !== "string") {
Utils.log.error("sap.ui.fl.Change.getTexts : sTextId is not defined");
}
if (this._oDefinition.texts) {
if (this._oDefinition.texts[sTextId]) {
return this._oDefinition.texts[sTextId].value;
}
}
return "";
};
/**
* Sets the new text for the given text id
*
* @param {string} sTextId
* text id which was used as part of the <code>oTexts</code> object
* @param {string} sNewText the new text for the given text id
*
* @public
*/
Change.prototype.setText = function(sTextId, sNewText) {
if (typeof (sTextId) !== "string") {
Utils.log.error("sap.ui.fl.Change.setTexts : sTextId is not defined");
return;
}
if (this._oDefinition.texts) {
if (this._oDefinition.texts[sTextId]) {
this._oDefinition.texts[sTextId].value = sNewText;
}
}
};
/**
* Returns true if the current layer is the same as the layer
* in which the change was created or the change is from the
* end-user layer and for this user created.
* @returns {boolean} is the change document read only
*
* @public
*/
Change.prototype.isReadOnly = function() {
var bIsReadOnly = this._isReadOnlyDueToLayer();
if ( !bIsReadOnly ){
bIsReadOnly = this._isReadOnlyWhenNotKeyUser();
}
return bIsReadOnly;
};
/**
* Checks if the change is read-only
* because the current user is not a key user and the change is "shared"
* @returns {boolean} Flag whether change is read only
*
* @private
*/
Change.prototype._isReadOnlyWhenNotKeyUser = function() {
var bIsReadOnly = false;
if ( !this.isUserDependent() ){
var sReference = this.getDefinition().reference;
if ( sReference ){
var oSettings = Settings.getInstanceOrUndef(sReference);
if ( oSettings ){
var bIsKeyUser = oSettings.isKeyUser();
if ( bIsKeyUser === false ){
bIsReadOnly = true;
}
}
}
}
return bIsReadOnly;
};
/**
* Returns true if the label is read only. The label might be read only because of the current layer or because the logon language differs from the original language of the change document.
*
* @returns {boolean} is the label read only
*
* @public
*/
Change.prototype.isLabelReadOnly = function() {
if (this._isReadOnlyDueToLayer()) {
return true;
}
return this._isReadOnlyDueToOriginalLanguage();
};
/**
* Checks if the layer allows modifying the file
* @returns {boolean} Flag whether change is read only
*
* @private
*/
Change.prototype._isReadOnlyDueToLayer = function() {
var sCurrentLayer;
sCurrentLayer = Utils.getCurrentLayer(this._bUserDependent);
return (this._oDefinition.layer !== sCurrentLayer);
};
/**
* A change can only be modified if the current language equals the original language.
* Returns false if the current language does not equal the original language of the change file.
* Returns false if the original language is initial.
*
* @returns {boolean} flag whether the current logon language differs from the original language of the change document
*
* @private
*/
Change.prototype._isReadOnlyDueToOriginalLanguage = function() {
var sCurrentLanguage, sOriginalLanguage;
sOriginalLanguage = this.getOriginalLanguage();
if (!sOriginalLanguage) {
return false;
}
sCurrentLanguage = Utils.getCurrentLanguage();
return (sCurrentLanguage !== sOriginalLanguage);
};
/**
* Mark the current change to be deleted persistently
*
* @public
*/
Change.prototype.markForDeletion = function() {
this._bIsDeleted = true;
};
/**
* Determines if the Change has to be updated to the backend
* @returns {boolean} content of the change document has changed (change is in dirty state)
* @private
*/
Change.prototype._isDirty = function() {
var sCurrentDefinition = JSON.stringify(this._oDefinition);
var sOriginDefinition = JSON.stringify(this._oOriginDefinition);
return (sCurrentDefinition !== sOriginDefinition);
};
/**
* Sets the transport request
*
* @param {string} sRequest Transport request
*
* @public
*/
Change.prototype.setRequest = function(sRequest) {
if (typeof (sRequest) !== "string") {
Utils.log.error("sap.ui.fl.Change.setRequest : sRequest is not defined");
}
this._sRequest = sRequest;
};
/**
* Gets the transport request
* @returns {string} Transport request
*
* @public
*/
Change.prototype.getRequest = function() {
return this._sRequest;
};
/**
* Gets the layer type for the change
* @returns {string} The layer of the change document
*
* @public
*/
Change.prototype.getLayer = function() {
return this._oDefinition.layer;
};
/**
* Gets the component for the change
* @returns {string} The SAPUI5 component this change is assigned to
*
* @public
*/
Change.prototype.getComponent = function() {
return this._oDefinition.reference;
};
/**
* Gets the creation timestamp
*
* @returns {String} creation timestamp
*
* @public
*/
Change.prototype.getCreation = function() {
return this._oDefinition.creation;
};
/**
* Returns true if the change is user dependent
* @returns {boolean} Change is only relevant for the current user
*
* @public
*/
Change.prototype.isUserDependent = function() {
return (this._bUserDependent);
};
/**
* Returns the pending action on the change item
* @returns {string} contains one of these values: DELETE/NEW/UPDATE/NONE
*
* @public
*/
Change.prototype.getPendingAction = function() {
if (this._bIsDeleted) {
return "DELETE";
} else if (!this._oDefinition.creation) {
return "NEW";
} else if (this._isDirty() === true) {
return "UPDATE";
}
return "NONE";
};
/**
* Gets the JSON definition of the change
* @returns {object} the content of the change document
*
* @public
*/
Change.prototype.getDefinition = function() {
return this._oDefinition;
};
/**
* Set the response from the backend after saving the change
* @param {object} oResponse the content of the change document
*
* @public
*/
Change.prototype.setResponse = function(oResponse) {
var sResponse = JSON.stringify(oResponse);
if (sResponse) {
this._oDefinition = JSON.parse(sResponse);
this._oOriginDefinition = JSON.parse(sResponse);
}
};
/**
* Creates and returns a instance of change instance
*
* @param {Object} [oPropertyBag] property bag
* @param {String} [oPropertyBag.service] name of the OData service
* @param {String} [oPropertyBag.componentName] name of the component
* @param {String} [oPropertyBag.changeType] type of the change
* @param {Object} [oPropertyBag.texts] map object with all referenced texts within the file
* these texts will be connected to the translation process
* @param {Object} [oPropertyBag.content] content of the new change
* @param {Boolean} [oPropertyBag.isVariant] variant?
* @param {String} [oPropertyBag.namespace] namespace
* @param {String} [oPropertyBag.packageName] ABAP package name
* @param {Object} [oPropertyBag.selector] name value pair of the attribute and value
* @param {String} [oPropertyBag.id] name/id of the file. if not set implicitly created
* @param {Boolean} [oPropertyBag.isVariant] name of the component
* @param {Boolean} [oPropertyBag.isUserDependent] true for enduser changes
*
* @returns {Object} The content of the change file
*
* @public
*/
Change.createInitialFileContent = function(oPropertyBag) {
function createDefaultFileName(){
var sFileName = jQuery.sap.uid().replace(/-/g, "_");
if ( oPropertyBag.changeType ){
sFileName += '_' + oPropertyBag.changeType;
}
return sFileName;
}
function createNamespace(){
var sComponentName;
var sReferenceName = oPropertyBag.reference.replace('.Component','');
if ( oPropertyBag.componentName && oPropertyBag.componentName.indexOf('{project.artifactId}') >= 0 ){
//special case when change is created within webIDE; will not work in case of application variants once we start supporting them
sComponentName = sReferenceName;
}else {
sComponentName = oPropertyBag.componentName;
}
var sNamespace = 'apps/' + sComponentName + '/changes/';
if ( sComponentName !== sReferenceName ){
//add the application variant id
sNamespace += sReferenceName + '/';
}
return sNamespace;
}
if (!oPropertyBag) {
oPropertyBag = {};
}
var oNewFile = {
fileName: oPropertyBag.id || createDefaultFileName(),
fileType: (oPropertyBag.isVariant) ? "variant" : "change",
changeType: oPropertyBag.changeType || "",
reference: oPropertyBag.reference || "",
packageName: oPropertyBag.packageName || "",
content: oPropertyBag.content || {},
selector: oPropertyBag.selector || {},
layer: Utils.getCurrentLayer(oPropertyBag.isUserDependent),
texts: oPropertyBag.texts || {},
namespace: createNamespace(),
creation: "",
originalLanguage: Utils.getCurrentLanguage(),
conditions: {},
support: {
generator: "Change.createInitialFileContent",
service: oPropertyBag.service || "",
user: ""
}
};
return oNewFile;
};
return Change;
}, true);
}; // end of sap/ui/fl/Change.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.ChangePersistence') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/*global Promise */
jQuery.sap.declare('sap.ui.fl.ChangePersistence'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/ChangePersistence",[
"sap/ui/fl/Change", "sap/ui/fl/Utils", "jquery.sap.global", "sap/ui/fl/LrepConnector", "sap/ui/fl/Cache"
], function(Change, Utils, $, LRepConnector, Cache) {
"use strict";
/**
* Helper object to access a change from the backend. Access helper object for each change (and variant) which was fetched from the backend
*
* @constructor
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.25.0
* @param {string} sComponentName - the name of the component this instance is responsible for
* @param {sap.ui.fl.LrepConnector} [oLrepConnector] the LREP connector
*/
var ChangePersistence = function(sComponentName, oLrepConnector) {
this._sComponentName = sComponentName;
if (!this._sComponentName) {
Utils.log.error("The Control does not belong to a SAPUI5 component. Personalization and changes for this control might not work as expected.");
throw new Error("Missing component name.");
}
this._oConnector = oLrepConnector || this._createLrepConnector();
this._aDirtyChanges = [];
};
/**
* Return the name of the SAPUI5 component. All changes are assigned to 1 SAPUI5 component. The SAPUI5 component also serves as authorization
* object.
*
* @returns {String} component name
* @public
*/
ChangePersistence.prototype.getComponentName = function() {
return this._sComponentName;
};
/**
* Creates a new instance of the LRepConnector
*
* @returns {sap.ui.fl.LrepConnector} LRep connector instance
* @private
*/
ChangePersistence.prototype._createLrepConnector = function() {
return LRepConnector.createConnector();
};
/**
* Calls the backend asynchronously and fetches all changes for the component. If there are any new changes (dirty state) whoch are not yet saved to the backend, these changes will not be returned
* @param {map} mPropertyBag - (optional) contains additional data that are needed for reading of changes
* - appDescriptor that belongs to actual component
* - siteId that belongs to actual component
* @see sap.ui.fl.Change
* @returns {Promise} resolving with an array of changes
* @public
*/
ChangePersistence.prototype.getChangesForComponent = function(mPropertyBag) {
return Cache.getChangesFillingCache(this._oConnector, this._sComponentName, mPropertyBag).then(function(oWrappedChangeFileContent) {
this._bHasLoadedChangesFromBackend = true;
if (!oWrappedChangeFileContent.changes || !oWrappedChangeFileContent.changes.changes) {
return [];
}
var aChanges = oWrappedChangeFileContent.changes.changes;
return aChanges.filter(preconditionsFulfilled).map(createChange);
}.bind(this));
function createChange(oChangeContent) {
return new Change(oChangeContent);
}
function preconditionsFulfilled(oChangeContent) {
if (oChangeContent.fileType !== 'change') {
return false;
}
if (oChangeContent.changeType === 'defaultVariant') {
return false;
}
//noinspection RedundantIfStatementJS
if (!oChangeContent.selector || !oChangeContent.selector.id) {
return false;
}
return true;
}
};
/**
* Gets the changes for the given view id. The complete view prefix has to match.
*
* Example:
* Change has selector id:
* view1--view2--controlId
*
* Will match for view:
* view1--view2
*
* Will not match for view:
* view1
* view1--view2--view3
*
* @param {string} sViewId - the id of the view, changes should be retrieved for
* @param {map} mPropertyBag - (optional) contains additional data that are needed for reading of changes
* - appDescriptor that belongs to actual component
* - siteId that belongs to actual component
* @returns {Promise} resolving with an array of changes
* @public
*/
ChangePersistence.prototype.getChangesForView = function(sViewId, mPropertyBag) {
return this.getChangesForComponent(mPropertyBag).then(function(aChanges) {
return aChanges.filter(changesHavingCorrectViewPrefix);
});
function changesHavingCorrectViewPrefix(oChange) {
var sSelectorId = oChange.getSelector().id;
var sSelectorIdViewPrefix = sSelectorId.slice(0, sSelectorId.lastIndexOf('--'));
return sSelectorIdViewPrefix === sViewId;
}
};
/**
* Adds a new change (could be variant as well) and returns the id of the new change.
*
* @param {object} vChange - The complete and finalized JSON object representation the file content of the change or a Change instance
* @returns {sap.ui.fl.Change} the newly created change object
* @public
*/
ChangePersistence.prototype.addChange = function(vChange) {
var oNewChange;
if (vChange instanceof Change){
oNewChange = vChange;
}else {
oNewChange = new Change(vChange);
}
this._aDirtyChanges.push(oNewChange);
return oNewChange;
};
/**
* Saves all dirty changes by calling the appropriate backend method
* (create for new changes, deleteChange for deleted changes). The methods
* are called sequentially to ensure order. After a change has been saved
* successfully, the cache is updated and the changes is removed from the dirty
* changes.
*
* @returns {Promise} resolving after all changes have been saved
*/
ChangePersistence.prototype.saveDirtyChanges = function() {
var aDirtyChangesClone = this._aDirtyChanges.slice(0);
var aDirtyChanges = this._aDirtyChanges;
var aRequests = this._getRequests(aDirtyChangesClone);
var aPendingActions = this._getPendingActions(aDirtyChangesClone);
if (aPendingActions.length === 1 && aRequests.length === 1 && aPendingActions[0] === 'NEW') {
var sRequest = aRequests[0];
var aPreparedDirtyChangesBulk = this._prepareDirtyChanges(aDirtyChanges);
return this._oConnector.create(aPreparedDirtyChangesBulk, sRequest).then(this._massUpdateCacheAndDirtyState(aDirtyChanges, aDirtyChangesClone));
} else {
return aDirtyChangesClone.reduce(function (sequence, oDirtyChange) {
var saveAction = sequence.then(this._performSingleSaveAction(oDirtyChange).bind(this));
saveAction.then(this._updateCacheAndDirtyState(aDirtyChanges, oDirtyChange));
return saveAction;
}.bind(this), Promise.resolve());
}
};
ChangePersistence.prototype._performSingleSaveAction = function (oDirtyChange) {
return function() {
if (oDirtyChange.getPendingAction() === 'NEW') {
return this._oConnector.create(oDirtyChange.getDefinition(), oDirtyChange.getRequest());
}
if (oDirtyChange.getPendingAction() === 'DELETE') {
return this._oConnector.deleteChange({
sChangeName: oDirtyChange.getId(),
sLayer: oDirtyChange.getLayer(),
sNamespace: oDirtyChange.getNamespace(),
sChangelist: oDirtyChange.getRequest()
});
}
};
};
ChangePersistence.prototype._updateCacheAndDirtyState = function (aDirtyChanges, oDirtyChange) {
var that = this;
return function() {
if (oDirtyChange.getPendingAction() === 'NEW') {
Cache.addChange(that._sComponentName, oDirtyChange.getDefinition());
}
if (oDirtyChange.getPendingAction() === 'DELETE') {
Cache.deleteChange(that._sComponentName, oDirtyChange.getDefinition());
}
var iIndex = aDirtyChanges.indexOf(oDirtyChange);
if (iIndex > -1) {
aDirtyChanges.splice(iIndex, 1);
}
};
};
ChangePersistence.prototype._massUpdateCacheAndDirtyState = function (aDirtyChanges, aDirtyChangesClone) {
var that = this;
jQuery.each(aDirtyChangesClone, function (index, oDirtyChange) {
that._updateCacheAndDirtyState(aDirtyChanges, oDirtyChange)();
});
};
ChangePersistence.prototype._getRequests = function (aDirtyChanges) {
var aRequests = [];
jQuery.each(aDirtyChanges, function (index, oChange) {
var sRequest = oChange.getRequest();
if (aRequests.indexOf(sRequest) === -1) {
aRequests.push(sRequest);
}
});
return aRequests;
};
ChangePersistence.prototype._getPendingActions = function (aDirtyChanges) {
var aPendingActions = [];
jQuery.each(aDirtyChanges, function (index, oChange) {
var sPendingAction = oChange.getPendingAction();
if (aPendingActions.indexOf(sPendingAction) === -1) {
aPendingActions.push(sPendingAction);
}
});
return aPendingActions;
};
ChangePersistence.prototype._prepareDirtyChanges = function (aDirtyChanges) {
var aChanges = [];
jQuery.each(aDirtyChanges, function (index, oChange) {
aChanges.push(oChange.getDefinition());
});
return aChanges;
};
ChangePersistence.prototype.getDirtyChanges = function() {
return this._aDirtyChanges;
};
/**
* Prepares a change to be deleted with the next call to
* @see {ChangePersistence#saveDirtyChanges}.
*
* If the given change is already in the dirty changes and
* has pending action 'NEW' it will be removed, assuming,
* it has just been created in the current session.
*
* Otherwise it will be marked for deletion.
*
* @param {sap.ui.fl.Change} oChange - the change to be deleted
*/
ChangePersistence.prototype.deleteChange = function(oChange) {
var index = this._aDirtyChanges.indexOf(oChange);
if (index > -1) {
if (oChange.getPendingAction() === 'DELETE'){
return;
}
this._aDirtyChanges.splice(index, 1);
return;
}
oChange.markForDeletion();
this._aDirtyChanges.push(oChange);
};
return ChangePersistence;
}, true);
}; // end of sap/ui/fl/ChangePersistence.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.ChangePersistenceFactory') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.ChangePersistenceFactory'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/ChangePersistenceFactory",[
"jquery.sap.global", "sap/ui/fl/ChangePersistence", "sap/ui/fl/Utils"
], function(jQuery, ChangePersistence, Utils) {
"use strict";
/**
* Factory to get or create a new instances of {sap.ui.fl.ChangePersistence}
* @constructor
* @alias sap.ui.fl.ChangePersistenceFactory
* @experimental Since 1.27.0
* @author SAP SE
* @version 1.36.12
*/
var ChangePersistenceFactory = {};
ChangePersistenceFactory._instanceCache = {};
/**
* Creates or returns an instance of the ChangePersistence
* @param {String} sComponentName The name of the component
* @returns {sap.ui.fl.ChangePersistence} instance
*
* @public
*/
ChangePersistenceFactory.getChangePersistenceForComponent = function(sComponentName) {
var oChangePersistence;
if (!ChangePersistenceFactory._instanceCache[sComponentName]) {
oChangePersistence = new ChangePersistence(sComponentName);
ChangePersistenceFactory._instanceCache[sComponentName] = oChangePersistence;
}
return ChangePersistenceFactory._instanceCache[sComponentName];
};
/**
* Creates or returns an instance of the ChangePersistence for the component of the specified control.
* The control needs to be embedded into a component.
* @param {sap.ui.core.Control} oControl The control for example a SmartField, SmartGroup or View
* @returns {sap.ui.fl.ChangePersistence} instance
*
* @public
*/
ChangePersistenceFactory.getChangePersistenceForControl = function(oControl) {
var sComponentId;
sComponentId = this._getComponentClassNameForControl(oControl);
return ChangePersistenceFactory.getChangePersistenceForComponent(sComponentId);
};
/**
* Returns the name of the component of the control
* @param {sap.ui.core.Control} oControl Control
* @returns {String} The name of the component. Undefined if no component was found
*
* @private
*/
ChangePersistenceFactory._getComponentClassNameForControl = function(oControl) {
return Utils.getComponentClassName(oControl);
};
return ChangePersistenceFactory;
}, true);
}; // end of sap/ui/fl/ChangePersistenceFactory.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.DefaultVariant') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.DefaultVariant'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/DefaultVariant",[
"jquery.sap.global", "sap/ui/fl/Change"
], function($, Change) {
"use strict";
/**
* DefaultVariant handles default variant changes without keeping control specific state.
* It knows how to create a default variant change, how to retrieve the default variant id from a given list of changes, etc.
* @constructor
* @alias sap.ui.fl.DefaultVariant
* @author SAP SE
*
* @version 1.36.12
*
* @experimental Since 1.25.0
*/
var DefaultVariant = function() {
};
/**
* Returns the id of the default variant. Returns an empty string if there is no default variant.
*
* @param {object} mChanges Map containing multiple change files.
*
* @returns {String} default variant id
*
* @public
*/
DefaultVariant.prototype.getDefaultVariantId = function(mChanges) {
var defaultVariantChange = this.getNewestDefaultVariantChangeDeleteTheRest(mChanges);
if (defaultVariantChange) {
return defaultVariantChange.getContent().defaultVariantName;
}
return "";
};
/**
* Returns the newest default variant change and marks the rest for deletion.
* A change with an empty string as creation is considered newer
* than a change with an iso date string. If multiple changes
* have an empty string, order is not guaranteed. That is a case
* that should not happen.
*
* @param {object} mChanges map containing multiple change files.
*
* @returns {array} default variant changes
*
* @public
*/
DefaultVariant.prototype.getNewestDefaultVariantChangeDeleteTheRest = function(mChanges) {
var aChanges = this.getDefaultVariantChanges(mChanges).sort(function(a, b) {
var aDate = new Date(a.getCreation());
var bDate = new Date(b.getCreation());
if (isNaN(aDate.getDate())) {
return -1;
}
if (isNaN(bDate.getDate())) {
return 1;
}
return bDate - aDate;
});
var oNewestChange = aChanges.shift();
aChanges.forEach(function(oChange) {
oChange.markForDeletion();
});
return oNewestChange;
};
/**
* Returns all default variant changes within the given map of changes
*
* @param {object} mChanges - map containing multiple change files.
*
* @returns {array} default variant changes
*
* @public
*/
DefaultVariant.prototype.getDefaultVariantChanges = function(mChanges) {
if (!mChanges || typeof mChanges !== 'object') {
return [];
}
return Object.keys(mChanges).map(changeIdsToChanges).filter(defaultVariantChanges);
function changeIdsToChanges(sChangeId) {
return mChanges[sChangeId];
}
function defaultVariantChanges(oChange) {
return oChange.getChangeType() === 'defaultVariant';
}
};
/**
* Updates the default variant id, if the given list of changes contains a default variant change.
* Only the newest is updated, the rest is marked for deletion.
*
* @param {object} mChanges map of changes
* @param {string} sNewDefaultVariantId the new default variant id
* @returns {object} the updated change, undefined if non was found
*
* @public
*/
DefaultVariant.prototype.updateDefaultVariantId = function(mChanges, sNewDefaultVariantId) {
var oNewsetChange = this.getNewestDefaultVariantChangeDeleteTheRest(mChanges);
if (oNewsetChange) {
oNewsetChange.getContent().defaultVariantName = sNewDefaultVariantId;
}
return oNewsetChange;
};
/**
* Creates the JSON content of a new change file, specifying the new default variant
*
* @param {object} mParameters map of parameters, see below
* @param {String} mParameters.defaultVariantName - id of the new default variant
* @param {String} mParameters.component - name of the UI5 component
* @param {object} mParameters.selector - stable propertyName:propertyValue
*
* @returns {Object} default variant change
*
* @private
*/
DefaultVariant.prototype._createChangeFile = function(mParameters) {
var oFileData;
mParameters.namespace = mParameters.component + '/changes/default';
mParameters.componentName = mParameters.component;
mParameters.changeType = 'defaultVariant';
oFileData = Change.createInitialFileContent(mParameters);
oFileData.content.defaultVariantName = mParameters.defaultVariantId;
oFileData.layer = 'USER';
return oFileData;
};
/**
* Creates an instance of {sap.ui.fl.Change}, specifying the new default variant
*
* @param {object} mParameters - map of parameters, see below
* @param {String} mParameters.defaultVariantName - id of the new default variant
* @param {String} mParameters.component - name of the UI5 component
* @param {object} mParameters.selector - stable propertyName:propertyValue
* @returns {sap.ui.fl.Change} Change
*
* @public
*/
DefaultVariant.prototype.createChangeObject = function(mParameters) {
var oFileContent, oChange;
oFileContent = this._createChangeFile(mParameters);
oChange = new Change(oFileContent);
return oChange;
};
return new DefaultVariant();
}, /* bExport= */true);
}; // end of sap/ui/fl/DefaultVariant.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.FakeLrepConnector') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/*global Promise */
jQuery.sap.declare('sap.ui.fl.FakeLrepConnector'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.thirdparty.URI'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/FakeLrepConnector",[
"jquery.sap.global", "sap/ui/thirdparty/URI", "sap/ui/fl/Utils", "sap/ui/fl/LrepConnector", "sap/ui/fl/Cache"
], function(jQuery, uri, FlexUtils, LrepConnector, Cache) {
"use strict";
var lrepConnector = Object.create(LrepConnector.prototype);
var instance;
/**
* Please use the @link {FakeLrepConnector#enableFakeConnector} function
* to enable the FakeLrepConnector.
*
* Provides a fake implementation for the sap.ui.fl.LrepConnector
* @param {String} sInitialComponentJsonPath - the relative path to a test-component-changes.json file
*
* @constructor
* @alias sap.ui.fl.FakeLrepConnector
* @experimental Since 1.27.0
* @author SAP SE
* @version 1.36.12
*/
function FakeLrepConnector(sInitialComponentJsonPath){
this.sInitialComponentJsonPath = sInitialComponentJsonPath;
}
for (var prop in lrepConnector){
if (typeof lrepConnector[prop] === 'function'){
/*eslint-disable noinspection, no-loop-func */
FakeLrepConnector.prototype[prop] = (function(prop){
return function() {
throw new Error('Method ' + prop + '() is not implemented in FakeLrepConnector.');
};
}(prop));
/*eslint-enable noinspection, no-loop-func */
}
}
FakeLrepConnector.prototype.loadChanges = function(sComponentClassName){
var initialComponentJsonPath = this.sInitialComponentJsonPath;
return new Promise(function(resolve, reject){
jQuery.getJSON(initialComponentJsonPath).done(function(oResponse){
var result = {
changes: oResponse,
componentClassName: sComponentClassName
};
resolve(result);
}).fail(function(error){
reject(error);
});
});
};
FakeLrepConnector.prototype.create = function(payload, changeList, isVariant){
// REVISE ensure old behavior for now, but check again for changes
if (!isVariant){
return Promise.resolve();
}
if (!payload.creation){
payload.creation = new Date().toISOString();
}
return Promise.resolve({
response: payload,
status: 'success'
});
};
FakeLrepConnector.prototype.update = function(payload, changeName, changelist, isVariant) {
// REVISE ensure old behavior for now, but check again for changes
if (!isVariant){
return Promise.resolve();
}
return Promise.resolve({
response: payload,
status: 'success'
});
};
FakeLrepConnector.prototype.deleteChange = function(params, isVariant){
// REVISE ensure old behavior for now, but check again for changes
if (!isVariant){
return Promise.resolve();
}
return Promise.resolve({
response: undefined,
status: 'nocontent'
});
};
FakeLrepConnector.prototype.send = function(sUri, sMethod, oData, mOptions){
return new Promise(function(resolve, reject){
handleGetTransports(sUri, sMethod, oData, mOptions, resolve, reject);
handleMakeChangesTransportable(sUri, sMethod, oData, mOptions, resolve, reject);
});
};
function handleMakeChangesTransportable(sUri, sMethod, oData, mOptions, resolve){
if (sUri.match(/^\/sap\/bc\/lrep\/actions\/make_changes_transportable\//) && sMethod === 'POST'){
resolve();
}
}
//REVISE Make response configurable
function handleGetTransports(sUri, sMethod, oData, mOptions, resolve, reject){
if (sUri.match(/^\/sap\/bc\/lrep\/actions\/gettransports\//)){
resolve({
response: {
"transports": [
{
"transportId": "U31K008488",
"description": "The Ultimate Transport",
"owner": "Fantasy Owner",
"locked": false
}
],
"localonly": false,
"errorCode": ""
}
});
}
}
/**
* Hooks into the @link {sap.ui.fl.LrepConnector.createConnector} factory
* function to enable the fake lrep connector.
*
* @param sInitialComponentJsonPath - the relative path to a test-component-changes.json file
*/
FakeLrepConnector.enableFakeConnector = function(sInitialComponentJsonPath){
Cache._entries = {};
if (FakeLrepConnector.enableFakeConnector.original){
return;
}
FakeLrepConnector.enableFakeConnector.original = LrepConnector.createConnector;
LrepConnector.createConnector = function(){
if (!instance) {
instance = new FakeLrepConnector(sInitialComponentJsonPath);
}
return instance;
};
};
/**
* Restore the original @link {sap.ui.fl.LrepConnector.createConnector} factory
* function.
*/
FakeLrepConnector.disableFakeConnector = function(){
if (FakeLrepConnector.enableFakeConnector.original){
LrepConnector.createConnector = FakeLrepConnector.enableFakeConnector.original;
}
};
return FakeLrepConnector;
}, true);
}; // end of sap/ui/fl/FakeLrepConnector.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.Persistence') ) {
/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/* global Promise */
jQuery.sap.declare('sap.ui.fl.Persistence'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/Persistence",[
"sap/ui/fl/Change", "sap/ui/fl/DefaultVariant", "sap/ui/fl/Utils", "jquery.sap.global", "sap/ui/fl/LrepConnector", "sap/ui/fl/Cache"
], function(Change, defaultVariant, Utils, $, LRepConnector, Cache) {
"use strict";
/**
* Helper object to access a change from the backend. Access helper object for each change (and variant) which was fetched from the backend
*
* @constructor
* @param {sap.ui.core.Control} oControl - the control for which the changes should be fetched
* @param {string} [sStableIdPropertyName='id'] the stable id
* @alias sap.ui.fl.Persistence
* @author <NAME>
* @version 1.36.12
* @experimental Since 1.25.0
*/
var Persistence = function(oControl, sStableIdPropertyName) {
this._oControl = oControl;
this._bHasLoadedChangesFromBackend = false;
this._sStableIdPropertyName = sStableIdPropertyName || 'id';
this._sStableId = this._getStableId();
this._sComponentName = Utils.getComponentClassName(oControl);
if (!this._sComponentName) {
Utils.log.error("The Control does not belong to a SAPUI5 component. Variants and Changes for this control might not work as expected.");
}
this._oAppDescriptor = Utils.getAppDescriptor(oControl);
this._sSiteId = Utils.getSiteId(oControl);
this._oChanges = {};
this._oMessagebundle = {};
this._oConnector = this._createLrepConnector();
};
/**
* Return the name of the SAPUI5 component. All changes are assigned to 1 SAPUI5 component. The SAPUI5 component also serves as authorization
* object.
*
* @returns {String} component name
* @public
*/
Persistence.prototype.getComponentName = function() {
return this._sComponentName;
};
/**
* Return the name of the SAPUI5 component. All changes are assigned to 1 SAPUI5 component. The SAPUI5 component also serves as authorization
* object.
*
* @param {string} sComponentName The name of the component
* @public
*/
Persistence.prototype.setComponentName = function(sComponentName) {
this._sComponentName = sComponentName;
};
/**
* Creates a new instance of the LRepConnector
*
* @returns {sap.ui.fl.LrepConnector} LRep connector instance
* @private
*/
Persistence.prototype._createLrepConnector = function() {
var sXsrfToken, mParams;
sXsrfToken = Utils.getXSRFTokenFromControl(this._oControl);
mParams = {
XsrfToken: sXsrfToken
};
return LRepConnector.createConnector(mParams);
};
/**
* Determines the value of the stable id property of the control
*
* @returns {String} Stable Id. Empty string if stable id determination failed
* @private
*/
Persistence.prototype._getStableId = function() {
if (!this._oControl) {
return undefined;
}
if ((this._sStableIdPropertyName) && (this._sStableIdPropertyName !== 'id')) {
var sStableId;
try {
sStableId = this._oControl.getProperty(this._sStableIdPropertyName);
} catch (exception) {
sStableId = "";
}
return sStableId;
}
if (typeof this._oControl.getId !== 'function') {
return undefined;
}
return this._oControl.getId();
};
/**
* Checks for the existance of a variant within the vendor layer
*
* @returns {boolean} bExistChangeInVendorLayer
* @private
*/
Persistence.prototype._existVendorLayerChange = function() {
var bExistChangeInVendorLayer = false;
jQuery.each(this._oChanges, function(sChangeKey, oChange) {
var oOriginDefinition = oChange._oOriginDefinition;
if (oOriginDefinition.layer === "VENDOR") {
bExistChangeInVendorLayer = true;
return false; // break foreach;
}
});
return bExistChangeInVendorLayer;
};
/**
* Searches for the ower (sap.ui.Component) of passed control
*
* @param {object} oControl a ui5Control
* @returns {sap.ui.Component} oOwnerComponent
* @private
*/
Persistence.prototype._getOwnerComponentOfControl = function(oControl) {
if (!oControl) {
return undefined;
}
var sOwnerId = sap.ui.core.Component.getOwnerIdFor(oControl);
if (sOwnerId) {
var oOwnerComponent = sap.ui.component(sOwnerId);
return oOwnerComponent;
}
return this._getOwnerComponentOfControl(oControl.getParent());
};
/**
* Binds a json model to the component the first time a variant within the vendor layer was detected
*
* @private
*/
Persistence.prototype._checkForMessagebundleBinding = function() {
if (this._existVendorLayerChange()) {
var oOwner = this._getOwnerComponentOfControl(this._oControl);
if (oOwner && !oOwner.getModel("i18nFlexVendor")) {
var oModel = new sap.ui.model.json.JSONModel(this._oMessagebundle);
oOwner.setModel(oModel, "i18nFlexVendor");
}
}
};
/**
* Calls the backend asynchronously and fetches all changes and variants which point to this control in the same component.
*
* @see sap.ui.fl.Change
* @returns {Promise} with parameter <code>aResults</code> which is a map with key changeId and value instance of sap.ui.fl.Change
* @public
*/
Persistence.prototype.getChanges = function() {
var that = this;
var sComponentName = this._sComponentName;
var mPropertyBag = {
appDescriptor: this._oAppDescriptor,
siteId: this._sSiteId
};
if (this._bHasLoadedChangesFromBackend === true) {
if (this._oMessagebundle) {
this._checkForMessagebundleBinding();
}
return Promise.resolve(this._oChanges);
}
return Cache.getChangesFillingCache(this._oConnector, sComponentName, mPropertyBag).then(that._resolveFillingCacheWithChanges.bind(that));
};
/**
* Intern method of 'getChanges' to handle the resolution of the deferred returned from 'Cache.getChangesFillingCache'.
*
* @returns {object} this._oChanges relevant changes filled by internal processing
* @private
*/
Persistence.prototype._resolveFillingCacheWithChanges = function(oFile) {
this._fillRelevantChanges(oFile);
if (oFile && oFile.changes && oFile.changes.messagebundle) {
this._oMessagebundle = oFile.changes.messagebundle;
this._checkForMessagebundleBinding();
}
this._bHasLoadedChangesFromBackend = true;
return this._oChanges;
};
/**
* Calls the backend asynchronously and fetches all changes and variants of the current component.
*
* @see sap.ui.fl.Change
* @returns {Promise} with parameter <code>aResults</code> which is a map with key changeId and value instance of sap.ui.fl.Change
* @public
*/
Persistence.prototype.getComponentChanges = function() {
var that = this;
var mPropertyBag = {
appDescriptor: this._oAppDescriptor,
siteId: this._sSiteId
};
return Cache.getChangesFillingCache(this._oConnector, this._sComponentName, mPropertyBag).then(function(oFile) {
var bNoFilter = true;
that._fillRelevantChanges(oFile, bNoFilter);
return that._oChanges;
});
};
/**
* Fill the map of <code>sap.ui.fl.Change</code> with all relevant changes
*
* @param {object} oFile content of Component-changes.json file
* @param {boolean} bNoFilter do not filter on stable ID
* @see sap.ui.fl.Change
* @private
*/
Persistence.prototype._fillRelevantChanges = function(oFile, bNoFilter) {
var aChangeList, len, oChangeContent, oSelector, oChange, j, sChangeId;
var that = this;
var fLogError = function(key, text) {
Utils.log.error("key : " + key + " and text : " + text.value);
};
var fAppendValidChanges = function(id, value) {
// when filtering set to inactive: add all changes but still filter variants
if (bNoFilter === true && oChangeContent.fileType === 'change' || that._sStableId === value) {
oChange = new Change(oChangeContent);
oChange.attachEvent(Change.events.markForDeletion, that._onDeleteChange.bind(that));
sChangeId = oChange.getId();
if (oChange.isValid()) {
if (that._oChanges[sChangeId] && oChange.isVariant()) {
Utils.log.error("Id collision - two or more variant files having the same id detected: " + sChangeId);
jQuery.each(oChange.getDefinition().texts, fLogError);
Utils.log.error("already exists in variant : ");
jQuery.each(that._oChanges[sChangeId].getDefinition().texts, fLogError);
}
that._oChanges[sChangeId] = oChange;
}
return false;
}
};
if (oFile && oFile.changes && oFile.changes.changes) {
aChangeList = oFile.changes.changes;
len = aChangeList.length;
for (j = 0; j < len; j++) {
oChangeContent = aChangeList[j];
oSelector = oChangeContent.selector;
if (oSelector) {
// filter out only controls of the current
jQuery.each(oSelector, fAppendValidChanges);
}
}
}
};
/**
* Returns the change for the provided id.
*
* @see sap.ui.fl.Change
* @param {string} sChangeId - the id of the change to get
* @returns {sap.ui.fl.Change} the found change
* @public
*/
Persistence.prototype.getChange = function(sChangeId) {
if (!sChangeId) {
Utils.log.error("sap.ui.fl.Persistence.getChange : sChangeId is not defined");
return undefined;
}
return this._oChanges[sChangeId];
};
/**
* Adds a new change (could be variant as well) and returns the id of the new change.
*
* @param {object} mParameters map of parameters, see below
* @param {string} mParameters.type - type <filterVariant, tableVariant, etc>
* @param {string} mParameters.ODataService - name of the OData service --> can be null
* @param {object} mParameters.texts - map object with all referenced texts within the file these texts will be connected to the translation
* process
* @param {object} mParameters.content - content of the new change
* @param {boolean} mParameters.isVariant - indicates if the change is a variant
* @param {string} mParameters.packageName - <optional> package name for the new entity <default> is $tmp
* @param {boolean} mParameters.isUserDependent - indicates if a change is only valid for the current user
* @param {boolean} [mParameters.id] - id of the change. The id has to be globally unique and should only be set in exceptional cases for example
* downport of variants
* @returns {string} the ID of the newly created change
* @public
*/
Persistence.prototype.addChange = function(mParameters) {
var oFile, oInfo, mInternalTexts, oChange;
if (!mParameters) {
return undefined;
}
if (!mParameters.type) {
Utils.log.error("sap.ui.fl.Persistence.addChange : type is not defined");
}
if (!mParameters.ODataService) {
Utils.log.error("sap.ui.fl.Persistence.addChange : ODataService is not defined");
}
var sContentType = jQuery.type(mParameters.content);
if (sContentType !== 'object' && sContentType !== 'array') {
Utils.log.error("mParameters.content is not of expected type object or array, but is: " + sContentType, "sap.ui.fl.Persistence#addChange");
}
// convert the text object to the internal structure
mInternalTexts = {};
if (typeof (mParameters.texts) === "object") {
jQuery.each(mParameters.texts, function(id, text) {
mInternalTexts[id] = {
value: text,
type: "XFLD"
};
});
}
var oAppDescr = Utils.getAppDescriptor(this._oControl);
var sComponentName = this._sComponentName; //only used in case ui core provides no app descriptor e.g. during unit tests
if ( oAppDescr && oAppDescr["sap.app"] ){
sComponentName = oAppDescr["sap.app"].componentName || oAppDescr["sap.app"].id;
}
oInfo = {
changeType: mParameters.type,
service: mParameters.ODataService,
texts: mInternalTexts,
content: mParameters.content,
reference: this._sComponentName, //in this case the component name can also be the value of sap-app-id
componentName: sComponentName,
isVariant: mParameters.isVariant,
packageName: mParameters.packageName,
isUserDependent: mParameters.isUserDependent
};
oInfo.selector = this._getSelector();
oFile = Change.createInitialFileContent(oInfo);
// If id is provided, overwrite generated id
if (mParameters.id) {
oFile.fileName = mParameters.id;
}
oChange = this.addChangeFile(oFile);
return oChange.getId();
};
/**
* Adds a new change (could be variant as well) and returns the id of the new change.
*
* @param {object} oChangeFile The complete and finalized JSON object representation the file content of the change
* @returns {sap.ui.fl.Change} the newly created change object
* @public
*/
Persistence.prototype.addChangeFile = function(oChangeFile) {
var oChange, sChangeId;
oChange = new Change(oChangeFile);
oChange.attachEvent(Change.events.markForDeletion, this._onDeleteChange.bind(this));
sChangeId = oChange.getId();
this._oChanges[sChangeId] = oChange;
return oChange;
};
Persistence.prototype.removeChangeFromPersistence = function(oChange) {
if (oChange.getPendingAction() !== 'NEW') {
return;
}
var sChangeToRemoveId = oChange.getId();
delete this._oChanges[sChangeToRemoveId];
};
/**
* Puts an existing change into the persistence.
*
* @param {sap.ui.fl.Change} oChange object
* @public
*/
Persistence.prototype.putChange = function(oChange) {
oChange.attachEvent(Change.events.markForDeletion, this._onDeleteChange.bind(this));
var sChangeId = oChange.getId();
this._oChanges[sChangeId] = oChange;
};
/**
* Returns a selector filled with the stableIdPropertyName and its value.
*
* @returns {Object} selector
* @private
*/
Persistence.prototype._getSelector = function() {
var mSelector;
mSelector = {};
if (this._sStableIdPropertyName) {
mSelector[this._sStableIdPropertyName] = this._sStableId;
}
return mSelector;
};
/**
* Retrieves the default variant for the current control
*
* @returns {String} id of the default variant
* @public
*/
Persistence.prototype.getDefaultVariantId = function() {
return this.getChanges().then(function(oChanges) {
return defaultVariant.getDefaultVariantId(oChanges);
});
};
/**
* Retrieves the default variant for the current control synchronously. WARNING: It is the responsibility of the consumer to make sure, that the
* changes have already been retrieved with getChanges. It's recommended to use the async API getDefaultVariantId which works regardless of any
* preconditions.
*
* @returns {String} id of the default variant
* @public
*/
Persistence.prototype.getDefaultVariantIdSync = function() {
return defaultVariant.getDefaultVariantId(this._oChanges);
};
/**
* Sets the default variant for the current control. A new change object is created or an existing is updated. This change object is kept in
* memory and can be flushed using saveAll. WARNING: It is the responsibility of the consumer to make sure, that the changes have already been
* retrieved with getChanges. It's recommended to use the async API setDefaultVariantIdId which works regardless of any preconditions.
*
* @param {string} sDefaultVariantId - the ID of the new default variant
* @returns {Object} the default variant change
* @public
*/
Persistence.prototype.setDefaultVariantIdSync = function(sDefaultVariantId) {
var mParameters, oChange;
var selector = {};
selector[this._sStableIdPropertyName] = this._sStableId;
mParameters = {
defaultVariantId: sDefaultVariantId,
reference: this._sComponentName,
selector: selector
};
oChange = defaultVariant.updateDefaultVariantId(this._oChanges, sDefaultVariantId);
if (oChange) {
return oChange;
}
oChange = defaultVariant.createChangeObject(mParameters);
oChange.attachEvent(Change.events.markForDeletion, this._onDeleteChange.bind(this));
var sChangeId = oChange.getId();
this._oChanges[sChangeId] = oChange;
return oChange;
};
/**
* Sets the default variant for the current control. A new change object is created or an existing is updated. This change object is kept in
* memory and can be flushed using saveAll.
*
* @param {string} sDefaultVariantId - the ID of the new default variant
* @returns {Promise} the default variant change
* @public
*/
Persistence.prototype.setDefaultVariantId = function(sDefaultVariantId) {
var mParameters, oChange;
var that = this;
return this.getChanges().then(function(oChanges) {
var selector = {};
selector[that._sStableIdPropertyName] = that._sStableId;
mParameters = {
defaultVariantId: sDefaultVariantId,
reference: that._sComponentName,
selector: selector
};
oChange = defaultVariant.updateDefaultVariantId(oChanges, sDefaultVariantId);
if (oChange) {
return oChange;
}
oChange = defaultVariant.createChangeObject(mParameters);
oChange.attachEvent(Change.events.markForDeletion, that._onDeleteChange.bind(that));
oChanges[oChange.getId()] = oChange;
return oChange;
});
};
/**
* Saves/flushes all current changes to the backend.
*
* @returns {Promise} resolving with an array of responses or rejecting with the first error
* @public
*/
Persistence.prototype.saveAll = function() {
var aPromises = [];
var that = this;
jQuery.each(this._oChanges, function(id, oChange) {
switch (oChange.getPendingAction()) {
case "NEW":
aPromises.push(that._oConnector.create(oChange.getDefinition(), oChange.getRequest(), oChange.isVariant()).then(function(result) {
oChange.setResponse(result.response);
if (Cache.isActive()) {
Cache.addChange(oChange.getComponent(), result.response);
}
return result;
}));
break;
case "UPDATE":
aPromises.push(that._oConnector.update(oChange.getDefinition(), oChange.getId(), oChange.getRequest(), oChange.isVariant()).then(function(result) {
oChange.setResponse(result.response);
if (Cache.isActive()) {
Cache.updateChange(oChange.getComponent(), result.response);
}
return result;
}));
break;
case "DELETE":
aPromises.push(that._oConnector.deleteChange({
sChangeName: oChange.getId(),
sLayer: oChange.getLayer(),
sNamespace: oChange.getNamespace(),
sChangelist: oChange.getRequest()
}, oChange.isVariant()).then(function(result) {
var sChangeId = oChange.getId();
// remove change from all referring Persistence instances
var mParameter = {
id: sChangeId
};
oChange.fireEvent(Change.events.markForDeletion, mParameter);
if (Cache.isActive()) {
Cache.deleteChange(oChange.getComponent(), oChange.getDefinition());
}
return result;
}));
break;
default:
break;
}
});
// TODO Consider not rejecting with first error, but wait for all promises and collect the results
return Promise.all(aPromises);
};
/**
* Event Handler for deletion event of sap.ui.fl.Change. Removes the change from the internal changes map
*
* @param {object} oEvent - the event with parameters
* @private
*/
Persistence.prototype._onDeleteChange = function(oEvent) {
var sChangeId;
sChangeId = oEvent.getParameter("id");
var oChange = this.getChange(sChangeId);
if (oChange.getPendingAction() === "DELETE") {
delete this._oChanges[sChangeId];
}
};
/**
* Returns a flag whether the variant downport scenario is enabled or not. This scenario is only enabled if the current layer is the vendor layer
* and the url paramater hotfix is set to true.
*
* @returns {boolean} Flag whether the variant downport scenario is enabled
* @public
*/
Persistence.prototype.isVariantDownport = function() {
var sLayer, bIsHotfix;
sLayer = Utils.getCurrentLayer();
bIsHotfix = Utils.isHotfixMode();
return ((sLayer === 'VENDOR') && (bIsHotfix));
};
return Persistence;
}, true);
}; // end of sap/ui/fl/Persistence.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.registry.ChangeRegistry') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.registry.ChangeRegistry'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/registry/ChangeRegistry",[
"sap/ui/fl/Utils", "jquery.sap.global", "sap/ui/fl/registry/ChangeRegistryItem", "sap/ui/fl/registry/SimpleChanges", "sap/ui/fl/registry/ChangeTypeMetadata", "sap/ui/fl/registry/Settings"
], function(Utils, jQuery, ChangeRegistryItem, SimpleChanges, ChangeTypeMetadata, Settings) {
"use strict";
/**
* Central registration for available change types on controls
* @constructor
* @alias sap.ui.fl.registry.ChangeRegistry
*
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*
*/
var ChangeRegistry = function() {
this._registeredItems = {};
this.simpleChanges = SimpleChanges;
this.initSettings();
};
ChangeRegistry._instance = undefined;
ChangeRegistry.getInstance = function() {
if (!ChangeRegistry._instance) {
ChangeRegistry._instance = new ChangeRegistry();
}
return ChangeRegistry._instance;
};
ChangeRegistry.prototype.registerControlsForChanges = function(mControlChanges) {
var that = this;
Object.keys(mControlChanges).forEach(function(sControlType){
mControlChanges[sControlType].forEach(function(oChangeType){
that.registerControlForSimpleChange(sControlType, oChangeType);
});
});
};
/**
* Adds registration for a control and a simple change
* @param {String} sControlType - Name of the control, for example "sap.ui.comp.smartfilterbar.SmartFilterBar"
* @param {sap.ui.fl.registry.SimpleChange.member} oSimpleChange - One of the simple changes
*
* @public
*/
ChangeRegistry.prototype.registerControlForSimpleChange = function(sControlType, oSimpleChange) {
var oChangeRegistryItem;
if (!sControlType) {
return;
}
if (!oSimpleChange || !oSimpleChange.changeType || !oSimpleChange.changeHandler) {
return;
}
oChangeRegistryItem = this._createChangeRegistryItemForSimpleChange(sControlType, oSimpleChange);
if (oChangeRegistryItem) {
this.addRegistryItem(oChangeRegistryItem);
}
};
/**
* Adds registration for a control and a simple change
* @param {String} sControlType - Name of the control, for example "sap.ui.comp.smartfilterbar.SmartFilterBar"
* @param {sap.ui.fl.registry.SimpleChange.member} oSimpleChange - One of the simple changes
* @returns {sap.ui.fl.registry.ChangeRegistryItem} the registry item
*
* @public
*/
ChangeRegistry.prototype._createChangeRegistryItemForSimpleChange = function(sControlType, oSimpleChange) {
var mParam, oChangeTypeMetadata, oChangeRegistryItem;
//Create change type metadata
mParam = {
name: oSimpleChange.changeType,
changeHandler: oSimpleChange.changeHandler
};
oChangeTypeMetadata = new ChangeTypeMetadata(mParam);
//Create change registry item
mParam = {
changeTypeMetadata: oChangeTypeMetadata,
controlType: sControlType
};
oChangeRegistryItem = new ChangeRegistryItem(mParam);
return oChangeRegistryItem;
};
/**
* Add a registry item for the controlType and changeType. If the item already exists, it will be overwritten
* @param {sap.ui.fl.registry.ChangeRegistryItem} oRegistryItem the registry item
* @public
*/
ChangeRegistry.prototype.addRegistryItem = function(oRegistryItem) {
var sChangeType, sControlType;
if (!oRegistryItem) {
return;
}
sChangeType = oRegistryItem.getChangeTypeName();
sControlType = oRegistryItem.getControlType();
this._registeredItems[sControlType] = this._registeredItems[sControlType] || {};
this._registeredItems[sControlType][sChangeType] = oRegistryItem;
};
/**
* Remove a registration for:
* - A single change type (only changeTypeName parameter set)
* - The complete registration on a certain control (only controlType parameter set)
* - Or all registrations of a change type on any control (both changeTypeName AND controlType set)
* @param {Object} mParam Description see below
* @param {String} [mParam.changeTypeName] Change type name which should be removed
* @param {String} [mParam.controlType] Control type which should be removed.
*
* @public
*/
ChangeRegistry.prototype.removeRegistryItem = function(mParam) {
if (!mParam.changeTypeName && !mParam.controlType) {
Utils.log.error("sap.ui.fl.registry.ChangeRegistry: ChangeType and/or ControlType required");
return;
}
//Either remove a specific changeType from a specific control type
if (mParam.controlType && mParam.changeTypeName) {
if (this._registeredItems[mParam.controlType]) {
if (Object.keys(this._registeredItems[mParam.controlType]).length === 1) { //only one changeType...
delete this._registeredItems[mParam.controlType];
} else {
delete this._registeredItems[mParam.controlType][mParam.changeTypeName];
}
}
//or remove by control type
} else if (mParam.controlType) {
if (this._registeredItems[mParam.controlType]) {
delete this._registeredItems[mParam.controlType];
}
//or via changeType on all control types
} else if (mParam.changeTypeName) {
for ( var controlTypeKey in this._registeredItems) {
var controlItem = this._registeredItems[controlTypeKey];
delete controlItem[mParam.changeTypeName];
}
}
};
/**
* Get a registration for:
* - All registration items with specific change type name on all controls (only changeTypeName parameter set)
* - The complete registration(s) on a certain control (only controlType parameter set)
* - Or all registrations of a change type name on any control (both changeTypeName AND controlType set)
* @param {Object} mParam Description see below
* @param {String} [mParam.changeTypeName] Change type to find registration(s) for this changeType
* @param {String} [mParam.controlType] Control type to find registration(s) for this controlType
* @param {String} [mParam.layer] Layer where changes are currently applied. If not provided no filtering for valid layers is done.
* @returns {Object} Returns an object in the format
* @example {
* "sap.ui.core.SampleControl":{
* "labelChange":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>},
* "visibility":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>}
* },
* "sap.ui.core.TestControl":{
* "visibility":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>}
* }
* }
* @public
*/
ChangeRegistry.prototype.getRegistryItems = function(mParam) {
if (!mParam.changeTypeName && !mParam.controlType) {
Utils.log.error("sap.ui.fl.registry.ChangeRegistry: Change Type Name and/or Control Type required");
}
var result = null;
if (mParam.controlType && mParam.changeTypeName) {
var controlRegistrations = this._registeredItems[mParam.controlType];
if (controlRegistrations) {
if (controlRegistrations[mParam.changeTypeName]) {
result = {};
result[mParam.controlType] = {};
result[mParam.controlType][mParam.changeTypeName] = controlRegistrations[mParam.changeTypeName];
}
}
} else if (mParam.controlType) {
if (this._registeredItems[mParam.controlType]) {
result = {};
//keep the actual registry items but clone the control-changetype object structure to not modify the registry during filtering
result[mParam.controlType] = {};
jQuery.each(this._registeredItems[mParam.controlType], function(sChangeTypeName, oRegistryItem) {
result[mParam.controlType][sChangeTypeName] = oRegistryItem;
});
}
} else if (mParam.changeTypeName) {
result = {};
for ( var controlTypeKey in this._registeredItems) {
if (this._registeredItems[controlTypeKey][mParam.changeTypeName]) {
result[controlTypeKey] = {};
result[controlTypeKey][mParam.changeTypeName] = this._registeredItems[controlTypeKey][mParam.changeTypeName];
}
}
}
//filter out disabled change types
this._filterChangeTypes(result, mParam.layer);
return result;
};
/**
* Retrieves the Flex Settings for a UI5 component.
*
* @param {string} sComponentName the UI5 component name for which settings are requested;
* if not provided, hardcoded settings will be used.
*
* @private
*/
ChangeRegistry.prototype.initSettings = function(sComponentName) {
this._oSettings = Settings.getInstanceOrUndef(sComponentName);
if (!this._oSettings) {
this._oSettings = new Settings({});
}
};
/**
* Removes registry items that are not enabled for the current writable layer.
* @param {object} oRegistryItems see example
* @param {string} sLayer persistency layer, if not provided no filtering is done.
* @example {
* "sap.ui.core.SampleControl":{
* "labelChange":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>},
* "visibility":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>}
* },
* "sap.ui.core.TestControl":{
* "visibility":{<type of @see sap.ui.fl.registry.ChangeRegistryItem>}
* }
* }
* @private
*/
ChangeRegistry.prototype._filterChangeTypes = function(oRegistryItems, sLayer) {
if (this._oSettings && sLayer && oRegistryItems) {
var that = this;
jQuery.each(oRegistryItems, function(sControlType, oControlReg) {
jQuery.each(oControlReg, function(sChangeType, oRegistryItem) {
var bIsChangeTypeEnabled = that._oSettings.isChangeTypeEnabled(sChangeType, sLayer);
if (!bIsChangeTypeEnabled) {
delete oControlReg[sChangeType];
}
});
});
}
};
ChangeRegistry.prototype.getDragInfo = function(sControlType) {
var controlTypeItems = this._registeredItems[sControlType];
if (controlTypeItems) {
return controlTypeItems.getDragInfo();
}
return null;
};
return ChangeRegistry;
}, true);
}; // end of sap/ui/fl/registry/ChangeRegistry.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.FlexController') ) {
/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/* global Promise */
jQuery.sap.declare('sap.ui.fl.FlexController'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.mvc.View'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/FlexController",[
"jquery.sap.global", "sap/ui/fl/Persistence", "sap/ui/fl/registry/ChangeRegistry", "sap/ui/fl/Utils", "sap/ui/fl/Change", "sap/ui/fl/registry/Settings", "sap/ui/fl/ChangePersistenceFactory", "sap/ui/core/mvc/View"
], function(jQuery, Persistence, ChangeRegistry, Utils, Change, FlexSettings, ChangePersistenceFactory, View) {
"use strict";
/**
* Retrieves changes (LabelChange, etc.) for a sap.ui.core.mvc.View and applies these changes
*
* @params {string} sComponentName -the component name the flex controler is responsible for
* @constructor
* @class
* @alias sap.ui.fl.FlexController
* @experimental Since 1.27.0
* @author SAP SE
* @version 1.36.12
*/
var FlexController = function(sComponentName) {
this._oChangePersistence = undefined;
this._sComponentName = sComponentName || "";
if (this._sComponentName) {
this._createChangePersistence();
}
};
/**
* Sets the component name of the FlexController
*
* @param {String} sComponentName The name of the component
* @public
*/
FlexController.prototype.setComponentName = function(sComponentName) {
this._sComponentName = sComponentName;
this._createChangePersistence();
};
/**
* Returns the component name of the FlexController
*
* @returns {String} the name of the component
* @public
*/
FlexController.prototype.getComponentName = function() {
return this._sComponentName;
};
/**
* Create a change
*
* @param {object} oChangeSpecificData property bag (nvp) holding the change information (see sap.ui.fl.Change#createInitialFileContent
* oPropertyBag). The property "packageName" is set to $TMP and internally since flex changes are always local when they are created.
* @param {sap.ui.core.Control} oControl control for which the change will be added
* @returns {sap.ui.fl.Change} the created change
* @public
*/
FlexController.prototype.createChange = function(oChangeSpecificData, oControl) {
var oChangeFileContent, oChange, ChangeHandler, oChangeHandler;
var oAppDescr = Utils.getAppDescriptor(oControl);
var sComponentName = this.getComponentName();
oChangeSpecificData.reference = sComponentName; //in this case the component name can also be the value of sap-app-id
if ( oAppDescr && oAppDescr["sap.app"] ){
oChangeSpecificData.componentName = oAppDescr["sap.app"].componentName || oAppDescr["sap.app"].id;
}else {
//fallback in case no appdescriptor is available (e.g. during unit testing)
oChangeSpecificData.componentName = sComponentName;
}
oChangeSpecificData.packageName = '$TMP'; // first a flex change is always local, until all changes of a component are made transportable
oChangeFileContent = Change.createInitialFileContent(oChangeSpecificData);
oChange = new Change(oChangeFileContent);
// for getting the change handler the control type and the change type are needed
ChangeHandler = this._getChangeHandler(oChange, oControl);
if (ChangeHandler) {
oChangeHandler = new ChangeHandler();
oChangeHandler.completeChangeContent(oChange, oChangeSpecificData);
} else {
throw new Error('Change handler could not be retrieved for change ' + JSON.stringify(oChangeSpecificData));
}
// first a flex change is always local, until all changes of a component are made transportable
// if ( oChangeSpecificData.transport ){
// oChange.setRequest(oChangeSpecificData.transport);
// }
return oChange;
};
/**
* Adds a change to the flex persistence (not yet saved). Will be saved with #saveAll.
*
* @param {object} oChangeSpecificData property bag (nvp) holding the change information (see sap.ui.fl.Change#createInitialFileContent
* oPropertyBag). The property "packageName" is set to $TMP and internally since flex changes are always local when they are created.
* @param {sap.ui.core.Control} oControl control for which the change will be added
* @returns {sap.ui.fl.Change} the created change
* @public
*/
FlexController.prototype.addChange = function(oChangeSpecificData, oControl) {
var oChange = this.createChange(oChangeSpecificData, oControl);
this._oChangePersistence.addChange(oChange);
return oChange;
};
/**
* Creates a new change and applies it immediately
*
* @param {object} oChangeSpecificData The data specific to the change, e.g. the new label for a RenameField change
* @param {sap.ui.core.Control} oControl The control where the change will be applied to
* @public
*/
FlexController.prototype.createAndApplyChange = function(oChangeSpecificData, oControl) {
var oChange = this.addChange(oChangeSpecificData, oControl);
try {
this.applyChange(oChange, oControl);
} catch (ex) {
this._oChangePersistence.deleteChange(oChange);
throw ex;
}
};
/**
* Saves all changes of a persistence instance.
*
* @returns {Promise} resolving with an array of responses or rejecting with the first error
* @public
*/
FlexController.prototype.saveAll = function() {
return this._oChangePersistence.saveDirtyChanges();
};
/**
* Loads and applies all changes for the specified view
*
* @params {object} oView - the view to process
* @returns {Promise} without parameters. Promise resolves once all changes of the view have been applied
* @public
*/
FlexController.prototype.processView = function(oView) {
var that = this;
var mPropertyBag = {
appDescriptor: Utils.getAppDescriptor(oView),
siteId: Utils.getSiteId(oView)
};
var bIsFlexEnabled = this._isFlexEnabled(oView);
if (!bIsFlexEnabled) {
return Promise.resolve("No control found, which enable flexibility features. Processing skipped.");
}
// do an async fetch of the flex settings
// to work with that settings during the session
return FlexSettings.getInstance(this.getComponentName(), mPropertyBag).then(function(oSettings) {
return that._getChangesForView(oView, mPropertyBag);
}).then(that._resolveGetChangesForView.bind(that))['catch'](function(error) {
Utils.log.error('Error processing view ' + error);
});
};
FlexController.prototype._resolveGetChangesForView = function(aChanges) {
var that = this;
var fChangeHandler, oChangeHandler;
aChanges.forEach(function(oChange) {
var oControl = that._getControlByChange(oChange);
if (oControl) {
fChangeHandler = that._getChangeHandler(oChange, oControl);
if (fChangeHandler) {
oChangeHandler = new fChangeHandler();
} else {
Utils.log.error("A change handler of type '" + oChange.getDefinition().changeType + "' does not exist");
}
if (oChangeHandler && oChangeHandler.getControlIdFromChangeContent) {
// check to avoid duplicate IDs
var sControlId = oChangeHandler.getControlIdFromChangeContent(oChange);
var bIsControlAlreadyInDOM = !!sap.ui.getCore().byId(sControlId);
if (!bIsControlAlreadyInDOM) {
that.applyChangeAndCatchExceptions(oChange, oControl);
} else {
var sId = oChange.getSelector().id;
Utils.log.error("A change of type '" + oChange.getDefinition().changeType + "' tries to add a object with an already existing ID ('" + sId + "')");
}
} else {
that.applyChangeAndCatchExceptions(oChange, oControl);
}
} else {
var oDefinition = oChange.getDefinition();
var sChangeType = oDefinition.changeType;
var sTargetControlId = oDefinition.selector.id;
var fullQualifiedName = oDefinition.namespace + "/" + oDefinition.fileName + "." + oDefinition.fileType;
Utils.log.error("A flexibility change tries to change a non existing control.",
"\n type of change: '" + sChangeType + "'" +
"\n LRep location of the change: " + fullQualifiedName +
"\n id of targeted control: '" + sTargetControlId + "'");
}
});
};
/**
* Triggers applyChange and catches exceptions, if some were thrown (logs changes that could not be applied)
*
* @param {sap.ui.fl.Change} oChange Change instance
* @param {sap.ui.core.Control} oControl Control instance
* @public
*/
FlexController.prototype.applyChangeAndCatchExceptions = function(oChange, oControl) {
var oChangeDefinition = oChange.getDefinition();
var sChangeNameSpace = oChangeDefinition.namespace;
try {
this.applyChange(oChange, oControl);
} catch (ex) {
Utils.log.error("Change could not be applied: [" + oChangeDefinition.layer + "]" + sChangeNameSpace + "/" + oChangeDefinition.fileName + "." + oChangeDefinition.fileType + ": " + ex);
}
};
/**
* Retrieves the corresponding change handler for the change and applies the change to the control
*
* @param {sap.ui.fl.Change} oChange Change instance
* @param {sap.ui.core.Control} oControl Control instance
* @public
*/
FlexController.prototype.applyChange = function(oChange, oControl) {
var ChangeHandler, oChangeHandler;
ChangeHandler = this._getChangeHandler(oChange, oControl);
if (!ChangeHandler) {
if (oChange && oControl) {
Utils.log.warning("Change handler implementation for change not found - Change ignored");
}
return;
}
try {
oChangeHandler = new ChangeHandler();
if (oChangeHandler && typeof oChangeHandler.applyChange === 'function') {
oChangeHandler.applyChange(oChange, oControl);
}
} catch (ex) {
this._setMergeError(true);
Utils.log.error("Change could not be applied. Merge error detected.");
throw ex;
}
};
/**
* Retrieves the <code>sap.ui.fl.registry.ChangeRegistryItem</code> for the given change and control
*
* @param {sap.ui.fl.Change} oChange - Change instance
* @param {sap.ui.core.Control} oControl Control instance
* @returns {sap.ui.fl.changeHandler.Base} the change handler. Undefined if not found.
* @private
*/
FlexController.prototype._getChangeHandler = function(oChange, oControl) {
var oChangeTypeMetadata, fChangeHandler;
oChangeTypeMetadata = this._getChangeTypeMetadata(oChange, oControl);
if (!oChangeTypeMetadata) {
return undefined;
}
fChangeHandler = oChangeTypeMetadata.getChangeHandler();
return fChangeHandler;
};
/**
* Retrieves the <code>sap.ui.fl.registry.ChangeRegistryItem</code> for the given change and control
*
* @param {sap.ui.fl.Change} oChange Change instance
* @param {sap.ui.core.Control} oControl Control instance
* @returns {sap.ui.fl.registry.ChangeTypeMetadata} the registry item containing the change handler. Undefined if not found.
* @private
*/
FlexController.prototype._getChangeTypeMetadata = function(oChange, oControl) {
var oChangeRegistryItem, oChangeTypeMetadata;
oChangeRegistryItem = this._getChangeRegistryItem(oChange, oControl);
if (!oChangeRegistryItem || !oChangeRegistryItem.getChangeTypeMetadata) {
return undefined;
}
oChangeTypeMetadata = oChangeRegistryItem.getChangeTypeMetadata();
return oChangeTypeMetadata;
};
/**
* Retrieves the <code>sap.ui.fl.registry.ChangeRegistryItem</code> for the given change and control
*
* @param {sap.ui.fl.Change} oChange Change instance
* @param {sap.ui.core.Control} oControl Control instance
* @returns {sap.ui.fl.registry.ChangeRegistryItem} the registry item containing the change handler. Undefined if not found.
* @private
*/
FlexController.prototype._getChangeRegistryItem = function(oChange, oControl) {
var sChangeType, sControlType, oChangeRegistryItem, sLayer;
if (!oChange || !oControl) {
return undefined;
}
sChangeType = oChange.getChangeType();
sControlType = Utils.getControlType(oControl);
if (!sChangeType || !sControlType) {
return undefined;
}
sLayer = oChange.getLayer();
oChangeRegistryItem = this._getChangeRegistry().getRegistryItems({
"changeTypeName": sChangeType,
"controlType": sControlType,
"layer": sLayer
});
if (oChangeRegistryItem && oChangeRegistryItem[sControlType] && oChangeRegistryItem[sControlType][sChangeType]) {
return oChangeRegistryItem[sControlType][sChangeType];
} else if (oChangeRegistryItem && oChangeRegistryItem[sControlType]) {
return oChangeRegistryItem[sControlType];
} else {
return oChangeRegistryItem;
}
};
/**
* Returns the change registry
*
* @returns {sap.ui.fl.registry.ChangeRegistry} Instance of the change registry
* @private
*/
FlexController.prototype._getChangeRegistry = function() {
var oInstance = ChangeRegistry.getInstance();
// make sure to use the most current flex settings that have been retrieved during processView
oInstance.initSettings(this.getComponentName());
return oInstance;
};
/**
* Returns the control where the change will be applied to. Undefined if control cannot be found.
*
* @param {sap.ui.fl.Change} oChange Change
* @returns {sap.ui.core.Control} Control where the change will be applied to
* @private
*/
FlexController.prototype._getControlByChange = function(oChange) {
var oSelector;
if (!oChange) {
return undefined;
}
oSelector = oChange.getSelector();
if (oSelector && typeof oSelector.id === "string") {
return sap.ui.getCore().byId(oSelector.id);
}
return undefined;
};
/**
* Retrieves the changes for the complete UI5 component
* @param {map} mPropertyBag - (optional) contains additional data that are needed for reading of changes
* - appDescriptor that belongs to actual component
* - siteId that belongs to actual component
* @returns {Promise} Promise resolves with a map of all {sap.ui.fl.Change} having the changeId as key
* @public
*/
FlexController.prototype.getComponentChanges = function(mPropertyBag) {
return this._oChangePersistence.getChangesForComponent(mPropertyBag);
};
/**
* Retrieves the changes for the view and its siblings (except nested views)
*
* @params {object} oView - the view
* @param {map} mPropertyBag - (optional) contains additional data that are needed for reading of changes
* - appDescriptor that belongs to actual component
* - siteId that belongs to actual component
* @returns {Promise} Promise resolves with a map of all {sap.ui.fl.Change} of a component
* @private
*/
FlexController.prototype._getChangesForView = function(oView, mPropertyBag) {
return this._oChangePersistence.getChangesForView(oView.getId(), mPropertyBag);
};
/**
* Creates a new instance of sap.ui.fl.Persistence based on the current component and caches the instance in a private member
*
* @returns {sap.ui.fl.Persistence} persistence instance
* @private
*/
FlexController.prototype._createChangePersistence = function() {
this._oChangePersistence = ChangePersistenceFactory.getChangePersistenceForComponent(this.getComponentName());
return this._oChangePersistence;
};
/**
* Discard changes on the server.
*
* @param {array} aChanges array of {sap.ui.fl.Change} to be discarded
* @returns {Promise} promise that resolves without parameters.
*/
FlexController.prototype.discardChanges = function(aChanges) {
var sActiveLayer = Utils.getCurrentLayer(false);
aChanges.forEach(function(oChange) {
// only discard changes of the currently active layer (CUSTOMER vs PARTNER vs VENDOR)
if (oChange && oChange.getLayer && oChange.getLayer() === sActiveLayer) {
this._oChangePersistence.deleteChange(oChange);
}
}.bind(this));
return this._oChangePersistence.saveDirtyChanges();
};
/**
* Searches for controls in the view control tree, which enable flexibility features.
*
* @param {sap.ui.core.Control} oParentControl Parent control instance
* @returns {boolean} true if the view contains controls, which enable flexibility features, false if not.
* @private
*/
FlexController.prototype._isFlexEnabled = function(oParentControl) {
var that = this;
var bIsFlexEnabled = false;
if (oParentControl.getMetadata) {
var oParentControlMetadata = oParentControl.getMetadata();
var oAggregations = oParentControlMetadata.getAllAggregations();
var aAggregationKeys = Object.keys(oAggregations);
jQuery.each(aAggregationKeys, function(iAggragationKeyIndex, sAggregationKey) {
if (sAggregationKey != "data" && oParentControlMetadata.getAggregation) {
// data has no flex, but cannot be accessed if the data contains a FlattenedDataset (resulting in an error)
var oAggregation = oParentControlMetadata.getAggregation(sAggregationKey);
if ( oAggregation && oAggregation.get) {
var aAggregations = oAggregation.get(oParentControl);
if (aAggregations) {
if (!Array.isArray(aAggregations)) {
// in case of an aggregation with a cardinality of 0..1 the object is returned not in an array.
aAggregations = [
aAggregations
];
}
jQuery.each(aAggregations, function(index, oChildControl) {
if (typeof oChildControl.getFlexEnabled === 'function' && oChildControl.getFlexEnabled()) {
bIsFlexEnabled = true;
return false; // break inner jQuery.each
} else {
bIsFlexEnabled = that._isFlexEnabled(oChildControl);
if (bIsFlexEnabled === true) {
return false; // break inner jQuery.each
}
}
});
if (bIsFlexEnabled === true) {
return false; // break outer jQuery.each
}
}
}
}
});
}
return bIsFlexEnabled;
};
FlexController.prototype.deleteChangesForControlDeeply = function(oControl) {
return Promise.resolve();
};
/**
* Set flag if an error has occured when merging changes
*
* @param {Boolean} bHasErrorOccured Indicator if an error has occured
* @private
*/
FlexController.prototype._setMergeError = function(bHasErrorOccured) {
// in this case FlexSettings.getInstance does not get passed (AppDescriptorId and SiteId) as setMergeErrorOccured ONLY enrich setting instance
// with runtime data. No direct backend call
return FlexSettings.getInstance(this.getComponentName()).then(function(oSettings) {
oSettings.setMergeErrorOccured(true);
});
};
return FlexController;
}, true);
}; // end of sap/ui/fl/FlexController.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.FlexControllerFactory') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.FlexControllerFactory'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/FlexControllerFactory",[
"jquery.sap.global", "sap/ui/fl/FlexController", "sap/ui/fl/Utils"
], function(jQuery, FlexController, Utils) {
"use strict";
/**
* Factory to create new instances of {sap.ui.fl.FlexController}
* @constructor
* @alias sap.ui.fl.FlexControllerFactory
* @experimental Since 1.27.0
* @author SAP SE
* @version 1.36.12
*/
var FlexControllerFactory = {};
FlexControllerFactory._instanceCache = {};
/**
* Creates or returns an instance of the FlexController
*
* @public
* @param {String} sComponentName The name of the component
* @returns {sap.ui.fl.FlexController} instance
*
*/
FlexControllerFactory.create = function(sComponentName) {
var oFlexController = FlexControllerFactory._instanceCache[sComponentName];
if (!oFlexController){
oFlexController = new FlexController(sComponentName);
FlexControllerFactory._instanceCache[sComponentName] = oFlexController;
}
return oFlexController;
};
/**
* Creates or returns an instance of the FlexController for the specified control.
* The control needs to be embedded into a View and the view needs to be embedded into a component.
* If one of this prerequisites is not fulfilled, no instance of FlexController will be returned.
*
* @public
* @param {sap.ui.core.Control} oControl The control
* @returns {sap.ui.fl.FlexController} instance
*/
FlexControllerFactory.createForControl = function(oControl) {
var sComponentName = Utils.getComponentClassName(oControl);
return FlexControllerFactory.create(sComponentName);
};
return FlexControllerFactory;
}, true);
}; // end of sap/ui/fl/FlexControllerFactory.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.PreprocessorImpl') ) {
/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/*global Promise */
// Provides object sap.ui.fl.ProcessorImpl
jQuery.sap.declare('sap.ui.fl.PreprocessorImpl'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Component'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/PreprocessorImpl",[
'jquery.sap.global', 'sap/ui/core/Component', 'sap/ui/fl/FlexControllerFactory', 'sap/ui/fl/Utils', 'sap/ui/fl/LrepConnector', 'sap/ui/fl/Cache'
], function(jQuery, Component, FlexControllerFactory, Utils, LrepConnector, Cache) {
'use strict';
/**
* The implementation of the <code>Preprocessor</code> for the SAPUI5 flexibility services that can be hooked in the <code>View</code> life cycle.
*
* @name sap.ui.fl.PreprocessorImpl
* @class
* @constructor
* @author <NAME>
* @version 1.36.12
* @experimental Since 1.27.0
*/
var FlexPreprocessorImpl = function(){
};
jQuery.sap.require("sap.ui.core.mvc.Controller");
sap.ui.require("sap/ui/core/mvc/Controller").registerExtensionProvider("sap.ui.fl.PreprocessorImpl");
/**
* Provides an array of extension providers. An extension provider is an object which were defined as controller extensions. These objects
* provides lifecycle and event handler functions of a specific controller.
*
* @param {string} sControllerName - name of the controller
* @param {string} sComponentId - unique id for the running controller - unique as well for manifest first
* @param {boolean} bAsync - flag whether <code>Promise</code> should be returned or not (async=true)
* @see sap.ui.controller for an overview of the available functions on controllers.
* @since 1.34.0
* @public
*/
FlexPreprocessorImpl.prototype.getControllerExtensions = function(sControllerName, sComponentId, bAsync) {
//D050664: Commented out due to ticket 1670158697. It will be corrected with backlog item CPOUIFDALLAS-919.
/*if (bAsync) {
return Cache.getChangesFillingCache(LrepConnector.createConnector(), sComponentId, undefined).then(function(oFileContent) {
var oChanges = oFileContent.changes;
var aExtensionProviders = [];
if (oChanges) {
jQuery.each(oChanges, function (index, oChange) {
if (oChange.changeType === "CodingExtension" && oChange.content && sControllerName === oChange.content.controllerName) {
aExtensionProviders.push(FlexPreprocessorImpl.getExtensionProvider(oChange));
}
});
}
return aExtensionProviders;
});
}*/
};
FlexPreprocessorImpl.getExtensionProvider = function(oChange) {
var sConvertedAsciiCodeContent = oChange.content.code;
var sConvertedCodeContent = Utils.asciiToString(sConvertedAsciiCodeContent);
var oExtensionProvider;
/*eslint-disable */
eval("oExtensionProvider = { " + sConvertedCodeContent + " } ");
/*eslint-enable */
return oExtensionProvider;
};
/**
* Asynchronous view processing method.
*
* @param {sap.ui.core.mvc.View} oView view to process
* @returns {jquery.sap.promise} result of the processing, promise if executed asynchronously
*
* @public
*/
FlexPreprocessorImpl.process = function(oView){
return Promise.resolve().then(function(){
var sComponentName = Utils.getComponentClassName(oView);
if ( !sComponentName || sComponentName.length === 0 ){
var sError = "no component name found for " + oView.getId();
jQuery.sap.log.info(sError);
throw new Error(sError);
}else {
var oFlexController = FlexControllerFactory.create(sComponentName);
return oFlexController.processView(oView);
}
}).then(function() {
jQuery.sap.log.debug("flex processing view " + oView.getId() + " finished");
return oView;
})["catch"](function(error) {
var sError = "view " + oView.getId() + ": " + error;
jQuery.sap.log.info(sError); //to allow control usage in applications that do not work with UI flex and components
// throw new Error(sError); // throw again, wenn caller handles the promise
return oView;
});
};
return FlexPreprocessorImpl;
}, /* bExport= */true);
}; // end of sap/ui/fl/PreprocessorImpl.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.core.EventDelegate') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.core.EventDelegate'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.base.EventProvider'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/core/EventDelegate",[
"jquery.sap.global", "sap/ui/fl/Utils", "sap/ui/base/EventProvider", "sap/ui/fl/registry/ChangeRegistry", "sap/ui/fl/core/FlexVisualizer"
], function(jQuery, Utils, EventProvider, ChangeRegistry, FlexVisualizer) {
"use strict";
/**
*
* @constructor
* @param {sap.ui.core.Control} oControl Control reference of the control which is currently in focus
* @param {Object} oSupportedRegistryItems Object with supported changes as registry items. Structure matches the returnvalue of @see sap.ui.fl.registry.ChangeRegistry#getRegistryItems *
* @alias sap.ui.fl.core.EventDelegate
*
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
* @private
*
*/
var EventDelegate = function(oControl, oSupportedRegistryItems) {
if (!oControl) {
Utils.log.error("sap.ui.fl.core.EventDelegate: Control required");
}
if (!oSupportedRegistryItems) {
Utils.log.error("sap.ui.fl.core.EventDelegate: Supported registry items required");
}
EventProvider.apply(this);
this._oControl = oControl;
this._oSupportedRegistryItems = oSupportedRegistryItems;
};
EventDelegate.prototype = jQuery.sap.newObject(EventProvider.prototype);
/**
* Register a control for using flexibility
* @param {sap.ui.core.Control} oControl Control which should be registered
*
* @public
*/
EventDelegate.registerControl = function(oControl) {
if (oControl) {
// check if the control is already registered
var i = 0;
if (oControl.aDelegates) {
for (i = 0; i < oControl.aDelegates.length; i++) {
var sType = "";
if (oControl.aDelegates[i].oDelegate && oControl.aDelegates[i].oDelegate.getType) {
sType = (oControl.aDelegates[i].oDelegate.getType());
}
if (sType === "Flexibility") {
return; // already added
}
}
}
EventDelegate.registerExplicitChanges(oControl);
}
};
/**
* Register a control for explicit changes - changes which use a dialog or similar to do the change and can only be activated in a certain mode
* @param {sap.ui.core.Control} oControl Control which should be registered
*
* @public
*/
EventDelegate.registerExplicitChanges = function(oControl) {
var oRegistry = ChangeRegistry.getInstance();
var mParam = {
controlType: Utils.getControlType(oControl)
};
var oSupportedRegistryItems = oRegistry.getRegistryItems(mParam);
// check if the control will be handled by personalization
if (Object.keys(oSupportedRegistryItems).length > 0) {
oControl.addEventDelegate(new EventDelegate(oControl, oSupportedRegistryItems));
}
};
/**
* Unregister the control which was registered before
*
* @public
*/
EventDelegate.unregisterControl = function() {
};
/**
* Function which is called on mouse-over on the registered control to trigger the flexibility framework
* @param {sap.ui.core.Event} oEvent Event parameters
*
* @public
*/
EventDelegate.prototype.onmouseover = function(oEvent) {
oEvent.stopPropagation();
// stopPropagation unfortunately kills column resize of table
// therefore custom property on the event
if (oEvent.handled) {
return;
} else {
oEvent.handled = true;
}
//TODO: Get from FlexController, once checked-in
if (FlexVisualizer.isPersonalizationMode()) {
if (this._oControl && !jQuery(this._oControl.getDomRef()).hasClass("sapuiflex-highlight")) {
FlexVisualizer.showDialog(this._oControl);
}
}
};
/**
* Function which is called on mouse-out on the registered control to notify that the control is not in scope anymore for flexibility
* @param {sap.ui.core.Event} oEvent Event parameters
*
* @public
*/
EventDelegate.prototype.onmouseout = function(oEvent) {
//TODO: Get from FlexController, once checked-in
if (FlexVisualizer.isPersonalizationMode()) {
if (this._oControl) {
FlexVisualizer.closeDialog();
}
}
};
return EventDelegate;
}, true);
}; // end of sap/ui/fl/core/EventDelegate.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.library') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.ui.fl.library'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('sap.ui.core.Core'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.library'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.mvc.XMLView'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.mvc.View'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/library",[
"sap/ui/core/Core",
"sap/ui/core/library",
"sap/ui/core/mvc/XMLView",
"sap/ui/core/mvc/View",
"sap/ui/fl/registry/ChangeRegistry",
"sap/ui/fl/registry/SimpleChanges"
],
function(Core, corelibrary, XMLView, View, ChangeRegistry, SimpleChanges) {
"use strict";
sap.ui.getCore().initLibrary({
name:"sap.ui.fl",
version:"1.36.12",
dependencies:["sap.ui.core"],
noLibraryCSS: true
});
if ( XMLView.registerPreprocessor ){
// Register preprocessor for TINAF changes
XMLView.registerPreprocessor('controls', "sap.ui.fl.Preprocessor", true);
}else {
//workaround solution until registerPreprocessor is available
//PreprocessorImpl because in the workaround case there is no preprocessor base object
View._sContentPreprocessor = "sap.ui.fl.PreprocessorImpl";
}
var registerChangeHandlerForOpenUI5Controls = function () {
//Flex Change Handler registration
var oChangeRegistry = ChangeRegistry.getInstance();
oChangeRegistry.registerControlsForChanges({
"sap.uxap.ObjectPageLayout": [
SimpleChanges.moveElements,
SimpleChanges.propertyChange
],
"sap.uxap.ObjectPageSection": [
SimpleChanges.hideControl,
SimpleChanges.unhideControl
],
"sap.uxap.ObjectPageHeader": [
SimpleChanges.propertyChange
],
"sap.uxap.ObjectPageHeaderActionButton": [
SimpleChanges.propertyChange
],
"sap.ui.table.Column": [
SimpleChanges.propertyChange
],
"sap.ui.table.Table" : [
SimpleChanges.moveElements
],
"sap.ui.table.AnalyticalTable" : [
SimpleChanges.moveElements
]
});
};
registerChangeHandlerForOpenUI5Controls();
return sap.ui.fl;
}, /* bExport= */ true);
}; // end of sap/ui/fl/library.js
if ( !jQuery.sap.isDeclared('sap.ui.fl.Preprocessor') ) {
/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
// Provides object sap.ui.fl.Processor
jQuery.sap.declare('sap.ui.fl.Preprocessor'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.base.Object'); // unlisted dependency retained
sap.ui.define("sap/ui/fl/Preprocessor",[
'jquery.sap.global', 'sap/ui/base/Object', 'sap/ui/fl/PreprocessorImpl'
], function(jQuery, BaseObject, PreprocessorImpl) {
'use strict';
/**
* The implementation of the <code>Preprocessor</code> for the SAPUI5 flexibility services that can be hooked in the <code>View</code> life cycle.
*
* @name sap.ui.fl.Preprocessor
* @class
* @constructor
* @author <NAME>
* @version 1.36.12
* @experimental Since 1.27.0
* @implements sap.ui.core.mvc.View.Preprocessor
*/
var FlexPreprocessor = BaseObject.extend("sap.ui.fl.Preprocessor", {
});
/**
* Asynchronous processing method that should be implemented by the inheriting Preprocessor class.
*
* @param {sap.ui.core.mvc.View} oView view to process
* @returns {jquery.sap.promise} result of the processing, promise if executed asynchronously
*
* @public
*/
FlexPreprocessor.process = function(oView){
return PreprocessorImpl.process(oView);
};
return FlexPreprocessor;
}, /* bExport= */true);
}; // end of sap/ui/fl/Preprocessor.js
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.ui.comp.variants.EditableVariantItem.
sap.ui.define(['jquery.sap.global', 'sap/m/ColumnListItem', 'sap/m/ColumnListItemRenderer', 'sap/ui/comp/library'],
function(jQuery, ColumnListItem, ColumnListItemRenderer, library) {
"use strict";
/**
* Constructor for a new variants/EditableVariantItem.
*
* @param {string} [sId] ID for the new control, generated automatically if no id is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* The EditableVariantItem class describes an editable variant list item for the Manage Variants popup.
* @extends sap.m.ColumnListItem
*
* @constructor
* @public
* @alias sap.ui.comp.variants.EditableVariantItem
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var EditableVariantItem = ColumnListItem.extend("sap.ui.comp.variants.EditableVariantItem", /** @lends sap.ui.comp.variants.EditableVariantItem.prototype */ { metadata : {
library : "sap.ui.comp",
properties : {
/**
* Key of the List Item
* @since 1.22.0
*/
key : {type : "string", group : "Misc", defaultValue : null},
/**
* Indicator if a variant is visible for all users.
* @since 1.26.0
*/
global : {type : "boolean", group : "Misc", defaultValue : null},
/**
* ABAP Package the variant is assigned. Used for transport functionality
* @since 1.26.0
*/
lifecyclePackage : {type : "string", group : "Misc", defaultValue : null},
/**
* Identifier of the transport object the variant is assigned to.
* @since 1.26.0
*/
lifecycleTransportId : {type : "string", group : "Misc", defaultValue : null},
/**
* Variant namespace
* @since 1.26.0
*/
namespace : {type : "string", group : "Misc", defaultValue : null},
/**
* Indication if variant can be changed
* @since 1.26.0
*/
readOnly : {type : "boolean", group : "Misc", defaultValue : false},
/**
* Flags for a variant to indicate why it might be read-only
* @since 1.26.0
* @deprecated Since version 1.28.0. Replaced by property <code>labelReadOnly</code>
*/
accessOptions : {type : "string", group : "Misc", defaultValue : null, deprecated: true},
/**
* Indicates if the variant label can be changed
* @since 1.28.0
*/
labelReadOnly : {type : "boolean", group : "Misc", defaultValue : false}
}
},
renderer: ColumnListItemRenderer.render
});
return EditableVariantItem;
}, /* bExport= */ true);
<file_sep>/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/* global Promise */
sap.ui.define([], function() {
"use strict";
/**
* @namespace
* @alias sap.ui.fl.fieldExt.Access
* @experimental Since 1.25.0
* @author SAP SE
* @version 1.36.12
*/
var Access = {};
/**
* Returns all Business Contexts for given service and EntityTypeName/EntitySetName. Not that only EntityTypeName or EntitySetName can be
* supplied. Providing both results in an exception
*
* @param {string} sServiceUri
* @param {string} sEntityTypeName
* @param {string} sEntitySetName
* @returns {array} aBusinessContexts
* @public
*/
Access.getBusinessContexts = function(sServiceUri, sEntityTypeName, sEntitySetName) {
// Determine ServiceName and ServiceVersion from Service URI
var sServiceName = this._parseServiceName(sServiceUri);
var sServiceVersion = this._parseServiceVersion(sServiceUri, sServiceName);
// Build URL for BusinessContextRetrievalService based on ServiceName, ServiceVersion, EntityName
var sBusinessContextRetrievalUri = this._buildBusinessContextRetrievalUri(sServiceName, sServiceVersion, sEntityTypeName, sEntitySetName);
// Execute Ajax call
var mAjaxSettings = this._getAjaxSettings();
var promise = this._executeAjaxCall(sBusinessContextRetrievalUri, mAjaxSettings, sServiceName, sServiceVersion, sEntityTypeName, sEntitySetName);
return promise;
};
/**
* Extracts ServiceName out of Service URI
*
* @private
* @param {string} sServiceUri
* @returns {string} sVersionName
*/
Access._parseServiceName = function(sServiceUri) {
var sServiceName, sServiceNameWithVersion;
var sODataPath = "sap/opu/odata";
var iIndexOfODataPath = sServiceUri.indexOf(sODataPath);
if (iIndexOfODataPath !== -1) {
// Remove service path prefix
var iEndOfsODataPath = iIndexOfODataPath + sODataPath.length;
sServiceNameWithVersion = sServiceUri.substring(iEndOfsODataPath);
var sSapPrefix = "/SAP";
var bHasSapPrefix = jQuery.sap.startsWith(sServiceNameWithVersion, sSapPrefix);
if (bHasSapPrefix) {
// case of sap specific namespace for the service
sServiceNameWithVersion = sServiceNameWithVersion.substring(sSapPrefix.length);
}
} else {
// Remove all stuff before and including the first slash
var iStartPositionOfServiceName = sServiceUri.lastIndexOf("/") + 1;
sServiceNameWithVersion = sServiceUri.substring(iStartPositionOfServiceName);
}
if (sServiceNameWithVersion.indexOf(";v=") != -1) {
// Cut away all URI stuff that comes before the serviceName
sServiceName = sServiceNameWithVersion.substring(0, sServiceNameWithVersion.indexOf(";v="));
} else {
sServiceName = sServiceNameWithVersion;
}
return sServiceName;
};
/**
* Extracts ServiceVersion out of Service URI
*
* @private
* @param {string} sServiceUri
* @param {string} sServiceName
* @returns {string} sVersionNumber
*/
Access._parseServiceVersion = function(sServiceUri, sServiceName) {
if (sServiceUri.indexOf(sServiceName + ";v=") != -1) {
// Cut away all URI stuff that comes before the serviceName
var iPositionOfServiceWithVersionFragment = sServiceUri.indexOf(sServiceName + ";v=");
var sRemainingUri = sServiceUri.substring(iPositionOfServiceWithVersionFragment);
// Get String from ";v=" up to the next "/" --> this is the version
// number
var iPositionAfterVersionPrefix = sServiceName.length + 3;
var sVersionNumber = sRemainingUri.slice(iPositionAfterVersionPrefix, sRemainingUri.indexOf("/"));
return sVersionNumber;
} else {// In this case there is no version information and so it is
// version 1
return "0001";
}
};
/**
* Builds URI for BusinessContext Retrieval
*
* @private
* @param {string} sServiceUri
* @param {string} sServiceName
* @param {string} sEntityName
* @param {string} sEntitySetName
* @returns {string} sBusinessContextRetrievalUri
*/
Access._buildBusinessContextRetrievalUri = function(sServiceName, sServiceVersion, sEntityName, sEntitySetName) {
if (sEntityName == null) {
sEntityName = '';
}
if (sEntitySetName == null) {
sEntitySetName = '';
}
if (((sEntitySetName.length == 0) && (sEntityName.length == 0)) || (!(sEntitySetName.length == 0) && !(sEntityName.length == 0))) {
throw new Error("sap.ui.fl.fieldExt.Access._buildBusinessContextRetrievalUri()" + "Inconsistent input parameters EntityName: " + sEntityName + " EntitySet: " + sEntitySetName);
}
// Example call:
// sap/opu/odata/SAP/APS_CUSTOM_FIELD_MAINTENANCE_SRV/GetBusinessContextsByEntityType?EntitySetName=''&EntityTypeName='BusinessPartner'&ServiceName='CFD_TSM_BUPA_MAINT_SRV'&ServiceVersion='0001'&$format=json
var sBusinessContextRetrievalUri = "/sap/opu/odata/SAP/APS_CUSTOM_FIELD_MAINTENANCE_SRV/GetBusinessContextsByEntityType?" + "EntitySetName=\'" + sEntitySetName + "\'" + "&EntityTypeName=\'" + sEntityName + "\'" + "&ServiceName=\'" + sServiceName + "\'" + "&ServiceVersion=\'" + sServiceVersion + "\'" + "&$format=json";
return sBusinessContextRetrievalUri;
};
/**
* Executes Ajax Call for BusinessContext Retrieval
*
* @private
* @param {string} sBusinessContextRetrievalUri
* @param {map} mRequestSettings
* @param {string} sServiceName
* @param {string} sServiceVersion
* @param {string} sEntityName
* @returns {Object} oPromise
*/
Access._executeAjaxCall = function(sBusinessContextRetrievalUri, mRequestSettings, sServiceName, sServiceVersion, sEntityType, sEntitySetName) {
var that = this;
var oDeferred = jQuery.Deferred();
jQuery.ajax(sBusinessContextRetrievalUri, mRequestSettings).done(function(data, textStatus, jqXHR) {
var aBusinessContexts = [];
if (data) {
var aBusinessContexts = that._extractBusinessContexts(data);
}
var oResult = {
BusinessContexts: aBusinessContexts,
ServiceName: sServiceName,
ServiceVersion: sServiceVersion
};
oDeferred.resolve(oResult);
}).fail(function(jqXHR, textStatus, errorThrown) {
var aErrorMessages = that._getMessagesFromXHR(jqXHR);
var oError = {
errorOccured: true,
errorMessages: aErrorMessages,
serviceName: sServiceName,
serviceVersion: sServiceVersion,
entityType: sEntityType,
entitySet: sEntitySetName
};
oDeferred.reject(oError);
});
return oDeferred.promise();
};
/**
* @private
* @returns {map} mSettings
*/
Access._getAjaxSettings = function() {
var mSettings = {
type: "GET",
async: true,
dataType: 'json'
};
return mSettings;
};
/**
* Extracts BusinessContext out of Request response data
*
* @private
* @param {object} oData
* @returns {array} BusinessContexts
*/
Access._extractBusinessContexts = function(data) {
var aResults = null;
var aBusinessContexts = [];
if (data && data.d) {
aResults = data.d.results;
}
if (aResults !== null && aResults.length > 0) {
for (var i = 0; i < aResults.length; i++) {
if (aResults[i].BusinessContext !== null) {
aBusinessContexts.push(aResults[i].BusinessContext);
}
}
}
return aBusinessContexts;
};
/**
* Extracts error messages from request failure response
*
* @private
* @param {object} oXHR
* @returns {array} errorMessages
*/
Access._getMessagesFromXHR = function(oXHR) {
var aMessages = [];
try {
var oErrorResponse = JSON.parse(oXHR.responseText);
if (oErrorResponse && oErrorResponse.error && oErrorResponse.error.message && oErrorResponse.error.message.value && oErrorResponse.error.message.value !== '') {
aMessages.push({
severity: "error",
text: oErrorResponse.error.message.value
});
} else {
aMessages.push({
severity: "error",
text: oXHR.responseText
});
}
} catch (e) {
// ignore
}
return aMessages;
};
return Access;
}, /* bExport= */true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare("sap.ui.comp.smartmicrochart.SmartAreaMicroChartRenderer");jQuery.sap.require("sap.ui.core.Renderer");jQuery.sap.require("sap.suite.ui.microchart.AreaMicroChartRenderer");sap.ui.comp.smartmicrochart.SmartAreaMicroChartRenderer=sap.ui.core.Renderer.extend(sap.suite.ui.microchart.AreaMicroChartRenderer);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.ui.comp.smartform.flexibility.FieldList.
sap.ui.define(['jquery.sap.global', 'sap/ui/comp/library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* Constructor for a new smartform/flexibility/FieldList.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Contains list of forms, groups and fields which can could be modified by the SAPUI5 flexibility services
* @extends sap.ui.core.Control
*
* @constructor
* @public
* @alias sap.ui.comp.smartform.flexibility.FieldList
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var FieldList = Control.extend("sap.ui.comp.smartform.flexibility.FieldList", /** @lends sap.ui.comp.smartform.flexibility.FieldList.prototype */ { metadata : {
library : "sap.ui.comp",
aggregations : {
/**
* Nodes representing either a Form, a Group or a field
*/
nodes : {type : "sap.ui.comp.smartform.flexibility.FieldListNode", multiple : true, singularName : "node"}
},
events : {
/**
* Event is fired when the selected node has changed
*/
selectionChanged : {},
/**
* Event is fired when the label of the node has changed
*/
labelChanged : {},
/**
* Event is fired when a node was hidden
*/
nodeHidden : {}
}
}});
/**
* init
*
* @public
*/
FieldList.prototype.init = function() {
// do something for initialization...
this._oSelectedNode = null;
};
/**
* Returns the currently selected field list node
*
* @returns {sap.ui.comp.smartform.flexibility.FieldListNode} field list node
* @public
*/
FieldList.prototype.getSelectedNode = function() {
return this._oSelectedNode;
};
/**
* Registers to the Selected event of the provided field list node
*
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oNode field list node
* @private
*/
FieldList.prototype._registerNodeSelectionChangedEvent = function(oNode) {
if (oNode) {
oNode.attachSelected(this._handleSelectionChanged.bind(this));
}
};
/**
* Registers to the LabelChanged event of the provided field list node
*
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oNode field list node
* @private
*/
FieldList.prototype._registerNodeLabelChangedEvent = function(oNode) {
if (oNode) {
oNode.attachLabelChanged(this._handleLabelChanged.bind(this));
}
};
/**
* Registers to the NodeHidden event of the provided field list node
*
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oNode field list node
* @private
*/
FieldList.prototype._registerNodeHiddenEvent = function(oNode) {
if (oNode) {
oNode.attachNodeHidden(this._handleNodeHidden.bind(this));
}
};
/**
* Deregisters to the Selected event of the provided field list node
*
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oNode field list node
* @private
*/
FieldList.prototype._deregisterNodeSelectionChangedEvent = function(oNode) {
if (oNode) {
oNode.detachSelected(this._handleSelectionChanged.bind(this));
}
};
/**
* Deregisters to the LabelChanged event of the provided field list node
*
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oNode field list node
* @private
*/ FieldList.prototype._deregisterNodeLabelChangedEvent = function(oNode) {
if (oNode) {
oNode.detachLabelChanged(this._handleLabelChanged.bind(this));
}
};
/**
* Deregisters to the NodeHidden event of the provided field list node
*
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oNode field list node
* @private
*/ FieldList.prototype._deregisterNodeHiddenEvent = function(oNode) {
if (oNode) {
oNode.detachNodeHidden(this._handleNodeHidden.bind(this));
}
};
/**
* Event handler for Selected event of the field list node
*
* @param {object} oEvent event
* @private
*/
FieldList.prototype._handleSelectionChanged = function(oEvent) {
var oNode;
oNode = oEvent.getParameter("target");
if (oNode) {
// this._setSelectedNode(oNode);
this.fireSelectionChanged({
node: oNode
});
}
};
/**
* Event handler for LabelChanged event of the field list node
*
* @param {object} oEvent event
* @private
*/
FieldList.prototype._handleLabelChanged = function(oEvent) {
var oNode;
oNode = oEvent.getParameter("target");
if (oNode) {
this.fireLabelChanged({
node: oNode
});
}
};
/**
* Event handler for NodeHidden event of the field list node
*
* @param {object} oEvent event
* @private
*/
FieldList.prototype._handleNodeHidden = function(oEvent) {
var oNode;
oNode = oEvent.getParameter("target");
if (oNode) {
this.fireNodeHidden({
node: oNode
});
}
};
/**
* Unselects the previoulsy registered field list node and selects the new field list node
*
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oNode field list node
* @private
*/
FieldList.prototype._setSelectedNode = function(oNode) {
if (!oNode) {
return;
}
if (this._oSelectedNode) {
this._oSelectedNode.setIsSelected(false);
}
this._oSelectedNode = oNode;
this._oSelectedNode.setIsSelected(true);
};
/**
* @private Overwritten - called when field list node is added
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oNode field list node
* @returns {sap.ui.comp.smartform.flexibility.FieldListNode} added field list node
*/
FieldList.prototype.addNode = function(oNode) {
this.addAggregation("nodes", oNode, true);
this._registerNodeSelectionChangedEvent(oNode);
this._registerNodeLabelChangedEvent(oNode);
this._registerNodeHiddenEvent(oNode);
return this;
};
/**
* @private Overwritten - called when field list node is destroyed
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oNode field list node
* @returns {sap.ui.comp.smartform.flexibility.FieldListNode} destroyed field list node
*/
FieldList.prototype.destroyNodes = function(oNode) {
var aNodes, length, i;
aNodes = this.getNodes();
length = aNodes.length;
for (i = 0; i < length; i++) {
this._deregisterNodeSelectionChangedEvent(aNodes[i]);
this._deregisterNodeLabelChangedEvent(aNodes[i]);
this._deregisterNodeHiddenEvent(aNodes[i]);
}
this.destroyAggregation("nodes");
return this;
};
/**
* @private Overwritten - called when field list node is removed
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oNode field list node
* @returns {sap.ui.comp.smartform.flexibility.FieldListNode | number} removed field list node
*/
FieldList.prototype.removeNode = function(oNode) {
this.removeAggregation("nodes", oNode);
if (typeof oNode === 'number') {
oNode = this.getNodes([
oNode
]);
}
this._deregisterNodeSelectionChangedEvent(oNode);
this._deregisterNodeLabelChangedEvent(oNode);
this._deregisterNodeHiddenEvent(oNode);
return this;
};
return FieldList;
}, /* bExport= */ true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
sap.ui.define(['jquery.sap.global','./Base'],function(q,B){"use strict";var U=function(){};U.prototype=q.sap.newObject(B.prototype);U.prototype.applyChange=function(c,C){if(C.setVisible){C.setVisible(true);}else{throw new Error("Provided control instance has no setVisible method");}};U.prototype.completeChangeContent=function(c,s){var C=c.getDefinition();if(!C.content){C.content={};}};return U;},true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
sap.ui.define([
'jquery.sap.global', './Base'
], function(jQuery, Base) {
"use strict";
/**
* Change handler for hiding of a control.
* @constructor
* @alias sap.ui.fl.changeHandler.HideControl
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*/
var HideControl = function() {
};
HideControl.prototype = jQuery.sap.newObject(Base.prototype);
/**
* Hides a control.
*
* @param {sap.ui.fl.Change} oChange change object with instructions to be applied on the control map
* @param {sap.ui.core.Control} oControl control that matches the change selector for applying the change
* @public
*/
HideControl.prototype.applyChange = function(oChange, oControl) {
if (oControl.setVisible) {
oControl.setVisible(false);
} else {
throw new Error("Provided control instance has no setVisible method");
}
};
/**
* Completes the change by adding change handler specific content
*
* @param {sap.ui.fl.Change} oChange change object to be completed
* @param {object} oSpecificChangeInfo as an empty object since no additional attributes are required for this operation
* @public
*/
HideControl.prototype.completeChangeContent = function(oChange, oSpecificChangeInfo) {
var oChangeJson = oChange.getDefinition();
if (!oChangeJson.content) {
oChangeJson.content = {};
}
};
return HideControl;
},
/* bExport= */true);
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP SE. All rights reserved
*/
/* global window*/
/**
*@class selectionDisplay
*@name selectionDisplay Fragment
*@description Holds the selections on the active step and displays them in a dialog using js fragment
*@memberOf sap.apf.ui.reuse.view
*
*/
sap.ui.jsfragment("sap.apf.ui.reuse.fragment.selectionDisplay", {
createContent : function(oController){
this.oController = oController;
this.contentWidth = jQuery(window).height() * 0.6 + "px"; // height and width for the dialog relative to the window
this.contentHeight = jQuery(window).height() * 0.6 + "px";
var self = this;
this.oCoreApi = oController.oCoreApi;
this.oUiApi = oController.oUiApi;
var closeButton = new sap.m.Button({
text : self.oCoreApi.getTextNotHtmlEncoded("close"),
press : function() {
self.selectionDisplayDialog.close();
self.selectionDisplayDialog.destroy();
}
});
var oActiveStep = this.oCoreApi.getActiveStep();
var selectedRepresentation = oActiveStep.getSelectedRepresentation();
var selectionData = typeof selectedRepresentation.getSelections === "function" ? selectedRepresentation.getSelections() : undefined; //Returns the filter selections
var selectedDimension = selectedRepresentation.getMetaData().getPropertyMetadata(selectedRepresentation.getParameter().requiredFilters[0]).label;
var oModel = new sap.ui.model.json.JSONModel();
//Preparing the data list in the dialog
if(selectionData !== undefined){
var oData = {
selectionData : selectionData
};
var selectionList = new sap.m.List({
items : {
path : "/selectionData",
template: new sap.m.StandardListItem({
title : "{text}"
})
}
});
oModel.setSizeLimit(selectedRepresentation.getSelections().length);
oModel.setData(oData);
selectionList.setModel(oModel);
self.selectionDisplayDialog = new sap.m.Dialog({
title : this.oCoreApi.getTextNotHtmlEncoded("selected-required-filter", [selectedDimension]) + " (" + selectionData.length + ")",
contentWidth : self.contentWidth,
contentHeight : self.contentHeight,
buttons : [closeButton],
content : [selectionList],
afterClose : function() {
self.selectionDisplayDialog.destroy();
}
});
return self.selectionDisplayDialog;
}
}
});<file_sep>sap.apf[version] = 1.36.10
sap.apf[dependencies] = sap.ui.core,sap.ca.ui,sap.m,sap.ui.layout,sap.ushell,sap.viz
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2015 SAP SE. All rights reserved
*/
sap.ui.define(["./LegendBase"],function(L){"use strict";var D=L.extend({metadata:{properties:{shape:{type:"sap.gantt.config.Shape"},xDimension:{type:"string"},yDimension:{type:"string"},xDomain:{type:"array"},yDomain:{type:"array"}}}});return D;},true);
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
/* global window*/
jQuery.sap.declare("sap.apf.ui.utils.print");
jQuery.sap.require("sap.apf.ui.utils.formatter");
/**
*@class PrintHelper
*@memberOf sap.apf.ui.utils
*@description has functions to perform printing of Analysis Path
*
*/
sap.apf.ui.utils.PrintHelper = function(oInject) {
"use strict";
var oCoreApi = oInject.oCoreApi;
var oUiApi = oInject.uiApi;
var oFilterIdHandler = oInject.oFilterIdHandler;
var nStepRenderCount, oChartSelectionPromise, nNoOfSteps;
this.oPrintLayout = {};
/**
*@method _increaseStepRenderCount increases the step render count as and when each step is rendered
**/
function _increaseStepRenderCount() {
++nStepRenderCount;
if (nNoOfSteps === nStepRenderCount) {
oChartSelectionPromise.resolve();
}
}
/**
*@method _createDivForPrint removes the existing div apfPrintArea. Later creates the div apfPrintArea
**/
function _createDivForPrint(oContext) {
if (!jQuery.isEmptyObject(oContext.oPrintLayout)) {
oContext.oPrintLayout.removeContent();
}
jQuery('#apfPrintArea').remove(); // removing the div which holds the printable content
jQuery("body").append('<div id="apfPrintArea"></div>'); //div which holds the printable content
oUiApi.createApplicationLayout(false).setBusy(true);//sets the Local Busy Indicator for the print
}
/**
*@method _getHeaderForFirstPage creates a header for the first page of print
*@returns header for first page of print
*/
function _getHeaderForFirstPage() {
var date = new Date();
var sAppName = oCoreApi.getApplicationConfigProperties().appName;
var sAnalysisPathTitle = oUiApi.getAnalysisPath().oSavedPathName.getTitle();
var headerForFirstPage = new sap.ui.core.HTML({
id : 'idAPFHeaderForFirstPage',
content : [ '<div class="subHeaderPrintWrapper"><p class="printHeaderTitle"> ' + oCoreApi.getTextHtmlEncoded(sAppName) + ' : ' + jQuery.sap.encodeHTML(sAnalysisPathTitle) + '</p>',
'<p class="printHeaderDate"> ' + date.toTimeString() + ' </p></div><div class="clear"></div>' ].join(""),
sanitizeContent : true
});
return headerForFirstPage;
}
/**
*@method _getPrintLayoutForFacetFiltersAndFooters creates a layout for facet filter and footers page
*@description Gets application specific filters and formats them for printing. Gets facet filter values for printing.
*@returns print layout for facet filters and footers
*/
function _getPrintLayoutForFacetFiltersAndFooters() {
var i, j, nIndex, oFacetFilterLists, oAppSpecificFilter, mFilterName, mFilterValue, aFiltersForPrining, filterObj, oFormatter, oFacetFilter, aSelectedItems, oFacetAndFooterLayout;
var aAppSpecificFilterExp = [], aAppSpecificFilters = [], sFilterValue = "", sFilterName = "", aSelectedFilters = [], filterValues = [], aAppSpecificFormattedFilters = [], aFacetFilters = [], oFilterValue = {};
//First : Get application specific filter values
var callback = oUiApi.getEventCallback(sap.apf.core.constants.eventTypes.printTriggered);
var callbackContext = {
getTextNotHtmlEncoded : oCoreApi.getTextNotHtmlEncoded
};
var aAllAppSpecificFilterIds = oFilterIdHandler.getAllInternalIds(); //get application specific filters
//Get the filter expression for the application specific filters(footers)
if (aAllAppSpecificFilterIds.length > 0) {
for(i = 0; i < aAllAppSpecificFilterIds.length; i++) {
oAppSpecificFilter = oFilterIdHandler.get(aAllAppSpecificFilterIds[i]).getExpressions();
aAppSpecificFilterExp.push(oAppSpecificFilter[0]);
}
}
//Returns formatted filter values from APF for application specific filters
function getAppSpecificFormattedFilters() {
function prepareFormattedFilterValues(oPropertyMetadata) {
sFilterName = "";
filterValues = [];
oFormatter = new sap.apf.ui.utils.formatter({
getEventCallback : oUiApi.getEventCallback.bind(oUiApi),
getTextNotHtmlEncoded : oCoreApi.getTextNotHtmlEncoded
}, oPropertyMetadata);
sFilterName = oPropertyMetadata.label;
filterValues.push(oFormatter.getFormattedValue(oPropertyMetadata.name, aAppSpecificFilterExp[i][j].value));
}
for(i = 0; i < aAppSpecificFilterExp.length; i++) {
for(j = 0; j < aAppSpecificFilterExp[i].length; j++) {
filterObj = aAppSpecificFilterExp[i][j];
oCoreApi.getMetadataFacade().getProperty(aAppSpecificFilterExp[i][j].name, prepareFormattedFilterValues);
filterObj["sName"] = sFilterName;
filterObj["value"] = filterValues;
aAppSpecificFilters.push(filterObj);
}
}
return aAppSpecificFilters;
}
if (callback !== undefined) { //If application has a print functionality on its own use it otherwise get formatted filter values for application specific filters from APF
aAppSpecificFormattedFilters = callback.apply(callbackContext, aAppSpecificFilterExp) || [];
aAppSpecificFormattedFilters = (aAppSpecificFormattedFilters.length > 0) ? aAppSpecificFormattedFilters : getAppSpecificFormattedFilters();
} else { //APF default formatting
aAppSpecificFormattedFilters = getAppSpecificFormattedFilters();
}
//Second : Get all the configured facet filters from APF
oFacetFilter = oUiApi.getFacetFilterForPrint();
function getTextsFromSelectedItems(aSelectedItems) {
aSelectedFilters = [];
aSelectedItems.forEach(function(oItem) {
aSelectedFilters.push(oItem.getText());
});
}
if (oFacetFilter) {//If there is a facet filter
oFacetFilterLists = oFacetFilter.getLists();
for(nIndex = 0; nIndex < oFacetFilterLists.length; nIndex++) {
aSelectedItems = [];
oFilterValue = {};
oFilterValue.sName = oFacetFilterLists[nIndex].getTitle();
if (!oFacetFilterLists[nIndex].getSelectedItems().length) {
aSelectedItems = oFacetFilterLists[nIndex].getItems();
} else {
aSelectedItems = oFacetFilterLists[nIndex].getSelectedItems();
}
getTextsFromSelectedItems(aSelectedItems);
oFilterValue.value = aSelectedFilters;
aFacetFilters.push(oFilterValue);
}
}
//Later : Merge the APF filters and application specific filters for printing; Application specific filters if available are printed first
aFiltersForPrining = aAppSpecificFormattedFilters.length > 0 ? aAppSpecificFormattedFilters.concat(aFacetFilters) : aFacetFilters;
oFacetAndFooterLayout = new sap.ui.layout.VerticalLayout({
id : 'idAPFFacetAndFooterLayout'
});
//Formatting the filter array
for(i = 0; i < aFiltersForPrining.length; i++) {
sFilterName = aFiltersForPrining[i].sName;
for(j = 0; j < aFiltersForPrining[i].value.length; j++) {
if (j !== aFiltersForPrining[i].value.length - 1) {
sFilterValue += aFiltersForPrining[i].value[j] + ", ";
} else {
sFilterValue += aFiltersForPrining[i].value[j];
}
}
mFilterName = new sap.m.Text({
text : sFilterName
}).addStyleClass("printFilterName");
mFilterValue = new sap.m.Text({
text : sFilterValue
}).addStyleClass("printFilterValue");
//Facet UI Layout
oFacetAndFooterLayout.addContent(mFilterName);
oFacetAndFooterLayout.addContent(mFilterValue);
//Reset the filter value
sFilterValue = "";
}
return oFacetAndFooterLayout;
}
/**
*@method _getHeaderForEachStep creates a header for each step page
*@returns header for step page
*/
function _getHeaderForEachStep(nIndex, nStepsLength) {
var oMessageObject;
var date = new Date();
var sAppName = oCoreApi.getApplicationConfigProperties().appName;
var sAnalysisPathTitle = oUiApi.getAnalysisPath().oSavedPathName.getTitle();
if (!sAppName) {
oMessageObject = oCoreApi.createMessageObject({
code : "6003",
aParameters : [ "sAppName" ]
});
oCoreApi.putMessage(oMessageObject);
}
var headerForEachStep = new sap.ui.core.HTML({
id : 'idAPFHeaderForEachStep' + nIndex,
content : [ '<div class="subHeaderPrintWrapper"><p class="printHeaderTitle"> ' + oCoreApi.getTextHtmlEncoded(sAppName) + ' : ' + jQuery.sap.encodeHTML(sAnalysisPathTitle) + '</p>',
'<p class="printHeaderDate"> ' + date.toTimeString() + ' </p></div><div class="clear"></div>', '<div class="printChipName"><p>' + oCoreApi.getTextHtmlEncoded("print-step-number", [ nIndex, nStepsLength ]) + '</p></div>' ]
.join(""),
sanitizeContent : true
});
return headerForEachStep;
}
/**
*@method _getRepresentationForPrint
*@param oStep is used to get the step information
*@returns the representation for printing
*/
function _getRepresentationForPrint(oStep) {
var data, metadata, oPrintContent, bIsLegendVisible = false, oRepresentation = {};
var oStepTitle = oCoreApi.getTextNotHtmlEncoded(oStep.title);
var oSelectedRepresentation = oStep.getSelectedRepresentation();
var oStepRepresentation = oSelectedRepresentation.bIsAlternateView ? oSelectedRepresentation.toggleInstance : oSelectedRepresentation;
//If alternate view(table representation)
if (oSelectedRepresentation.bIsAlternateView) {
data = oStep.getSelectedRepresentation().getData();
metadata = oStep.getSelectedRepresentation().getMetaData();
oStepRepresentation.setData(data, metadata);
}
if (oStepRepresentation.type === sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
oPrintContent = oStepRepresentation.getPrintContent(oStepTitle);
oRepresentation = oPrintContent.oTableForPrint.getContent()[0];
var aSelectedItems = oPrintContent.aSelectedListItems;
oRepresentation.attachUpdateFinished(function() {
aSelectedItems.forEach(function(item) {
oRepresentation.setSelectedItem(item);
});
_increaseStepRenderCount();
});
oRepresentation.setWidth("1000px");
} else {//If not a table representation
oPrintContent = oStepRepresentation.getPrintContent(oStepTitle);
oRepresentation = oPrintContent.oChartForPrinting;
//If the chart is vizFrame make selections after rendering of chart and update the step render count
if (oRepresentation.vizSelection) {
oRepresentation.attachRenderComplete(function() {
oRepresentation.vizSelection(oPrintContent.aSelectionOnChart);
_increaseStepRenderCount();
});
} else {//If the chart is Viz make selections after initialization of chart and update the step render count
oRepresentation.attachInitialized(function() {
oRepresentation.selection(oPrintContent.aSelectionOnChart);
_increaseStepRenderCount();
});
}
}
//Show/Hide Legend for print content
if (oStepRepresentation.bIsLegendVisible === undefined || oStepRepresentation.bIsLegendVisible === true) {
bIsLegendVisible = true;
}
if (oRepresentation.setVizProperties) { //Check if it is Viz Frame Charts
oRepresentation.setVizProperties({
legend : {
visible : bIsLegendVisible
},
sizeLegend : {
visible : bIsLegendVisible
}
});
} else {//fall back for viz charts
if (oRepresentation.setLegend !== undefined) {
oRepresentation.setLegend(new sap.viz.ui5.types.legend.Common({
visible : bIsLegendVisible
}));
}
if (oRepresentation.setSizeLegend !== undefined) {
oRepresentation.setSizeLegend(new sap.viz.ui5.types.legend.Common({
visible : bIsLegendVisible
}));
}
}
return oRepresentation;
}
/**
*@method _getPrintLayoutForEachStep defines layout used by each step when being printed
*@usage _getPrintLayoutForEachStep has to be used to get the layout for individual steps in analysis path.
*@param oStep is used to get the step information
*@param nIndex is index of the step being printed
*@param nStepsLength is the total number of steps in an Analysis Path
*@returns the printLayout for a step in an Analysis Path.
*/
function _getPrintLayoutForEachStep(oStep, nIndex, nStepsLength) {
var oStepLayout;
var oChartLayout = new sap.ui.layout.VerticalLayout({
id : 'idAPFChartLayout' + nIndex
});
oChartLayout.addContent(_getRepresentationForPrint(oStep));
oStepLayout = new sap.ui.layout.VerticalLayout({
id : 'idAPFStepLayout' + nIndex,
content : [ _getHeaderForEachStep(nIndex, nStepsLength), oChartLayout ]
}).addStyleClass("representationContent"); // @comment : apfoPrintLayout class not provided in css
return oStepLayout;
}
/**
*@method Print used to print all the steps in Analysis Path.
*@usage PrintHelper().doPrint has to be used for printing Analysis Path
*/
this.doPrint = function() {
var i, j, nIndex, oChart, colCount, table, stepNo, oSelectedRepresentation, oPrintFirstPageLayout;
var domContent = "", pTimer = 2000, self = this;
nStepRenderCount = 0;
var aAllSteps = oCoreApi.getSteps();
nNoOfSteps = aAllSteps.length;
this.oPrintLayout = new sap.ui.layout.VerticalLayout({
id : "idAPFPrintLayout"
});
_createDivForPrint(this);
oChartSelectionPromise = jQuery.Deferred();
if (nNoOfSteps === 0) {
oChartSelectionPromise.resolve();
}
//Facet Filter and footers are printed in the initial page along with the header
oPrintFirstPageLayout = new sap.ui.layout.VerticalLayout({
id : 'idAPFPrintFirstPageLayout',
content : [ _getHeaderForFirstPage(), _getPrintLayoutForFacetFiltersAndFooters() ]
}).addStyleClass("representationContent");
this.oPrintLayout.addContent(oPrintFirstPageLayout);
//Consecutive pages with one step each is printed
for(j = 0; j < aAllSteps.length; j++) {
nIndex = parseInt(j, 10) + 1;
this.oPrintLayout.addContent(_getPrintLayoutForEachStep(aAllSteps[j], nIndex, aAllSteps.length));
}
this.oPrintLayout.placeAt("apfPrintArea");
if (jQuery(".v-geo-container").length) {//set the timer if geomap exists
pTimer = 4000;
}
window.setTimeout(function() {
oUiApi.createApplicationLayout(false).setBusy(false); //Removes the Local Busy Indicator after the print
}, pTimer - 150);
window.setTimeout(function() { //Set Timeout to load the content on to dom
jQuery("#" + self.oPrintLayout.sId + " > div:not(:last-child)").after("<div class='page-break'> </div>");
domContent = self.oPrintLayout.getDomRef(); // Get the DOM Reference
table = jQuery('#apfPrintArea .sapUiTable');
if (table.length) {
colCount = jQuery('#apfPrintArea .printTable .sapMListTblHeader .sapMListTblCell').length;
if (colCount > 11) {
jQuery("#setPrintMode").remove();
jQuery("<style id='setPrintMode' > @media print and (min-resolution: 300dpi) { @page {size : landscape;}}</style>").appendTo("head");
} else {
jQuery("#setPrintMode").remove();
jQuery("<style id='setPrintMode'>@media print and (min-resolution: 300dpi) { @page {size : portrait;}}</style>").appendTo("head");
}
}
jQuery("#apfPrintArea").empty(); //Clear the apfPrintArea
jQuery("#sap-ui-static > div").hide(); // Hide popup
jQuery("#apfPrintArea").append(jQuery(domContent).html()); //Push it to apfPrintArea
for(i = 0; i < jQuery("#apfPrintArea").siblings().length; i++) {
//TODO alternate way of hiding the content and printing only the representations?????
jQuery("#apfPrintArea").siblings()[i].hidden = true; // hiding the content apart from apfPrintArea div
}
//Wait until all the have been rendered with selections and then print
oChartSelectionPromise.then(function() {
window.print(); //print the content
});
window.setTimeout(function() {
for(i = 0; i < jQuery("#apfPrintArea").siblings().length; i++) {
jQuery("#apfPrintArea").siblings()[i].hidden = false;
}
for(stepNo = 0; stepNo < aAllSteps.length; stepNo++) {
oSelectedRepresentation = aAllSteps[stepNo].getSelectedRepresentation();
oSelectedRepresentation = oSelectedRepresentation.bIsAlternateView ? oSelectedRepresentation.toggleInstance : oSelectedRepresentation;
//Check if the representation is not a table representation; if not destroy the chart instance
if (oSelectedRepresentation.type !== sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION) {
//Access layout content to retrieve the chart; Destroy the chart to prevent memory leaks
oChart = self.oPrintLayout.getContent()[stepNo + 1].getContent()[1].getContent()[0];
oChart.destroy();
oChart = null;
}
}
self.oPrintLayout.destroy(); //Destroy the reference & remove from dom
self.oPrintLayout = null;
}, 10);
}, pTimer);
};
};<file_sep>// Copyright (c) 2009-2014 SAP SE, All Rights Reserved
/**
* @fileOverview This file contains miscellaneous utility functions.
*/
(function () {
"use strict";
/*global dispatchEvent, document, jQuery, localStorage, sap */
// ensure that sap.ushell exists
jQuery.sap.declare("sap.ovp.cards.AnnotationHelper");
sap.ovp.cards.AnnotationHelper = {};
sap.ovp.cards.AnnotationHelper.formatFunctions = {count: 0};
sap.ovp.cards.AnnotationHelper.NumberFormatFunctions = {};
sap.ovp.cards.AnnotationHelper.criticalityConstants = {
StateValues : {
None : "None",
Negative : "Error",
Critical : "Warning",
Positive : "Success"
},
ColorValues : {
None : "Neutral",
Negative : "Error",
Critical : "Critical",
Positive : "Good"
}
};
function getCacheEntry(iContext, sKey) {
if (iContext.getSetting) {
var oCache = iContext.getSetting("_ovpCache");
return oCache[sKey];
}
return undefined;
}
function setCacheEntry(iContext, sKey, oValue) {
if (iContext.getSetting) {
var oCache = iContext.getSetting("_ovpCache");
oCache[sKey] = oValue;
}
}
function criticality2state(criticality, oCriticalityConfigValues) {
var sState = oCriticalityConfigValues.None;
if (criticality && criticality.EnumMember) {
var val = criticality.EnumMember;
if (endsWith(val, 'Negative')) {
sState = oCriticalityConfigValues.Negative;
} else if (endsWith(val, 'Critical')) {
sState = oCriticalityConfigValues.Critical;
} else if (endsWith(val, 'Positive')) {
sState = oCriticalityConfigValues.Positive;
}
}
return sState;
}
function endsWith(sString, sSuffix) {
return sString && sString.indexOf(sSuffix, sString.length - sSuffix.length) !== -1;
}
function generateCriticalityCalculationStateFunction(criticalityCalculation, oCriticalityConfigValues) {
return function (value) {
value = Number(value);
var sDirection = criticalityCalculation.ImprovementDirection.EnumMember;
var oCriticality = {};
var deviationLow = getNumberValue(criticalityCalculation.DeviationRangeLowValue);
var deviationHigh = getNumberValue(criticalityCalculation.DeviationRangeHighValue);
var toleranceLow = getNumberValue(criticalityCalculation.ToleranceRangeLowValue);
var toleranceHigh = getNumberValue(criticalityCalculation.ToleranceRangeHighValue);
if (endsWith(sDirection, "Minimize") || endsWith(sDirection, "Minimizing")) {
if (value <= toleranceHigh) {
oCriticality.EnumMember = "Positive";
} else if (value > deviationHigh) {
oCriticality.EnumMember = "Negative";
} else {
oCriticality.EnumMember = "Critical";
}
} else if (endsWith(sDirection, "Maximize") || endsWith(sDirection, "Maximizing")) {
if (value >= toleranceLow) {
oCriticality.EnumMember = "Positive";
} else if (value < deviationLow) {
oCriticality.EnumMember = "Negative";
} else {
oCriticality.EnumMember = "Critical";
}
} else if (endsWith(sDirection, "Target")) {
if (value >= toleranceLow && value <= toleranceHigh) {
oCriticality.EnumMember = "Positive";
} else if (value < deviationLow || value > deviationHigh) {
oCriticality.EnumMember = "Negative";
} else {
oCriticality.EnumMember = "Critical";
}
}
return criticality2state(oCriticality, oCriticalityConfigValues);
};
}
function getSortedDataFields(iContext, aCollection) {
var sCacheKey = iContext.getPath() + "-DataFields-Sorted";
var aSortedFields = getCacheEntry(iContext, sCacheKey);
if (!aSortedFields) {
var aDataPoints = getSortedDataPoints(iContext, aCollection);
var aDataPointsValues = aDataPoints.map(function (oDataPoint) {
return oDataPoint.Value.Path;
});
aDataPointsValues = aDataPointsValues.filter(function (element) {
return !!element;
});
aSortedFields = aCollection.filter(function (item) {
if (item.RecordType === "com.sap.vocabularies.UI.v1.DataField" && aDataPointsValues.indexOf(item.Value.Path) === -1) {
return true;
}
return false;
});
sortCollectionByImportance(aSortedFields);
setCacheEntry(iContext, sCacheKey, aSortedFields);
}
return aSortedFields;
}
function getSortedDataPoints(iContext, aCollection) {
var sCacheKey = iContext.getPath() + "-DataPoints-Sorted";
var aSortedFields = getCacheEntry(iContext, sCacheKey);
if (!aSortedFields) {
aSortedFields = aCollection.filter(isDataFieldForAnnotation);
sortCollectionByImportance(aSortedFields);
var sEntityTypePath;
for (var i = 0; i < aSortedFields.length; i++) {
sEntityTypePath = iContext.getPath().substr(0, iContext.getPath().lastIndexOf("/") + 1);
aSortedFields[i] = iContext.getModel().getProperty(getTargetPathForDataFieldForAnnotation(sEntityTypePath,aSortedFields[i]));
sEntityTypePath = "";
}
setCacheEntry(iContext, sCacheKey, aSortedFields);
}
return aSortedFields;
}
function isDataFieldForAnnotation(oItem) {
if (oItem.RecordType === "com.sap.vocabularies.UI.v1.DataFieldForAnnotation"
&&
oItem.Target.AnnotationPath.match(/@com.sap.vocabularies.UI.v1.DataPoint.*/)) {
return true;
}
return false;
}
function getTargetPathForDataFieldForAnnotation(sEntityTypePath, oDataFieldForAnnotation) {
if (sEntityTypePath && !endsWith(sEntityTypePath,'/')) {
sEntityTypePath += '/';
}
return sEntityTypePath + oDataFieldForAnnotation.Target.AnnotationPath.slice(1);
}
function getImportance(oDataField) {
var sImportance;
if (oDataField["com.sap.vocabularies.UI.v1.Importance"]) {
sImportance = oDataField["com.sap.vocabularies.UI.v1.Importance"].EnumMember;
}
return sImportance;
}
function sortCollectionByImportance(aCollection) {
aCollection.sort(function (a, b) {
var aImportance = getImportance(a),
bImportance = getImportance(b);
if (aImportance === bImportance) {
return 0;
}
if (aImportance === "com.sap.vocabularies.UI.v1.ImportanceType/High") {
return -1;
} else if (bImportance === "com.sap.vocabularies.UI.v1.ImportanceType/High") {
return 1;
} else if (aImportance === "com.sap.vocabularies.UI.v1.ImportanceType/Medium") {
return -1;
} else if (bImportance === "com.sap.vocabularies.UI.v1.ImportanceType/Medium") {
return 1;
} else if (aImportance === "com.sap.vocabularies.UI.v1.ImportanceType/Low") {
return -1;
} else if (bImportance === "com.sap.vocabularies.UI.v1.ImportanceType/Low") {
return 1;
}
return -1;
});
return aCollection;
}
function formatDataField(iContext, aCollection, index) {
var item = getSortedDataFields(iContext, aCollection)[index];
if (item) {
return formatField(iContext, item);
}
return "";
}
function getDataFieldName(iContext, aCollection, index) {
var item = getSortedDataFields(iContext, aCollection)[index];
if (item) {
return item.Label.String;
}
return "";
}
function getDataPointName(iContext, aCollection, index) {
var item = getSortedDataPoints(iContext, aCollection)[index];
if (item && item.Title) {
return item.Title.String;
}
return "";
}
function formatDataPoint(iContext, aCollection, index) {
var item = getSortedDataPoints(iContext, aCollection)[index];
if (!item) {
return "";
}
var oModel = iContext.getSetting('ovpCardProperties');
var oEntityType = oModel.getProperty("/entityType");
var oMetaModel = oModel.getProperty("/metaModel");
return _formatDataPoint(iContext, item, oEntityType, oMetaModel);
}
function _formatDataPoint(iContext, oItem, oEntityType, oMetaModel) {
if (!oItem || !oItem.Value) {
return "";
}
var oEntityTypeProperty = oMetaModel.getODataProperty(oEntityType, oItem.Value.Path);
//Support sap:text attribute
if (oEntityTypeProperty && oEntityTypeProperty["sap:text"]) {
oEntityTypeProperty = oMetaModel.getODataProperty(oEntityType, oEntityTypeProperty["sap:text"]);
oItem = {Value: {Path: oEntityTypeProperty.name}};
}
return formatField(iContext, oItem);
}
function formatField(iContext, item, bDontIncludeUOM, bIncludeOnlyUOM) {
if (item.Value.Apply) {
return sap.ui.model.odata.AnnotationHelper.format(iContext, item.Value);
}
var oModel = iContext.getSetting('ovpCardProperties');
var oEntityType = oModel.getProperty("/entityType");
var oMetaModel = oModel.getProperty("/metaModel");
return _formatField(iContext, item, oEntityType, oMetaModel, bDontIncludeUOM, bIncludeOnlyUOM);
}
function _formatField(iContext, oItem, oEntityType, oMetaModel, bDontIncludeUOM, bIncludeOnlyUOM) {
if (oItem.Value.Apply) {
return sap.ui.model.odata.AnnotationHelper.format(iContext, oItem.Value);
}
var oEntityTypeProperty = oMetaModel.getODataProperty(oEntityType, oItem.Value.Path);
var result = "";
var functionName;
if (!bIncludeOnlyUOM) {
//Support association
if (oItem.Value.Path.split("/").length > 1) {
oEntityTypeProperty = getNavigationSuffix(oMetaModel, oEntityType, oItem.Value.Path);
}
if (!oEntityTypeProperty) {
return "";
}
//Item has ValueFormat annotation
if (oItem.ValueFormat && oItem.ValueFormat.NumberOfFractionalDigits) {
functionName = getNumberFormatFunctionName(oItem.ValueFormat.NumberOfFractionalDigits.Int);
result = "{path:'" + oItem.Value.Path + "', formatter: '" + functionName + "'}";
} else if (oEntityTypeProperty["scale"]) {
//If there is no value format annotation, we will use the metadata scale property
functionName = getNumberFormatFunctionName(oEntityTypeProperty["scale"]);
result = "{path:'" + oEntityTypeProperty.name + "', formatter: '" + functionName + "'}";
} else {
result = sap.ui.model.odata.AnnotationHelper.format(iContext, oItem.Value);
}
}
if (!bDontIncludeUOM) {
//Add currency using path or string
if (oEntityTypeProperty["Org.OData.Measures.V1.ISOCurrency"]) {
var oCurrency = oEntityTypeProperty["Org.OData.Measures.V1.ISOCurrency"];
if (oCurrency.Path) {
result = result + " {path: '" + oCurrency.Path + "'}";
} else if (oCurrency.String) {
result = result + " " + oCurrency.String;
}
}
//Add unit using path or string
if (oEntityTypeProperty["Org.OData.Measures.V1.Unit"]) {
var oUnit = oEntityTypeProperty["Org.OData.Measures.V1.Unit"];
if (oUnit.Path) {
result = result + " {path: '" + oUnit.Path + "'}";
} else if (oUnit.String) {
result = result + " " + oUnit.String;
}
}
}
if (result[0] === " "){
result = result.substring(1);
}
return result;
}
function getNumberFormatFunctionName(numberOfFractionalDigits) {
var functionName = "formatNumberCalculation" + numberOfFractionalDigits;
if (!sap.ovp.cards.AnnotationHelper.NumberFormatFunctions[functionName]) {
sap.ovp.cards.AnnotationHelper.NumberFormatFunctions[functionName] = generateNumberFormatFunc(Number(numberOfFractionalDigits));
}
return "sap.ovp.cards.AnnotationHelper.NumberFormatFunctions." + functionName;
}
function generateNumberFormatFunc(numOfFragmentDigit) {
return function (value) {
jQuery.sap.require("sap.ui.core.format.NumberFormat");
var formatNumber = sap.ui.core.format.NumberFormat.getFloatInstance({
style: 'short',
showMeasure: false,
minFractionDigits: numOfFragmentDigit,
maxFractionDigits: numOfFragmentDigit
});
return formatNumber.format(Number(value));
};
}
function getNavigationSuffix(oMetaModel, oEntityType, sProperty) {
var aParts = sProperty.split("/");
if (aParts.length > 1) {
for (var i = 0; i < (aParts.length - 1); i++) {
var oAssociationEnd = oMetaModel.getODataAssociationEnd(oEntityType, aParts[i]);
if (oAssociationEnd) {
oEntityType = oMetaModel.getODataEntityType(oAssociationEnd.type);
}
}
return oMetaModel.getODataProperty(oEntityType, aParts[aParts.length - 1]);
}
}
function formatDataPointState(iContext, aCollection, index) {
var aDataPoints = getSortedDataPoints(iContext, aCollection);
var sState = "None";
if (aDataPoints.length > index) {
var item = aDataPoints[index];
sState = formatDataPointToValue(iContext, item, sap.ovp.cards.AnnotationHelper.criticalityConstants.StateValues);
}
return sState;
}
function formatDataPointToValue(iContext, oDataPoint, oCriticalityConfigValues) {
var sState = oCriticalityConfigValues.None;
if (oDataPoint.Criticality) {
sState = criticality2state(oDataPoint.Criticality, oCriticalityConfigValues);
} else if (oDataPoint.CriticalityCalculation) {
var sFormattedPath = sap.ui.model.odata.AnnotationHelper.format(iContext, oDataPoint.Value);
var sPath = sFormattedPath.match(/path *: *'.*?',/g);
if (sPath) {
var fFormatFunc = generateCriticalityCalculationStateFunction(oDataPoint.CriticalityCalculation, oCriticalityConfigValues);
sap.ovp.cards.AnnotationHelper.formatFunctions.count++;
var fName = "formatCriticalityCalculation" + sap.ovp.cards.AnnotationHelper.formatFunctions.count;
sap.ovp.cards.AnnotationHelper.formatFunctions[fName] = fFormatFunc;
sState = "{" + sPath + " formatter: 'sap.ovp.cards.AnnotationHelper.formatFunctions." + fName + "'}";
}
}
return sState;
}
function getNavigationPrefix(oMetaModel, oEntityType, sProperty) {
var sExpand = "";
var aParts = sProperty.split("/");
if (aParts.length > 1) {
for (var i = 0; i < (aParts.length - 1); i++) {
var oAssociationEnd = oMetaModel.getODataAssociationEnd(oEntityType, aParts[i]);
if (oAssociationEnd) {
oEntityType = oMetaModel.getODataEntityType(oAssociationEnd.type);
if (sExpand) {
sExpand = sExpand + "/";
}
sExpand = sExpand + aParts[i];
} else {
return sExpand;
}
}
}
return sExpand;
}
sap.ovp.cards.AnnotationHelper.formatField = function (iContext, oItem) {
return formatField(iContext,oItem);
};
/*
* This formatter method parses the List-Card List's items aggregation path in the Model.
* The returned path may contain also sorter definition (for the List) sorting is defined
* appropriately via respected Annotations.
*
* @param iContext
* @param itemsPath
* @returns List-Card List's items aggregation path in the Model
*/
sap.ovp.cards.AnnotationHelper.formatItems = function (iContext, oEntitySet) {
var oModel = iContext.getSetting('ovpCardProperties');
var bAddODataSelect = oModel.getProperty("/addODataSelect");
var oMetaModel = oModel.getProperty("/metaModel");
var oEntityType = oMetaModel.getODataEntityType(oEntitySet.entityType);
var oSelectionVariant = oEntityType[oModel.getProperty('/selectionAnnotationPath')];
var oPresentationVariant = oEntityType[oModel.getProperty('/presentationAnnotationPath')];
var sEntitySetPath = "/" + oEntitySet.name;
var aAnnotationsPath = Array.prototype.slice.call(arguments, 2);
//check if entity set needs parameters
// if selection-annotations path is supplied - we need to resolve it in order to resolve the full entity-set path
if (oSelectionVariant) {
if (oSelectionVariant && oSelectionVariant.Parameters) {
// in case we have UI.SelectionVariant annotation defined on the entityType including Parameters - we need to resolve the entity-set path to include it
sEntitySetPath = sap.ovp.cards.AnnotationHelper.resolveParameterizedEntitySet(iContext.getSetting('dataModel'), oEntitySet, oSelectionVariant);
}
}
var result = "{path: '" + sEntitySetPath + "', length: " + getItemsLength(oModel);
//prepare the select fields in case flag is on
var aSelectFields = [];
if (bAddODataSelect) {
aSelectFields = getSelectFields(iContext, oMetaModel, oEntityType, aAnnotationsPath);
}
//prepare the expand list if navigation properties are used
var aExpand = getExpandList(oMetaModel, oEntityType, aAnnotationsPath);
//add select and expand parameters to the binding info string if needed
if (aSelectFields.length > 0 || aExpand.length > 0) {
result = result + ", parameters: {";
if (aSelectFields.length > 0) {
result = result + "select: '" + aSelectFields.join(',') + "'";
}
if (aExpand.length > 0) {
if (aSelectFields.length > 0) {
result = result + ", ";
}
result = result + "expand: '" + aExpand.join(',') + "'";
}
result = result + "}";
}
//apply sorters information
var aSorters = getSorters(oModel, oPresentationVariant);
if (aSorters.length > 0) {
result = result + ", sorter:" + JSON.stringify(aSorters);
}
//apply filters information
var aFilters = getFilters(oModel, oSelectionVariant);
if (aFilters.length > 0) {
result = result + ", filters:" + JSON.stringify(aFilters);
}
result = result + "}";
// returning the parsed path for the Card's items-aggregation binding
return result;
};
/**
* returns an array of navigation properties prefixes to be used in an odata $expand parameter
*
* @param oMetaModel - metamodel to get the annotations to query
* @param oEntityType - the relevant entityType
* @param aAnnotationsPath - an array of annotation path to check
* @returns {Array} of navigation properties prefixes to be used in an odata $expand parameter
*/
function getExpandList(oMetaModel, oEntityType, aAnnotationsPath) {
var aExpand = [];
var sAnnotationPath, oBindingContext, aColl, sExpand;
//loop over the annotation paths
for (var i = 0; i < aAnnotationsPath.length; i++) {
if (!aAnnotationsPath[i]) {
continue;
}
sAnnotationPath = oEntityType.$path + "/" + aAnnotationsPath[i];
oBindingContext = oMetaModel.createBindingContext(sAnnotationPath);
aColl = oBindingContext.getObject();
//if the annotationPath does not exists there is no BindingContext
aColl = aColl ? aColl : [];
for (var j = 0; j < aColl.length; j++) {
if (aColl[j].Value && aColl[j].Value.Path) {
sExpand = getNavigationPrefix(oMetaModel, oEntityType, aColl[j].Value.Path);
if (sExpand && aExpand.indexOf(sExpand) === -1) {
aExpand.push(sExpand);
}
}
}
}
return aExpand;
}
/**
* returns an array of properties paths to be used in an odata $select parameter
*
* @param oMetaModel - metamodel to get the annotations to query
* @param oEntityType - the relevant entityType
* @param aAnnotationsPath - an array of annotation path to check
* @returns {Array} of properties paths to be used in an odata $select parameter
*/
function getSelectFields(iContext, oMetaModel, oEntityType, aAnnotationsPath) {
var aSelectFields = [];
var sAnnotationPath, oBindingContext, aColl;
//loop over the annotation paths
for (var i = 0; i < aAnnotationsPath.length; i++) {
if (!aAnnotationsPath[i]) {
continue;
}
sAnnotationPath = oEntityType.$path + "/" + aAnnotationsPath[i];
oBindingContext = oMetaModel.createBindingContext(sAnnotationPath);
aColl = oBindingContext.getObject();
//if the annotationPath does not exists there is no BindingContext
aColl = aColl ? aColl : [];
var oItem;
var aItemValue;
var sFormattedField;
var sRecordType;
for (var j = 0; j < aColl.length; j++) {
aItemValue = [];
oItem = aColl[j];
sFormattedField = "";
sRecordType = oItem.RecordType;
if (sRecordType === "com.sap.vocabularies.UI.v1.DataField") {
// in case of a DataField we format the field to get biding string
sFormattedField = _formatField(iContext,oItem,oEntityType,oMetaModel);
} else if (sRecordType === "com.sap.vocabularies.UI.v1.DataFieldForAnnotation") {
// in case of DataFieldForAnnotation we resolve the DataPoint target path of the DataField and format the field to get biding string
var sTargetPath = getTargetPathForDataFieldForAnnotation(oEntityType.$path, oItem);
sFormattedField = _formatDataPoint(iContext, oMetaModel.getProperty(sTargetPath), oEntityType, oMetaModel);
} else if (sRecordType === "com.sap.vocabularies.UI.v1.DataFieldWithUrl" && oItem.Url) {
// format the URL ONLY IN CASE NO UrlRef member resides under it
var sFormattedUrl;
if (!oItem.Url.UrlRef) {
sFormattedUrl = sap.ui.model.odata.AnnotationHelper.format(iContext, oItem.Url);
}
// meaning binding which needs to be evaluated at runtime
if (sFormattedUrl && sFormattedUrl.substring(0,2) === "{=") {
sFormattedField = sFormattedUrl;
}
}
// if we have found a relevant binding-info-string this iteration then parse it to get binded properties
if (sFormattedField) {
aItemValue = getPropertiesFromBindingString(sFormattedField);
}
if (aItemValue && aItemValue.length > 0) {
// for each property found we check if has sap:unit and sap:text
var sItemValue;
for (var k = 0; k < aItemValue.length; k++) {
sItemValue = aItemValue[k];
// if this property is found for the first time - look for its unit and text properties as well
if (!aSelectFields[sItemValue]) {
aSelectFields[sItemValue] = true;
// checking if we need to add also the sap:unit property of the field's value
var sUnitPropName = getUnitColumn(sItemValue, oEntityType);
if (sUnitPropName && sUnitPropName !== sItemValue) {
aSelectFields[sUnitPropName] = true;
}
// checking if we need to add also the sap:text property of the field's value
var sTextPropName = getTextPropertyForEntityProperty(oMetaModel, oEntityType, sItemValue);
if (sTextPropName && sTextPropName !== sItemValue) {
aSelectFields[sTextPropName] = true;
}
}
}
}
}
}
// return all relevant property names
return Object.keys(aSelectFields);
}
function getPropertiesFromBindingString(sBinding) {
var regexBindingEvaluation = /\${([a-zA-Z0-9|\/]*)/g;
var regexBindingNoPath = /[^[{]*[a-zA-Z0-9]/g;
var regexBindingPath = /path *\: *\'([a-zA-Z0-9]+)*\'/g;
var regex, index, matches = [];
if (sBinding.substring(0, 2) === "{=") {
/*
meaning binding string looks like "{= <rest of the binding string>}"
which is a binding which needs to be evaluated using some supported function
properties appear as ${propertyName} inside the string
*/
regex = regexBindingEvaluation;
/* index is 1 as each match found by this regular expression (by invoking regex.exec(string) below) */
/* is an array of 2 items, for example ["${Address}", "Address"] so we need the 2nd result each match found */
index = 1;
} else if (sBinding.indexOf("path") !== -1) {
/* In a scenario where binding contains string like "{propertyName} {path:'propertyName'}" */
/* Here we get the properties without path and add it to array matches*/
var matchWithNoPath = regexBindingNoPath.exec(sBinding);
while (matchWithNoPath) {
if (matchWithNoPath[0].indexOf("path") === -1) {
matches.push(matchWithNoPath[0]);
}
matchWithNoPath = regexBindingNoPath.exec(sBinding);
}
/* meaning binding contains string like "{path:'propertyName'}" */
regex = regexBindingPath;
/* index is 1 as each match found by this regular expression (by invoking regex.exec(string) below) */
/* is an array of 2 items, for example ["{path: 'Address'}", "Address"] so we need the 2nd result each match found */
index = 1;
} else {
/* meaning binding contains string like "{'propertyName'}" */
regex = regexBindingNoPath;
/* index is 0 as each match found by this regular expression (by invoking regex.exec(string) below) */
/* is an array of one item, for example ["Address"] so we need the 1st result each match found */
index = 0;
}
var match = regex.exec(sBinding);
while (match) {
if (match[index]) {
matches.push(match[index]);
}
match = regex.exec(sBinding);
}
return matches;
}
/**
* return the sorters that need to be applyed on an aggregation
*
* @param ovpCardProperties - card properties model which might contains sort configurations
* @param oPresentationVariant - optional presentation variant annotation with SortOrder configuration
* @returns {Array} of model sorters
*/
function getSorters(ovpCardProperties, oPresentationVariant) {
var aSorters = [];
var oSorter, bDescending;
//get the configured sorter if exist and append them to the sorters array
var sPropertyPath = ovpCardProperties.getProperty("/sortBy");
if (sPropertyPath) {
// If sorting is enabled by card configuration
var sSortOrder = ovpCardProperties.getProperty('/sortOrder');
if (sSortOrder && sSortOrder.toLowerCase() !== 'descending') {
bDescending = false;
} else {
bDescending = true;
}
oSorter = {
path: sPropertyPath,
descending: bDescending
};
aSorters.push(oSorter);
}
//get the sorters from the presentation variant annotations if exists
var aSortOrder = oPresentationVariant && oPresentationVariant.SortOrder || undefined;
var oSortOrder, sPropertyPath;
if (aSortOrder) {
for (var i = 0; i < aSortOrder.length; i++) {
oSortOrder = aSortOrder[i];
sPropertyPath = oSortOrder.Property.PropertyPath;
bDescending = getBooleanValue(oSortOrder.Descending, true);
oSorter = {
path: sPropertyPath,
descending: bDescending
};
aSorters.push(oSorter);
}
}
return aSorters;
}
sap.ovp.cards.AnnotationHelper.getCardFilters = function (ovpCardProperties) {
var oEntityType = ovpCardProperties.getProperty('/entityType');
var oSelectionVariant = oEntityType[ovpCardProperties.getProperty('/selectionAnnotationPath')];
return getFilters(ovpCardProperties, oSelectionVariant);
};
/**
* return the filters that need to be applyed on an aggregation
*
* @param ovpCardProperties - card properties model which might contains filters configurations
* @param oSelectionVariant - optional selection variant annotation with SelectOptions configuration
* @returns {Array} of model filters
*/
function getFilters(ovpCardProperties, oSelectionVariant) {
var aFilters = [];
//get the configured filters if exist and append them to the filter array
var aConfigFilters = ovpCardProperties.getProperty("/filters");
if (aConfigFilters) {
aFilters = aFilters.concat(aConfigFilters);
}
//get the filters from the selection variant annotations if exists
var aSelectOptions = oSelectionVariant && oSelectionVariant.SelectOptions;
var oSelectOption, sPropertyPath, oRange;
if (aSelectOptions) {
for (var i = 0; i < aSelectOptions.length; i++) {
oSelectOption = aSelectOptions[i];
sPropertyPath = oSelectOption.PropertyName.PropertyPath;
//a select option might contains more then one filter in the Ranges array
for (var j = 0; j < oSelectOption.Ranges.length; j++) {
oRange = oSelectOption.Ranges[j];
if (oRange.Sign.EnumMember === "com.sap.vocabularies.UI.v1.SelectionRangeSignType/I") {
//create the filter. the Low value is mandatory
var oFilter = {
path: sPropertyPath,
operator: oRange.Option.EnumMember.split("/")[1],
value1: getPrimitiveValue(oRange.Low),
value2: getPrimitiveValue(oRange.High)
};
//append the filter to the filters array
aFilters.push(oFilter);
}
}
}
}
return aFilters;
}
function getBooleanValue(oValue, bDefault) {
if (oValue && oValue.Boolean) {
if (oValue.Boolean.toLowerCase() === "true") {
return true;
} else if (oValue.Boolean.toLowerCase() === "false") {
return false;
}
}
return bDefault;
}
function getNumberValue(oValue) {
var value;
if (oValue) {
if (oValue.String) {
value = Number(oValue.String);
} else if (oValue.Int) {
value = Number(oValue.Int);
} else if (oValue.Decimal) {
value = Number(oValue.Decimal);
} else if (oValue.Double) {
value = Number(oValue.Double);
} else if (oValue.Single) {
value = Number(oValue.Single);
}
}
return value;
}
function getPrimitiveValue(oValue) {
var value;
if (oValue) {
if (oValue.String) {
value = oValue.String;
} else if (oValue.Boolean) {
value = getBooleanValue(oValue);
} else {
value = getNumberValue(oValue);
}
}
return value;
}
//This object is responsive for devices
//the id build by Type-ListType-flavor
var ITEM_LENGTH = {
"List_condensed": {phone: 5, tablet: 5, desktop: 5},
"List_extended": {phone: 3, tablet: 3, desktop: 3},
"List_condensed_bar": {phone: 5, tablet: 5, desktop: 5},
"List_extended_bar": {phone: 3, tablet: 3, desktop: 3},
"Table": {phone: 5, tablet: 5, desktop: 5},
"Stack_simple": {phone: 20, tablet: 20, desktop: 20},
"Stack_complex": {phone: 5, tablet: 5, desktop: 5}
};
function getItemsLength(oOvpCardPropertiesModel) {
var type = oOvpCardPropertiesModel.getProperty('/contentFragment');
var listType = oOvpCardPropertiesModel.getProperty('/listType');
var flavor = oOvpCardPropertiesModel.getProperty('/listFlavor');
var oItemSizes;
var device = "desktop";
//get current device
if (sap.ui.Device.system.phone) {
device = "phone";
} else if (sap.ui.Device.system.tablet) {
device = "tablet";
}
//check the current card type and get the sizes objects
if (type == "sap.ovp.cards.list.List") {
if (listType == "extended") {
if (flavor == "bar") {
oItemSizes = ITEM_LENGTH["List_extended_bar"];
} else {
oItemSizes = ITEM_LENGTH["List_extended"];
}
} else if (flavor == "bar") {
oItemSizes = ITEM_LENGTH["List_condensed_bar"];
} else {
oItemSizes = ITEM_LENGTH["List_condensed"];
}
} else if (type == "sap.ovp.cards.table.Table") {
oItemSizes = ITEM_LENGTH["Table"];
} else if (type == "sap.ovp.cards.stack.Stack") {
if (oOvpCardPropertiesModel.getProperty('/objectStreamCardsNavigationProperty')) {
oItemSizes = ITEM_LENGTH["Stack_complex"];
} else {
oItemSizes = ITEM_LENGTH["Stack_simple"];
}
}
if (oItemSizes) {
return oItemSizes[device];
}
return 5;
}
sap.ovp.cards.AnnotationHelper.formatUrl = function (iContext, sUrl) {
if (sUrl.charAt(0) === '/' || sUrl.indexOf("http") === 0) {
return sUrl;
}
var sBaseUrl = iContext.getModel().getProperty("/baseUrl");
if (sBaseUrl) {
return sBaseUrl + "/" + sUrl;
}
return sUrl;
};
sap.ovp.cards.AnnotationHelper.getDataPointsCount = function (iContext, aCollection) {
var aDataPoints = getSortedDataPoints(iContext, aCollection);
return aDataPoints.length;
};
sap.ovp.cards.AnnotationHelper.getFirstDataPointValue = function (iContext, aCollection) {
return sap.ovp.cards.AnnotationHelper.getDataPointValue(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.getSecondDataPointValue = function (iContext, aCollection) {
return sap.ovp.cards.AnnotationHelper.getDataPointValue(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.getDataPointValue = function (iContext, aCollection, index) {
var aDataPoints = getSortedDataPoints(iContext, aCollection),
oDataPoint = aDataPoints[index];
if (oDataPoint && oDataPoint.Value && oDataPoint.Value.Path) {
return oDataPoint.Value.Path;
}
return "";
};
sap.ovp.cards.AnnotationHelper.getFirstDataFieldName = function (iContext, aCollection) {
return getDataFieldName(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.getSecondDataFieldName = function (iContext, aCollection) {
return getDataFieldName(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.getThirdDataFieldName = function (iContext, aCollection) {
return getDataFieldName(iContext, aCollection, 2);
};
sap.ovp.cards.AnnotationHelper.formatFirstDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.formatSecondDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.formatThirdDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 2);
};
sap.ovp.cards.AnnotationHelper.formatFourthDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 3);
};
sap.ovp.cards.AnnotationHelper.formatFifthDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 4);
};
sap.ovp.cards.AnnotationHelper.formatSixthDataFieldValue = function (iContext, aCollection) {
return formatDataField(iContext, aCollection, 5);
};
sap.ovp.cards.AnnotationHelper.getFirstDataPointName = function (iContext, aCollection) {
return getDataPointName(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.getSecondDataPointName = function (iContext, aCollection) {
return getDataPointName(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.getThirdDataPointName = function (iContext, aCollection) {
return getDataPointName(iContext, aCollection, 2);
};
sap.ovp.cards.AnnotationHelper.formatFirstDataPointValue = function (iContext, aCollection) {
return formatDataPoint(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.formatSecondDataPointValue = function (iContext, aCollection) {
return formatDataPoint(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.formatThirdDataPointValue = function (iContext, aCollection) {
return formatDataPoint(iContext, aCollection, 2);
};
sap.ovp.cards.AnnotationHelper.formatFirstDataPointState = function (iContext, aCollection) {
return formatDataPointState(iContext, aCollection, 0);
};
sap.ovp.cards.AnnotationHelper.formatSecondDataPointState = function (iContext, aCollection) {
return formatDataPointState(iContext, aCollection, 1);
};
sap.ovp.cards.AnnotationHelper.formatThirdDataPointState = function (iContext, aCollection) {
return formatDataPointState(iContext, aCollection, 2);
};
sap.ovp.cards.AnnotationHelper.formatKPIHeaderState = function (iContext, oDataPoint) {
return formatDataPointToValue(iContext, oDataPoint, sap.ovp.cards.AnnotationHelper.criticalityConstants.ColorValues);
};
/*
* @param iContext
* @returns 0 for false - there are no actions for this context
* 1 for true - there are actions for this context
* does not return actual boolean - so we won't need to parse the result in the xml
*/
sap.ovp.cards.AnnotationHelper.hasActions = function (iContext, aCollection) {
var oItem;
for (var i = 0; i < aCollection.length; i++){
oItem = aCollection[i];
if (oItem.RecordType === "com.sap.vocabularies.UI.v1.DataFieldForIntentBasedNavigation" ||
oItem.RecordType === "com.sap.vocabularies.UI.v1.DataFieldForAction" ||
oItem.RecordType === "com.sap.vocabularies.UI.v1.DataFieldWithUrl"){
return 1;
}
}
return 0;
};
sap.ovp.cards.AnnotationHelper.isFirstDataPointPercentageUnit = function (iContext, aCollection) {
var oDataPoint = getSortedDataPoints(iContext, aCollection)[0];
if (oDataPoint && oDataPoint.Value && oDataPoint.Value.Path) {
var sEntityTypePath = iContext.getPath().substr(0, iContext.getPath().lastIndexOf("/") + 1);
var oModel = iContext.getModel();
var oEntityType = oModel.getProperty(sEntityTypePath);
var oProperty = oModel.getODataProperty(oEntityType, oDataPoint.Value.Path);
if (oProperty && oProperty["Org.OData.Measures.V1.Unit"]) {
return oProperty["Org.OData.Measures.V1.Unit"].String === "%";
}
}
return false;
};
sap.ovp.cards.AnnotationHelper.resolveEntityTypePath = function (oAnnotationPathContext) {
var sAnnotationPath = oAnnotationPathContext.getObject();
var oModel = oAnnotationPathContext.getModel();
var oMetaModel = oModel.getProperty("/metaModel");
var oEntitySet = oMetaModel.getODataEntitySet(oModel.getProperty("/entitySet"));
var oEntityType = oMetaModel.getODataEntityType(oEntitySet.entityType);
sAnnotationPath = oEntityType.$path + "/" + sAnnotationPath;
return oMetaModel.createBindingContext(sAnnotationPath);
};
sap.ovp.cards.AnnotationHelper.resolveParameterizedEntitySet = function (oDataModel, oEntitySet, oSelectionVariant) {
jQuery.sap.require("sap.ui.model.analytics.odata4analytics");
var path = "";
var o4a = new sap.ui.model.analytics.odata4analytics.Model(sap.ui.model.analytics.odata4analytics.Model.ReferenceByModel(oDataModel));
var queryResult = o4a.findQueryResultByName(oEntitySet.name);
var queryResultRequest = new sap.ui.model.analytics.odata4analytics.QueryResultRequest(queryResult);
var parameterization = queryResult.getParameterization();
if (parameterization) {
queryResultRequest.setParameterizationRequest(new sap.ui.model.analytics.odata4analytics.ParameterizationRequest(parameterization));
jQuery.each(oSelectionVariant.Parameters, function () {
if (this.RecordType === "com.sap.vocabularies.UI.v1.IntervalParameter") {
queryResultRequest.getParameterizationRequest().setParameterValue(
this.PropertyName.PropertyPath,
this.PropertyValueFrom.String,
this.PropertyValueTo.String
);
} else {
queryResultRequest.getParameterizationRequest().setParameterValue(
this.PropertyName.PropertyPath,
this.PropertyValue.String
);
}
});
}
try {
path = queryResultRequest.getURIToQueryResultEntitySet();
} catch (exception) {
queryResult = queryResultRequest.getQueryResult();
path = "/" + queryResult.getEntitySet().getQName();
jQuery.sap.log.error("getEntitySetPathWithParameters", "binding path with parameters failed - " + exception
|| exception.message);
}
return path;
};
sap.ovp.cards.AnnotationHelper.getAssociationObject = function (oModel, sAssociation, ns) {
// find a nicer way of getting association set entry in meta model
var aAssociations = oModel.getServiceMetadata().dataServices.schema[0].association;
for (var i = 0; i < aAssociations.length; i++) {
if (ns + "." + aAssociations[i].name === sAssociation) {
return aAssociations[i];
}
}
};
/**************************** Formatters & Helpers for KPI-Header logic ****************************/
/* Returns binding path for singleton */
sap.ovp.cards.AnnotationHelper.getAggregateNumber = function (iContext, oEntitySet, oDataPoint, oSelectionVariant) {
var measure = oDataPoint.Value.Path;
var ret = "";
var bParams = oSelectionVariant && oSelectionVariant.Parameters;
var filtersString = "";
if (bParams) {
var dataModel = iContext.getSetting("dataModel");
var path = sap.ovp.cards.AnnotationHelper.resolveParameterizedEntitySet(dataModel, oEntitySet, oSelectionVariant);
ret += "{path: '" + path + "'";
} else {
ret += "{path: '/" + oEntitySet.name + "'";
}
ret += ", length: 1";
var oOvpCardSettings = iContext.getSetting('ovpCardProperties');
var oEntityType = oOvpCardSettings.getProperty("/entityType");
var unitColumn = getUnitColumn(measure, oEntityType);
var aFilters = getFilters(oOvpCardSettings, oSelectionVariant);
if (aFilters.length > 0) {
filtersString += ", filters: " + JSON.stringify(aFilters);
}
var selectArr = [];
selectArr.push(measure);
if (unitColumn) {
selectArr.push(unitColumn);
}
if (oDataPoint.TrendCalculation && oDataPoint.TrendCalculation.ReferenceValue && oDataPoint.TrendCalculation.ReferenceValue.Path) {
selectArr.push(oDataPoint.TrendCalculation.ReferenceValue.Path);
}
return ret + ", parameters:{select:'" + selectArr.join(",") + "'}" + filtersString + "}";
};
/* Creates binding path for NumericContent value */
sap.ovp.cards.AnnotationHelper.formThePathForAggregateNumber = function (iContext, dataPoint) {
if (!dataPoint || !dataPoint.Value || !dataPoint.Value.Path) {
return "";
}
return formatField(iContext, dataPoint, true, false);
};
/* Creates binding path for trend icon */
sap.ovp.cards.AnnotationHelper.formThePathForTrendIcon = function (dataPoint) {
if (!dataPoint || !dataPoint.Value || !dataPoint.Value.Path || !dataPoint.TrendCalculation) {
return "";
}
if (dataPoint.TrendCalculation &&
dataPoint.TrendCalculation.ReferenceValue &&
dataPoint.TrendCalculation.ReferenceValue.Path) {
return "{parts: [{path:'" + dataPoint.Value.Path + "'}, {path:'" + dataPoint.TrendCalculation.ReferenceValue.Path + "'}], formatter: 'sap.ovp.cards.AnnotationHelper.returnTrendDirection'}";
} else {
return "{parts: [{path:'" + dataPoint.Value.Path + "'}], formatter: 'sap.ovp.cards.AnnotationHelper.returnTrendDirection'}";
}
};
/* Formatter for Trend Direction for Header */
sap.ovp.cards.AnnotationHelper.returnTrendDirection = function (aggregateValue, referenceValue) {
aggregateValue = Number(aggregateValue);
var ovpModel = this.getModel("ovpCardProperties");
if (!ovpModel) {
return;
}
var fullQualifier = ovpModel.getProperty("/dataPointAnnotationPath");
var dataPoint = ovpModel.getProperty("/entityType")[fullQualifier];
var finalReferenceValue, upDifference, downDifference;
if (dataPoint.TrendCalculation.ReferenceValue) {
if (dataPoint.TrendCalculation.ReferenceValue.Path) {
finalReferenceValue = Number(referenceValue);
} else {
finalReferenceValue = getNumberValue(dataPoint.TrendCalculation.ReferenceValue);
}
}
if (dataPoint.TrendCalculation.UpDifference) {
upDifference = getNumberValue(dataPoint.TrendCalculation.UpDifference);
}
if (dataPoint.TrendCalculation.DownDifference) {
downDifference = getNumberValue(dataPoint.TrendCalculation.DownDifference);
}
if (!dataPoint.TrendCalculation.UpDifference && (aggregateValue - finalReferenceValue >= 0)) {
return "Up";
}
if (!dataPoint.TrendCalculation.DownDifference && (aggregateValue - finalReferenceValue <= 0)) {
return "Down";
}
if (finalReferenceValue && upDifference && (aggregateValue - finalReferenceValue >= upDifference)) {
return "Up";
}
if (finalReferenceValue && downDifference && (aggregateValue - finalReferenceValue <= downDifference)) {
return "Down";
}
};
/* Creates binding path for UOM placeholder */
sap.ovp.cards.AnnotationHelper.formThePathForUOM = function (iContext, dataPoint) {
if (!dataPoint || !dataPoint.Value || !dataPoint.Value.Path) {
return "";
}
return formatField(iContext, dataPoint, false, true);
};
/* Creates binding path for % change */
sap.ovp.cards.AnnotationHelper.formPathForPercentageChange = function (dataPoint) {
if (!dataPoint || !dataPoint.TrendCalculation || !dataPoint.TrendCalculation.ReferenceValue) {
return "";
}
if (dataPoint.TrendCalculation.ReferenceValue.Path) {
return "{parts: [{path:'" + dataPoint.Value.Path + "'}, {path:'" + dataPoint.TrendCalculation.ReferenceValue.Path + "'}], formatter: 'sap.ovp.cards.AnnotationHelper.returnPercentageChange'}";
} else {
return "{parts: [{path:'" + dataPoint.Value.Path + "'}], formatter: 'sap.ovp.cards.AnnotationHelper.returnPercentageChange'}";
}
};
/* Formatter for % change for Header */
sap.ovp.cards.AnnotationHelper.returnPercentageChange = function (aggregateValue, referenceValuePath) {
jQuery.sap.require("sap.ui.core.format.NumberFormat");
var ret = "";
aggregateValue = Number(aggregateValue);
var ovpModel = this.getModel("ovpCardProperties");
if (!ovpModel) {
return ret;
}
var fullQualifier = ovpModel.getProperty("/dataPointAnnotationPath");
var dataPoint = ovpModel.getProperty("/entityType")[fullQualifier];
var referenceValue;
if (!dataPoint.TrendCalculation) {
return ret;
}
if (dataPoint.TrendCalculation.ReferenceValue) {
if (dataPoint.TrendCalculation.ReferenceValue.String) {
referenceValue = Number(dataPoint.TrendCalculation.ReferenceValue.String);
}
if (dataPoint.TrendCalculation.ReferenceValue.Path) {
referenceValue = Number(referenceValuePath);
}
if (!referenceValue || referenceValue == 0) {
return ret;
}
var percentNumber = ((Number(aggregateValue) - referenceValue) / referenceValue);
var percentFormatter = sap.ui.core.format.NumberFormat.getPercentInstance({
style: 'short',
minFractionDigits: 2,
maxFractionDigits: 2
});
return percentFormatter.format(percentNumber);
}
};
/*
* Reads groupBy from annotation and prepares comma separated list
*/
sap.ovp.cards.AnnotationHelper.listGroupBy = function (oPresentationVariant) {
var result = "";
var bPV = oPresentationVariant && oPresentationVariant.GroupBy;
if (!bPV) {
return result;
}
var metaModel = this.getModel('ovpCardProperties').getProperty("/metaModel");
var oEntityType = this.getModel('ovpCardProperties').getProperty("/entityType");
var groupByList;
if (oPresentationVariant.GroupBy.constructor === Array) {
groupByList = oPresentationVariant.GroupBy;
} else if (!oPresentationVariant.GroupBy.Collection) {
return result;
} else {
groupByList = oPresentationVariant.GroupBy.Collection;
}
var propVal;
jQuery.each(groupByList, function () {
propVal = getLabelForEntityProperty(metaModel, oEntityType, this.PropertyPath);
if (!propVal) {
return;
}
result += propVal;
result += ", ";
});
if (result[result.length - 1] === " " && result[result.length - 2] === ",") {
result = result.substring(0, result.length - 2);
}
return result == "" ? "" : sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("By", [result]);
};
/*
* returns the string for the filter-by values of the KPI Header
* */
sap.ovp.cards.AnnotationHelper.formTheFilterByString = function(iContext, oSelectionVariant) {
var oCardPropsModel = iContext.getSetting('ovpCardProperties');
var oEntityType = oCardPropsModel.getProperty("/entityType");
var oMetaModel = oCardPropsModel.getProperty("/metaModel");
var aFilters = getFilters(oCardPropsModel, oSelectionVariant);
var sProp;
var sTextPropKey;
//Clean from Filter array all the filters with sap-text that the filter array contains there sap-text
for (var i = 0; i < aFilters.length; i++ ) {
sProp = aFilters[i].path;
sTextPropKey = getTextPropertyForEntityProperty(oMetaModel, oEntityType, sProp);
//Check if there is sap-text, in case there is checks that the Filter array contains it
if (sTextPropKey !== sProp) {
for (var j = 0; j < aFilters.length; j++ ) {
// if there is sap test - we won't show the original filter (instead we will show the sap-text) and we clean it from the array
if ((aFilters[j].path == sTextPropKey)){
aFilters.splice(i, 1);
break;
}
}
}
}
// build the filter string
return generateStringForFilters(aFilters);
};
/************************ METADATA PARSERS ************************/
function generateStringForFilters(aFilters) {
var aFormatterFilters = [];
for (var i = 0; i < aFilters.length; i++ ) {
aFormatterFilters.push(generateSingleFilter(aFilters[i]));
}
return aFormatterFilters.join(', ');
}
function generateSingleFilter(oFilter) {
var bNotOperator = false;
var sFormattedFilter = oFilter.value1;
if (oFilter.operator[0] === "N") {
bNotOperator = true;
}
if (oFilter.value2) {
sFormattedFilter += " - " + oFilter.value2;
}
if (bNotOperator) {
sFormattedFilter = sap.ui.getCore().getLibraryResourceBundle("sap.ovp").getText("kpiHeader_Filter_NotOperator", [sFormattedFilter]);
}
return sFormattedFilter;
}
/* Returns column name that contains the unit for the measure */
function getUnitColumn (measure, oEntityType) {
var properties = oEntityType.property;
for (var i = 0, len = properties.length; i < len; i++) {
if (properties[i].name == measure) {
if (properties[i].hasOwnProperty("sap:unit")) {
return properties[i]["sap:unit"];
}
break;
}
}
return null;
}
function getLabelForEntityProperty(oMetadata, oEntityType, sPropertyName) {
return getAttributeValueForEntityProperty(oMetadata, oEntityType,
sPropertyName, "com.sap.vocabularies.Common.v1.Label");
}
function getTextPropertyForEntityProperty(oMetamodel, oEntityType, sPropertyName) {
return getAttributeValueForEntityProperty(oMetamodel, oEntityType,
sPropertyName, "sap:text");
}
function getAttributeValueForEntityProperty(oMetamodel, oEntityType, sPropertyName, sAttributeName) {
var oProp = oMetamodel.getODataProperty(oEntityType, sPropertyName);
if (!oProp) {
jQuery.sap.log.error("No Property Found for with Name '" + sPropertyName
+ " For Entity-Type '" + oEntityType.name + "'");
return;
}
var oPropAttVal = oProp[sAttributeName];
if (oPropAttVal) {
if (sAttributeName === "com.sap.vocabularies.Common.v1.Label") {
return oPropAttVal.String;
}
return oPropAttVal;
}
return oProp.name;
}
sap.ovp.cards.AnnotationHelper._criticality2state = criticality2state;
sap.ovp.cards.AnnotationHelper._generateCriticalityCalculationStateFunction = generateCriticalityCalculationStateFunction;
sap.ovp.cards.AnnotationHelper._getPropertiesFromBindingString = getPropertiesFromBindingString;
sap.ovp.cards.AnnotationHelper.sortCollectionByImportance = sortCollectionByImportance;
sap.ovp.cards.AnnotationHelper.formatField.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formThePathForAggregateNumber.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formThePathForUOM.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formTheFilterByString.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getAggregateNumber.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getFirstDataFieldName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getSecondDataFieldName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getThirdDataFieldName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatFirstDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatSecondDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatThirdDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatFourthDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatFifthDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatSixthDataFieldValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getDataPointsCount.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getFirstDataPointName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getSecondDataPointName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getThirdDataPointName.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatFirstDataPointValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatSecondDataPointValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatThirdDataPointValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatFirstDataPointState.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatSecondDataPointState.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatThirdDataPointState.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatKPIHeaderState.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatItems.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.formatUrl.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.hasActions.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getFirstDataPointValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.getSecondDataPointValue.requiresIContext = true;
sap.ovp.cards.AnnotationHelper.isFirstDataPointPercentageUnit.requiresIContext = true;
}());
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.ui.comp.smartform.flexibility.FieldListNode.
sap.ui.define(['jquery.sap.global', 'sap/m/CheckBox', 'sap/m/FlexBox', 'sap/ui/comp/library', './Input', 'sap/ui/core/Control', 'sap/m/Button'],
function(jQuery, CheckBox, FlexBox, library, Input, Control, Button) {
"use strict";
/**
* Constructor for a new smartform/flexibility/FieldListNode.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* A node within the field list control
* @extends sap.ui.core.Control
*
* @constructor
* @public
* @alias sap.ui.comp.smartform.flexibility.FieldListNode
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var FieldListNode = Control.extend("sap.ui.comp.smartform.flexibility.FieldListNode", /** @lends sap.ui.comp.smartform.flexibility.FieldListNode.prototype */ { metadata : {
library : "sap.ui.comp",
properties : {
/**
* The label
*/
label : {type : "string", group : "Misc", defaultValue : null},
/**
* is visible flag
*/
isVisible : {type : "boolean", group : "Misc", defaultValue : null},
/**
* is node selected
*/
isSelected : {type : "boolean", group : "Misc", defaultValue : null}
},
aggregations : {
/**
* Nodes representing either a Form, a Group or a field
*/
nodes : {type : "sap.ui.comp.smartform.flexibility.FieldListNode", multiple : true, singularName : "node"},
/**
* private aggregation
*/
layout : {type : "sap.ui.core.Control", multiple : false}
},
events : {
/**
* node was selected
*/
selected : {
parameters : {
/**
* The inner node which was clicked
*/
target : {type : "sap.ui.comp.smartform.flexibility.FieldListNode"}
}
},
/**
* label of node was changed
*/
labelChanged : {
parameters : {
/**
* The inner node which was clicked
*/
target : {type : "sap.ui.comp.smartform.flexibility.FieldListNode"}
}
},
/**
* node was hidden
*/
nodeHidden : {
parameters : {
/**
* The inner node which was hidden
*/
target : {type : "sap.ui.comp.smartform.flexibility.FieldListNode"}
}
}
}
}});
/**
* Init
*
* @private
*/
FieldListNode.prototype.init = function() {
this._textResources = sap.ui.getCore().getLibraryResourceBundle("sap.ui.comp");
this._oLayout = new FlexBox({
direction : sap.m.FlexDirection.Row,
justifyContent: sap.m.FlexJustifyContent.SpaceBetween
});
// inputField
this._oLabelInputField = new Input(this.getId() + '-Input');
this._oLabelInputField.addStyleClass("sapUiCompFieldListNodeLabelInputField");
this._oLabelInputField.setValue(this.getLabel());
this._oLabelInputField.setEditable(false);
this._oLabelInputField.attachChange(this._onLabelChanged.bind(this));
this._oLabelInputField.attachSelectedByKeyboard(this._onLabelSelectedByKeyboard.bind(this));
this._oLabelInputField.setLayoutData(new sap.m.FlexItemData({
}));
this._oLayout.addItem(this._oLabelInputField);
// delete button
this._oDeleteButton = new Button(this.getId() + '_Button');
this._oDeleteButton.setType("Transparent");
this._oDeleteButton.setIcon("sap-icon://decline");
this._oDeleteButton.setIconDensityAware(false);
this._oDeleteButton.setTooltip(this._textResources.getText("FORM_PERS_VIS_CHECKBOX_TOOLTIP"));
this._oDeleteButton.attachPress(this._hideNode.bind(this));
this._oDeleteButton.setLayoutData(new sap.m.FlexItemData({
}));
this._oLayout.addItem(this._oDeleteButton);
this.setLayout(this._oLayout);
};
/**
* Overwritten - Sets the label property
*
* @param {string} sLabel Label
* @public
*/
FieldListNode.prototype.setLabel = function(sLabel) {
this._oLabelInputField.setValue(sLabel);
this.setProperty("label", sLabel);
};
/**
* Overwritten - Sets the isVisible property
*
* @param {boolean} bIsVisible isVisible
* @public
*/
FieldListNode.prototype.setIsVisible = function(bIsVisible) {
if (this.getModel()) {
this.getModel().setData(this.getModel().getData());
}
this.setProperty("isVisible", bIsVisible);
this.setVisible(bIsVisible);
};
/**
* Overwritten - Sets the isSelected property
*
* @param {boolean} bIsSelected field list node selected
* @public
*/
FieldListNode.prototype.setIsSelected = function(bIsSelected) {
if (!bIsSelected) {
this._oLabelInputField.setEditable(false);
}
this.setProperty("isSelected", bIsSelected);
};
/**
* Event handler - called when the user press the hide button
*
* @param {object} oEvent Event
* @private
*/
FieldListNode.prototype._hideNode = function(oEvent) {
this.setIsVisible(false);
this._fireNodeHiddenAndDelegateToParent(this);
};
/**
* Event handler - called when the user changes the label
*
* @param {object} oEvent Event
* @public
*/
FieldListNode.prototype._onLabelChanged = function(oEvent) {
var sLabel;
sLabel = this._oLabelInputField.getValue();
if (sLabel !== this.getLabel()) {
this.setProperty("label", sLabel);
}
this._oLabelInputField.setEditable(false);
this._fireLabelChangedAndDelegateToParent(this);
};
/**
* Event handler - called when the user has selected the label using the keyboard
*
* @param {object} oEvent Event
* @public
*/
FieldListNode.prototype._onLabelSelectedByKeyboard = function(oEvent) {
this._oLabelInputField.setEditable(true);
this._fireSelectedAndDelegateToParent(this);
};
/**
* Overwritten - Registers to DOM events after rendering
*
* @private
*/
FieldListNode.prototype.onAfterRendering = function() {
this.registerToDOMEvents();
};
/**
* Overwritten - Registers to DOM events before rendering
*
* @private
*/
FieldListNode.prototype.onBeforeRendering = function() {
this.deregisterToDOMEvents();
};
/**
* @private Registers to DOM events like mouse events
*/
FieldListNode.prototype.registerToDOMEvents = function() {
jQuery("#" + this.getId()).on('click', jQuery.proxy(this._handleClick, this));
};
/**
* @private Deregisters from DOM events
*/
FieldListNode.prototype.deregisterToDOMEvents = function() {
jQuery("#" + this.getId()).off('click');
};
/**
* @private Event handler, called when the user clicks somewhere into the form. Raises the Selected event.
* @param {object} oEvent event
*/
FieldListNode.prototype._handleClick = function(oEvent) {
var target, oSourceNode;
target = oEvent.target || oEvent.srcElement;
if (target) {
oSourceNode = sap.ui.getCore().byId(target.id); // Get SAPUI5 control by DOM reference
if (!(oSourceNode instanceof FieldListNode)) {
if (target.parentElement) {
oSourceNode = sap.ui.getCore().byId(target.parentElement.id); // Get SAPUI5 control by DOM reference
}
}
}
// If node is already selected and label is clicked, make label editable
if ((oSourceNode === this._oLabelInputField) && this.getIsSelected()) {
this._oLabelInputField.setEditable(true);
}
// Fire event only if a field list node was clicked
if (oSourceNode === this || oSourceNode === this._oLabelInputField) {
this._fireSelectedAndDelegateToParent(this);
}
};
/**
* @private Fires the is selected event for itself and for the parent field list node
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oFieldListNode field list node instance
*/
FieldListNode.prototype._fireSelectedAndDelegateToParent = createFireEventAndDelegateToParent('fireSelected', '_fireSelectedAndDelegateToParent');
/**
* @private Fires the is labelChanged event for itself and for the parent field list node
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oFieldListNode field list node instance
*/
FieldListNode.prototype._fireLabelChangedAndDelegateToParent = createFireEventAndDelegateToParent('fireLabelChanged', '_fireLabelChangedAndDelegateToParent');
/**
* @private Fires the is NodeHidden event for itself and for the parent field list node
* @param {sap.ui.comp.smartform.flexibility.FieldListNode} oFieldListNode field list node instance
*/
FieldListNode.prototype._fireNodeHiddenAndDelegateToParent = createFireEventAndDelegateToParent('fireNodeHidden', '_fireNodeHiddenAndDelegateToParent');
function createFireEventAndDelegateToParent(sFunctionNameToFireEvent, sFunctionNameOnParent){
return function(oFieldListNode){
var oParent;
if (!(oFieldListNode instanceof FieldListNode)) {
return;
}
this[sFunctionNameToFireEvent]({
target: oFieldListNode
});
// Call parent to fire event, too
oParent = this.getParent();
if (oParent && oParent instanceof FieldListNode) {
oParent[sFunctionNameOnParent](oFieldListNode);
}
};
}
return FieldListNode;
}, /* bExport= */ true);
<file_sep>/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
/* global Promise */
sap.ui.define([
"jquery.sap.global", "sap/ui/fl/Persistence", "sap/ui/fl/registry/ChangeRegistry", "sap/ui/fl/Utils", "sap/ui/fl/Change", "sap/ui/fl/registry/Settings", "sap/ui/fl/ChangePersistenceFactory", "sap/ui/core/mvc/View"
], function(jQuery, Persistence, ChangeRegistry, Utils, Change, FlexSettings, ChangePersistenceFactory, View) {
"use strict";
/**
* Retrieves changes (LabelChange, etc.) for a sap.ui.core.mvc.View and applies these changes
*
* @params {string} sComponentName -the component name the flex controler is responsible for
* @constructor
* @class
* @alias sap.ui.fl.FlexController
* @experimental Since 1.27.0
* @author SAP SE
* @version 1.36.12
*/
var FlexController = function(sComponentName) {
this._oChangePersistence = undefined;
this._sComponentName = sComponentName || "";
if (this._sComponentName) {
this._createChangePersistence();
}
};
/**
* Sets the component name of the FlexController
*
* @param {String} sComponentName The name of the component
* @public
*/
FlexController.prototype.setComponentName = function(sComponentName) {
this._sComponentName = sComponentName;
this._createChangePersistence();
};
/**
* Returns the component name of the FlexController
*
* @returns {String} the name of the component
* @public
*/
FlexController.prototype.getComponentName = function() {
return this._sComponentName;
};
/**
* Create a change
*
* @param {object} oChangeSpecificData property bag (nvp) holding the change information (see sap.ui.fl.Change#createInitialFileContent
* oPropertyBag). The property "packageName" is set to $TMP and internally since flex changes are always local when they are created.
* @param {sap.ui.core.Control} oControl control for which the change will be added
* @returns {sap.ui.fl.Change} the created change
* @public
*/
FlexController.prototype.createChange = function(oChangeSpecificData, oControl) {
var oChangeFileContent, oChange, ChangeHandler, oChangeHandler;
var oAppDescr = Utils.getAppDescriptor(oControl);
var sComponentName = this.getComponentName();
oChangeSpecificData.reference = sComponentName; //in this case the component name can also be the value of sap-app-id
if ( oAppDescr && oAppDescr["sap.app"] ){
oChangeSpecificData.componentName = oAppDescr["sap.app"].componentName || oAppDescr["sap.app"].id;
}else {
//fallback in case no appdescriptor is available (e.g. during unit testing)
oChangeSpecificData.componentName = sComponentName;
}
oChangeSpecificData.packageName = '$TMP'; // first a flex change is always local, until all changes of a component are made transportable
oChangeFileContent = Change.createInitialFileContent(oChangeSpecificData);
oChange = new Change(oChangeFileContent);
// for getting the change handler the control type and the change type are needed
ChangeHandler = this._getChangeHandler(oChange, oControl);
if (ChangeHandler) {
oChangeHandler = new ChangeHandler();
oChangeHandler.completeChangeContent(oChange, oChangeSpecificData);
} else {
throw new Error('Change handler could not be retrieved for change ' + JSON.stringify(oChangeSpecificData));
}
// first a flex change is always local, until all changes of a component are made transportable
// if ( oChangeSpecificData.transport ){
// oChange.setRequest(oChangeSpecificData.transport);
// }
return oChange;
};
/**
* Adds a change to the flex persistence (not yet saved). Will be saved with #saveAll.
*
* @param {object} oChangeSpecificData property bag (nvp) holding the change information (see sap.ui.fl.Change#createInitialFileContent
* oPropertyBag). The property "packageName" is set to $TMP and internally since flex changes are always local when they are created.
* @param {sap.ui.core.Control} oControl control for which the change will be added
* @returns {sap.ui.fl.Change} the created change
* @public
*/
FlexController.prototype.addChange = function(oChangeSpecificData, oControl) {
var oChange = this.createChange(oChangeSpecificData, oControl);
this._oChangePersistence.addChange(oChange);
return oChange;
};
/**
* Creates a new change and applies it immediately
*
* @param {object} oChangeSpecificData The data specific to the change, e.g. the new label for a RenameField change
* @param {sap.ui.core.Control} oControl The control where the change will be applied to
* @public
*/
FlexController.prototype.createAndApplyChange = function(oChangeSpecificData, oControl) {
var oChange = this.addChange(oChangeSpecificData, oControl);
try {
this.applyChange(oChange, oControl);
} catch (ex) {
this._oChangePersistence.deleteChange(oChange);
throw ex;
}
};
/**
* Saves all changes of a persistence instance.
*
* @returns {Promise} resolving with an array of responses or rejecting with the first error
* @public
*/
FlexController.prototype.saveAll = function() {
return this._oChangePersistence.saveDirtyChanges();
};
/**
* Loads and applies all changes for the specified view
*
* @params {object} oView - the view to process
* @returns {Promise} without parameters. Promise resolves once all changes of the view have been applied
* @public
*/
FlexController.prototype.processView = function(oView) {
var that = this;
var mPropertyBag = {
appDescriptor: Utils.getAppDescriptor(oView),
siteId: Utils.getSiteId(oView)
};
var bIsFlexEnabled = this._isFlexEnabled(oView);
if (!bIsFlexEnabled) {
return Promise.resolve("No control found, which enable flexibility features. Processing skipped.");
}
// do an async fetch of the flex settings
// to work with that settings during the session
return FlexSettings.getInstance(this.getComponentName(), mPropertyBag).then(function(oSettings) {
return that._getChangesForView(oView, mPropertyBag);
}).then(that._resolveGetChangesForView.bind(that))['catch'](function(error) {
Utils.log.error('Error processing view ' + error);
});
};
FlexController.prototype._resolveGetChangesForView = function(aChanges) {
var that = this;
var fChangeHandler, oChangeHandler;
aChanges.forEach(function(oChange) {
var oControl = that._getControlByChange(oChange);
if (oControl) {
fChangeHandler = that._getChangeHandler(oChange, oControl);
if (fChangeHandler) {
oChangeHandler = new fChangeHandler();
} else {
Utils.log.error("A change handler of type '" + oChange.getDefinition().changeType + "' does not exist");
}
if (oChangeHandler && oChangeHandler.getControlIdFromChangeContent) {
// check to avoid duplicate IDs
var sControlId = oChangeHandler.getControlIdFromChangeContent(oChange);
var bIsControlAlreadyInDOM = !!sap.ui.getCore().byId(sControlId);
if (!bIsControlAlreadyInDOM) {
that.applyChangeAndCatchExceptions(oChange, oControl);
} else {
var sId = oChange.getSelector().id;
Utils.log.error("A change of type '" + oChange.getDefinition().changeType + "' tries to add a object with an already existing ID ('" + sId + "')");
}
} else {
that.applyChangeAndCatchExceptions(oChange, oControl);
}
} else {
var oDefinition = oChange.getDefinition();
var sChangeType = oDefinition.changeType;
var sTargetControlId = oDefinition.selector.id;
var fullQualifiedName = oDefinition.namespace + "/" + oDefinition.fileName + "." + oDefinition.fileType;
Utils.log.error("A flexibility change tries to change a non existing control.",
"\n type of change: '" + sChangeType + "'" +
"\n LRep location of the change: " + fullQualifiedName +
"\n id of targeted control: '" + sTargetControlId + "'");
}
});
};
/**
* Triggers applyChange and catches exceptions, if some were thrown (logs changes that could not be applied)
*
* @param {sap.ui.fl.Change} oChange Change instance
* @param {sap.ui.core.Control} oControl Control instance
* @public
*/
FlexController.prototype.applyChangeAndCatchExceptions = function(oChange, oControl) {
var oChangeDefinition = oChange.getDefinition();
var sChangeNameSpace = oChangeDefinition.namespace;
try {
this.applyChange(oChange, oControl);
} catch (ex) {
Utils.log.error("Change could not be applied: [" + oChangeDefinition.layer + "]" + sChangeNameSpace + "/" + oChangeDefinition.fileName + "." + oChangeDefinition.fileType + ": " + ex);
}
};
/**
* Retrieves the corresponding change handler for the change and applies the change to the control
*
* @param {sap.ui.fl.Change} oChange Change instance
* @param {sap.ui.core.Control} oControl Control instance
* @public
*/
FlexController.prototype.applyChange = function(oChange, oControl) {
var ChangeHandler, oChangeHandler;
ChangeHandler = this._getChangeHandler(oChange, oControl);
if (!ChangeHandler) {
if (oChange && oControl) {
Utils.log.warning("Change handler implementation for change not found - Change ignored");
}
return;
}
try {
oChangeHandler = new ChangeHandler();
if (oChangeHandler && typeof oChangeHandler.applyChange === 'function') {
oChangeHandler.applyChange(oChange, oControl);
}
} catch (ex) {
this._setMergeError(true);
Utils.log.error("Change could not be applied. Merge error detected.");
throw ex;
}
};
/**
* Retrieves the <code>sap.ui.fl.registry.ChangeRegistryItem</code> for the given change and control
*
* @param {sap.ui.fl.Change} oChange - Change instance
* @param {sap.ui.core.Control} oControl Control instance
* @returns {sap.ui.fl.changeHandler.Base} the change handler. Undefined if not found.
* @private
*/
FlexController.prototype._getChangeHandler = function(oChange, oControl) {
var oChangeTypeMetadata, fChangeHandler;
oChangeTypeMetadata = this._getChangeTypeMetadata(oChange, oControl);
if (!oChangeTypeMetadata) {
return undefined;
}
fChangeHandler = oChangeTypeMetadata.getChangeHandler();
return fChangeHandler;
};
/**
* Retrieves the <code>sap.ui.fl.registry.ChangeRegistryItem</code> for the given change and control
*
* @param {sap.ui.fl.Change} oChange Change instance
* @param {sap.ui.core.Control} oControl Control instance
* @returns {sap.ui.fl.registry.ChangeTypeMetadata} the registry item containing the change handler. Undefined if not found.
* @private
*/
FlexController.prototype._getChangeTypeMetadata = function(oChange, oControl) {
var oChangeRegistryItem, oChangeTypeMetadata;
oChangeRegistryItem = this._getChangeRegistryItem(oChange, oControl);
if (!oChangeRegistryItem || !oChangeRegistryItem.getChangeTypeMetadata) {
return undefined;
}
oChangeTypeMetadata = oChangeRegistryItem.getChangeTypeMetadata();
return oChangeTypeMetadata;
};
/**
* Retrieves the <code>sap.ui.fl.registry.ChangeRegistryItem</code> for the given change and control
*
* @param {sap.ui.fl.Change} oChange Change instance
* @param {sap.ui.core.Control} oControl Control instance
* @returns {sap.ui.fl.registry.ChangeRegistryItem} the registry item containing the change handler. Undefined if not found.
* @private
*/
FlexController.prototype._getChangeRegistryItem = function(oChange, oControl) {
var sChangeType, sControlType, oChangeRegistryItem, sLayer;
if (!oChange || !oControl) {
return undefined;
}
sChangeType = oChange.getChangeType();
sControlType = Utils.getControlType(oControl);
if (!sChangeType || !sControlType) {
return undefined;
}
sLayer = oChange.getLayer();
oChangeRegistryItem = this._getChangeRegistry().getRegistryItems({
"changeTypeName": sChangeType,
"controlType": sControlType,
"layer": sLayer
});
if (oChangeRegistryItem && oChangeRegistryItem[sControlType] && oChangeRegistryItem[sControlType][sChangeType]) {
return oChangeRegistryItem[sControlType][sChangeType];
} else if (oChangeRegistryItem && oChangeRegistryItem[sControlType]) {
return oChangeRegistryItem[sControlType];
} else {
return oChangeRegistryItem;
}
};
/**
* Returns the change registry
*
* @returns {sap.ui.fl.registry.ChangeRegistry} Instance of the change registry
* @private
*/
FlexController.prototype._getChangeRegistry = function() {
var oInstance = ChangeRegistry.getInstance();
// make sure to use the most current flex settings that have been retrieved during processView
oInstance.initSettings(this.getComponentName());
return oInstance;
};
/**
* Returns the control where the change will be applied to. Undefined if control cannot be found.
*
* @param {sap.ui.fl.Change} oChange Change
* @returns {sap.ui.core.Control} Control where the change will be applied to
* @private
*/
FlexController.prototype._getControlByChange = function(oChange) {
var oSelector;
if (!oChange) {
return undefined;
}
oSelector = oChange.getSelector();
if (oSelector && typeof oSelector.id === "string") {
return sap.ui.getCore().byId(oSelector.id);
}
return undefined;
};
/**
* Retrieves the changes for the complete UI5 component
* @param {map} mPropertyBag - (optional) contains additional data that are needed for reading of changes
* - appDescriptor that belongs to actual component
* - siteId that belongs to actual component
* @returns {Promise} Promise resolves with a map of all {sap.ui.fl.Change} having the changeId as key
* @public
*/
FlexController.prototype.getComponentChanges = function(mPropertyBag) {
return this._oChangePersistence.getChangesForComponent(mPropertyBag);
};
/**
* Retrieves the changes for the view and its siblings (except nested views)
*
* @params {object} oView - the view
* @param {map} mPropertyBag - (optional) contains additional data that are needed for reading of changes
* - appDescriptor that belongs to actual component
* - siteId that belongs to actual component
* @returns {Promise} Promise resolves with a map of all {sap.ui.fl.Change} of a component
* @private
*/
FlexController.prototype._getChangesForView = function(oView, mPropertyBag) {
return this._oChangePersistence.getChangesForView(oView.getId(), mPropertyBag);
};
/**
* Creates a new instance of sap.ui.fl.Persistence based on the current component and caches the instance in a private member
*
* @returns {sap.ui.fl.Persistence} persistence instance
* @private
*/
FlexController.prototype._createChangePersistence = function() {
this._oChangePersistence = ChangePersistenceFactory.getChangePersistenceForComponent(this.getComponentName());
return this._oChangePersistence;
};
/**
* Discard changes on the server.
*
* @param {array} aChanges array of {sap.ui.fl.Change} to be discarded
* @returns {Promise} promise that resolves without parameters.
*/
FlexController.prototype.discardChanges = function(aChanges) {
var sActiveLayer = Utils.getCurrentLayer(false);
aChanges.forEach(function(oChange) {
// only discard changes of the currently active layer (CUSTOMER vs PARTNER vs VENDOR)
if (oChange && oChange.getLayer && oChange.getLayer() === sActiveLayer) {
this._oChangePersistence.deleteChange(oChange);
}
}.bind(this));
return this._oChangePersistence.saveDirtyChanges();
};
/**
* Searches for controls in the view control tree, which enable flexibility features.
*
* @param {sap.ui.core.Control} oParentControl Parent control instance
* @returns {boolean} true if the view contains controls, which enable flexibility features, false if not.
* @private
*/
FlexController.prototype._isFlexEnabled = function(oParentControl) {
var that = this;
var bIsFlexEnabled = false;
if (oParentControl.getMetadata) {
var oParentControlMetadata = oParentControl.getMetadata();
var oAggregations = oParentControlMetadata.getAllAggregations();
var aAggregationKeys = Object.keys(oAggregations);
jQuery.each(aAggregationKeys, function(iAggragationKeyIndex, sAggregationKey) {
if (sAggregationKey != "data" && oParentControlMetadata.getAggregation) {
// data has no flex, but cannot be accessed if the data contains a FlattenedDataset (resulting in an error)
var oAggregation = oParentControlMetadata.getAggregation(sAggregationKey);
if ( oAggregation && oAggregation.get) {
var aAggregations = oAggregation.get(oParentControl);
if (aAggregations) {
if (!Array.isArray(aAggregations)) {
// in case of an aggregation with a cardinality of 0..1 the object is returned not in an array.
aAggregations = [
aAggregations
];
}
jQuery.each(aAggregations, function(index, oChildControl) {
if (typeof oChildControl.getFlexEnabled === 'function' && oChildControl.getFlexEnabled()) {
bIsFlexEnabled = true;
return false; // break inner jQuery.each
} else {
bIsFlexEnabled = that._isFlexEnabled(oChildControl);
if (bIsFlexEnabled === true) {
return false; // break inner jQuery.each
}
}
});
if (bIsFlexEnabled === true) {
return false; // break outer jQuery.each
}
}
}
}
});
}
return bIsFlexEnabled;
};
FlexController.prototype.deleteChangesForControlDeeply = function(oControl) {
return Promise.resolve();
};
/**
* Set flag if an error has occured when merging changes
*
* @param {Boolean} bHasErrorOccured Indicator if an error has occured
* @private
*/
FlexController.prototype._setMergeError = function(bHasErrorOccured) {
// in this case FlexSettings.getInstance does not get passed (AppDescriptorId and SiteId) as setMergeErrorOccured ONLY enrich setting instance
// with runtime data. No direct backend call
return FlexSettings.getInstance(this.getComponentName()).then(function(oSettings) {
oSettings.setMergeErrorOccured(true);
});
};
return FlexController;
}, true);
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
/**
* @class messageHandler
* @memberOf sap.apf.ui.reuse.view
* @name messageHandler
*/
sap.ui.jsview("sap.apf.ui.reuse.view.messageHandler", {
/**
* @this {sap.apf.ui.reuse.view.messageHandler}
* @description messageHandler view
*/
/**
* @memberOf sap.apf.ui.reuse.view.messageHandler
* @method initializeHandler
* @param oMessageObject
* @description UI handle for error messages to be shown on notification bar
*/
initializeHandler : function(oMessageObject) {
this.getController().showMessage(oMessageObject);
},
getControllerName : function() {
return "sap.apf.ui.reuse.controller.messageHandler";
},
createContent : function(oController) {
jQuery.sap.require("sap.m.MessageToast");
jQuery.sap.require("sap.ca.ui.message.message");
}
});<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
/*global sap, jQuery, OData */
jQuery.sap.declare('sap.apf.core.request');
jQuery.sap.require('sap.apf.utils.utils');
jQuery.sap.require('sap.apf.core.utils.filter');
jQuery.sap.require('sap.apf.core.utils.filterTerm');
jQuery.sap.require('sap.ui.thirdparty.datajs');
jQuery.sap.require("sap.apf.core.utils.filterSimplify");
(function() {
'use strict';
/**
* @class The Request object represents an OData GET request. It receives a
* filter which is then mapped to a URI query and appended to the request
* URI. Its role is to send an asynchronous OData request to the server,
* receive the response, parse it and provision it as an array of
* objects. The request will use a callback mechanism handling the
* asynchronous request behavior. The callback routes control back to the
* Path object.
* @param {Object} oInject - references to other handlers
* @param oConfig - Configuration Object for a Request.
*/
sap.apf.core.Request = function(oInject, oConfig) {
var oMessageHandler = oInject.messageHandler;
var oCoreApi = oInject.coreApi;
var sServiceRootPath = oConfig.service;
var selectProperties = oConfig.selectProperties;
var oUriGenerator = oCoreApi.getUriGenerator();
var oMessageObject;
if (sServiceRootPath === undefined) {
oMessageObject = oMessageHandler.createMessageObject({
code : '5015',
aParameters : [ oConfig.id ]
});
oMessageHandler.putMessage(oMessageObject);
}
var oMetadata = oCoreApi.getMetadata(sServiceRootPath);
var oUriComponents = oMetadata.getUriComponents(oConfig.entityType);
var sEntitySet, snavigationProperty;
if (oUriComponents) {
sEntitySet = oUriComponents.entitySet;
snavigationProperty = oUriComponents.navigationProperty;
}
oMessageHandler.check(sEntitySet !== undefined, 'Invalid request configuration: An entityset does not exist under the service ' + oConfig.entityType);
oMessageHandler.check(snavigationProperty !== undefined, 'Invalid request configuration: A usable navigation does not exist for the service ' + oConfig.entityType);
this.type = oConfig.type;
/**
* @description A request object that can send (many) asynchronous OData GET requests to the server. It uses a POST $batch operation wrapping the GET.
* @param {Object} oFilter - An sap.apf.core.utils filter object.
* @param {Function} fnCallback - A function called after the response was successfully received and parsed.
* @param {Object} oRequestOptions - An optional object containing additional query string options
* Format: { orderby : [{ property : <property_name>, order : <asc|desc>}], top : <integer>, skip : <integer> }
*/
this.sendGetInBatch = function(oFilter, fnCallback, oRequestOptions) {
var oParameters = retrieveParameters(oFilter);
var oFilterApplicableForRequest;
var filterSimplify;
checkFilterForRequiredProperties(oFilter);
if (oFilter && oFilter.getProperties) {
oFilterApplicableForRequest = oFilter.reduceToProperty(oMetadata.getFilterableProperties(sEntitySet));
if (oCoreApi.getStartParameterFacade().isFilterReductionActive()) {
filterSimplify = new sap.apf.core.utils.FilterReduction();
oFilterApplicableForRequest = filterSimplify.filterReduction(oMessageHandler, oFilterApplicableForRequest);
}
}
checkRequestOptionsConsistency(oRequestOptions);
var oPaging = oRequestOptions && oRequestOptions.paging;
var oSortingFields = oRequestOptions && oRequestOptions.orderby;
var sUrlEntityType = oUriGenerator.buildUri(oMessageHandler, sEntitySet, selectProperties, oFilterApplicableForRequest, oParameters, oSortingFields, oPaging, undefined, formatValue, snavigationProperty);
var oRequest = {
method : 'POST',
headers : {
'x-csrf-token' : oCoreApi.getXsrfToken(sServiceRootPath)
},
requestUri : oUriGenerator.getAbsolutePath(sServiceRootPath) + '$batch',
data : {
__batchRequests : [ {
requestUri : sUrlEntityType,
method : 'GET',
headers : {
'Accept-Language' : sap.ui.getCore().getConfiguration().getLanguage(),
'x-csrf-token' : oCoreApi.getXsrfToken(sServiceRootPath)
}
} ]
}
};
var fnSuccess = function(data, response) {
var oResponse = {};
var sUrl = '';
if (data && data.__batchResponses && data.__batchResponses[0].data) {
oResponse.data = data.__batchResponses[0].data.results;
oResponse.metadata = oCoreApi.getEntityTypeMetadata(oConfig.service, oConfig.entityType);
if (data.__batchResponses[0].data.__count) {
oResponse.count = parseInt(data.__batchResponses[0].data.__count, 10);
}
} else if (data && data.__batchResponses[0] && data.__batchResponses[0].response && data.__batchResponses[0].message) {
sUrl = response.requestUri;
var sMessage = data.__batchResponses[0].message;
var sErrorDetails = data.__batchResponses[0].response.body;
var sHttpStatusCode = data.__batchResponses[0].response.statusCode;
oResponse = oMessageHandler.createMessageObject({
code : '5001',
aParameters : [ sHttpStatusCode, sMessage, sErrorDetails, sUrl ]
});
} else {
sUrl = response.requestUri || sUrlEntityType;
oResponse = oMessageHandler.createMessageObject({
code : '5001',
aParameters : [ 'unknown', 'unknown error', 'unknown error', sUrl ]
});
}
fnCallback(oResponse, false);
};
var fnError = function(error) {
var sMessage = 'unknown error';
var sErrorDetails = 'unknown error';
var sUrl = sUrlEntityType;
if (error.message !== undefined) {
sMessage = error.message;
}
var sHttpStatusCode = 'unknown';
if (error.response && error.response.statusCode) {
sHttpStatusCode = error.response.statusCode;
sErrorDetails = error.response.statusText || '';
sUrl = error.response.requestUri || sUrlEntityType;
}
if (error.messageObject && error.messageObject.type === 'messageObject') {
fnCallback(error.messageObject);
} else {
fnCallback(oMessageHandler.createMessageObject({
code : '5001',
aParameters : [ sHttpStatusCode, sMessage, sErrorDetails, sUrl ]
}));
}
};
oCoreApi.odataRequest(oRequest, fnSuccess, fnError, OData.batchHandler);
};
function formatValue(sProperty, value) {
var strDelimiter = "'";
var oEntityMetadata = oMetadata.getPropertyMetadata(sEntitySet, sProperty);
if (oEntityMetadata && oEntityMetadata.dataType) {
return sap.apf.utils.formatValue(value, oEntityMetadata.dataType.type);
}
if (typeof value === 'number') {
return value;
}
return strDelimiter + sap.apf.utils.escapeOdata(value) + strDelimiter;
}
function checkRequestOptionsConsistency(oRequestOptions) {
var aPropertyNames, i;
if (!oRequestOptions) {
return;
}
aPropertyNames = Object.getOwnPropertyNames(oRequestOptions);
for(i = 0; i < aPropertyNames.length; i++) {
if (aPropertyNames[i] !== 'orderby' && aPropertyNames[i] !== 'paging') {
oMessageHandler.putMessage(oMessageHandler.createMessageObject({
code : '5032',
aParameters : [ sEntitySet, aPropertyNames[i] ]
}));
}
}
}
function checkFilterForRequiredProperties(oFilter) {
var aFilterableProperties = oMetadata.getFilterableProperties(sEntitySet);
var sRequiredFilterProperty = '';
var oEntityTypeMetadata = oMetadata.getEntityTypeAnnotations(sEntitySet);
var oMessageObject2;
if (oEntityTypeMetadata.requiresFilter !== undefined && oEntityTypeMetadata.requiresFilter === 'true') {
if (oEntityTypeMetadata.requiredProperties !== undefined) {
sRequiredFilterProperty = oEntityTypeMetadata.requiredProperties;
}
}
if (sRequiredFilterProperty === '') {
return;
}
if (jQuery.inArray(sRequiredFilterProperty, aFilterableProperties) === -1) {
oMessageObject2 = oMessageHandler.createMessageObject({
code : '5006',
aParameters : [ sEntitySet, sRequiredFilterProperty ]
});
oMessageHandler.putMessage(oMessageObject2);
}
var aPropertiesInFilter = oFilter.getProperties();
// test, whether all required properties are in filter
if (jQuery.inArray(sRequiredFilterProperty, aPropertiesInFilter) === -1) {
oMessageObject2 = oMessageHandler.createMessageObject({
code : '5005',
aParameters : [ sEntitySet, sRequiredFilterProperty ]
});
oMessageHandler.putMessage(oMessageObject2);
}
}
function retrieveParameters(oFilter) {
var oParameters = {};
var aParameters;
var numberOfParameters;
var aTermsContainingParameter;
var i;
var oParameterTerm;
aParameters = oMetadata.getParameterEntitySetKeyProperties(sEntitySet);
if (aParameters !== undefined) {
numberOfParameters = aParameters.length;
} else {
numberOfParameters = 0;
}
if (numberOfParameters > 0) {
for(i = 0; i < numberOfParameters; i++) {
if (oFilter && oFilter instanceof sap.apf.core.utils.Filter) {
aTermsContainingParameter = oFilter.getFilterTermsForProperty(aParameters[i].name);
oParameterTerm = aTermsContainingParameter[aTermsContainingParameter.length - 1];
}
if (oParameterTerm instanceof sap.apf.core.utils.FilterTerm) {
addParameter(i, oParameterTerm.getValue());
} else if (aParameters[i].defaultValue) {
addParameter(i, aParameters[i].defaultValue);
} else {
oMessageHandler.putMessage(oMessageHandler.createMessageObject({
code : '5016',
aParameters : [ aParameters[i].name ]
}));
}
}
}
return oParameters;
function addParameter(index, value) {
var formatedValue;
if (aParameters[index].dataType.type === 'Edm.String') {
oParameters[aParameters[index].name] = (jQuery.sap.encodeURL("'" + sap.apf.utils.escapeOdata(value) + "'"));
} else if (aParameters[index].dataType.type) {
formatedValue = sap.apf.utils.formatValue(value, aParameters[index].dataType.type);
if (typeof formatedValue === 'string') {
oParameters[aParameters[index].name] = jQuery.sap.encodeURL(formatedValue);
} else {
oParameters[aParameters[index].name] = formatedValue;
}
} else if (typeof value === 'string') {
oParameters[aParameters[index].name] = jQuery.sap.encodeURL(sap.apf.utils.escapeOdata(value));
} else {
oParameters[aParameters[index].name] = value;
}
}
}
};
}());
<file_sep>(function () {
"use strict";
/*global jQuery, sap */
jQuery.sap.declare("sap.ovp.cards.generic.Component");
jQuery.sap.require("sap.ui.core.UIComponent");
jQuery.sap.require("sap.ovp.cards.AnnotationHelper");
sap.ui.core.UIComponent.extend("sap.ovp.cards.generic.Component", {
// use inline declaration instead of component.json to save 1 round trip
metadata: {
properties: {
"contentFragment": {
"type": "string"
},
"headerExtensionFragment": {
"type": "string"
},
"contentPosition": {
"type": "string",
"defaultValue": "Middle"
},
"footerFragment": {
"type": "string"
},
"identificationAnnotationPath":{
"type": "string",
"defaultValue": "com.sap.vocabularies.UI.v1.Identification"
},
"selectionAnnotationPath":{
"type": "string"
},
"filters": {
"type": "object"
},
"addODataSelect": {
"type": "boolean",
"defaultValue": false
}
},
version: "1.36.12",
library: "sap.ovp",
includes: [],
dependencies: {
libs: [ "sap.m" ],
components: []
},
config: {}
},
/**
* Default "abstract" empty function.
* In case there is a need to enrich the default preprocessor which provided by OVP, the extended Component should provide this function and return a preprocessor object.
* @public
* @returns {Object} SAPUI5 preprocessor object
*/
getCustomPreprocessor: function () {},
getPreprocessors : function(ovplibResourceBundle) {
var oComponentData = this.getComponentData(),
oSettings = oComponentData.settings,
oModel = oComponentData.model,
oMetaModel,
oEntityTypeContext,
oEntitySetContext;
//Backwards compatibility to support "description" property
if (oSettings.description && !oSettings.subTitle) {
oSettings.subTitle = oSettings.description;
}
if (oModel){
var oMetaModel = oModel.getMetaModel();
var oEntitySet = oMetaModel.getODataEntitySet(oSettings.entitySet);
var sEntitySetPath = oMetaModel.getODataEntitySet(oSettings.entitySet, true);
var oEntityType = oMetaModel.getODataEntityType(oEntitySet.entityType);
oEntitySetContext = oMetaModel.createBindingContext(sEntitySetPath);
oEntityTypeContext = oMetaModel.createBindingContext(oEntityType.$path);
}
var oCardProperties = this._getCardPropertyDefaults();
oCardProperties = jQuery.extend(true, {metaModel: oMetaModel, entityType: oEntityType}, oCardProperties, oSettings);
var oOvpCardPropertiesModel = new sap.ui.model.json.JSONModel(oCardProperties);
var ovplibResourceBundle = this.getOvplibResourceBundle();
var oDefaultPreprocessors = {
xml: {
bindingContexts: {entityType: oEntityTypeContext, entitySet: oEntitySetContext},
models: {entityType: oMetaModel, entitySet:oMetaModel, ovpMeta: oMetaModel, ovpCardProperties: oOvpCardPropertiesModel, ovplibResourceBundle: ovplibResourceBundle},
ovpCardProperties: oOvpCardPropertiesModel,
dataModel: oModel,
_ovpCache: {}
}
};
return jQuery.extend(true, {}, this.getCustomPreprocessor(), oDefaultPreprocessors);
},
_getCardPropertyDefaults: function(){
var oCardProperties = {};
var oPropsDef = this.getMetadata().getAllProperties();
var oPropDef;
for (var propName in oPropsDef){
oPropDef = oPropsDef[propName];
if (oPropDef.defaultValue !== undefined){
oCardProperties[oPropDef.name] = oPropDef.defaultValue;
}
}
return oCardProperties;
},
getOvplibResourceBundle: function(){
if (!this.ovplibResourceBundle){
var oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ovp");
this.ovplibResourceBundle = oResourceBundle ? new sap.ui.model.resource.ResourceModel({bundleUrl: oResourceBundle.oUrlInfo.url}) : null;
}
return this.ovplibResourceBundle;
},
createContent: function () {
var oComponentData = this.getComponentData && this.getComponentData();
var oModel = oComponentData.model;
var oPreprocessors = this.getPreprocessors();
var oView;
oView = sap.ui.view({
preprocessors: oPreprocessors,
type: sap.ui.core.mvc.ViewType.XML,
viewName: "sap.ovp.cards.generic.Card"
});
oView.setModel(oModel);
// check if i18n model is available and then add it to card view
if (oComponentData.i18n) {
oView.setModel(oComponentData.i18n, "@i18n");
}
oView.setModel(oPreprocessors.xml.ovpCardProperties, "ovpCardProperties");
oView.setModel(this.getOvplibResourceBundle(), "ovplibResourceBundle");
return oView;
}
});
})();
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.ui.comp.smartform.flexibility.Input.
sap.ui.define(['jquery.sap.global', 'sap/m/Input', 'sap/ui/comp/library'],
function(jQuery, Input1, library) {
"use strict";
/**
* Constructor for a new smartform/flexibility/Input.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Input field with special focus handling
* @extends sap.m.Input
*
* @constructor
* @public
* @alias sap.ui.comp.smartform.flexibility.Input
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var Input = Input1.extend("sap.ui.comp.smartform.flexibility.Input", /** @lends sap.ui.comp.smartform.flexibility.Input.prototype */ { metadata : {
library : "sap.ui.comp",
events : {
/**
* Fired when the field is readonly, focused and user pressed Space
*/
selectedByKeyboard : {}
}
}});
Input.prototype.init = function() {
Input1.prototype.init.call(this);
};
Input.prototype.onAfterRendering = function() {
var oDomRef;
Input1.prototype.onAfterRendering.apply(this);
oDomRef = this.getDomRef();
if (oDomRef) {
oDomRef.tabIndex = 0;
}
};
Input.prototype.onkeydown = function(oEvent) {
var nKeyCode;
Input1.prototype.onkeydown.apply(this, arguments);
nKeyCode = oEvent.keyCode;
if (nKeyCode === 32) { // Blank pressed
if (this.getEditable() === false) {
this.fireSelectedByKeyboard();
}
}
};
Input.prototype.onsapescape = function(oEvent) {
Input1.prototype.onsapescape.apply(this, arguments);
oEvent.stopPropagation(); // Prevent closing the dialog
this.setEditable(false);
};
// onsapenter (compared to onkeydown) is called before the value is saved
Input.prototype.onsapenter = function (oEvent) {
if (!this.getValue()) {
this.resetOnEmptyValue();
}
Input1.prototype.onsapenter.apply(this, arguments);
this.setEditable(false);
};
Input.prototype.resetOnEmptyValue = function (oEvent) {
if (!this.getValue()) {
this.setValue(this._lastValue);
this.onValueRevertedByEscape(this._lastValue);
}
};
Input.prototype.onsapfocusleave = function (oEvent) {
this.resetOnEmptyValue();
Input1.prototype.onsapfocusleave.apply(this, arguments);
};
return Input;
}, /* bExport= */ true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define([
'sap/ui/fl/Utils', 'jquery.sap.global', 'sap/ui/fl/changeHandler/Base'
], function(Utils, jQuery, Base) {
"use strict";
/**
* Change handler for renaming a smart form group element.
* @constructor
* @alias sap.ui.fl.changeHandler.RenameField
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*/
var RenameField = function() {
};
RenameField.prototype = jQuery.sap.newObject(Base.prototype);
/**
* Renames a smart form group element.
*
* @param {sap.ui.fl.Change} oChangeWrapper change wrapper object with instructions to be applied on the control map
* @param {sap.ui.core.Control} oControl control that matches the change selector for applying the change
* @public
*/
RenameField.prototype.applyChange = function(oChangeWrapper, oControl) {
var oChange = oChangeWrapper.getDefinition();
if (oChange.texts && oChange.texts.fieldLabel && this._isProvided(oChange.texts.fieldLabel.value)) {
if (!oControl) {
throw new Error("no Control provided for renaming");
}
if (typeof oControl.setLabel === 'function') {
oControl.unbindProperty("label");
oControl.setLabel(oChange.texts.fieldLabel.value);
} else if (typeof oControl.setTitle === 'function') {
oControl.unbindProperty("title");
oControl.setTitle(oChange.texts.fieldLabel.value);
} else {
throw new Error('Control does not support "renameField" change');
}
} else {
Utils.log.error("Change does not contain sufficient information to be applied: [" + oChange.layer + "]" + oChange.namespace + "/" + oChange.fileName + "." + oChange.fileType);
//however subsequent changes should be applied
}
};
/**
* Completes the change by adding change handler specific content
*
* @param {sap.ui.fl.Change} oChangeWrapper change wrapper object to be completed
* @param {object} oSpecificChangeInfo with attribute fieldLabel, the new field label to be included in the change
* @public
*/
RenameField.prototype.completeChangeContent = function(oChangeWrapper, oSpecificChangeInfo) {
var oChange = oChangeWrapper.getDefinition();
if (this._isProvided(oSpecificChangeInfo.fieldLabel)) {
this.setTextInChange(oChange, "fieldLabel", oSpecificChangeInfo.fieldLabel, "XFLD");
} else {
throw new Error("oSpecificChangeInfo.fieldLabel attribute required");
}
};
/**
* Checks if a string is provided as also empty strings are allowed for the fields
*/
RenameField.prototype._isProvided = function(sString){
return typeof (sString) === "string";
};
return RenameField;
},
/* bExport= */true);
<file_sep>/*!
*
* SAP UI development toolkit for HTML5 (SAPUI5)
* (c) Copyright 2009-2015 SAP SE. All rights reserved
*
*/
/* ----------------------------------------------------------------------------------
* Hint: This is a derived (generated) file. Changes should be done in the underlying
* source files only (*.control, *.js) or they will be lost after the next generation.
* ---------------------------------------------------------------------------------- */
// Provides control sap.suite.ui.commons.ProcessFlow.
jQuery.sap.declare("sap.suite.ui.commons.ProcessFlow");
jQuery.sap.require("sap.suite.ui.commons.library");
jQuery.sap.require("sap.ui.core.Control");
/**
* Constructor for a new ProcessFlow.
*
* Accepts an object literal <code>mSettings</code> that defines initial
* property values, aggregated and associated objects as well as event handlers.
*
* If the name of a setting is ambiguous (e.g. a property has the same name as an event),
* then the framework assumes property, aggregation, association, event in that order.
* To override this automatic resolution, one of the prefixes "aggregation:", "association:"
* or "event:" can be added to the name of the setting (such a prefixed name must be
* enclosed in single or double quotes).
*
* The supported settings are:
* <ul>
* <li>Properties
* <ul>
* <li>{@link #getFoldedCorners foldedCorners} : boolean (default: false)</li>
* <li>{@link #getScrollable scrollable} : boolean (default: true)</li>
* <li>{@link #getWheelZoomable wheelZoomable} : boolean (default: true)</li>
* <li>{@link #getShowLabels showLabels} : boolean (default: false)</li></ul>
* </li>
* <li>Aggregations
* <ul>
* <li>{@link #getNodes nodes} : sap.suite.ui.commons.ProcessFlowNode[]</li>
* <li>{@link #getLanes lanes} <strong>(default aggregation)</strong> : sap.suite.ui.commons.ProcessFlowLaneHeader[]</li></ul>
* </li>
* <li>Associations
* <ul></ul>
* </li>
* <li>Events
* <ul>
* <li>{@link sap.suite.ui.commons.ProcessFlow#event:nodeTitlePress nodeTitlePress} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li>
* <li>{@link sap.suite.ui.commons.ProcessFlow#event:nodePress nodePress} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li>
* <li>{@link sap.suite.ui.commons.ProcessFlow#event:labelPress labelPress} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li>
* <li>{@link sap.suite.ui.commons.ProcessFlow#event:headerPress headerPress} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li>
* <li>{@link sap.suite.ui.commons.ProcessFlow#event:onError onError} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li></ul>
* </li>
* </ul>
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Complex control that enables you to display documents or other items in their flow.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.8
*
* @constructor
* @public
* @name sap.suite.ui.commons.ProcessFlow
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
sap.ui.core.Control.extend("sap.suite.ui.commons.ProcessFlow", { metadata : {
publicMethods : [
// methods
"getZoomLevel", "setZoomLevel", "zoomIn", "zoomOut", "updateModel", "getFocusedNode", "updateNodesOnly", "setSelectedPath"
],
library : "sap.suite.ui.commons",
properties : {
"foldedCorners" : {type : "boolean", group : "Misc", defaultValue : false},
"scrollable" : {type : "boolean", group : "Misc", defaultValue : true},
"wheelZoomable" : {type : "boolean", group : "Behavior", defaultValue : true},
"showLabels" : {type : "boolean", group : "Appearance", defaultValue : false}
},
defaultAggregation : "lanes",
aggregations : {
"_connections" : {type : "sap.suite.ui.commons.ProcessFlowConnection", multiple : true, singularName : "_connection", visibility : "hidden"},
"nodes" : {type : "sap.suite.ui.commons.ProcessFlowNode", multiple : true, singularName : "node"},
"lanes" : {type : "sap.suite.ui.commons.ProcessFlowLaneHeader", multiple : true, singularName : "lane"}
},
events : {
"nodeTitlePress" : {deprecated: true},
"nodePress" : {},
"labelPress" : {},
"headerPress" : {},
"onError" : {}
}
}});
/**
* Creates a new subclass of class sap.suite.ui.commons.ProcessFlow with name <code>sClassName</code>
* and enriches it with the information contained in <code>oClassInfo</code>.
*
* <code>oClassInfo</code> might contain the same kind of informations as described in {@link sap.ui.core.Element.extend Element.extend}.
*
* @param {string} sClassName name of the class to be created
* @param {object} [oClassInfo] object literal with informations about the class
* @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.core.ElementMetadata.
* @return {function} the created class / constructor function
* @public
* @static
* @name sap.suite.ui.commons.ProcessFlow.extend
* @function
*/
sap.suite.ui.commons.ProcessFlow.M_EVENTS = {'nodeTitlePress':'nodeTitlePress','nodePress':'nodePress','labelPress':'labelPress','headerPress':'headerPress','onError':'onError'};
/**
* Getter for property <code>foldedCorners</code>.
* This property defines the folded corners for the single node control. The following values exist:
* - true: means folded corner
* - false/null/undefined: means normal corner
*
* Default value is <code>false</code>
*
* @return {boolean} the value of property <code>foldedCorners</code>
* @public
* @name sap.suite.ui.commons.ProcessFlow#getFoldedCorners
* @function
*/
/**
* Setter for property <code>foldedCorners</code>.
*
* Default value is <code>false</code>
*
* @param {boolean} bFoldedCorners new value for property <code>foldedCorners</code>
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#setFoldedCorners
* @function
*/
/**
* Getter for property <code>scrollable</code>.
* By default, the control body is embedded into a scroll container of fixed size, so the user
* can put the control into a fixe sized layout.
* When the control body (the graph) gets larger than the container cuts the overflowing parts of the graph and the cut parts can be viewed by scroling the control body.
* When the control body fits into the container limits, obviously no scrolling is possible (and makes sense).
*
* The scrolling feature can be turned off by setting this property value to false,
* so the width/height of the whole control will change as the flow graph gets smaller/larger.
* In this case the control body could not be scrolled, as the control body size matches the control container size.
*
* Default value is <code>true</code>
*
* @return {boolean} the value of property <code>scrollable</code>
* @public
* @name sap.suite.ui.commons.ProcessFlow#getScrollable
* @function
*/
/**
* Setter for property <code>scrollable</code>.
*
* Default value is <code>true</code>
*
* @param {boolean} bScrollable new value for property <code>scrollable</code>
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#setScrollable
* @function
*/
/**
* Getter for property <code>wheelZoomable</code>.
* The property specifies if to enable semantic zooming by mouse wheel events on desktop browsers.
*
* Default value is <code>true</code>
*
* @return {boolean} the value of property <code>wheelZoomable</code>
* @public
* @name sap.suite.ui.commons.ProcessFlow#getWheelZoomable
* @function
*/
/**
* Setter for property <code>wheelZoomable</code>.
*
* Default value is <code>true</code>
*
* @param {boolean} bWheelZoomable new value for property <code>wheelZoomable</code>
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#setWheelZoomable
* @function
*/
/**
* Getter for property <code>showLabels</code>.
* Defines if the connection labels are shown or not.
*
* Default value is <code>false</code>
*
* @return {boolean} the value of property <code>showLabels</code>
* @public
* @name sap.suite.ui.commons.ProcessFlow#getShowLabels
* @function
*/
/**
* Setter for property <code>showLabels</code>.
*
* Default value is <code>false</code>
*
* @param {boolean} bShowLabels new value for property <code>showLabels</code>
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#setShowLabels
* @function
*/
/**
* Getter for aggregation <code>nodes</code>.<br/>
* This is the aggregation of the node controls put into the table to the calculated cells.
*
* @return {sap.suite.ui.commons.ProcessFlowNode[]}
* @public
* @name sap.suite.ui.commons.ProcessFlow#getNodes
* @function
*/
/**
* Inserts a node into the aggregation named <code>nodes</code>.
*
* @param {sap.suite.ui.commons.ProcessFlowNode}
* oNode the node to insert; if empty, nothing is inserted
* @param {int}
* iIndex the <code>0</code>-based index the node should be inserted at; for
* a negative value of <code>iIndex</code>, the node is inserted at position 0; for a value
* greater than the current size of the aggregation, the node is inserted at
* the last position
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#insertNode
* @function
*/
/**
* Adds some node <code>oNode</code>
* to the aggregation named <code>nodes</code>.
*
* @param {sap.suite.ui.commons.ProcessFlowNode}
* oNode the node to add; if empty, nothing is inserted
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#addNode
* @function
*/
/**
* Removes an node from the aggregation named <code>nodes</code>.
*
* @param {int | string | sap.suite.ui.commons.ProcessFlowNode} vNode the node to remove or its index or id
* @return {sap.suite.ui.commons.ProcessFlowNode} the removed node or null
* @public
* @name sap.suite.ui.commons.ProcessFlow#removeNode
* @function
*/
/**
* Removes all the controls in the aggregation named <code>nodes</code>.<br/>
* Additionally unregisters them from the hosting UIArea.
* @return {sap.suite.ui.commons.ProcessFlowNode[]} an array of the removed elements (might be empty)
* @public
* @name sap.suite.ui.commons.ProcessFlow#removeAllNodes
* @function
*/
/**
* Checks for the provided <code>sap.suite.ui.commons.ProcessFlowNode</code> in the aggregation named <code>nodes</code>
* and returns its index if found or -1 otherwise.
*
* @param {sap.suite.ui.commons.ProcessFlowNode}
* oNode the node whose index is looked for.
* @return {int} the index of the provided control in the aggregation if found, or -1 otherwise
* @public
* @name sap.suite.ui.commons.ProcessFlow#indexOfNode
* @function
*/
/**
* Destroys all the nodes in the aggregation
* named <code>nodes</code>.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#destroyNodes
* @function
*/
/**
* Getter for aggregation <code>lanes</code>.<br/>
* This is a header of the table for the process flow control.
*
* <strong>Note</strong>: this is the default aggregation for ProcessFlow.
* @return {sap.suite.ui.commons.ProcessFlowLaneHeader[]}
* @public
* @name sap.suite.ui.commons.ProcessFlow#getLanes
* @function
*/
/**
* Inserts a lane into the aggregation named <code>lanes</code>.
*
* @param {sap.suite.ui.commons.ProcessFlowLaneHeader}
* oLane the lane to insert; if empty, nothing is inserted
* @param {int}
* iIndex the <code>0</code>-based index the lane should be inserted at; for
* a negative value of <code>iIndex</code>, the lane is inserted at position 0; for a value
* greater than the current size of the aggregation, the lane is inserted at
* the last position
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#insertLane
* @function
*/
/**
* Adds some lane <code>oLane</code>
* to the aggregation named <code>lanes</code>.
*
* @param {sap.suite.ui.commons.ProcessFlowLaneHeader}
* oLane the lane to add; if empty, nothing is inserted
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#addLane
* @function
*/
/**
* Removes an lane from the aggregation named <code>lanes</code>.
*
* @param {int | string | sap.suite.ui.commons.ProcessFlowLaneHeader} vLane the lane to remove or its index or id
* @return {sap.suite.ui.commons.ProcessFlowLaneHeader} the removed lane or null
* @public
* @name sap.suite.ui.commons.ProcessFlow#removeLane
* @function
*/
/**
* Removes all the controls in the aggregation named <code>lanes</code>.<br/>
* Additionally unregisters them from the hosting UIArea.
* @return {sap.suite.ui.commons.ProcessFlowLaneHeader[]} an array of the removed elements (might be empty)
* @public
* @name sap.suite.ui.commons.ProcessFlow#removeAllLanes
* @function
*/
/**
* Checks for the provided <code>sap.suite.ui.commons.ProcessFlowLaneHeader</code> in the aggregation named <code>lanes</code>
* and returns its index if found or -1 otherwise.
*
* @param {sap.suite.ui.commons.ProcessFlowLaneHeader}
* oLane the lane whose index is looked for.
* @return {int} the index of the provided control in the aggregation if found, or -1 otherwise
* @public
* @name sap.suite.ui.commons.ProcessFlow#indexOfLane
* @function
*/
/**
* Destroys all the lanes in the aggregation
* named <code>lanes</code>.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#destroyLanes
* @function
*/
/**
* This event is fired when a process flow node title was
* clicked. The user can access the clicked process flow node control object which is the only argument of the event handler.
*
* @name sap.suite.ui.commons.ProcessFlow#nodeTitlePress
* @event
* @deprecated Since version 1.26.
* Should not be used any longer, use nodePress event instead ( click on the node)
* @param {sap.ui.base.Event} oControlEvent
* @param {sap.ui.base.EventProvider} oControlEvent.getSource
* @param {object} oControlEvent.getParameters
* @param {object} oControlEvent.getParameters.oEvent This object represents the wrapped process flow node object.
* @public
*/
/**
* Attach event handler <code>fnFunction</code> to the 'nodeTitlePress' event of this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/>.
* When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified
* otherwise to this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/> itself.
*
* This event is fired when a process flow node title was
* clicked. The user can access the clicked process flow node control object which is the only argument of the event handler.
*
* @param {object}
* [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* [oListener] Context object to call the event handler with. Defaults to this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/> itself.
*
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @deprecated Since version 1.26.
* Should not be used any longer, use nodePress event instead ( click on the node)
* @name sap.suite.ui.commons.ProcessFlow#attachNodeTitlePress
* @function
*/
/**
* Detach event handler <code>fnFunction</code> from the 'nodeTitlePress' event of this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/>
*
* The passed function and listener object must match the ones used for event registration.
*
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* oListener Context object on which the given function had to be called.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @deprecated Since version 1.26.
* Should not be used any longer, use nodePress event instead ( click on the node)
* @name sap.suite.ui.commons.ProcessFlow#detachNodeTitlePress
* @function
*/
/**
* Fire event nodeTitlePress to attached listeners.
*
* Expects following event parameters:
* <ul>
* <li>'oEvent' of type <code>object</code> This object represents the wrapped process flow node object.</li>
* </ul>
*
* @param {Map} [mArguments] the arguments to pass along with the event.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @protected
* @deprecated Since version 1.26.
* Should not be used any longer, use nodePress event instead ( click on the node)
* @name sap.suite.ui.commons.ProcessFlow#fireNodeTitlePress
* @function
*/
/**
* This event is fired when a process flow node was clicked.
*
* @name sap.suite.ui.commons.ProcessFlow#nodePress
* @event
* @param {sap.ui.base.Event} oControlEvent
* @param {sap.ui.base.EventProvider} oControlEvent.getSource
* @param {object} oControlEvent.getParameters
* @param {object} oControlEvent.getParameters.oEvent This object represents the wrapped process flow node object.
* @public
*/
/**
* Attach event handler <code>fnFunction</code> to the 'nodePress' event of this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/>.
* When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified
* otherwise to this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/> itself.
*
* This event is fired when a process flow node was clicked.
*
* @param {object}
* [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* [oListener] Context object to call the event handler with. Defaults to this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/> itself.
*
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#attachNodePress
* @function
*/
/**
* Detach event handler <code>fnFunction</code> from the 'nodePress' event of this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/>
*
* The passed function and listener object must match the ones used for event registration.
*
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* oListener Context object on which the given function had to be called.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#detachNodePress
* @function
*/
/**
* Fire event nodePress to attached listeners.
*
* Expects following event parameters:
* <ul>
* <li>'oEvent' of type <code>object</code> This object represents the wrapped process flow node object.</li>
* </ul>
*
* @param {Map} [mArguments] the arguments to pass along with the event.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @protected
* @name sap.suite.ui.commons.ProcessFlow#fireNodePress
* @function
*/
/**
* This event is fired when a process flow connection label was clicked.
*
* @name sap.suite.ui.commons.ProcessFlow#labelPress
* @event
* @param {sap.ui.base.Event} oControlEvent
* @param {sap.ui.base.EventProvider} oControlEvent.getSource
* @param {object} oControlEvent.getParameters
* @param {object} oControlEvent.getParameters.oEvent This object represents the label information.
* @public
*/
/**
* Attach event handler <code>fnFunction</code> to the 'labelPress' event of this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/>.
* When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified
* otherwise to this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/> itself.
*
* This event is fired when a process flow connection label was clicked.
*
* @param {object}
* [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* [oListener] Context object to call the event handler with. Defaults to this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/> itself.
*
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#attachLabelPress
* @function
*/
/**
* Detach event handler <code>fnFunction</code> from the 'labelPress' event of this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/>
*
* The passed function and listener object must match the ones used for event registration.
*
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* oListener Context object on which the given function had to be called.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#detachLabelPress
* @function
*/
/**
* Fire event labelPress to attached listeners.
*
* Expects following event parameters:
* <ul>
* <li>'oEvent' of type <code>object</code> This object represents the label information.</li>
* </ul>
*
* @param {Map} [mArguments] the arguments to pass along with the event.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @protected
* @name sap.suite.ui.commons.ProcessFlow#fireLabelPress
* @function
*/
/**
* This event is fired when the header column was clicked.
*
* @name sap.suite.ui.commons.ProcessFlow#headerPress
* @event
* @param {sap.ui.base.Event} oControlEvent
* @param {sap.ui.base.EventProvider} oControlEvent.getSource
* @param {object} oControlEvent.getParameters
* @param {object} oControlEvent.getParameters.oEvent This object represents the wrapped process flow lane header object.
* @public
*/
/**
* Attach event handler <code>fnFunction</code> to the 'headerPress' event of this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/>.
* When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified
* otherwise to this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/> itself.
*
* This event is fired when the header column was clicked.
*
* @param {object}
* [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* [oListener] Context object to call the event handler with. Defaults to this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/> itself.
*
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#attachHeaderPress
* @function
*/
/**
* Detach event handler <code>fnFunction</code> from the 'headerPress' event of this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/>
*
* The passed function and listener object must match the ones used for event registration.
*
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* oListener Context object on which the given function had to be called.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#detachHeaderPress
* @function
*/
/**
* Fire event headerPress to attached listeners.
*
* Expects following event parameters:
* <ul>
* <li>'oEvent' of type <code>object</code> This object represents the wrapped process flow lane header object.</li>
* </ul>
*
* @param {Map} [mArguments] the arguments to pass along with the event.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @protected
* @name sap.suite.ui.commons.ProcessFlow#fireHeaderPress
* @function
*/
/**
* This event is fired when an issue occurs with the process flow calculation. In most cases, there is an issue with the data. The console contains the detailed error description with the errors.
*
* @name sap.suite.ui.commons.ProcessFlow#onError
* @event
* @param {sap.ui.base.Event} oControlEvent
* @param {sap.ui.base.EventProvider} oControlEvent.getSource
* @param {object} oControlEvent.getParameters
* @param {object} oControlEvent.getParameters.oEvent This parameters contains the localized string with error message.
* @public
*/
/**
* Attach event handler <code>fnFunction</code> to the 'onError' event of this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/>.
* When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified
* otherwise to this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/> itself.
*
* This event is fired when an issue occurs with the process flow calculation. In most cases, there is an issue with the data. The console contains the detailed error description with the errors.
*
* @param {object}
* [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* [oListener] Context object to call the event handler with. Defaults to this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/> itself.
*
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#attachOnError
* @function
*/
/**
* Detach event handler <code>fnFunction</code> from the 'onError' event of this <code>sap.suite.ui.commons.ProcessFlow</code>.<br/>
*
* The passed function and listener object must match the ones used for event registration.
*
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* oListener Context object on which the given function had to be called.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @public
* @name sap.suite.ui.commons.ProcessFlow#detachOnError
* @function
*/
/**
* Fire event onError to attached listeners.
*
* Expects following event parameters:
* <ul>
* <li>'oEvent' of type <code>object</code> This parameters contains the localized string with error message.</li>
* </ul>
*
* @param {Map} [mArguments] the arguments to pass along with the event.
* @return {sap.suite.ui.commons.ProcessFlow} <code>this</code> to allow method chaining
* @protected
* @name sap.suite.ui.commons.ProcessFlow#fireOnError
* @function
*/
/**
* This method returns the current zoom level of the control.
*
* @name sap.suite.ui.commons.ProcessFlow#getZoomLevel
* @function
* @type sap.suite.ui.commons.ProcessFlowZoomLevel
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
/**
* This method sets the new zoom level. If the input is wrong, it is ignored and the previous value stays.
*
* @name sap.suite.ui.commons.ProcessFlow#setZoomLevel
* @function
* @param {sap.suite.ui.commons.ProcessFlowZoomLevel} oNewZoomLevel
* This method sets new zoom level. The enumeration ensures that only available levels are used.
* @type sap.suite.ui.commons.ProcessFlowZoomLevel
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
/**
* This method decreases the zoom level. More details are displayed in the node.
*
* @name sap.suite.ui.commons.ProcessFlow#zoomIn
* @function
* @type sap.suite.ui.commons.ProcessFlowZoomLevel
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
/**
* This method increases the zoom level. Less details are displayed in the node.
*
* @name sap.suite.ui.commons.ProcessFlow#zoomOut
* @function
* @type sap.suite.ui.commons.ProcessFlowZoomLevel
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
/**
* This method triggers the update of the model and correspondingly the rerender method.
*
* @name sap.suite.ui.commons.ProcessFlow#updateModel
* @function
* @type void
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
/**
* This method returns the nodeId of the node, which is focused.
*
* @name sap.suite.ui.commons.ProcessFlow#getFocusedNode
* @function
* @type string
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
/**
* This method should be called when the contents of the nodes were changed. It updates only the nodes and rerenders the ProcessFlow.
*
* @name sap.suite.ui.commons.ProcessFlow#updateNodesOnly
* @function
* @type void
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
/**
* This method sets or resets the selected path between two nodes. To reset the selected path, the method has to be called with null/null.
*
* @name sap.suite.ui.commons.ProcessFlow#setSelectedPath
* @function
* @type void
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
// Start of sap/suite/ui/commons/ProcessFlow.js
///**
// * This file defines behavior for the control.
// */
jQuery.sap.require("sap.m.Image");
/*
* Resource bundle for the localized strings.
*/
sap.suite.ui.commons.ProcessFlow.prototype._resBundle = null;
/**
* Zoom level for the control. It is propagated to all created sub controls.
*/
sap.suite.ui.commons.ProcessFlow.prototype._zoomLevel = sap.suite.ui.commons.ProcessFlowZoomLevel.Two;
/**
* The wheel events time-out.
*/
sap.suite.ui.commons.ProcessFlow.prototype._wheelTimeout = null;
/**
* Set to true when the focus is changing to another node.
*/
sap.suite.ui.commons.ProcessFlow.prototype._isFocusChanged = false;
/**
* The wheel events timestamp for the last wheel event occurrence.
*/
sap.suite.ui.commons.ProcessFlow.prototype._wheelTimestamp = null;
/**
* The wheel events flag, if a wheel event was recently processed.
*/
sap.suite.ui.commons.ProcessFlow.prototype._wheelCalled = false;
/**
* The internal matrix after calculation. Use for keyboard movement.
*/
sap.suite.ui.commons.ProcessFlow.prototype._internalCalcMatrix = false;
/**
* The internal list of connection mappings (source/target/connectionParts)
*/
sap.suite.ui.commons.ProcessFlow.prototype._internalConnectionMap = null;
/**
* Internal lanes, which can differ from original ones. Especially when more nodes are in
* the same lane.
*/
sap.suite.ui.commons.ProcessFlow.prototype._internalLanes = false;
/**
* Definition for jump over more elements based on the visual design.
*/
sap.suite.ui.commons.ProcessFlow.prototype._jumpOverElements = 5;
/**
* Last node with navigation focus. It is marked when the focus out event
* is handled.
*/
sap.suite.ui.commons.ProcessFlow.prototype._lastNavigationFocusNode = false;
/**
* Set up the cursor classes.
*/
sap.suite.ui.commons.ProcessFlow.prototype._defaultCursorClass = "sapSuiteUiDefaultCursorPF";
if (sap.ui.Device.browser.msie) {
sap.suite.ui.commons.ProcessFlow.prototype._grabCursorClass = "sapSuiteUiGrabCursorIEPF";
sap.suite.ui.commons.ProcessFlow.prototype._grabbingCursorClass = "sapSuiteUiGrabbingCursorIEPF";
} else {
sap.suite.ui.commons.ProcessFlow.prototype._grabCursorClass = "sapSuiteUiGrabCursorPF";
sap.suite.ui.commons.ProcessFlow.prototype._grabbingCursorClass = "sapSuiteUiGrabbingCursorPF";
}
sap.suite.ui.commons.ProcessFlow.prototype._mousePreventEvents = 'contextmenu dblclick';
sap.suite.ui.commons.ProcessFlow.prototype._mouseEvents = 'contextmenu mousemove mouseleave mousedown mouseup mouseenter';
sap.suite.ui.commons.ProcessFlow.prototype._mouseWheelEvent = (sap.ui.Device.browser.mozilla) ? 'DOMMouseScroll MozMousePixelScroll' : 'mousewheel wheel';
sap.suite.ui.commons.ProcessFlow.prototype._headerHasFocus = false;
sap.suite.ui.commons.ProcessFlow.prototype._isInitialZoomLevelNeeded = true;
/**
* Variables used for overflow scrolling.
*/
sap.suite.ui.commons.ProcessFlow.prototype._bDoScroll = !sap.ui.Device.system.desktop || (sap.ui.Device.os.windows && sap.ui.Device.os.version === 8);
sap.suite.ui.commons.ProcessFlow.prototype._scrollStep = 192;
sap.suite.ui.commons.ProcessFlow.prototype._bPreviousScrollForward = false; //Remember the item overflow state.
sap.suite.ui.commons.ProcessFlow.prototype._bPreviousScrollBack = false;
sap.suite.ui.commons.ProcessFlow.prototype._iInitialArrowTop = undefined;
sap.suite.ui.commons.ProcessFlow.prototype._iInitialCounterTop = undefined;
sap.suite.ui.commons.ProcessFlow.prototype._bRtl = false;
sap.suite.ui.commons.ProcessFlow.prototype._arrowScrollable = null;
sap.suite.ui.commons.ProcessFlow.prototype._iTouchStartScrollTop = undefined;
sap.suite.ui.commons.ProcessFlow.prototype._iTouchStartScrollLeft = undefined;
sap.suite.ui.commons.ProcessFlow.prototype._bSetFocusOnce = true;
sap.suite.ui.commons.ProcessFlow.prototype.init = function () {
this._bRtl = sap.ui.getCore().getConfiguration().getRTL();
if (!this._resBundle) {
this._resBundle = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.commons");
}
this._internalLanes = this.getLanes();
this.$("scrollContainer").bind('keydown', jQuery.proxy(this.onkeydown, this));
this.$("scrollContainer").bind('keyup', jQuery.proxy(this.onkeyup, this));
};
/**
* Function destroys all the object components.
*/
sap.suite.ui.commons.ProcessFlow.prototype.exit = function () {
if (this.getNodes()) {
for (var i = 0; i < this.getNodes().length; i++) {
this.getNodes()[i].destroy();
}
this.getNodes = null;
}
if (this._internalLanes) {
for (var i = 0; i < this._internalLanes.length; i++) {
this._internalLanes[i].destroy();
}
this._internalLanes = null;
}
var aInternalConnectionAgg = this.getAggregation("_connections");
if (aInternalConnectionAgg) {
for (var i = 0; i < aInternalConnectionAgg.length; i++) {
aInternalConnectionAgg[i].destroy();
}
aInternalConnectionAgg = null;
}
if (this._oArrowLeft) {
this._oArrowLeft.destroy();
}
if (this._oArrowRight) {
this._oArrowRight.destroy();
}
if (this._resizeRegId) {
sap.ui.core.ResizeHandler.deregister(this._resizeRegId);
}
if (this._internalCalcMatrix) {
delete this._internalCalcMatrix;
this._internalCalcMatrix = null;
}
this.$("scrollContainer").unbind(this._mousePreventEvents, this._handlePrevent);
this.$("scrollContainer").unbind(this._mouseEvents, jQuery.proxy(this._registerMouseEvents, this));
this.$("scrollContainer").unbind(this._mouseWheelEvent, jQuery.proxy(this._registerMouseWheel, this));
this.$("scrollContainer").unbind('keydown', jQuery.proxy(this.onkeydown, this));
this.$("scrollContainer").unbind('scroll', jQuery.proxy(this._onScroll, this));
};
sap.suite.ui.commons.ProcessFlow.prototype.onBeforeRendering = function () {
this.$("scrollContainer").unbind(this._mousePreventEvents, this._handlePrevent);
this.$("scrollContainer").unbind(this._mouseEvents, jQuery.proxy(this._registerMouseEvents, this));
this.$("scrollContainer").unbind(this._mouseWheelEvent, jQuery.proxy(this._registerMouseWheel, this));
this.$("scrollContainer").unbind('keydown', jQuery.proxy(this.onkeydown, this));
this.$("scrollContainer").unbind('scroll', jQuery.proxy(this._onScroll, this));
};
/**
* Function handles the exception based on the business requirements.
*/
sap.suite.ui.commons.ProcessFlow.prototype._handleException = function (exc) {
var textToDisplay = this._resBundle.getText('PF_ERROR_INPUT_DATA');
this.fireOnError({ text: textToDisplay });
jQuery.sap.log.error("Error loading data for the process flow with id : " + this.getId());
if (exc instanceof Array) {
for (var i = 0 ; i < exc.length; i++) {
jQuery.sap.log.error("Detailed description (" + i + ") :" + exc[i]);
}
} else {
jQuery.sap.log.error("Detailed description :" + exc);
}
};
/**
* Function updates the lanes, if more nodes belong to the same lane
* it must check the node consistency, so this is done the first time the consistency check runs.
*
* @private
*/
sap.suite.ui.commons.ProcessFlow.prototype._updateLanesFromNodes = function () {
sap.suite.ui.commons.ProcessFlow.NodeElement.createNodeElementsFromProcessFlowNodes(this.getNodes(), this.getLanes());
var aInternalNodes = this._arrangeNodesByParentChildRelation(this.getNodes());
this._internalLanes = sap.suite.ui.commons.ProcessFlow.NodeElement.updateLanesFromNodes(this.getLanes(), aInternalNodes).lanes;
};
/**
* Function creates the lane header objects.
*
* @private
* @returns {sap.suite.ui.commons.ProcessFlowLaneHeader[]} Array containing lane headers for current ProcessFlow
*/
sap.suite.ui.commons.ProcessFlow.prototype._getOrCreateLaneMap = function () {
if (!this._internalLanes || this._internalLanes.length <= 0) {
this._updateLanesFromNodes();
}
var mapPositionToLane = sap.suite.ui.commons.ProcessFlow.NodeElement.createMapFromLanes(this._internalLanes,
jQuery.proxy(this.ontouchend, this), this._isHeaderMode()).positionMap;
return mapPositionToLane;
};
/**
* This function sorts the internal array of nodes in terms all parents are followed by their children, i.e. no child occurs before his parent in the array.
*
* @private
* @param {sap.suite.ui.commons.ProcessFlowNode[]} aInternalNodes an internal array of nodes to be sorted.
* @returns {sap.suite.ui.commons.ProcessFlowNode[]} aInternalNodes sorted internal array of nodes.
* @since 1.26
*/
sap.suite.ui.commons.ProcessFlow.prototype._arrangeNodesByParentChildRelation = function (aInternalNodes) {
var cInternalNodes = aInternalNodes ? aInternalNodes.length : 0;
var aChildren = [];
var i, j;
// Move parents before their children, if they are in the same lane.
if (cInternalNodes > 0) {
this._setParentForNodes(aInternalNodes);
for (i = 0; i < cInternalNodes; i++) {
aChildren = aInternalNodes[i].getChildren();
if (aChildren) {
var cChildren = aChildren.length;
for (j = 0; j < cChildren; j++) {
aChildren[j] = sap.suite.ui.commons.ProcessFlow._getChildIdByElement(aChildren[j]).toString();
}
}
for (j = 0; j < i; j++) {
if (jQuery.inArray(aInternalNodes[j].getNodeId(), aChildren) > -1 && aInternalNodes[j].getLaneId() === aInternalNodes[i].getLaneId()) {
aInternalNodes.splice(j, 0, aInternalNodes[i]);
aInternalNodes.splice(i + 1, 1);
aInternalNodes = this._arrangeNodesByParentChildRelation(aInternalNodes);
break;
}
}
}
}
return aInternalNodes;
};
/**
* Function creates matrix with positions of nodes and connections. This is
* relative node connection representation and does not cover real page layout.
*
* @private
* @returns The created ProcessFlow control
*/
sap.suite.ui.commons.ProcessFlow.prototype._getOrCreateProcessFlow = function () {
if (!this._internalLanes || this._internalLanes.length <= 0) {
this._updateLanesFromNodes();
}
this.applyNodeDisplayState();
var internalNodes = this.getNodes();
/*tempNodeArray is internal node representation */
var result = sap.suite.ui.commons.ProcessFlow.NodeElement.createNodeElementsFromProcessFlowNodes(internalNodes, this._internalLanes);
var elementForId = result.elementForId;
var elementsForLane = result.elementsForLane;
sap.suite.ui.commons.ProcessFlow.NodeElement.calculateLaneStatePieChart(elementsForLane, this._internalLanes, internalNodes, this);
var calcMatrix = this.calculateMatrix(elementForId);
calcMatrix = this.addFirstAndLastColumn(calcMatrix);
//Convert NodeElements back to ProcessFlowNodes.
for (var i = 0; i < calcMatrix.length; i++) {
for (var j = 0; j < calcMatrix[i].length; j++) {
if (calcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlow.NodeElement) {
calcMatrix[i][j] = elementForId[calcMatrix[i][j].nodeId].oNode;
}
}
}
this._internalCalcMatrix = calcMatrix;
return calcMatrix;
};
/**
* Function applies the changes to the display state based on the requirements.
* If any node is in the highlighted state all others go to the dimmed state.
*
* @public
*/
sap.suite.ui.commons.ProcessFlow.prototype.applyNodeDisplayState = function () {
var aInternalNodes = this.getNodes(),
iNodeCount = aInternalNodes ? aInternalNodes.length : 0,
i = 0;
if (iNodeCount === 0) {
return;
} else {
// First put all the nodes to the regular state - if possible
while (i < iNodeCount) {
aInternalNodes[i]._setRegularState();
i++;
}
// Check for the highlighted or selected node- at least one is required
i = 0;
while ((i < iNodeCount) && !aInternalNodes[i].getHighlighted() && !aInternalNodes[i].getSelected()) {
i++;
}
// If a highlighted or selected node was found, set the others to dimmed state
if (i < iNodeCount) {
i = 0;
while (i < iNodeCount) {
if (!aInternalNodes[i].getHighlighted() && !aInternalNodes[i].getSelected()) {
aInternalNodes[i]._setDimmedState();
}
i++;
}
}
}
};
/**
* Function adds first and last column, which serves for the special header signs. It has to add
* single cell to all internal arrays.
*
* @param calculatedMatrix
* @returns {Object[]} The calculated matrix including first and last column
*/
sap.suite.ui.commons.ProcessFlow.prototype.addFirstAndLastColumn = function (calculatedMatrix) {
if (!calculatedMatrix || calculatedMatrix.length <= 0) {
return [];
}
var originalX = calculatedMatrix.length;
for (var i = 0; i < originalX; i++) {
calculatedMatrix[i].unshift(null);
calculatedMatrix[i].push(null);
}
return calculatedMatrix;
};
/**
* Function calculates a virtual matrix with nodes and connections.
*
* @private
* @param elementForId contains a map of the node id's to node elements
* @throws an array with messages on processing errors
* @returns {Object[]} The composed virtual matrix
*/
sap.suite.ui.commons.ProcessFlow.prototype.calculateMatrix = function (elementForId) {
var internalMatrixCalculation,
oElementInfo,
highestLaneNumber,
rows,
return2DimArray;
//No calculation in case of zero input.
if (!elementForId || (elementForId.length === 0)) {
return [];
}
internalMatrixCalculation = new sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation(this);
internalMatrixCalculation.checkInputNodeConsistency(elementForId);
oElementInfo = internalMatrixCalculation.retrieveInfoFromInputArray(elementForId);
internalMatrixCalculation.resetPositions();
highestLaneNumber = oElementInfo.highestLanePosition + 1;
// Worst case, all children are in the same lane with so many rows.
rows = Object.keys(elementForId).length > 3 ? Object.keys(elementForId).length - 1 : 2;
return2DimArray = internalMatrixCalculation.createMatrix(rows, highestLaneNumber);
for (var i = 0; i < oElementInfo.rootElements.length; i++) {
internalMatrixCalculation.posy = oElementInfo.rootElements[i].lane;
return2DimArray = internalMatrixCalculation.processCurrentElement(oElementInfo.rootElements[i], elementForId, return2DimArray);
}
return2DimArray = internalMatrixCalculation.doubleColumnsInMatrix(return2DimArray);
return2DimArray = internalMatrixCalculation.calculatePathInMatrix(return2DimArray);
return2DimArray = internalMatrixCalculation.removeEmptyLines(return2DimArray);
return return2DimArray;
};
/**
* This is a virtual node holding necessary data to create virtual matrix.
*
* @private
* @param {string} id id of the PF node
* @param {number} oLane lane position of the node
* @param {sap.suite.ui.commons.ProcessFlowNode} oNode a PF node
* @param {Number[]} aNodeParents array of parent id's of the oNode
*/
sap.suite.ui.commons.ProcessFlow.NodeElement = function (id, oLane, oNode, aNodeParents) {
this.nodeId = id;
this.lane = oLane;
this.state = oNode.getState();
this.displayState = oNode._getDisplayState();
this.isProcessed = false;
if (jQuery.isArray(aNodeParents)) {
this.aParent = aNodeParents;
} else {
this.oParent = aNodeParents;
}
this.oNode = oNode;
};
/**
* Another type of the node element constructor.
*
* @private
* @param id node id
* @param lane lane position
* @param oNode reference to a PF node control
* @param aNodeParents reference to the ids of parents of the oNode
* @returns A new node element
*/
sap.suite.ui.commons.ProcessFlow.NodeElement.initNodeElement = function (sId, oLane, oNode, aNodeParents) {
return new sap.suite.ui.commons.ProcessFlow.NodeElement(sId, oLane, oNode, aNodeParents);
};
/**
* Extend the NodeElement object with to String function.
*
* @private
*/
sap.suite.ui.commons.ProcessFlow.NodeElement.prototype = {
toString: function () {
return this.nodeId;
},
containsChildren: function (that) {
if (!that) {
return false;
}
if (!(that instanceof sap.suite.ui.commons.ProcessFlow.NodeElement)) {
return false;
}
if (this.oNode.getChildren() && that.oNode.getChildren() && this.oNode.getChildren().length && that.oNode.getChildren().length) {
for (var i = 0; i < this.oNode.getChildren().length; i++) {
if (that.oNode.getChildren().indexOf(this.oNode.getChildren()[i]) >= 0) {
return true;
}
}
}
return false;
}
};
/**
* Function calculates the state part of the lane from nodes belong to this lane.
*/
sap.suite.ui.commons.ProcessFlow.NodeElement.calculateLaneStatePieChart = function (elementsForLane, laneArray, internalNodes, processFlowObject) {
// Check input parameters.
if (!elementsForLane || !laneArray || !internalNodes) {
return;
}
//First, check if all nodes are in the regular state. If not, only the highlighted ones are taken into calculation.
for (var i = 0; i < internalNodes.length; i++) {
processFlowObject._bHighlightedMode = internalNodes[i].getHighlighted();
if (processFlowObject._bHighlightedMode) {
break;
}
}
var positive = 0;
var negative = 0;
var neutral = 0;
var planned = 0;
for (var i = 0; i < laneArray.length; i++) {
var laneObject = laneArray[i];
var elements = elementsForLane[laneObject.getLaneId()];
//If we do not have nodes, nothing needs to be calculated.
if (!elements) {
continue;
}
positive = 0;
negative = 0;
neutral = 0;
planned = 0;
for (var j = 0; j < elements.length; j++) {
//Maybe ...oNode.getHighlighted() can be used instead of the big selector which needs to be maintained in case of extensions.
if (!processFlowObject._bHighlightedMode ||
(elements[j].oNode._getDisplayState() == sap.suite.ui.commons.ProcessFlowDisplayState.Highlighted ||
elements[j].oNode._getDisplayState() == sap.suite.ui.commons.ProcessFlowDisplayState.HighlightedFocused ||
elements[j].oNode._getDisplayState() == sap.suite.ui.commons.ProcessFlowDisplayState.SelectedHighlighted ||
elements[j].oNode._getDisplayState() == sap.suite.ui.commons.ProcessFlowDisplayState.SelectedHighlightedFocused)) {
switch (elements[j].oNode.getState()) {
case sap.suite.ui.commons.ProcessFlowNodeState.Positive:
positive++;
break;
case sap.suite.ui.commons.ProcessFlowNodeState.Negative:
negative++;
break;
case sap.suite.ui.commons.ProcessFlowNodeState.Planned:
planned++;
break;
case sap.suite.ui.commons.ProcessFlowNodeState.Neutral:
neutral++;
break;
//plannedNegative belong to the Negative group
case sap.suite.ui.commons.ProcessFlowNodeState.PlannedNegative:
negative++;
break;
}
}
} // End of nodes for single lane.
var stateData = [{state: sap.suite.ui.commons.ProcessFlowNodeState.Positive, value:positive},
{state: sap.suite.ui.commons.ProcessFlowNodeState.Negative, value:negative},
{state: sap.suite.ui.commons.ProcessFlowNodeState.Neutral, value:neutral},
{state: sap.suite.ui.commons.ProcessFlowNodeState.Planned, value:planned}];
laneObject.setState(stateData);
}
};
/**
* This function must check and calculate the potentially new lanes.
* This is, because more nodes can be located in the same lane. In this case,
* the new artificial lane is created and positioned just after original one.
*
* @param aProcessFlowLanes the original lane array
* @param aInternalNodes internal nodes
* @returns {Object} Dynamic object containing laines and nodes
*/
sap.suite.ui.commons.ProcessFlow.NodeElement.updateLanesFromNodes = function (aProcessFlowLanes, aInternalNodes) {
var createMapResult = sap.suite.ui.commons.ProcessFlow.NodeElement.createMapFromLanes(aProcessFlowLanes, null, false);
var mapLanesArrayPosition = createMapResult.positionMap;
var mapLanesArrayId = createMapResult.idMap;
var oNode = {};
var tempProcessFlowLanes = aProcessFlowLanes.slice();
var bPotentialNewLaneExists;
var tempLanesPos = {};
var nPos = 0;
for (var i = 0; i < aInternalNodes.length; i++) {
oNode[aInternalNodes[i].getNodeId()] = aInternalNodes[i];
}
for (var i = 0; i < aInternalNodes.length; i++) {
var node = aInternalNodes[i];
var children = node.getChildren() || [];
var positionUp = 1; //Check the move up for the given sublanes of the lane. Every new sublane creation.
var potentialNewLaneId = null;
var potentialNewLane = null;
// Makes plus 1 effect.
for (var j = 0; j < children.length; j++) { // Check the children.
var sChildId = sap.suite.ui.commons.ProcessFlow._getChildIdByElement(children[j]);
var childrenNode = oNode[sChildId];
if (childrenNode && (node.getLaneId() == childrenNode.getLaneId())) {
// Create new lane id and check the lane.
potentialNewLaneId = childrenNode.getLaneId() + positionUp;
potentialNewLane = mapLanesArrayId[potentialNewLaneId];
if (!potentialNewLane) { // If we have the lane already.
var origLaneObject = mapLanesArrayId[node.getLaneId()];
potentialNewLane = sap.suite.ui.commons.ProcessFlow.NodeElement.createNewProcessFlowElement(origLaneObject, potentialNewLaneId, origLaneObject.getPosition() + positionUp);
// Update the maps and output array.
mapLanesArrayId[potentialNewLane.getLaneId()] = potentialNewLane;
tempProcessFlowLanes.splice(potentialNewLane.getPosition(), 0, potentialNewLane);
}
// Assign new lane to children
// The new laneId should not override the old one, therefore it is stored in a hidden property
childrenNode._setMergedLaneId(potentialNewLane.getLaneId());
}
// Move also the assignment of this lane for all children. Otherwise it is bad ...
// so, take the children of current children and move the lane position to the new lane, if necessary
// it is in the case when the lane is the same as was PARENT node. this is important to understand,
// that this children is already moved to new one, so parent lane is compared.
// This is a recursion.
sap.suite.ui.commons.ProcessFlow.NodeElement.changeLaneOfChildren(node.getLaneId(), childrenNode, oNode);
}
// Now we should move all positions up about the number positionUp.
// Also the position map is in wrong state now.
// Now work with all vector, later on we can move only to lanes with higher position than working one.
if (potentialNewLane) {
tempLanesPos = {};
bPotentialNewLaneExists = false;
for (var key in mapLanesArrayPosition) {
if (potentialNewLane.getLaneId() == mapLanesArrayPosition[key].getLaneId()) {
bPotentialNewLaneExists = true;
break;
}
if (parseInt(key) >= potentialNewLane.getPosition()) {
var tempLaneObject = mapLanesArrayPosition[key];
tempLanesPos[tempLaneObject.getPosition() + positionUp] = tempLaneObject;
// tempLaneObject.setPosition(tempLaneObject.getPosition()+positionUp);
}
}
if (!bPotentialNewLaneExists) {
for (var w in tempLanesPos) {
nPos = parseInt(w);
// The moved position should not override the old one, therefore it is stored in a hidden property
tempLanesPos[nPos]._setMergedPosition(nPos);
}
tempLanesPos[potentialNewLane.getPosition()] = potentialNewLane;
for (var v = 0; v < potentialNewLane.getPosition(); v++) {
tempLanesPos[v] = mapLanesArrayPosition[v];
}
mapLanesArrayPosition = tempLanesPos;
}
}
}
return { lanes: tempProcessFlowLanes, nodes: aInternalNodes };
};
sap.suite.ui.commons.ProcessFlow.NodeElement.changeLaneOfChildren = function (origLaneId, currentNode, nodeArray) {
var children = currentNode.getChildren();
if (children) {
for (var i = 0; i < children.length; i++) {
var childId = sap.suite.ui.commons.ProcessFlow._getChildIdByElement(children[i]);
var childrenNode = nodeArray[childId];
if (childrenNode.getLaneId() == origLaneId) {
childrenNode._setMergedLaneId(currentNode.getLaneId());
sap.suite.ui.commons.ProcessFlow.NodeElement.changeLaneOfChildren(origLaneId, childrenNode, nodeArray);
}
}
}
};
sap.suite.ui.commons.ProcessFlow.NodeElement.createNewProcessFlowElement = function (originalElement, newLaneId, newPosition) {
var cloneElement = new sap.suite.ui.commons.ProcessFlowLaneHeader({
laneId: newLaneId,
iconSrc: originalElement.getIconSrc(),
text: originalElement.getText(),
state: originalElement.getState(),
position: newPosition,
zoomLevel: originalElement.getZoomLevel()
});
return cloneElement;
};
/**
* This function creates the map where key = position value - lane element.
*
* @private
* @param {sap.suite.ui.commons.ProcessFlowLaneHeader[]} aProcessFlowLanes array of lanes
* @param {function} fnTapHandler tap handler for the lane header element
* @param {boolean} bHeaderMode should be true, if the process flow is in the header mode
* @returns {Object} Map of lane positions to lane header element control instances
*/
sap.suite.ui.commons.ProcessFlow.NodeElement.createMapFromLanes = function (aProcessFlowLanes, fnTapHandler, bHeaderMode) {
var oLane,
aMapLaneArrayPosition = {},
aMapLaneArrayId = {},
nLanes = aProcessFlowLanes ? aProcessFlowLanes.length : 0,
i = 0;
if (!nLanes) {
return {};
} else {
while (i < nLanes) {
oLane = aProcessFlowLanes[i];
if (oLane instanceof sap.suite.ui.commons.ProcessFlowLaneHeader) {
aMapLaneArrayPosition[oLane.getPosition()] = oLane;
aMapLaneArrayId[oLane.getLaneId()] = oLane;
// Forward the icon click events from the lane header items to the ProcessFlow control.
if (fnTapHandler) {
oLane.attachPress(fnTapHandler);
}
oLane._setHeaderMode(bHeaderMode);
}
i++;
}
return { positionMap: aMapLaneArrayPosition, idMap: aMapLaneArrayId };
}
};
/**
*
* This function transforms from process flow node element into the internal
* node element. The strategy is to work inside algorithm only with internal
* representation.
*
* @private
* @parameter processFlowNodes PF nodes from the controls interface, preprocessed - so they all have a valid (user entered, resp. generated) lane id
* @parameter elementsForLane
* @returns {Object} Element containing elementForId(NodeElement) and elementsForLane (NodeElement[])
*/
sap.suite.ui.commons.ProcessFlow.NodeElement.createNodeElementsFromProcessFlowNodes = function (processFlowNodes, processFlowLanes) {
var aPositionForLaneId = {}, // Map holds the transition between lane id and position.
aElementsForLane = {}, // Holds a map from laneId to array of the elements for given laneId.
aParentsForChild = {},
oNode,
iNodeCount = processFlowNodes ? processFlowNodes.length : 0,
sNodeId,
oLane,
iLaneCount = processFlowLanes ? processFlowLanes.length : 0,
sLaneId,
aPositions = [],
iLanePosition,
aChildren,
sChild,
nChildCount,
i,
j,
aElementForId = {};
if (iNodeCount === 0) {
return { elementForId: {}, elementsForLane: {} };
}
if (iLaneCount === 0) {
throw ["No lane definition although there is a node definition."];
}
i = 0;
while (i < iLaneCount) {
oLane = processFlowLanes[i];
sLaneId = oLane.getLaneId();
iLanePosition = oLane.getPosition();
if (aPositionForLaneId[sLaneId]) {
throw ["The lane with id: " + sLaneId + " is defined at least twice. (Lane error)"];
}
aPositionForLaneId[sLaneId] = iLanePosition;
if (jQuery.inArray(iLanePosition, aPositions) > -1) {
throw ["The position " + iLanePosition + " is defined at least twice. (Lane error)."];
} else {
aPositions.push(iLanePosition);
}
aElementsForLane[sLaneId] = [];
i++;
}
// search for the parent
i = 0;
while (i < iNodeCount) {
oNode = processFlowNodes[i];
if (oNode instanceof sap.suite.ui.commons.ProcessFlowNode) {
sNodeId = oNode.getNodeId();
sLaneId = oNode.getLaneId();
aChildren = oNode.getChildren() || [];
nChildCount = aChildren.length;
j = 0;
while (j < nChildCount) {
sChild = sap.suite.ui.commons.ProcessFlow._getChildIdByElement(aChildren[j]);
aParentsForChild[sChild] = aParentsForChild[sChild] || [];
aParentsForChild[sChild].push(sNodeId);
j++;
}
}
i++;
}
i = 0;
while (i < iNodeCount) {
oNode = processFlowNodes[i];
if (oNode instanceof sap.suite.ui.commons.ProcessFlowNode) {
sNodeId = oNode.getNodeId();
if (!sNodeId) {
throw ["There is a node which has no node id defined. (Title=" + oNode.getTitle() + ") and array position: " + i];
}
sLaneId = oNode.getLaneId();
iLanePosition = aPositionForLaneId[sLaneId];
if (typeof iLanePosition !== 'number') {
throw ["For the node " + sNodeId + " position (lane) is not defined."];
}
if (!aElementForId[sNodeId]) {
aElementForId[sNodeId] = sap.suite.ui.commons.ProcessFlow.NodeElement.initNodeElement(sNodeId, iLanePosition, oNode, aParentsForChild[sNodeId]);
aElementsForLane[sLaneId].push(aElementForId[sNodeId]);
} else {
throw ["The node id " + sNodeId + " is used second time."];
}
}
i++;
}
return { elementForId: aElementForId, elementsForLane: aElementsForLane };
};
/**
* Constructor of the algorithm object.
*
* @private
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation = function (parentControl) {
this.parentControl = parentControl;
this.posx = 0;
this.posy = 0;
this.nodePositions = {};
this.mapChildToNode = {};
};
/**
* Function checks consistency of the node array. It checks,
* if all children defined for the nodes are also presented as the nodes themselves.
*
* @public
* @param elementForId Map of node id's to NodeElements. Expectation is to have at least 1 element there. No check for empty array.
* @throws array of error messages produced during the consistency check
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.checkInputNodeConsistency = function (elementForId) {
var returnArr = [],
j,
sChildId,
nChildCount,
aChildren,
oElement;
//Preparation phase
Object.keys(elementForId).forEach(function (sElementId) {
oElement = elementForId[sElementId];
aChildren = oElement.oNode.getChildren();
nChildCount = aChildren ? aChildren.length : 0;
j = 0;
while (j < nChildCount) {
sChildId = sap.suite.ui.commons.ProcessFlow._getChildIdByElement(aChildren[j]);
if (!elementForId[sChildId]) {
returnArr.push("Node identificator " + sChildId + " used in children definition is not presented as the node itself. Element : " + oElement.nodeId);
}
j++;
}
});
if (returnArr.length > 0) {
throw returnArr;
}
};
/**
* Function resets the positions into initial one to keep new calculation
* without side effects.
*
* @private
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.resetPositions = function () {
this.posx = 0;
this.posy = 0;
delete this.nodePositions;
delete this.mapChildToNode;
this.nodePositions = {};
this.mapChildToNode = {};
};
/**
* Function creates matrix based on the length.
*
* @private
* @param {String} length number of columns
* @returns {Object[]} Array with two dimensions
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.createMatrix = function (length) {
length = parseInt(length, 10);
var arr = new Array(length || 0);
var i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while (i--) {
arr[length - 1 - i] = this.createMatrix.apply(this, args);
}
}
return arr;
};
/**
* Function retrieves the important information from input array.
*
* @private
* @param elementForId map of element id's to elements
* @returns {Object} Element containing highestLanePosition(number) and rootElements (Element[])
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.retrieveInfoFromInputArray = function (elementForId) {
var highestLanePosition = 0,
rootElements = [],
oElement;
Object.keys(elementForId).forEach(function (sElementId) {
oElement = elementForId[sElementId];
if (!oElement.oParent && !oElement.aParent) {
rootElements.push(oElement);
}
if (highestLanePosition < oElement.lane) {
highestLanePosition = oElement.lane;
}
});
return {
'highestLanePosition': highestLanePosition,
'rootElements': rootElements
};
};
/**
* Function doubles the matrix for drawing purposes and it only doubles the columns and add undefined values there.
*
* @private
* @returns {Object[]} Array with doubled colummns
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.doubleColumnsInMatrix = function (currentMatrix) {
var matrixY = 0;
for (var i = 0; i < currentMatrix.length; i++) {
matrixY = matrixY > currentMatrix[i].length ? matrixY : currentMatrix[i].length;
}
var doubleArray = new Array(currentMatrix.length || 0);
for (var i = 0; i < doubleArray.length; i++) {
doubleArray[i] = new Array(matrixY * 2 - 1);
for (var j = 0; j < matrixY; j++) {
if (currentMatrix[i][j]) {
doubleArray[i][2 * j] = currentMatrix[i][j];
}
}
}
return doubleArray;
};
/**
* Function removes empty lines from the matrix.
*
* @returns {Object[]} Array where empty lines have been removed
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.removeEmptyLines = function (originalMatrix) {
//First check the number of valid lines.
var numberOfLines = 0;
for (var i = 0; i < originalMatrix.length; i++) {
for (var j = 0; j < originalMatrix[i].length; j++) {
if (originalMatrix[i][j]) {
numberOfLines++;
break;
}
}
}
var returnArray = this.createMatrix(numberOfLines, originalMatrix[0].length);
for (var i = 0; i < numberOfLines; i++) {
for (var j = 0; j < originalMatrix[i].length; j++) {
returnArray[i][j] = null; // everything is at least null
if (originalMatrix[i][j]) {
returnArray[i][j] = originalMatrix[i][j];
}
}
}
return returnArray;
};
/**
* Creates the matrix where the nodes are already positioned correctly.
*
* @public
* @param currentElement actually processed element
* @param elementForId map of all the available elements
* @param return2DimArray the updated virtual matrix
* @returns The updated virtual matrix
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.processCurrentElement = function (currentElement, elementForId, return2DimArray) {
var aElementsChildIds,
aElementsChildren,
that = this,
bNoChildInUpperRow = true, // If there is a child already drawn in an upper row, it is required to move to the next line
bMoveToNextLine = true; // This is the check for repeated parent-child relationship. The childrenArr is not empty but
// in fact it is required to move to the next line.
if (currentElement.isProcessed) {
return return2DimArray;
}
this.nodePositions[currentElement.nodeId] = {
'c': currentElement,
'x': this.posx,
'y': this.posy * 2
};
return2DimArray[this.posx][this.posy++] = currentElement;
aElementsChildIds = currentElement.oNode.getChildren();
currentElement.isProcessed = true;
aElementsChildren = this.sortBasedOnChildren(aElementsChildIds, elementForId);
if (aElementsChildren) {
aElementsChildren.forEach(function (oChild) {
if (!oChild.isProcessed) {
bMoveToNextLine = false;
while (that.posy < oChild.lane) {
return2DimArray[that.posx][that.posy++] = null;
}
return2DimArray = that.processCurrentElement(oChild, elementForId, return2DimArray);
}
else {
// Child has already been processed, which means there is a connection pointing to the right.
// Therefore it is necessary to move to the next line so that the next child element is not drawn in the connection.
if (bNoChildInUpperRow && bMoveToNextLine) {
that.posx++;
bNoChildInUpperRow = false;
}
}
});
}
if (!aElementsChildIds || bMoveToNextLine) {
// Check if we moved already to the next line in the forEach loop
if (bNoChildInUpperRow) {
this.posx++;
}
this.posy = 0;
}
return return2DimArray;
};
/**
* Sort based on the child proximity. If 2 children has some common children they get next to each other.
*
* @private
* @param aElementsChildIds child ids of the currently processed node
* @param elementForId contains a map of the node id's to node elements
* @returns {sap.suite.ui.commons.ProcessFlow.NodeElement} Array containing sorted child elements (first sort by lanes, than the elements having the same children gets next to each other)
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.sortBasedOnChildren = function (aElementsChildIds, elementForId) {
var oElementsForLane = {},
aElements,
laneId = null,
aLaneIds,
aNmbrChildren,
bNmbrChildren,
finalSortedArray = [],
aSingleLaneContent,
aSingleContent,
oProcessedChildElement;
if (aElementsChildIds) {
aElementsChildIds.forEach(function (oChildId) {
var sChildId = sap.suite.ui.commons.ProcessFlow._getChildIdByElement(oChildId);
aElements = oElementsForLane[elementForId[sChildId].lane];
if (!aElements) {
oElementsForLane[elementForId[sChildId].lane] = aElements = [];
}
aElements.push(elementForId[sChildId]);
});
} else {
return [];
}
aLaneIds = [];
for (laneId in oElementsForLane) {
aLaneIds.push(laneId);
//Sort the Nodes (related to currend lane) descending by amount of children.
oElementsForLane[laneId].sort(function (a, b) {
//Lane needs not to be checked.
//If it is the same one, check for the same children.
//In this case return 0
aNmbrChildren = (a.oNode.getChildren() || []).length;
bNmbrChildren = (b.oNode.getChildren() || []).length;
return bNmbrChildren - aNmbrChildren;
});
}
//Sort the Lanes descending by laneId.
aLaneIds = aLaneIds.sort(function (a, b) {
return b - a;
});
//Now we have in aLaneIds the lane orderd (descending by laneId)
//Based on that we take from map the elements for the lanes.
//Now order based on the children.
aLaneIds.forEach(function (laneId) {
aSingleLaneContent = oElementsForLane[laneId];
if (aSingleLaneContent.length > 1) {
aSingleContent = [];
//We iterate through all the children and
//put all the nodes having at least 1 common child next to each other.
oProcessedChildElement = aSingleLaneContent.shift();
while (oProcessedChildElement) {
if (aSingleContent.indexOf(oProcessedChildElement) < 0) {
aSingleContent.push(oProcessedChildElement);
}
aSingleLaneContent.forEach(function (oSiblingElement) {
if (oProcessedChildElement.containsChildren(oSiblingElement)) {
aSingleContent.push(oSiblingElement);
}
});
oProcessedChildElement = aSingleLaneContent.shift();
}
finalSortedArray = finalSortedArray.concat(aSingleContent);
} else {
finalSortedArray = finalSortedArray.concat(aSingleLaneContent);
}
});
return finalSortedArray;
};
/**
* Function calculates the connection and writes into the virtual matrix. It gets the matrix plus
* parent children relationship.
*
* @param OriginalMatrix the matrix with the setup of nodes
* @returns {Object[]} The matrix updated with the calculated paths
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.calculatePathInMatrix = function (originalMatrix) {
var currentElement = null;
for (var key in this.nodePositions) {
if (this.nodePositions.hasOwnProperty(key)) {
currentElement = this.nodePositions[key];
var aChildren = currentElement.c.oNode.getChildren();
for (var i = 0; aChildren && i < aChildren.length; i++) {
var sChildId = sap.suite.ui.commons.ProcessFlow._getChildIdByElement(aChildren[i]);
var positionChildrenObject = this.nodePositions[sChildId];
originalMatrix = this.calculateSingleNodeConnection(currentElement,
positionChildrenObject, currentElement.x, currentElement.y,
positionChildrenObject.x, positionChildrenObject.y, originalMatrix);
}
}
}
return originalMatrix;
};
/**
* Function based on the parent children position calculated the path from parent to children. The idea is like following
* go from parent half right and use next connection column to go up or down. Afterwards on the line with children go
* horizontal.
*
* @param nodeParent
* @param nodeChildren
* @param parentX
* @param parentY
* @param childrenX
* @param childrenY
* @param originalMatrix
* @returns {Object[]} The original Matrix
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.calculateSingleNodeConnection = function (
nodeParent, nodeChildren, parentX, parentY, childrenX, childrenY, originalMatrix) {
var hor = childrenY - parentY;
var ver = childrenX - parentX;
if (hor < 0) {
var errMsg = ["Problem with negative horizontal movement",
"Parent node is " + nodeParent.c.toString(),
"Children node is " + nodeChildren.c.toString(),
"Coordinates : '" + parentX + "','" + parentY + "','" + childrenX + "','" + childrenY + "'"];
throw errMsg;
} else if (ver <= -1) {
// Half left and up
var bNormalHorizontalLinePossible = this.checkIfHorizontalLinePossible(originalMatrix, childrenX, parentY + 2, childrenY);
var yPosition = childrenY - 1;
if (bNormalHorizontalLinePossible) {
yPosition = parentY + 1;
}
var xPosition = parentX;
if (bNormalHorizontalLinePossible) {
xPosition = childrenX;
}
originalMatrix[parentX][yPosition] = this.createConnectionElement(
originalMatrix[parentX][yPosition], sap.suite.ui.commons.ProcessFlow.cellEdgeConstants.LU,
nodeParent, nodeChildren, false);
//Going up to the children.
originalMatrix = this.writeVerticalLine(originalMatrix, parentX, childrenX, yPosition, nodeParent, nodeChildren);
originalMatrix[childrenX][yPosition] =
this.createConnectionElement(originalMatrix[childrenX][yPosition],
sap.suite.ui.commons.ProcessFlow.cellEdgeConstants.UR, nodeParent,
nodeChildren, (yPosition == childrenY - 1));
//Pure right.
var startY = parentY + 2;
var endY = childrenY;
if (!bNormalHorizontalLinePossible) {
startY = parentY + 1;
endY = yPosition + 1;
}
originalMatrix = this.writeHorizontalLine(originalMatrix, xPosition, startY, endY, nodeParent, nodeChildren);
} else if (ver === 0) {
originalMatrix = this.writeHorizontalLine(originalMatrix, parentX, parentY + 1, childrenY, nodeParent, nodeChildren);
} else if (ver === 1) {
//1 row down and do horizontal line.
//Half and down.
originalMatrix[parentX][parentY + 1] = this.createConnectionElement(originalMatrix[parentX][parentY + 1],
sap.suite.ui.commons.ProcessFlow.cellEdgeConstants.LD, nodeParent,
nodeChildren, false);
//Down and right.
originalMatrix[childrenX][parentY + 1] = this.createConnectionElement(originalMatrix[childrenX][parentY + 1],
sap.suite.ui.commons.ProcessFlow.cellEdgeConstants.DR, nodeParent,
nodeChildren, (parentY + 1) === (childrenY - 1));
//Horizontal line to the target.
originalMatrix = this.writeHorizontalLine(originalMatrix, childrenX, parentY + 2, childrenY, nodeParent, nodeChildren);
} else { //ver > 1
//Go down until children and do horizontal line.
//Half left and down.
originalMatrix[parentX][parentY + 1] = this.createConnectionElement(originalMatrix[parentX][parentY + 1],
sap.suite.ui.commons.ProcessFlow.cellEdgeConstants.LD, nodeParent,
nodeChildren, false);
originalMatrix = this.writeVerticalLine(originalMatrix, childrenX, parentX, parentY + 1, nodeParent, nodeChildren);
//Half down and right.
originalMatrix[childrenX][parentY + 1] = this.createConnectionElement(originalMatrix[childrenX][parentY + 1],
sap.suite.ui.commons.ProcessFlow.cellEdgeConstants.DR, nodeParent,
nodeChildren, (parentY + 1) === (childrenY - 1));
originalMatrix = this.writeHorizontalLine(originalMatrix, childrenX, parentY + 2, childrenY, nodeParent, nodeChildren);
}
return originalMatrix;
};
/**
* Write vertical line from firstrow to lastrow on the column position.
*
* @private
* @returns {Object[]} The original matrix containing vertical line connections
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.writeVerticalLine = function (originalMatrix, firstRow, lastRow, column, nodeParent, nodeChildren) {
for (var j = firstRow - 1; j > lastRow; j--) {
originalMatrix[j][column] = this.createConnectionElement(originalMatrix[j][column],
sap.suite.ui.commons.ProcessFlow.cellEdgeConstants.DU, nodeParent,
nodeChildren, false);
}
return originalMatrix;
};
/**
* Checks if the horizontal line is possible.
*
* @private
* @param originalMatrix
* @param row
* @param firstColumn
* @param lastColumn
* @returns {boolean} Function return true, if the path is free, otherwise false
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.checkIfHorizontalLinePossible = function (
originalMatrix, row, firstColumn, lastColumn) {
var bLinePossible = true;
for (var i = firstColumn; i < lastColumn; i++) {
if (originalMatrix[row][i] instanceof sap.suite.ui.commons.ProcessFlow.NodeElement) {
bLinePossible = false;
break;
}
}
return bLinePossible;
};
/**
* Function calculated and writes horizontal line.
*
* @param originalMatrix matrix to write to
* @param row the horizontal position
* @param firstColumn where to start
* @param lastColumn where to stop
* @param nodeParent definition of initial node
* @param nodeChildren definition of target node
* @returns {Object[]} The original Matrix including the horizontal lines
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.writeHorizontalLine = function (
originalMatrix, row, firstColumn, lastColumn, nodeParent, nodeChildren) {
var bPotentialArrow = (row == nodeChildren.x);
//No arrow, no last line ... somewhere else will be (up and right).
if (!bPotentialArrow) {
lastColumn--;
}
for (var i = firstColumn; i < lastColumn; i++) {
originalMatrix[row][i] =
this.createConnectionElement(originalMatrix[row][i], sap.suite.ui.commons.ProcessFlow.cellEdgeConstants.LR, nodeParent, nodeChildren, (i == (lastColumn - 1)) && bPotentialArrow);
}
return originalMatrix;
};
/**
* Function adds new connection element to the cell in the matrix. It is an additive approach where during the
* drawing phase all the connections in one cell will be joined together.
*
* @private
* @param originalConnectionValue
* @param addStringValue
* @param initialNode
* @param targetNode
* @param bArrowRequired
* @returns {sap.suite.ui.commons.ProcessFlowConnection} The connection element
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype.createConnectionElement = function (originalConnectionValue, addStringValue, initialNode, targetNode, bArrowRequired) {
var tempOriginalConnectionValue = originalConnectionValue;
if (!tempOriginalConnectionValue) {
tempOriginalConnectionValue = new sap.suite.ui.commons.ProcessFlowConnection();
}
if (tempOriginalConnectionValue instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var displayState = this._calculateConnectionDisplayStateBySourceAndTargetNode(initialNode.c.oNode, targetNode.c.oNode);
var objConn = {
flowLine: addStringValue,
targetNodeState: targetNode.c.state,
displayState: displayState,
hasArrow: bArrowRequired
};
tempOriginalConnectionValue.addConnectionData(objConn);
}
return tempOriginalConnectionValue;
};
/**
* Calculates the correct display state for a connection based on the source and the target node.
*
* @private
* @param {sap.suite.ui.commons.ProcessFlowNode} sourceNode for calculation
* @param {sap.suite.ui.commons.ProcessFlowNode} targetNode for calculation
* @returns {sap.suite.ui.commons.ProcessFlowDisplayState} The resulting displayState
*/
sap.suite.ui.commons.ProcessFlow.InternalMatrixCalculation.prototype._calculateConnectionDisplayStateBySourceAndTargetNode = function (sourceNode, targetNode) {
var bSourceIsHighlighted = sourceNode.getHighlighted();
var bSourceIsSelected = sourceNode.getSelected();
var bSourceIsDimmed = sourceNode._getDimmed();
var bTargetIsHighlighted = targetNode.getHighlighted();
var bTargetIsSelected = targetNode.getSelected();
var bTargetIsDimmed = targetNode._getDimmed();
var displayState = sap.suite.ui.commons.ProcessFlowDisplayState.Regular;
if (bSourceIsSelected && bTargetIsSelected) {
displayState = sap.suite.ui.commons.ProcessFlowDisplayState.Selected;
} else if (bSourceIsHighlighted && bTargetIsHighlighted) {
displayState = sap.suite.ui.commons.ProcessFlowDisplayState.Highlighted;
} else if ((bSourceIsDimmed || bTargetIsDimmed) ||
bSourceIsHighlighted && bTargetIsSelected ||
bSourceIsSelected && bTargetIsHighlighted) {
//If the node is not in state dimmed and no direct connection between select/highlighted nodes is available, set dimmed state.
displayState = sap.suite.ui.commons.ProcessFlowDisplayState.Dimmed;
}
return displayState;
};
sap.suite.ui.commons.ProcessFlow.cellEdgeConstants = {
'LU': 'tl', //It is going from Left to the middle and afterwards Up = top left.
'LD': 'lb', //It is going from Left to the middle and afterwards Down = left bottom.
'DU': 'tb', //It is going from Down to the middle and afterwards Up = top bottom.
'LR': 'rl', //It is going from Left to the middle and afterwards Right = right left.
'DR': 'rt', //It is going from Down to the middle and afterwards Right = right top.
'UR': 'rb' //It is going from Up to the middle and afterwards Right = right bottom.
};
sap.suite.ui.commons.ProcessFlow.prototype.addNode = function (addNode) {
return this.addAggregation("nodes", addNode, false);
};
/**
* Function sets the zoom level.
*
* @param zoomLevel. this is a new zoom level of the type sap.suite.ui.commons.ProcessFlowZoomLevel
*/
sap.suite.ui.commons.ProcessFlow.prototype.setZoomLevel = function (zoomLevel) {
var $scrollContainer = this.$("scrollContainer");
var oScrollContainerContextOld;
var oScrollContainerContextNew;
if ($scrollContainer.context) {
oScrollContainerContextOld = {
scrollWidth: $scrollContainer.context.scrollWidth,
scrollHeight: $scrollContainer.context.scrollHeight,
scrollLeft: $scrollContainer.context.scrollLeft,
scrollTop: $scrollContainer.context.scrollTop
};
oScrollContainerContextNew = oScrollContainerContextOld;
if (this._zoomLevel === zoomLevel) {
this._isInitialZoomLevelNeeded = false;
return;
}
}
if (!(zoomLevel in sap.suite.ui.commons.ProcessFlowZoomLevel)) { // Enumeration
this._handleException("\"" + zoomLevel + "\" is not a valid entry of the enumeration for property zoom level of ProcessFlow");
return;
}
this._zoomLevel = zoomLevel;
//When setting the initial zoomlevel, invalidate() has to be called,
//because the method call comes from onAfterRendering() and to call the rerender() is not allowed.
if (this._isInitialZoomLevelNeeded) {
this._isInitialZoomLevelNeeded = false;
this.invalidate();
//In all other cases, the rerender() has to be called, so that the offset can be set afterwards.
} else {
this.rerender();
}
if (oScrollContainerContextOld) {
//Set the grab cursor class in case for touch devices
if (sap.ui.Device.support.touch || jQuery.sap.simulateMobileOnDesktop) {
var iHeight = parseInt(this.$("scrollContainer").css("height").slice(0, -2), 10);
var iWidth = parseInt(this.$("scrollContainer").css("width").slice(0, -2), 10);
var iScrollHeight = this.$("scrollContainer")[0].scrollHeight;
var iScrollWidth = this.$("scrollContainer")[0].scrollWidth;
if (this.getScrollable() && (iScrollHeight > iHeight || iScrollWidth > iWidth)) {
this._switchCursors(this.$("scrollContainer"), this._defaultCursorClass, this._grabCursorClass);
this.$("scrollContainer").css("overflow", "auto");
}
}
//Sets the scroll offset to the scrollContainer.
$scrollContainer = this.$("scrollContainer");
oScrollContainerContextNew = this._getScrollContainerOnZoomChanged(oScrollContainerContextOld, $scrollContainer);
$scrollContainer.scrollLeft(oScrollContainerContextNew.scrollLeft);
$scrollContainer.scrollTop(oScrollContainerContextNew.scrollTop);
this._adjustAndShowArrow();
//Avoids not setting the focus on clickable elements.
if (this._isFocusChanged) {
this._setFocusToNode();
this._isFocusChanged = false;
}
}
};
/**
* Function returns current zoom level.
*
* @returns {String} The zoomLevel
*/
sap.suite.ui.commons.ProcessFlow.prototype.getZoomLevel = function () {
return this._zoomLevel;
};
/**
* Function sets new zoom level with smaller level of details. Having the least detail view it stays as it is.
*
* @returns {String} The updated zoomLevel
*/
sap.suite.ui.commons.ProcessFlow.prototype.zoomOut = function () {
var currentZoomLevel = this.getZoomLevel();
var newLevel = currentZoomLevel;
switch (currentZoomLevel) {
case (sap.suite.ui.commons.ProcessFlowZoomLevel.One):
newLevel = sap.suite.ui.commons.ProcessFlowZoomLevel.Two;
break;
case (sap.suite.ui.commons.ProcessFlowZoomLevel.Two):
newLevel = sap.suite.ui.commons.ProcessFlowZoomLevel.Three;
break;
case (sap.suite.ui.commons.ProcessFlowZoomLevel.Three):
newLevel = sap.suite.ui.commons.ProcessFlowZoomLevel.Four;
break;
}
this.setZoomLevel(newLevel);
return this.getZoomLevel();
};
/**
* Function sets new zoom level with higher level of details. Having max details it stays as it is.
*
* @returns {String} The updated zoomLevel
*/
sap.suite.ui.commons.ProcessFlow.prototype.zoomIn = function () {
var currentZoomLevel = this.getZoomLevel();
var newLevel = currentZoomLevel;
switch (currentZoomLevel) {
case (sap.suite.ui.commons.ProcessFlowZoomLevel.Four):
newLevel = sap.suite.ui.commons.ProcessFlowZoomLevel.Three;
break;
case (sap.suite.ui.commons.ProcessFlowZoomLevel.Three):
newLevel = sap.suite.ui.commons.ProcessFlowZoomLevel.Two;
break;
case (sap.suite.ui.commons.ProcessFlowZoomLevel.Two):
newLevel = sap.suite.ui.commons.ProcessFlowZoomLevel.One;
break;
}
this.setZoomLevel(newLevel);
return this.getZoomLevel();
};
/**
* Updates the model and rerenders the control.
*/
sap.suite.ui.commons.ProcessFlow.prototype.updateModel = function () {
//reset nodes' laneIds for merged lanes
var aNodes = this.getNodes();
var that = this;
aNodes.forEach(function(that){
that._mergedLaneId = false;
})
// reset lanes' position that was created for merged lanes
var aLanes = this.getLanes();
var that = this;
aLanes.forEach(function(that){
that._mergedLanePosition = false;
})
//Initialize internalLanes so that they get recalculated from the new nodes.
this._internalLanes = [];
if (this._isHeaderMode()) {
var laneModel = this.getBindingInfo("lanes");
this.getModel(laneModel.model).refresh();
}
else {
var nodeModel = this.getBindingInfo("nodes");
this.getModel(nodeModel.model).refresh();
}
this.rerender();
};
/**
* Updates the nodes and rerenders the control.
*/
sap.suite.ui.commons.ProcessFlow.prototype.updateNodesOnly = function () {
var nodeModel = this.getBindingInfo("nodes");
this.getModel(nodeModel.model).refresh();
this.rerender();
};
/**
* Function returns the nodeId of the node which is focused.
*
* @returns {String} The id of focused node
*/
sap.suite.ui.commons.ProcessFlow.prototype.getFocusedNode = function () {
if (this._lastNavigationFocusNode.sId) {
return this._lastNavigationFocusNode.sId;
}
};
/**
* Handles the ontouched event.
*
* @private
* @param {sap.ui.base.Event} oEvent
*/
sap.suite.ui.commons.ProcessFlow.prototype.ontouchend = function (oEvent) {
if (oEvent.target && oEvent.target.id.indexOf("arrowScroll") != -1) {
this._onArrowClick(oEvent);
}
else {
if (!sap.ui.Device.support.touch && !jQuery.sap.simulateMobileOnDesktop) {
this.onAfterRendering();
} else {
this._adjustAndShowArrow();
}
if (oEvent === null || oEvent.oSource === undefined) {
return false;
}
oEvent.preventDefault();
if (this && this._isHeaderMode()) {
//Reset lanes as they could be redefined completely in headerPress Event - also necessary for merged lanes.
this._internalLanes = [];
this.fireHeaderPress(this);
}
}
return false;
};
/**
* Checks if ProcessFlow is in header mode.
*
* @returns {Boolean} Value which describes if ProcessFlow is in header mode
*/
sap.suite.ui.commons.ProcessFlow.prototype._isHeaderMode = function () {
var aNodes = this.getNodes();
return !aNodes || (aNodes.length === 0);
};
/**
* Switch cursors for scrollable/non-scrollable content.
*
* @private
* @param {object} $scrollContainer the affected scroll container (jQuery object)
* @param {String} sCursorClassFrom class containing the original cursor definition
* @param {String} sCursorClassTo class containing the new cursor definition
* @since 1.22
*/
sap.suite.ui.commons.ProcessFlow.prototype._switchCursors = function ($scrollContainer, sCursorClassFrom, sCursorClassTo) {
if ($scrollContainer.hasClass(sCursorClassFrom)) {
$scrollContainer.removeClass(sCursorClassFrom);
}
if (!$scrollContainer.hasClass(sCursorClassTo)) {
$scrollContainer.addClass(sCursorClassTo);
}
};
/**
* Clear the mouse handlers for the scrolling functionality.
*
* @private
* @since 1.22
*/
sap.suite.ui.commons.ProcessFlow.prototype._clearHandlers = function ($scrollContainer) {
$scrollContainer.bind(this._mousePreventEvents, jQuery.proxy(this._handlePrevent, this));
};
sap.suite.ui.commons.ProcessFlow.prototype._handlePrevent = function (oEvent) {
if (oEvent && !oEvent.isDefaultPrevented()) {
oEvent.preventDefault();
}
if (oEvent && !oEvent.isPropagationStopped()) {
oEvent.stopPropagation();
}
if (oEvent && !oEvent.isImmediatePropagationStopped()) {
oEvent.stopImmediatePropagation();
}
};
/**
* Standard method called after the control rendering.
*/
sap.suite.ui.commons.ProcessFlow.prototype.onAfterRendering = function () {
var bScrollable = false,
$content = this.$("scroll-content"),
iHeight,
iWidth,
iScrollWidth,
iScrollHeight;
//Initializes scrolling.
this._checkOverflow(this.getDomRef("scrollContainer"), this.$());
this.nCursorXPosition = 0;
this.nCursorYPosition = 0;
if ($content && $content.length) {
//Sets PF node icon cursors, because these are unfortunately set as inline styles, so they cannot be overriden by applying a CSS class.
this.$("scrollContainer").find('.sapSuiteUiCommonsProcessFlowNode .sapUiIcon').css("cursor", "inherit");
if (this.getScrollable()) {
iHeight = parseInt(this.$("scrollContainer").css("height").slice(0, -2), 10);
iWidth = parseInt(this.$("scrollContainer").css("width").slice(0, -2), 10);
iScrollHeight = $content[0].scrollHeight;
iScrollWidth = $content[0].scrollWidth;
if (iScrollHeight <= iHeight && iScrollWidth <= iWidth) {
this._clearHandlers(this.$("scrollContainer"));
//No scrolling makes sense, so clean up the mouse handlers and switch the cursors.
this._switchCursors(this.$("scrollContainer"), this._grabCursorClass, this._defaultCursorClass);
} else {
this._switchCursors(this.$("scrollContainer"), this._defaultCursorClass, this._grabCursorClass);
bScrollable = true;
}
} else {
this._clearHandlers(this.$("scrollContainer"));
this._switchCursors(this.$("scrollContainer"), this._grabCursorClass, this._defaultCursorClass);
$content.css("position", "static");
}
if (bScrollable) {
//Initialize top margin of arrow and counter.
if (!this._iInitialArrowTop || !this._iInitialCounterTop) {
this._iInitialArrowTop = parseInt(this.$("arrowScrollRight").css("top"), 10);
this._iInitialCounterTop = parseInt(this.$("counterRight").css("top"), 10);
}
if (sap.ui.Device.os.windows && sap.ui.Device.system.combi && sap.ui.Device.browser.chrome) {
//Win8 Surface: Chrome.
this.$("scrollContainer").bind(this._mouseEvents, jQuery.proxy(this._registerMouseEvents, this));
this.$("scrollContainer").css("overflow", "auto");
} else if (sap.ui.Device.os.windows && sap.ui.Device.system.combi && sap.ui.Device.browser.msie && (sap.ui.Device.browser.version > 9)) {
//Win8 Surface: IE 10 and higher.
this.$("scrollContainer").bind(this._mouseEvents, jQuery.proxy(this._registerMouseEvents, this));
this.$("scrollContainer").css("overflow", "auto");
this.$("scrollContainer").css("-ms-overflow-style", "none");
} else if (!sap.ui.Device.support.touch && !jQuery.sap.simulateMobileOnDesktop) {
// Desktop
this.$("scrollContainer").bind(this._mouseEvents, jQuery.proxy(this._registerMouseEvents, this));
} else {
// Mobile: use native scrolling.
this._clearHandlers(this.$("scrollContainer"));
this.$("scrollContainer").css("overflow", "auto");
}
} else { //Not scrollable ProcessFlow: Set overflow for chevron navigation anyway.
if (this._bDoScroll) {
//Is Not Desktop OR Is Win8.
this.$("scrollContainer").css("overflow", "auto");
} else {
this.$("scrollContainer").css("overflow", "hidden");
}
}
if (this.getWheelZoomable() && sap.ui.Device.system.desktop && !this._isHeaderMode()) {
this.$("scrollContainer").bind(this._mouseWheelEvent, jQuery.proxy(this._registerMouseWheel, this));
}
if (this._bDoScroll) {
//Bind scroll event for mobile.
this.$("scrollContainer").bind("scroll", jQuery.proxy(this._onScroll, this));
}
this._resizeRegId = sap.ui.core.ResizeHandler.register(this, jQuery.proxy(sap.suite.ui.commons.ProcessFlow.prototype._onResize, this));
if (this._isInitialZoomLevelNeeded) {
this._initZoomLevel();
}
//Sets the focus to the next node if PF was in headers mode before rerendering.
if (this._headerHasFocus) {
this._headerHasFocus = false;
var $nodeToFocus = this.$("scroll-content").children().children().children(1).children("td[tabindex='0']").first().children();
var oNodeToFocus = sap.ui.getCore().byId($nodeToFocus[0].id);
this._changeNavigationFocus(null, oNodeToFocus);
}
}
};
sap.suite.ui.commons.ProcessFlow.prototype._initZoomLevel = function () {
//Set initial ZoomLevel according to ProcessFlow container size.
//Breakpoints: until 599px = Level 4 / 600px-1023px = Level 3 / from 1024px = Level 2.
if (this.$()) {
var iWidth = this.$().width();
if (iWidth) {
if (iWidth < sap.m.ScreenSizes.tablet) {
this.setZoomLevel(sap.suite.ui.commons.ProcessFlowZoomLevel.Four);
} else if (iWidth < sap.m.ScreenSizes.desktop) {
this.setZoomLevel(sap.suite.ui.commons.ProcessFlowZoomLevel.Three);
} else {
this.setZoomLevel(sap.suite.ui.commons.ProcessFlowZoomLevel.Two);
}
}
}
};
sap.suite.ui.commons.ProcessFlow.prototype._registerMouseWheel = function (oEvent) {
var oDirection = oEvent.originalEvent.wheelDelta || -oEvent.originalEvent.detail;
if (oDirection === 0) {
//for IE only
oDirection = -oEvent.originalEvent.deltaY;
}
var that = this;
if (oEvent && !oEvent.isDefaultPrevented()) {
oEvent.preventDefault();
oEvent.originalEvent.returnValue = false;
}
var waitTime = 300;
var doNotListen = function () {
var diff = new Date() - that._wheelTimestamp;
if (diff < waitTime) {
that._wheelTimeout = jQuery.sap.delayedCall(waitTime - diff, that, doNotListen);
} else {
that._wheelTimeout = null;
that._wheelCalled = false;
}
};
if (!that._wheelCalled) {
that._wheelCalled = true;
if (oDirection < 0) {
this._isFocusChanged = true;
that.zoomOut();
} else {
this._isFocusChanged = true;
that.zoomIn();
}
}
if (!that._wheelTimeout) {
that._wheelTimestamp = new Date();
that._wheelTimeout = jQuery.sap.delayedCall(waitTime, that, doNotListen);
}
if (oEvent && !oEvent.isPropagationStopped()) {
oEvent.stopPropagation();
}
if (oEvent && !oEvent.isImmediatePropagationStopped()) {
oEvent.stopImmediatePropagation();
}
};
/**
* @private
*/
sap.suite.ui.commons.ProcessFlow.prototype._registerMouseEvents = function (oEvent) {
if (oEvent && !oEvent.isDefaultPrevented()) {
oEvent.preventDefault();
}
switch (oEvent.type) {
case 'mousemove':
if (this.$("scrollContainer").hasClass(this._grabbingCursorClass)) {
if (sap.ui.getCore().getConfiguration().getRTL()) {
this.$("scrollContainer").scrollLeftRTL(this.nCursorXPosition - oEvent.pageX);
} else {
this.$("scrollContainer").scrollLeft(this.nCursorXPosition - oEvent.pageX);
}
this.$("scrollContainer").scrollTop(this.nCursorYPosition - oEvent.pageY);
this._adjustAndShowArrow();
}
break;
case 'mousedown':
this._switchCursors(this.$("scrollContainer"), this._defaultCursorClass, this._grabbingCursorClass);
if (sap.ui.getCore().getConfiguration().getRTL()) {
this.nCursorXPosition = this.$("scrollContainer").scrollLeftRTL() + oEvent.pageX;
} else {
this.nCursorXPosition = this.$("scrollContainer").scrollLeft() + oEvent.pageX;
}
this.nCursorYPosition = this.$("scrollContainer").scrollTop() + oEvent.pageY;
if (sap.ui.Device.system.combi) {
//For Win8 surface no touchstart event is fired, but the mousedown event instead do initialization here
this._iTouchStartScrollLeft = this.$("scrollContainer").scrollLeft();
if (this.getScrollable()) {
this._iTouchStartScrollTop = this.$("scrollContainer").scrollTop();
}
}
break;
case 'mouseup':
this._switchCursors(this.$("scrollContainer"), this._grabbingCursorClass, this._grabCursorClass);
break;
case 'mouseleave':
this.$("scrollContainer").removeClass(this._grabbingCursorClass);
this.$("scrollContainer").removeClass(this._grabCursorClass);
this.$("scrollContainer").addClass(this._defaultCursorClass);
break;
case 'mouseenter':
this.$("scrollContainer").removeClass(this._defaultCursorClass);
if (oEvent.buttons === null) {
if (oEvent.which === 1) {
this.$("scrollContainer").addClass(this._grabbingCursorClass);
} else {
this.$("scrollContainer").addClass(this._grabCursorClass);
}
} else {
if (oEvent.buttons === 0) {
this.$("scrollContainer").addClass(this._grabCursorClass);
} else if (oEvent.buttons === 1) {
this.$("scrollContainer").addClass(this._grabbingCursorClass);
}
}
break;
}
//Check if the event was triggered by a click on a Connection Label and allow the propagation of the event.
//Otherwise default click event in Connection Label is interrupted.
if (oEvent.target && oEvent.target.parentElement && oEvent.target.parentElement.parentElement &&
oEvent.target.parentElement.parentElement instanceof sap.suite.ui.commons.ProcessFlowConnectionLabel) {
if (oEvent && !oEvent.isPropagationStopped()) {
oEvent.stopPropagation();
}
if (oEvent && !oEvent.isImmediatePropagationStopped()) {
oEvent.stopImmediatePropagation();
}
}
};
/**
* Control resize handler for setting the cursor type/scroll setup.
*
* @private
*/
sap.suite.ui.commons.ProcessFlow.prototype._onResize = function () {
var iActualTime = new Date().getTime();
if (!this._iLastResizeEventTime || ((iActualTime - this._iLastResizeEventTime) < 50)) {
//Start to handle after the second resize event (below 50ms).
if (!this._iLastResizeHandlingTime || (iActualTime - this._iLastResizeHandlingTime > 500)) { //Handle each .5s.
this.onAfterRendering();
this._iLastResizeHandlingTime = new Date().getTime();
}
} else {
this._iLastResizeHandlingTime = null;
}
this._iLastResizeEventTime = new Date().getTime();
};
/*
* Move Enumeration.
*
* @private
*/
sap.suite.ui.commons.ProcessFlow._enumMoveDirection = {
'LEFT': 'left',
'RIGHT': 'right',
'UP': 'up',
'DOWN': 'down'
};
/** Sets the tab focus on the given element or to _lastNavigationFocusNode if no parameter is given. If no parameter
* is given and _lastNavigationFocusNode is false, nothing happens.
*
* @private
* @param {sap.suite.ui.commons.ProcessFlowNode} the node to focus.
*/
sap.suite.ui.commons.ProcessFlow.prototype._setFocusToNode = function (oNode) {
//If there's a node as parameter.
if (oNode) {
if (oNode instanceof sap.suite.ui.commons.ProcessFlowNode) {
jQuery("#" + oNode.sId).parent().focus();
oNode._setNavigationFocus(true);
oNode.rerender();
} else if (oNode instanceof sap.suite.ui.commons.ProcessFlowConnectionLabel) {
oNode.$().focus();
oNode._setNavigationFocus(true);
}
// If there's no parameter, set the focus to _lastNavigationFocusNode if is not false
} else if (this._lastNavigationFocusNode) {
if (this._lastNavigationFocusNode instanceof sap.suite.ui.commons.ProcessFlowNode) {
jQuery("#" + this._lastNavigationFocusNode.sId).parent().focus();
this._lastNavigationFocusNode._setNavigationFocus(true);
this._lastNavigationFocusNode.rerender();
} else if (this._lastNavigationFocusNode instanceof sap.suite.ui.commons.ProcessFlowConnectionLabel) {
this._lastNavigationFocusNode.$().focus();
this._lastNavigationFocusNode._setNavigationFocus(true);
}
}
};
/**
* Changes the navigation focus from the actual node to the node specified as parameter.
* Calls rerender on both nodes.
*
* @private
* @param {sap.suite.ui.commons.ProcessFlowNode} oNodeFrom the old focused node
* @param {sap.suite.ui.commons.ProcessFlowNode} oNodeTo the new node to focus to
* @since 1.23
*/
sap.suite.ui.commons.ProcessFlow.prototype._changeNavigationFocus = function (oNodeFrom, oNodeTo) {
if (oNodeFrom && oNodeTo && (oNodeFrom.getId() !== oNodeTo.getId())) {
jQuery.sap.log.debug("Rerendering PREVIOUS node with id '" + oNodeFrom.getId() +
"' navigation focus : " + oNodeFrom._getNavigationFocus());
oNodeFrom._setNavigationFocus(false);
if (oNodeFrom instanceof sap.suite.ui.commons.ProcessFlowNode) {
oNodeFrom.rerender();
}
}
if (oNodeTo) {
jQuery.sap.log.debug("Rerendering CURRENT node with id '" + oNodeTo.getId() +
"' navigation focus : " + oNodeTo._getNavigationFocus());
oNodeTo._setNavigationFocus(true);
if (oNodeTo instanceof sap.suite.ui.commons.ProcessFlowNode) {
oNodeTo.rerender();
}
this._lastNavigationFocusNode = oNodeTo;
this._onFocusChanged();
}
};
/**
* Function reacts on page up and page down. It should go 5 lines up or down
* or little bit less if there is not enough space.
* With alt page up move focus left by 5 items maximum.
* With alt page down move focus right by 5 items maximum.
*
* @private
* @param direction please see sap.suite.ui.commons.ProcessFlow._enumMoveDirection
* @param altKey, true if alt key is pressed, false otherwise
* @returns {Boolean} Value describes if a new node was found
*/
sap.suite.ui.commons.ProcessFlow.prototype._moveOnePage = function (direction, altKey) {
direction = direction || sap.suite.ui.commons.ProcessFlow._enumMoveDirection.UP;
altKey = altKey || false;
//Search for navigated element.
var origX = 0, origY = 0;
var newX = 0, newY = 0;
var nodesOver = 0;
var bNewNodeFound = false;
for (var i = 0; i < this._internalCalcMatrix.length; i++) {
for (var j = 0; j < this._internalCalcMatrix[i].length; j++) {
if (this._internalCalcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlowNode && this._internalCalcMatrix[i][j]._getNavigationFocus()) {
origX = i;
origY = j;
break;
} else if (this._internalCalcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][j]._getVisibleLabel();
if (label && label._getNavigationFocus()) {
origX = i;
origY = j;
break;
}
}
}
}
//Going 5 elements on the same row.
if (altKey) {
if (direction == sap.suite.ui.commons.ProcessFlow._enumMoveDirection.UP) {
for (var j = origY - 1; j >= 0 && nodesOver < this._jumpOverElements; j--) {
if (this._internalCalcMatrix[origX][j] instanceof sap.suite.ui.commons.ProcessFlowNode && (!this._bHighlightedMode || this._internalCalcMatrix[origX][j].getHighlighted())) {
nodesOver++;
newX = origX;
newY = j;
bNewNodeFound = true;
} else if (this._internalCalcMatrix[origX][j] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[origX][j]._getVisibleLabel();
if (label && label.getEnabled()) {
nodesOver++;
newX = origX;
newY = j;
bNewNodeFound = true;
}
}
}
} else if (direction === sap.suite.ui.commons.ProcessFlow._enumMoveDirection.DOWN) {
for (var j = origY + 1; j < this._internalCalcMatrix[origX].length && nodesOver < this._jumpOverElements; j++) {
if (this._internalCalcMatrix[origX][j] instanceof sap.suite.ui.commons.ProcessFlowNode && (!this._bHighlightedMode || this._internalCalcMatrix[origX][j].getHighlighted())) {
nodesOver++;
newX = origX;
newY = j;
bNewNodeFound = true;
} else if (this._internalCalcMatrix[origX][j] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[origX][j]._getVisibleLabel();
if (label && label.getEnabled()) {
nodesOver++;
newX = origX;
newY = j;
bNewNodeFound = true;
}
}
}
}
} else {
if (direction == sap.suite.ui.commons.ProcessFlow._enumMoveDirection.UP) {
for (var i = origX - 1; i >= 0 && nodesOver < this._jumpOverElements; i--) {
if (this._internalCalcMatrix[i][origY] instanceof sap.suite.ui.commons.ProcessFlowNode && (!this._bHighlightedMode || this._internalCalcMatrix[i][origY].getHighlighted())) {
nodesOver++;
newX = i;
newY = origY;
bNewNodeFound = true;
} else if (this._internalCalcMatrix[i][origY] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][origY]._getVisibleLabel();
if (label && label.getEnabled()) {
nodesOver++;
newX = i
newY = origY;
bNewNodeFound = true;
}
}
}
} else if (direction === sap.suite.ui.commons.ProcessFlow._enumMoveDirection.DOWN) {
for (var i = origX + 1; i < this._internalCalcMatrix.length && nodesOver < this._jumpOverElements; i++) {
if (this._internalCalcMatrix[i][origY] instanceof sap.suite.ui.commons.ProcessFlowNode && (!this._bHighlightedMode || this._internalCalcMatrix[i][origY].getHighlighted())) {
nodesOver++;
newX = i;
newY = origY;
bNewNodeFound = true;
} else if (this._internalCalcMatrix[i][origY] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][origY]._getVisibleLabel();
if (label && label.getEnabled()) {
nodesOver++;
newX = i
newY = origY;
bNewNodeFound = true;
}
}
}
}
}
if (bNewNodeFound) {
if (this._internalCalcMatrix[origX][origY] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
this._internalCalcMatrix[origX][origY]._getVisibleLabel()._setNavigationFocus(false);
} else {
this._internalCalcMatrix[origX][origY]._setNavigationFocus(false);
}
if (this._internalCalcMatrix[newX][newY] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[newX][newY]._getVisibleLabel();
label._setNavigationFocus(true);
this._lastNavigationFocusNode = label;
} else {
this._internalCalcMatrix[newX][newY]._setNavigationFocus(true);
this._lastNavigationFocusNode = this._internalCalcMatrix[newX][newY];
}
}
return bNewNodeFound;
};
/**
* Function reacts on home/end. it should go to the first/last element on given row.
* With ctrl it goes to the first/last active element on the process flow
* or little bit less if there is not enough space.
*
* @private
* @param direction please see sap.suite.ui.commons.ProcessFlow._enumMoveDirection LEFT -> HOME, RIGHT -> END
* @param ctrlKey, true if ctrl key is pressed
* @returns {Boolean} Value describes if a new node was found
*/
sap.suite.ui.commons.ProcessFlow.prototype._moveHomeEnd = function (direction, ctrlKey) {
direction = direction || sap.suite.ui.commons.ProcessFlow._enumMoveDirection.RIGHT;
ctrlKey = ctrlKey || false;
//Search for navigated element.
var origX = 0, origY = 0;
var newX = 0, newY = 0;
var bNewNodeFound = false;
for (var i = 0; i < this._internalCalcMatrix.length; i++) {
for (var j = 0; j < this._internalCalcMatrix[i].length; j++) {
if (this._internalCalcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlowNode && this._internalCalcMatrix[i][j]._getNavigationFocus()) {
origX = i;
origY = j;
break;
} else if (this._internalCalcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][j]._getVisibleLabel();
if (label && label._getNavigationFocus()) {
origX = i;
origY = j;
break;
}
}
}
}
//Going to the first / last element on the given column.
if (ctrlKey) {
if (direction == sap.suite.ui.commons.ProcessFlow._enumMoveDirection.LEFT) {
for (var i = 0; i < origX ; i++) {
if (this._internalCalcMatrix[i][origY] instanceof sap.suite.ui.commons.ProcessFlowNode && (!this._bHighlightedMode || this._internalCalcMatrix[i][origY].getHighlighted())) {
newX = i;
newY = origY;
bNewNodeFound = true;
break;
} else if (this._internalCalcMatrix[i][origY] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][origY]._getVisibleLabel();
if (label && label.getEnabled()) {
newX = i
newY = origY;
bNewNodeFound = true;
break;
}
}
}
} else if (direction === sap.suite.ui.commons.ProcessFlow._enumMoveDirection.RIGHT) {
for (var i = this._internalCalcMatrix.length - 1; i > origX; i--) {
if (this._internalCalcMatrix[i][origY] instanceof sap.suite.ui.commons.ProcessFlowNode && (!this._bHighlightedMode || this._internalCalcMatrix[i][origY].getHighlighted())) {
newX = i;
newY = origY;
bNewNodeFound = true;
break;
} else if (this._internalCalcMatrix[i][origY] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][origY]._getVisibleLabel();
if (label && label.getEnabled()) {
newX = i
newY = origY;
bNewNodeFound = true;
break;
}
}
}
}
} else { //Going to the first/last element of the row.
if (direction == sap.suite.ui.commons.ProcessFlow._enumMoveDirection.LEFT) {
for (var j = 0; j < origY; j++) {
if (this._internalCalcMatrix[origX][j] instanceof sap.suite.ui.commons.ProcessFlowNode && (!this._bHighlightedMode || this._internalCalcMatrix[origX][j].getHighlighted())) {
newX = origX;
newY = j;
bNewNodeFound = true;
break;
} else if (this._internalCalcMatrix[origX][j] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[origX][j]._getVisibleLabel();
if (label && label.getEnabled()) {
newX = origX;
newY = j;
bNewNodeFound = true;
break;
}
}
}
} else if (direction === sap.suite.ui.commons.ProcessFlow._enumMoveDirection.RIGHT) {
for (var j = this._internalCalcMatrix[origX].length - 1; j > origY; j--) {
if (this._internalCalcMatrix[origX][j] instanceof sap.suite.ui.commons.ProcessFlowNode && (!this._bHighlightedMode || this._internalCalcMatrix[origX][j].getHighlighted())) {
newX = origX;
newY = j;
bNewNodeFound = true;
break;
} else if (this._internalCalcMatrix[origX][j] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[origX][j]._getVisibleLabel();
if (label && label.getEnabled()) {
newX = origX;
newY = j;
bNewNodeFound = true;
break;
}
}
}
}
}
if (bNewNodeFound) {
if (this._internalCalcMatrix[origX][origY] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
this._internalCalcMatrix[origX][origY]._getVisibleLabel()._setNavigationFocus(false);
} else {
this._internalCalcMatrix[origX][origY]._setNavigationFocus(false);
}
if (this._internalCalcMatrix[newX][newY] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[newX][newY]._getVisibleLabel();
label._setNavigationFocus(true);
this._lastNavigationFocusNode = label;
} else {
this._internalCalcMatrix[newX][newY]._setNavigationFocus(true);
this._lastNavigationFocusNode = this._internalCalcMatrix[newX][newY];
}
}
return bNewNodeFound;
};
/**
* Function moves the focus to the next node based on tab behaviour.
* First going left, after to the next row.
*
* @private
* @param direction please see enumeration Direction ( sap.suite.ui.commons.ProcessFlow._enumMoveDirection )
* @returns {Boolean} true if the next element is possible to set. False if there is not more elements to set.
*/
sap.suite.ui.commons.ProcessFlow.prototype._moveToNextNode = function (direction, step) {
//First find the current focus element.
direction = direction || sap.suite.ui.commons.ProcessFlow._enumMoveDirection.RIGHT;
if (sap.ui.getCore().getConfiguration().getRTL()) {
if (direction === sap.suite.ui.commons.ProcessFlow._enumMoveDirection.RIGHT) {
direction = sap.suite.ui.commons.ProcessFlow._enumMoveDirection.LEFT;
} else if (direction === sap.suite.ui.commons.ProcessFlow._enumMoveDirection.LEFT) {
direction = sap.suite.ui.commons.ProcessFlow._enumMoveDirection.RIGHT;
}
}
step = step || 1;
var bFocusNodeFound = false;
var bNewNodeSet = false;
var origX = 0, origY = 1;
if (!this._internalCalcMatrix) {
return;
}
//First search for node which is focused.
var posX = 0, posY = 0;
for (var i = 0; i < this._internalCalcMatrix.length; i++) {
for (var j = 0; j < this._internalCalcMatrix[i].length; j++) {
if (this._internalCalcMatrix[i][j]) {
if (this._internalCalcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlowNode && this._internalCalcMatrix[i][j]._getNavigationFocus()) {
origX = posX = i;
origY = posY = j;
bFocusNodeFound = true;
break;
} else if (this._internalCalcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][j]._getVisibleLabel();
if (label && label._getNavigationFocus() && label.getEnabled()) {
origX = posX = i;
origY = posY = j;
bFocusNodeFound = true;
break;
}
}
}
}
if (bFocusNodeFound) {
break;
}
}
if (direction == sap.suite.ui.commons.ProcessFlow._enumMoveDirection.RIGHT) {
for (var i = posX; i < this._internalCalcMatrix.length; i++) {
for (var j = posY + 1; j < this._internalCalcMatrix[i].length; j++) {
if (this._internalCalcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlowNode) {
if (bFocusNodeFound && (!this._bHighlightedMode || this._internalCalcMatrix[i][j].getHighlighted())) {
this._internalCalcMatrix[i][j]._setNavigationFocus(true);
this._lastNavigationFocusNode = this._internalCalcMatrix[i][j];
bNewNodeSet = true;
break;
}
} else if (this._internalCalcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][j]._getVisibleLabel();
if (label && bFocusNodeFound && label.getEnabled()) {
label._setNavigationFocus(true);
this._lastNavigationFocusNode = label;
bNewNodeSet = true;
break;
}
}
}
//Shortcut, we have done already everything.
posY = 0; //First posX line was from posY, now from zero again. The plus one does not hurt, because first column is empty.
if (bNewNodeSet) {
break;
}
}
}
if (direction == sap.suite.ui.commons.ProcessFlow._enumMoveDirection.LEFT) {
for (var i = posX; i >= 0 ; i--) {
for (var j = posY - 1; j >= 0; j--) {
if (this._internalCalcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlowNode) {
if (bFocusNodeFound && (!this._bHighlightedMode || this._internalCalcMatrix[i][j].getHighlighted())) {
this._lastNavigationFocusNode = this._internalCalcMatrix[i][j]._setNavigationFocus(true);
this._lastNavigationFocusNode = this._internalCalcMatrix[i][j];
bNewNodeSet = true;
break;
}
} else if (this._internalCalcMatrix[i][j] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][j]._getVisibleLabel();
if (label && bFocusNodeFound && label.getEnabled()) {
label._setNavigationFocus(true);
this._lastNavigationFocusNode = label;
bNewNodeSet = true;
break;
}
}
}
if (i > 0) {
posY = this._internalCalcMatrix[i - 1].length;
}
//Shortcut, we have done already everything.
if (bNewNodeSet) {
break;
}
}
}
var deviation,
yPositionLeft,
yPositionRight;
if (direction == sap.suite.ui.commons.ProcessFlow._enumMoveDirection.UP) {
for (var i = posX - 1; i >= 0 ; i--) {
//We have single line, check from posY first left, after right.
deviation = 0;
while (!bNewNodeSet) {
yPositionLeft = posY - deviation;
yPositionRight = posY + deviation;
if (yPositionLeft >= 0 && this._internalCalcMatrix[i][yPositionLeft] instanceof sap.suite.ui.commons.ProcessFlowNode) {
if (bFocusNodeFound && (!this._bHighlightedMode || this._internalCalcMatrix[i][yPositionLeft].getHighlighted())) {
this._internalCalcMatrix[i][yPositionLeft]._setNavigationFocus(true);
this._lastNavigationFocusNode = this._internalCalcMatrix[i][yPositionLeft];
bNewNodeSet = true;
break;
}
} else if (yPositionLeft >= 0 && this._internalCalcMatrix[i][yPositionLeft] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][yPositionLeft]._getVisibleLabel();
if (label && bFocusNodeFound && label.getEnabled()) {
label._setNavigationFocus(true);
this._lastNavigationFocusNode = label;
bNewNodeSet = true;
break;
}
}//End of processflownode for left.
if (yPositionRight < this._internalCalcMatrix[i].length && this._internalCalcMatrix[i][yPositionRight] instanceof sap.suite.ui.commons.ProcessFlowNode) {
if (bFocusNodeFound && (!this._bHighlightedMode || this._internalCalcMatrix[i][yPositionRight].getHighlighted())) {
this._internalCalcMatrix[i][yPositionRight]._setNavigationFocus(true);
this._lastNavigationFocusNode = this._internalCalcMatrix[i][yPositionRight];
bNewNodeSet = true;
break;
}
} else if (yPositionRight >= 0 && this._internalCalcMatrix[i][yPositionRight] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][yPositionRight]._getVisibleLabel();
if (label && bFocusNodeFound && label.getEnabled()) {
label._setNavigationFocus(true);
this._lastNavigationFocusNode = label;
bNewNodeSet = true;
break;
}
} //End of processflownode for right.
//We are out of this line for Y position.
if (yPositionLeft < 0 && yPositionRight > this._internalCalcMatrix[i].length) {
break;
}
deviation++;
}
}
}
if (direction == sap.suite.ui.commons.ProcessFlow._enumMoveDirection.DOWN) {
for (var i = posX + 1; i < this._internalCalcMatrix.length ; i++) {
//We have single line, check from posY first left, after right.
deviation = 0;
while (!bNewNodeSet) {
yPositionLeft = posY - deviation;
yPositionRight = posY + deviation;
if (yPositionLeft >= 0 && this._internalCalcMatrix[i][yPositionLeft] instanceof sap.suite.ui.commons.ProcessFlowNode) {
if (bFocusNodeFound && (!this._bHighlightedMode || this._internalCalcMatrix[i][yPositionLeft].getHighlighted())) {
this._lastNavigationFocusNode = this._internalCalcMatrix[i][yPositionLeft]._setNavigationFocus(true);
this._lastNavigationFocusNode = this._internalCalcMatrix[i][yPositionLeft];
bNewNodeSet = true;
break;
}
} else if (yPositionLeft >= 0 && this._internalCalcMatrix[i][yPositionLeft] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][yPositionLeft]._getVisibleLabel();
if (label && bFocusNodeFound && label.getEnabled()) {
label._setNavigationFocus(true);
this._lastNavigationFocusNode = label;
bNewNodeSet = true;
break;
}
}//End of processflownode for left.
if (yPositionRight < this._internalCalcMatrix[i].length && this._internalCalcMatrix[i][yPositionRight] instanceof sap.suite.ui.commons.ProcessFlowNode) {
if (bFocusNodeFound && (!this._bHighlightedMode || this._internalCalcMatrix[i][yPositionRight].getHighlighted())) {
this._lastNavigationFocusNode = this._internalCalcMatrix[i][yPositionRight]._setNavigationFocus(true);
this._lastNavigationFocusNode = this._internalCalcMatrix[i][yPositionRight];
bNewNodeSet = true;
break;
}
} else if (yPositionRight >= 0 && this._internalCalcMatrix[i][yPositionRight] instanceof sap.suite.ui.commons.ProcessFlowConnection) {
var label = this._internalCalcMatrix[i][yPositionRight]._getVisibleLabel();
if (label && bFocusNodeFound && label.getEnabled()) {
label._setNavigationFocus(true);
this._lastNavigationFocusNode = label;
bNewNodeSet = true;
break;
}
}//End of processflownode for right.
//We are out of this line for Y position.
if (yPositionLeft < 0 && yPositionRight > this._internalCalcMatrix[i].length) {
break;
}
deviation++;
}
}
}
if (bNewNodeSet) {
if (this._internalCalcMatrix[origX][origY] instanceof sap.suite.ui.commons.ProcessFlowNode) {
this._internalCalcMatrix[origX][origY]._setNavigationFocus(false);
} else {
this._internalCalcMatrix[origX][origY]._getVisibleLabel()._setNavigationFocus(false);
}
}
return bNewNodeSet;
};
// ==============================================================================================
// == Keyboard events handling support
// ==============================================================================================
// Internal PF flag whether navigation focus should be released from this control.
sap.suite.ui.commons.ProcessFlow.prototype._bNFocusOutside = false;
// Internal PF flag whether we operate in highlighted mode.
sap.suite.ui.commons.ProcessFlow.prototype._bHighlightedMode = false;
//--------------------------------------------------------------------------------------------
/**
* ProcessFlow has the focus, now it is neccessary to set the navigation
* the method is called both when ProcessFlow gets the focus and at any click event.
*/
sap.suite.ui.commons.ProcessFlow.prototype.onfocusin = function (oEvent) {
//Set the navigation focus to the lane header if in lanes-only mode.
if (this._isHeaderMode()) {
this._setFocusOnHeader(true);
} else { //set the focus on the first node
if (this._bSetFocusOnce) {
this._bSetFocusOnce = false;
if (!this._lastNavigationFocusNode) {
var $nodeToFocus = this.$("scroll-content").children().children().children(1).children("td[tabindex='0']").first().children();
var oNodeToFocus = sap.ui.getCore().byId($nodeToFocus[0].id);
this._changeNavigationFocus(null, oNodeToFocus);
} else {//there is a previous focus on process flow
this._changeNavigationFocus(null, this._lastNavigationFocusNode);
}
}
}
};
sap.suite.ui.commons.ProcessFlow.prototype.onfocusout = function (oEvent) {
this._bSetFocusOnce = true;
if (this._lastNavigationFocusNode && this._lastNavigationFocusNode._getNavigationFocus()) {
this._lastNavigationFocusNode._setNavigationFocus(false);
if (this._lastNavigationFocusNode instanceof sap.suite.ui.commons.ProcessFlowNode) {
this._lastNavigationFocusNode.rerender();
}
}
jQuery.sap.log.info("focus out");
};
/**
* Method called on zoom change.
* Scrolls the PF content after a zoom change so, that the focused content of the scroll container stays in focus (if possible).
*
* @private
* @returns {Object} The scroll container context
* @since 1.26
*/
sap.suite.ui.commons.ProcessFlow.prototype._getScrollContainerOnZoomChanged = function (oScrollContainerContext, $scrollContainer) {
oScrollContainerContext.scrollLeft = Math.round($scrollContainer.context.scrollWidth / oScrollContainerContext.scrollWidth * oScrollContainerContext.scrollLeft);
oScrollContainerContext.scrollTop = Math.round($scrollContainer.context.scrollHeight / oScrollContainerContext.scrollHeight * oScrollContainerContext.scrollTop);
oScrollContainerContext.scrollWidth = $scrollContainer.context.scrollWidth;
oScrollContainerContext.scrollHeight = $scrollContainer.context.scrollHeight;
return oScrollContainerContext;
};
/**
* Method called on navigation focus change.
* Scrolls the PF content, so the node is as close to the middle of the scroll container viewport as possible.
*
* @private
* @since 1.23
*/
sap.suite.ui.commons.ProcessFlow.prototype._onFocusChanged = function () {
var oFocusedNode = this._lastNavigationFocusNode,
$focusedNode = oFocusedNode ? oFocusedNode.$() : null,
iScrollContainerInnerWidth,
iScrollContainerInnerHeight,
iScrollLeft,
iScrollTop,
$scrollContent,
iContentInnerWidth,
iContentInnerHeight,
iNodeOuterWidth,
iNodeOuterHeight,
oPositionInContent,
iNodeLeftPosition,
iNodeTopPosition,
iNodeRightPosition,
iNodeBottomPosition,
iCorrectionLeft, iCorrectionTop,
iScrollTimeInMillis = 500;
if (oFocusedNode && this.getScrollable()) {
jQuery.sap.log.debug("The actually focused node is " + oFocusedNode.getId());
// If the element (oNode) is a label, get the data from the TD parent element, otherwise it won't work precisely
if (oFocusedNode instanceof sap.suite.ui.commons.ProcessFlowConnectionLabel) {
iNodeOuterWidth = $focusedNode.parent().parent().parent().outerWidth();
iNodeOuterHeight = $focusedNode.parent().parent().parent().outerHeight();
oPositionInContent = $focusedNode.parent().parent().parent().position();
} else {
iNodeOuterWidth = $focusedNode.outerWidth();
iNodeOuterHeight = $focusedNode.outerHeight();
oPositionInContent = $focusedNode.position();
}
jQuery.sap.log.debug("Node outer width x height [" + iNodeOuterWidth + " x " + iNodeOuterHeight + "]");
jQuery.sap.log.debug("Position of node in the content is [" + oPositionInContent.left + ", " + oPositionInContent.top + "]");
$scrollContent = this.$("scroll-content");
iScrollContainerInnerWidth = this.$("scrollContainer").innerWidth();
iScrollContainerInnerHeight = this.$("scrollContainer").innerHeight();
jQuery.sap.log.debug("Scroll container inner width x height [" + iScrollContainerInnerWidth + " x " + iScrollContainerInnerHeight + "]");
iScrollLeft = this.$("scrollContainer").scrollLeft();
iScrollTop = this.$("scrollContainer").scrollTop();
jQuery.sap.log.debug("Current scroll offset is [" + iScrollLeft + ", " + iScrollTop + "]");
iContentInnerWidth = $scrollContent.innerWidth();
iContentInnerHeight = $scrollContent.innerHeight();
jQuery.sap.log.debug("Scroll content inner width x height [" + iContentInnerWidth + " x " + iContentInnerHeight + "]");
//Defines 4 borders (L: Left, R: Right, T: Top, B: Bottom) for position of the clicked node in the visible content.
iNodeLeftPosition = -iScrollLeft + oPositionInContent.left;
iNodeRightPosition = iNodeLeftPosition + iNodeOuterWidth;
iNodeTopPosition = -iScrollTop + oPositionInContent.top;
iNodeBottomPosition = iNodeTopPosition + iNodeOuterHeight;
//Checks if the node lies (even in part) outside of the scroll container visible part.
if ((iNodeRightPosition > iScrollContainerInnerWidth) || (iNodeLeftPosition < 0) || (iNodeBottomPosition > iScrollContainerInnerHeight) || (iNodeTopPosition < 0)) {
//iCorrectionLeft, correction on left direction to center the node.
iCorrectionLeft = Math.round((iScrollContainerInnerWidth - iNodeOuterWidth) / 2);
iCorrectionLeft = Math.max(iScrollContainerInnerWidth - iContentInnerWidth + oPositionInContent.left, iCorrectionLeft);
iCorrectionLeft = Math.min(oPositionInContent.left, iCorrectionLeft);
//iCorrectionTop, correction on upwards to center the node.
iCorrectionTop = Math.round((iScrollContainerInnerHeight - iNodeOuterHeight) / 2);
iCorrectionTop = Math.max(iScrollContainerInnerHeight - iContentInnerHeight + oPositionInContent.top, iCorrectionTop);
iCorrectionTop = Math.min(oPositionInContent.top, iCorrectionTop);
jQuery.sap.log.debug("Node lies outside the scroll container, scrolling from [" + iNodeLeftPosition + "," + iNodeTopPosition + "] to [" + iCorrectionLeft + "," + iCorrectionTop + "]");
this._isFocusChanged = true;
this.$("scrollContainer").animate({
scrollTop: oPositionInContent.top - iCorrectionTop,
scrollLeft: oPositionInContent.left - iCorrectionLeft
}, iScrollTimeInMillis, "swing", jQuery.proxy(this._adjustAndShowArrow, this));
} else {
jQuery.sap.log.debug("Node lies inside the scroll container, no scrolling happens.");
this._setFocusToNode(oFocusedNode);
}
} else { //Non scrollable needs also to set the focus.
this._setFocusToNode(oFocusedNode);
this._adjustAndShowArrow();
}
};
/**
* Method called if the ProcessFlow has the navigation focus and the key '+' is pressed ( for keyboard support).
*
* @private
* @since 1.26
*/
sap.suite.ui.commons.ProcessFlow.prototype.onsapplus = function (oEvent) {
this._isFocusChanged = true;
this.zoomIn();
};
/**
* Method called if the ProcessFlow has the navigation focus and the key '-' is pressed ( for keyboard support).
*
* @private
* @since 1.26
*/
sap.suite.ui.commons.ProcessFlow.prototype.onsapminus = function (oEvent) {
this._isFocusChanged = true;
this.zoomOut();
};
/**
* Method called if ProcessFlow has the navigation focus and the Tab key is pressed.
*
* @private
*/
sap.suite.ui.commons.ProcessFlow.prototype.onsaptabnext = function (oEvent) {
var bNextElementToFocus = true;
var $activeElement = oEvent.target;
if (oEvent.target && oEvent.target.childElementCount > 0) {
$activeElement = oEvent.target.childNodes[0];
}
var oActiveElement = sap.ui.getCore().byId($activeElement.id);
if (oActiveElement && !(oActiveElement instanceof sap.suite.ui.commons.ProcessFlowNode) && !(oActiveElement instanceof sap.suite.ui.commons.ProcessFlowConnectionLabel)) {
if (!this._isHeaderMode() && !this._lastNavigationFocusNode) {
var $nodeToFocus = this.$("scroll-content").children().children().children(1).children("td[tabindex='0']").first().children();
var oNodeToFocus = sap.ui.getCore().byId($nodeToFocus[0].id);
this._changeNavigationFocus(null, oNodeToFocus);
bNextElementToFocus = false;
} else if (this._lastNavigationFocusNode) {
this._changeNavigationFocus(null, this._lastNavigationFocusNode);
bNextElementToFocus = false;
}
}
if (this._isHeaderMode() && bNextElementToFocus) { //lanes-only
if (!this._headerHasFocus) {
this._setFocusOnHeader(true);
} else {
this._setFocusOnHeader(false);
}
} else {
if ((this._lastNavigationFocusNode instanceof sap.suite.ui.commons.ProcessFlowNode) || (this._lastNavigationFocusNode instanceof sap.suite.ui.commons.ProcessFlowConnectionLabel)) {
this._lastNavigationFocusNode.rerender();
}
}
//release focus
if (bNextElementToFocus) {
var oNextElementToFocus = this.$().nextAll().find(":focusable").first();
if (oNextElementToFocus.length === 0) {
setNextFocusableElement.bind(this)();
}
oNextElementToFocus.focus();
jQuery.sap.log.debug("saptabnext: Keyboard focus has been changed to element: id='" + oNextElementToFocus.id + "' outerHTML='" + bNextElementToFocus.outerHTML + "'");
oNextElementToFocus = null;
}
oEvent.preventDefault();
function setNextFocusableElement() {
//set focus on the next element outside the ProcessFlow control
var $parent = this.$().parent();
do {
oNextElementToFocus = $parent.next(":focusable");
if (oNextElementToFocus.length === 0) {
oNextElementToFocus = $parent.nextAll().find(":focusable").first();
}
$parent = $parent.parent();
} while (($parent.length !== 0) && (oNextElementToFocus.length === 0));
return;
}
};
/**
* Method called if ProcessFlow has the navigation focus and Tab and Shift keys are pressed simultaneously.
*
* @private
*/
sap.suite.ui.commons.ProcessFlow.prototype.onsaptabprevious = function (oEvent) {
var oPrevElementToFocus = null;
var $activeElement = oEvent.target;
if ((!this._lastNavigationFocusNode || !this._lastNavigationFocusNode._getNavigationFocus()) && oEvent.target && oEvent.target.childElementCount > 0) {
$activeElement = oEvent.target.childNodes[0];
}
var oActiveElement = sap.ui.getCore().byId($activeElement.id);
if (oActiveElement && ((oActiveElement instanceof sap.suite.ui.commons.ProcessFlowNode) || (oActiveElement instanceof sap.suite.ui.commons.ProcessFlowConnection))) {
if (!this._isHeaderMode() && !this._lastNavigationFocusNode) {
var $nodeToFocus = this.$("scroll-content").children().children().children(1).children("td[tabindex='0']").first().children();
var oNodeToFocus = sap.ui.getCore().byId($nodeToFocus[0].id);
this._changeNavigationFocus(null, oNodeToFocus);
} else if (this._lastNavigationFocusNode) {//there is a previous focus on process flow
this._changeNavigationFocus(null, this._lastNavigationFocusNode);
oEvent.preventDefault();
return;
}
}
if (this._isHeaderMode()) { //lanes-only.
if (!this._headerHasFocus) {
this._setFocusOnHeader(true);
} else {
this._setFocusOnHeader(false);
oPrevElementToFocus = this.$().prevAll().find(":focusable").first();
}
} else {
oPrevElementToFocus = this.$().prev(":focusable");
if (oPrevElementToFocus.length === 0) {
oPrevElementToFocus = this.$().prevAll().find(":focusable").first();
}
if (this._lastNavigationFocusNode) {
this._lastNavigationFocusNode._setNavigationFocus(false);
}
if (this._lastNavigationFocusNode instanceof sap.suite.ui.commons.ProcessFlowNode) {
this._lastNavigationFocusNode.rerender();
}
}
//release focus
if (oPrevElementToFocus) {
//set focus on the previous element outside the ProcessFlow control
if (oPrevElementToFocus.length === 0) {
setPrevFocusableElement.bind(this)();
} else if (oPrevElementToFocus.first().length !== 0) {
oPrevElementToFocus = jQuery(oPrevElementToFocus.first());
}
oPrevElementToFocus.focus();
jQuery.sap.log.debug("saptabnext: Keyboard focus has been set on element: id='" + oPrevElementToFocus.id + "' outerHTML='" + oPrevElementToFocus.outerHTML + "'");
oPrevElementToFocus = null;
}
oEvent.preventDefault();
function setPrevFocusableElement() {
var $parent = this.$();
do {
oPrevElementToFocus = $parent.prev(":focusable");
if (oPrevElementToFocus.length === 0) {
oPrevElementToFocus = $parent.prevAll().find(":focusable").last();
}
$parent = $parent.parent();
} while (($parent.length !== 0) && (oPrevElementToFocus.length === 0));
return;
}
};
/**
* Method called if ProcessFlow has the navigation focus and Spacebar or Enter key are pressed.
*
* @private
*/
sap.suite.ui.commons.ProcessFlow.prototype.onsapselect = function (oEvent) {
if (this._isHeaderMode()) { //lanes-only.
this._internalLanes = [];
this.fireHeaderPress(this);
var $nodeToFocus = this.$("scroll-content").children().children().children(1).children("td[tabindex='0']").first().children();
var oNodeToFocus = sap.ui.getCore().byId($nodeToFocus[0].id);
this._changeNavigationFocus(null, oNodeToFocus);
} else {
if (this._lastNavigationFocusNode instanceof sap.suite.ui.commons.ProcessFlowNode && this._lastNavigationFocusNode._getNavigationFocus()) {
this.fireNodePress(this._lastNavigationFocusNode);
}
}
};
/**
* Method called if ProcessFlow has the navigation focus and the Down arrow key is pressed
*
* @private
*/
sap.suite.ui.commons.ProcessFlow.prototype.onkeydown = function (oEvent) {
var keycode = (oEvent.keyCode ? oEvent.keyCode : oEvent.which);
jQuery.sap.log.debug("ProcessFlow::keyboard input has been catched and action going to start: keycode=" + keycode);
var bElementFocusChanged = false;
var ctrlKeyPressed = oEvent.ctrlKey;
var altKeyPressed = oEvent.altKey;
var oPreviousNavigationElement = this._lastNavigationFocusNode;
switch (keycode) {
case jQuery.sap.KeyCodes.ARROW_RIGHT:
bElementFocusChanged = this._moveToNextNode(sap.suite.ui.commons.ProcessFlow._enumMoveDirection.RIGHT);
break;
case jQuery.sap.KeyCodes.ARROW_LEFT:
bElementFocusChanged = this._moveToNextNode(sap.suite.ui.commons.ProcessFlow._enumMoveDirection.LEFT);
break;
case jQuery.sap.KeyCodes.ARROW_DOWN:
bElementFocusChanged = this._moveToNextNode(sap.suite.ui.commons.ProcessFlow._enumMoveDirection.DOWN);
break;
case jQuery.sap.KeyCodes.ARROW_UP:
bElementFocusChanged = this._moveToNextNode(sap.suite.ui.commons.ProcessFlow._enumMoveDirection.UP);
break;
case jQuery.sap.KeyCodes.PAGE_UP:
bElementFocusChanged = this._moveOnePage(sap.suite.ui.commons.ProcessFlow._enumMoveDirection.UP, altKeyPressed);
break;
case jQuery.sap.KeyCodes.PAGE_DOWN:
bElementFocusChanged = this._moveOnePage(sap.suite.ui.commons.ProcessFlow._enumMoveDirection.DOWN, altKeyPressed);
break;
case jQuery.sap.KeyCodes.HOME:
bElementFocusChanged = this._moveHomeEnd(sap.suite.ui.commons.ProcessFlow._enumMoveDirection.LEFT, ctrlKeyPressed);
break;
case jQuery.sap.KeyCodes.END:
bElementFocusChanged = this._moveHomeEnd(sap.suite.ui.commons.ProcessFlow._enumMoveDirection.RIGHT, ctrlKeyPressed);
break;
case jQuery.sap.KeyCodes.NUMPAD_0:
case jQuery.sap.KeyCodes.DIGIT_0:
this._initZoomLevel();
break;
case jQuery.sap.KeyCodes.ENTER:
case jQuery.sap.KeyCodes.SPACE:
//ENTER and SPACE (or sapselect) are fired according to the spec, but we need to prevent the default behavior.
oEvent.preventDefault();
return;
default:
//It was not our key, let default action be executed if any.
return;
}
//It was our key, default action has to suppressed.
oEvent.preventDefault();
if (bElementFocusChanged) {
//We have to re-render when we changed Element-focus inside our control.
this._changeNavigationFocus(oPreviousNavigationElement, this._lastNavigationFocusNode);
}
};
/**
* Merge values of node states for several nodes.
*
* @private
* @param {array} aLaneIdNodeStates node states for all nodes of the same laneId
* @param altKey, true if alt key is pressed, false otherwise
* @returns {Object[]} aResult Array of cumulated node states for aLaneIdNodeStates
*/
sap.suite.ui.commons.ProcessFlow.prototype._mergeLaneIdNodeStates = function (aLaneIdNodeStates) {
var iPositive = 0;
var iNegative = 0;
var iNeutral = 0;
var iPlanned = 0;
for (var iState = 0; iState < 4; iState++) {
for (var iNode = 0; iNode < aLaneIdNodeStates.length; iNode++) {
switch (aLaneIdNodeStates[iNode][iState].state) {
case sap.suite.ui.commons.ProcessFlowNodeState.Positive:
iPositive = iPositive + aLaneIdNodeStates[iNode][iState].value;
break;
case sap.suite.ui.commons.ProcessFlowNodeState.Negative:
iNegative = iNegative + aLaneIdNodeStates[iNode][iState].value;
break;
case sap.suite.ui.commons.ProcessFlowNodeState.Neutral:
iNeutral = iNeutral + aLaneIdNodeStates[iNode][iState].value;
break;
case sap.suite.ui.commons.ProcessFlowNodeState.Planned:
iPlanned = iPlanned + aLaneIdNodeStates[iNode][iState].value;
break;
//plannedNegative belong to Negative group
case sap.suite.ui.commons.ProcessFlowNodeState.PlannedNegative:
iNegative = iNegative + aLaneIdNodeStates[iNode][iState].value;
break;
}
}
}
var aResult = [{ state: sap.suite.ui.commons.ProcessFlowNodeState.Positive, value: iPositive },
{ state: sap.suite.ui.commons.ProcessFlowNodeState.Negative, value: iNegative },
{ state: sap.suite.ui.commons.ProcessFlowNodeState.Neutral, value: iNeutral },
{ state: sap.suite.ui.commons.ProcessFlowNodeState.Planned, value: iPlanned }];
return aResult;
};
/**
* Sets or removes navigation focus on the Lane header ( for keyboard support ).
*
* @private
* @param {boolean} if true the navigation focus is set, if false the navigation focus is removed
* @since 1.26
*/
sap.suite.ui.commons.ProcessFlow.prototype._setFocusOnHeader = function (setFlag) {
var thead = jQuery.sap.byId(this.getId() + "-thead");
if (setFlag) {
thead.focus();
thead.addClass("sapSuiteUiCommonsPFHeaderFocused");
this._headerHasFocus = true;
}
else {
thead.blur();
thead.removeClass("sapSuiteUiCommonsPFHeaderFocused");
this._headerHasFocus = false;
}
};
/**
* Handles the click on the arrows.
*
* @private
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype._onArrowClick = function (oEvent) {
var sTargetId = oEvent.target.id;
if (sTargetId) {
var sId = this.getId();
//For scroll buttons: Prevent IE from firing beforeunload event -> see CSN 4378288 2012
oEvent.preventDefault();
//On mobile devices, the click on arrows has no effect.
if (sTargetId == sId + "-arrowScrollLeft" && sap.ui.Device.system.desktop) {
//Scroll back/left button.
this._scroll(-this._scrollStep, 500);
} else if (sTargetId == sId + "-arrowScrollRight" && sap.ui.Device.system.desktop) {
//Scroll forward/right button.
this._scroll(this._scrollStep, 500);
}
}
};
/**
* Scrolls the header if possible, using an animation.
*
* @private
* @param iDelta how far to scroll
* @param iDuration how long to scroll (ms)
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype._scroll = function (iDelta, iDuration) {
var oDomRef = this.getDomRef("scrollContainer");
var iScrollLeft = oDomRef.scrollLeft;
if (!!!sap.ui.Device.browser.internet_explorer && this._bRtl) {
iDelta = -iDelta;
} //RTL lives in the negative space.
var iScrollTarget = iScrollLeft + iDelta;
jQuery(oDomRef).stop(true, true).animate({ scrollLeft: iScrollTarget }, iDuration, jQuery.proxy(this._adjustAndShowArrow, this));
};
/**
* Adjusts the arrow position and shows the arrow.
*
* @private
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype._adjustAndShowArrow = function () {
this._checkOverflow(this.getDomRef("scrollContainer"), this.$());
if (this.getScrollable()) {
this._moveArrowAndCounterVertical();
}
if (this._isFocusChanged) {
this._setFocusToNode(this._lastNavigationFocusNode);
this._isFocusChanged = false;
}
};
/**
* Gets the icon of the requested arrow (left/right).
*
* @private
* @param sName left or right
* @returns icon of the requested arrow
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype._getScrollingArrow = function (sName) {
var src;
if (sap.ui.Device.system.desktop) {
//Use navigation arrows on desktop and win8 combi devices.
src = "sap-icon://navigation-" + sName + "-arrow";
} else {
//Use slim arrows on mobile devices.
src = "sap-icon://slim-arrow-" + sName;
}
var mProperties = {
src: src
};
var sLeftArrowClass = "sapPFHArrowScrollLeft";
var sRightArrowClass = "sapPFHArrowScrollRight";
var aCssClassesToAddLeft = ["sapPFHArrowScroll", sLeftArrowClass];
var aCssClassesToAddRight = ["sapPFHArrowScroll", sRightArrowClass];
if (sName === "left") {
if (!this._oArrowLeft) {
this._oArrowLeft = sap.m.ImageHelper.getImageControl(this.getId() + "-arrowScrollLeft", null, this, mProperties, aCssClassesToAddLeft);
}
return this._oArrowLeft;
}
if (sName === "right") {
if (!this._oArrowRight) {
this._oArrowRight = sap.m.ImageHelper.getImageControl(this.getId() + "-arrowScrollRight", null, this, mProperties, aCssClassesToAddRight);
}
return this._oArrowRight;
}
};
/**
* Checks if scrolling is needed.
*
* @private
* @param oScrollContainer the scroll container
* @param $processFlow the ProcessFlow container
* @returns true if scrolling is needed, otherwise false
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype._checkScrolling = function (oScrollContainer, $processFlow) {
var bScrolling = false;
//Check if there are more lanes than displayed.
if (oScrollContainer) {
if (oScrollContainer.scrollWidth > oScrollContainer.clientWidth) {
//Scrolling possible.
bScrolling = true;
}
}
if (this._arrowScrollable !== bScrolling) {
$processFlow.toggleClass("sapPFHScrollable", bScrolling);
$processFlow.toggleClass("sapPFHNotScrollable", !bScrolling);
this._arrowScrollable = bScrolling;
}
return bScrolling;
};
/**
* Sets the scroll width depending on the zoom level.
*
* @private
* @param oScrollContainer the scroll container
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype._setScrollWidth = function (oScrollContainer) {
//The distance to scroll depends on the ZoomLevel.
switch (this.getZoomLevel()) {
case (sap.suite.ui.commons.ProcessFlowZoomLevel.One):
this._scrollStep = 240;
break;
case (sap.suite.ui.commons.ProcessFlowZoomLevel.Two):
this._scrollStep = 192;
break;
case (sap.suite.ui.commons.ProcessFlowZoomLevel.Three):
this._scrollStep = 168;
break;
case (sap.suite.ui.commons.ProcessFlowZoomLevel.Four):
this._scrollStep = 128;
break;
}
};
/**
* Calculates the left counter.
*
* @private
* @returns {Number} The left counter
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype._updateLeftCounter = function () {
var iScrollDelta;
if (!this._bRtl) { //Normal LTR mode.
iScrollDelta = this.$("scrollContainer").scrollLeft();
}
else { //RTL mode.
iScrollDelta = this.$("scrollContainer").scrollRightRTL();
}
var counterLeft = Math.round(iScrollDelta / this._scrollStep);
this.$("counterLeft").text(counterLeft.toString());
return counterLeft;
};
/**
* Calculates the right counter.
*
* @private
* @param availableWidth
* @param realWidth
* @returns {Number} The right counter
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype._updateRightCounter = function (availableWidth, realWidth) {
var iScrollDelta;
var counterRight;
if (!this._bRtl) { //Normal LTR mode.
iScrollDelta = this.$("scrollContainer").scrollLeft();
counterRight = Math.round((realWidth - iScrollDelta - availableWidth) / this._scrollStep);
}
else { //RTL mode.
iScrollDelta = this.$("scrollContainer").scrollLeftRTL();
counterRight = Math.round(iScrollDelta / this._scrollStep);
}
this.$("counterRight").text(counterRight.toString());
return counterRight;
};
/**
* For scrollable ProcessFlow : move arrows and counter vertically when scrolling.
*
* @private
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype._moveArrowAndCounterVertical = function () {
var iScrollTop = this.$("scrollContainer").scrollTop();
if (iScrollTop > 0) {
var iArrowTop = this._iInitialArrowTop - iScrollTop;
var iCounterTop = this._iInitialCounterTop - iScrollTop;
var iDiffArrowCounter = this._iInitialCounterTop - this._iInitialArrowTop;
if (iArrowTop > 0) {
this.$("arrowScrollRight").css("top", iArrowTop + "px");
this.$("arrowScrollLeft").css("top", iArrowTop + "px");
}
else {
this.$("arrowScrollRight").css("top", "0px");
this.$("arrowScrollLeft").css("top", "0px");
}
if (iCounterTop > iDiffArrowCounter) {
this.$("counterRight").css("top", iCounterTop + "px");
this.$("counterLeft").css("top", iCounterTop + "px");
}
else {
this.$("counterRight").css("top", iDiffArrowCounter + "px");
this.$("counterLeft").css("top", iDiffArrowCounter + "px");
}
}
else {
this.$("arrowScrollRight").css("top", this._iInitialArrowTop + "px");
this.$("arrowScrollLeft").css("top", this._iInitialArrowTop + "px");
this.$("counterRight").css("top", this._iInitialCounterTop + "px");
this.$("counterLeft").css("top", this._iInitialCounterTop + "px");
}
};
/**
* Changes the state of the scroll arrows depending on whether they are required due to overflow.
*
* @private
* @param oScrollContainer the scroll container
* @param $processFlow the ProcessFlow container
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype._checkOverflow = function (oScrollContainer, $processFlow) {
if (this._checkScrolling(oScrollContainer, $processFlow) && oScrollContainer) {
this._setScrollWidth(oScrollContainer);
//Check whether scrolling to the left is possible.
var bScrollBack = false;
var bScrollForward = false;
var iOffset = 20; //Display arrow and counter only if the distance to the end of the scroll container is at least 20px.
var iScrollLeft = this.$("scrollContainer").scrollLeft();
var realWidth = oScrollContainer.scrollWidth;
var availableWidth = oScrollContainer.clientWidth;
if (Math.abs(realWidth - availableWidth) == 1) { //Avoid rounding issues see CSN 1316630 2013
realWidth = availableWidth;
}
if (!this._bRtl) { //Normal LTR mode.
if (iScrollLeft > iOffset) {
bScrollBack = true;
}
if ((realWidth > availableWidth) && (iScrollLeft + availableWidth + iOffset < realWidth)) {
bScrollForward = true;
}
} else { //RTL mode.
var $ScrollContainer = jQuery(oScrollContainer);
if ($ScrollContainer.scrollLeftRTL() > iOffset) {
bScrollForward = true;
}
if ($ScrollContainer.scrollRightRTL() > iOffset) {
bScrollBack = true;
}
}
//Update left and right counter.
this._updateLeftCounter();
this._updateRightCounter(availableWidth, realWidth);
//Only do DOM changes if the state changed to avoid periodic application of identical values.
if ((bScrollForward !== this._bPreviousScrollForward) || (bScrollBack !== this._bPreviousScrollBack)) {
this._bPreviousScrollForward = bScrollForward;
this._bPreviousScrollBack = bScrollBack;
$processFlow.toggleClass("sapPFHScrollBack", bScrollBack);
$processFlow.toggleClass("sapPFHNoScrollBack", !bScrollBack);
$processFlow.toggleClass("sapPFHScrollForward", bScrollForward);
$processFlow.toggleClass("sapPFHNoScrollForward", !bScrollForward);
}
} else {
this._bPreviousScrollForward = false;
this._bPreviousScrollBack = false;
}
};
/**
* Handles the onScroll event.
*
* @private
*/
sap.suite.ui.commons.ProcessFlow.prototype._onScroll = function (oEvent) {
var iScrollLeft = this.$("scrollContainer").scrollLeft();
var iDelta = Math.abs(iScrollLeft - this._iTouchStartScrollLeft);
//Only valid if the focus does not change.
if (iDelta > (this._scrollStep / 4) && !this._isFocusChanged) {
//Update arrows when 1/4 lane was scrolled.
this._adjustAndShowArrow();
this._iTouchStartScrollLeft = iScrollLeft;
}
else {
//Update vertical alignment of arrows if only vertical scrolling is possible.
if (this.getScrollable()) {
var iScrollTop = this.$("scrollContainer").scrollTop();
var iDeltaTop = Math.abs(iScrollTop - this._iTouchStartScrollTop);
if (iDeltaTop > 10) {
this._moveArrowAndCounterVertical();
this._iTouchStartScrollTop = iScrollTop;
}
}
}
};
/**
* Initializes left and top distance when scrolling starts.
*
* @private
* @param {jQuery.Event} oEvent
* @since 1.30
*/
sap.suite.ui.commons.ProcessFlow.prototype.ontouchstart = function (oEvent) {
this._iTouchStartScrollLeft = this.$("scrollContainer").scrollLeft();
if (this.getScrollable()) {
this._iTouchStartScrollTop = this.$("scrollContainer").scrollTop();
}
};
/**
* Sets the parent association for given nodes.
*
* @private
* @param {sap.suite.ui.commons.ProcessFlowNode[]} aInternalNodes Array of nodes to set parents on
*/
sap.suite.ui.commons.ProcessFlow.prototype._setParentForNodes = function (aInternalNodes) {
var cInternalNodes = aInternalNodes ? aInternalNodes.length : 0;
var aChildren;
var i, j;
//Cleanup association to avoid duplicates.
for (var currentNode in aInternalNodes) {
aInternalNodes[currentNode].removeAllAssociation("parents", true);
}
for (i = 0; i < cInternalNodes; i++) {
aChildren = aInternalNodes[i].getChildren();
if (aChildren) {
for (j = 0; j < aChildren.length; j++) {
var childNode = this._getNode(sap.suite.ui.commons.ProcessFlow._getChildIdByElement(aChildren[j]), aInternalNodes);
if (childNode) {
childNode.addAssociation("parents", aInternalNodes[i], true);
}
}
}
}
};
/**
* Returns the node from the given array which matches to the given nodeId.
*
* @private
* @param {String} nodeId Id of node to retrieve
* @param {sap.suite.ui.commons.ProcessFlowNode[]} aInternalNodes Array of nodes to search in
* @returns {sap.suite.ui.commons.ProcessFlowNode} Found ProcessFlow node
*/
sap.suite.ui.commons.ProcessFlow.prototype._getNode = function (nodeId, aInternalNodes) {
for (var i = 0; i < aInternalNodes.length; i++) {
if (aInternalNodes[i].getNodeId() === nodeId.toString()) {
return aInternalNodes[i];
}
}
};
/**
* Returns the lane from the _internalLanes array which matches to the given laneId.
*
* @private
* @param {String} laneId Id of lane to retrieve
* @returns {sap.suite.ui.commons.ProcessFlowLaneHeader} The lane header element
*/
sap.suite.ui.commons.ProcessFlow.prototype._getLane = function (laneId) {
for (var i = 0; i < this._internalLanes.length; i++) {
if (this._internalLanes[i].getLaneId() === laneId) {
return this._internalLanes[i];
}
}
};
/**
* Returns the id of the given child node element. Since child elements can be string or object, this function checks the type and
* returns the nodeId.
*
* @private
* @param {Object/String} The child element containing the nodeId
* @returns {Number} The id of the child element
*/
sap.suite.ui.commons.ProcessFlow._getChildIdByElement = function (oChildElement) {
if (typeof oChildElement === 'object') {
return oChildElement.nodeId;
} else {
return oChildElement;
}
};
/**
* Creates the connection map objects between the source and target nodes
* incl. label information and connection parts, based on the calculated matrix.
*
* @private
* @returns {Object} The Connection map
*/
sap.suite.ui.commons.ProcessFlow.prototype._getConnectionsMap = function () {
//Example:
// var connectionMap = [];
// var connectionMapEntry = {};
// connectionMapEntry.sourceNode = matrix[0][1];
// connectionMapEntry.targetNode = matrix[4][3];
// connectionMapEntry.label = "label from code, needs to be mapped";
// connectionMapEntry.connectionParts = [
// {x:0, y:2},
// {x:1, y:2},
// {x:2, y:2},
// {x:3, y:2},
// {x:4, y:2}
// ];
var aConnections = [];
var aNodes = this.getNodes();
for (var i = 0; i < aNodes.length; i++) {
var oPositionOfSourceNode = this._getPositionOfNodeInMatrix(this._internalCalcMatrix, aNodes[i]);
var aChildren = aNodes[i].getChildren();
if (aChildren) {
for (var j = 0; j < aChildren.length; j++) {
var oConnectionMapEntry = {};
oConnectionMapEntry.sourceNode = aNodes[i];
var childId = sap.suite.ui.commons.ProcessFlow._getChildIdByElement(aChildren[j]);
var childNode = this._getNode(childId, aNodes);
if (childNode) {
if (typeof aChildren[j] === 'object') {
oConnectionMapEntry.label = aChildren[j].connectionLabel;
}
oConnectionMapEntry.targetNode = childNode;
//Find position in matrix
var oPositionOfTargetNode = this._getPositionOfNodeInMatrix(this._internalCalcMatrix, oConnectionMapEntry.targetNode);
oConnectionMapEntry.connectionParts = this._calculateConnectionParts(this._internalCalcMatrix, oPositionOfSourceNode, oPositionOfTargetNode);
aConnections.push(oConnectionMapEntry);
}
}
}
}
this._internalConnectionMap = aConnections;
return aConnections;
};
/**
* Returns the position (coordinates x/y) of the given ProcessFlowNode in calculated matrix of ProcessFlow.
*
* @private
* @param {Object} The calculated matrix of the current ProcessFlow
* @param {sap.suite.ui.commons.ProcessFlowNode} The node for which the position is required
* @returns {Object} The position of the node in the calculated matrix (x/y)
*/
sap.suite.ui.commons.ProcessFlow.prototype._getPositionOfNodeInMatrix = function (aMatrix, oNode) {
var position = {};
for (var i = 0; i < aMatrix.length; i++) {
var currentLine = aMatrix[i];
for (var j = 0; j < currentLine.length; j++) {
var currentCell = currentLine[j];
if (currentCell &&
currentCell instanceof sap.suite.ui.commons.ProcessFlowNode &&
currentCell.getNodeId() === oNode.getNodeId()) {
position.y = i;
position.x = j;
return position;
}
}
}
return position;
};
/**
* Calculates the connection parts (coordinates in matrix) between source and target node.
*
* @private
* @param {Object} The calculated matrix of the current ProcessFlow
* @param {Object} The position of the source node in the calculated matrix (x/y)
* @param {Object} The position of the target node in the calculated matrix (x/y)
* @returns {Object[]} Array of all connection parts, relevant for connection between source and target node
*/
sap.suite.ui.commons.ProcessFlow.prototype._calculateConnectionParts = function (aMatrix, oPositionOfSourceNode, oPositionOfTargetNode) {
//Example:
//var connectionParts = [
// {x:0, y:2},
// {x:1, y:2},
// {x:2, y:2},
// {x:3, y:2},
// {x:4, y:2}
// ];
var aConnectionParts = [];
var cY = oPositionOfSourceNode.y;
var cX = oPositionOfSourceNode.x;
//Increase column+1 (step 1 right), independent from target position since target will ever be right from source.
cX++;
aConnectionParts.push({ x: cX, y: cY });
//Increase (row+1) till we are in the row of target node (n steps down) if target is below source in matrix.
//Decrease (row-1) till we are in the row of target node (n steps up) if target is above source in matrix.
if (oPositionOfTargetNode.y >= oPositionOfSourceNode.y) {
while (cY < oPositionOfTargetNode.y) {
cY++;
aConnectionParts.push({ x: cX, y: cY });
}
} else {
while (cY > oPositionOfTargetNode.y) {
cY--;
aConnectionParts.push({ x: cX, y: cY });
}
}
//Increase column+1 till we are in column of target node (n steps right)
while (cX < oPositionOfTargetNode.x - 1) {
cX++;
aConnectionParts.push({ x: cX, y: cY });
}
return aConnectionParts;
};
/**
* Returns the connectionMapEntries which are relevant for the given sap.suite.ui.commonsProcessFlowConnectionLabel.
* Means all entries having the same target node as current entry (based on current label).
*
* @private
* @param {sap.suite.ui.commons.ProcessFlowConnectionLabel} The label for which the map entries are required
* @returns {Object[]} Array with relevant connectionMapEntries for the given label
*/
sap.suite.ui.commons.ProcessFlow.prototype._getConnectionMapEntries = function (oConnectionLabel) {
var aFilteredConnectionMaps = [];
var connectionMapWithLabel = null;
var oEntry = null;
//Find relevant connectionMapEntry, containing given Label.
if (this._internalConnectionMap) {
for (var i = 0; i < this._internalConnectionMap.length; i++) {
oEntry = this._internalConnectionMap[i];
if (oEntry.label &&
oEntry.label.getId() === oConnectionLabel.getId()) {
connectionMapWithLabel = oEntry;
break;
}
}
//Collect all connectionMapEntries with same target node as the one, containing the Label.
oEntry = null;
for (var j = 0; j < this._internalConnectionMap.length; j++) {
oEntry = this._internalConnectionMap[j];
if (oEntry.targetNode &&
oEntry.targetNode.getNodeId() === connectionMapWithLabel.targetNode.getNodeId()) {
aFilteredConnectionMaps.push(oEntry);
}
}
}
return aFilteredConnectionMaps;
};
/**
* Handles the click of labels and triggers the related ProcessFlow event.
*
* @private
* @params {Object} Event Args, containing the label and related information
*/
sap.suite.ui.commons.ProcessFlow.prototype._handleLabelClick = function (oEvent) {
if (oEvent) {
var oConnectionLabel = oEvent.getSource();
//Check if user clicked on icon.
if (oConnectionLabel instanceof sap.ui.core.Icon) {
oConnectionLabel = oConnectionLabel.getParent();
}
if (oConnectionLabel instanceof sap.suite.ui.commons.ProcessFlowConnectionLabel) {
var aRelevantConnectionMapEntries = this._getConnectionMapEntries(oConnectionLabel);
var eventArgsToFire = this._createLabelPressEventArgs(oConnectionLabel, aRelevantConnectionMapEntries);
this.fireLabelPress(eventArgsToFire);
}
}
}
/**
* Sets the path between source and target node to selected status and rerenders the control. If parameters are null, sets all nodes to normal status.
*
* @public
* @param {String} sourceNodeId of the path or null
* @param {String} targetNodeId of the path or null
* @since 1.32
*/
sap.suite.ui.commons.ProcessFlow.prototype.setSelectedPath = function (sourceNodeId, targetNodeId) {
var aNodes = this.getNodes();
if (aNodes) {
if (sourceNodeId && targetNodeId) {
var cNodesFound = 0;
for (var i = 0; i < aNodes.length; i++) {
if (aNodes[i].getNodeId() === sourceNodeId || aNodes[i].getNodeId() === targetNodeId) {
aNodes[i].setSelected(true);
cNodesFound++;
} else {
aNodes[i].setSelected(false);
}
}
if (cNodesFound == 2) {
this.rerender();
}
} else if (!sourceNodeId && !targetNodeId) {
for (var i = 0; i < aNodes.length; i++) {
aNodes[i].setSelected(false);
}
this.rerender();
}
}
};
/**
* Sets the focus to the given Label
*
* @public
* @param {sap.suite.ui.commons.ProcessFlowConnectionlabel} Label to focus
* @since 1.32
*/
sap.suite.ui.commons.ProcessFlow.prototype.setFocusToLabel = function (oLabel) {
this._changeNavigationFocus(this._lastNavigationFocusNode, oLabel);
};
/**
* Creates the eventArgs for fireLabelPress of ProcessFlow.
* Additional object is necessary, since connectionmaps are containing too much information (e.g. parts).
*
* @private
* @param {sap.suite.ui.commons.ProcessFlowConnectionlabel} Label which has been selected by user (clicked)
* @param {Object[]} The relevant connection maps for the selected label
* @returns {Object} Event args for fireLabelPress
*/
sap.suite.ui.commons.ProcessFlow.prototype._createLabelPressEventArgs = function (oConnectionLabel, aConnectionMapEntries) {
var oEvent = {};
var aEventArgsConnectionValues = [];
if (aConnectionMapEntries) {
for (var i = 0; i < aConnectionMapEntries.length; i++) {
var oEventArgsConnectionValue = {
sourceNode: aConnectionMapEntries[i].sourceNode,
targetNode: aConnectionMapEntries[i].targetNode,
label: aConnectionMapEntries[i].label
};
aEventArgsConnectionValues.push(oEventArgsConnectionValue);
}
}
oEvent.selectedLabel = oConnectionLabel;
oEvent.connections = aEventArgsConnectionValues;
return oEvent;
};
/**
* Overwrites setShowLabels of ProcessFlow control to apply additional functionality.
*
* @param {Boolean} New value for showLabels
*/
sap.suite.ui.commons.ProcessFlow.prototype.setShowLabels = function (bNewValue) {
var bOldValue = this.getShowLabels();
if (bOldValue && !bNewValue) { //Only if status has been changed from show to hide
this.setProperty("showLabels", bNewValue, true);
// Resets the selected path in case labels have been disabled for the current control.
if (!this.getShowLabels()) {
this.setSelectedPath(null, null);
}
} else {
this.setProperty("showLabels", bNewValue);
}
};<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
jQuery.sap.declare("sap.apf.core.odataRequest");jQuery.sap.require("sap.ui.thirdparty.datajs");jQuery.sap.require("sap.apf.core.utils.checkForTimeout");(function(){'use strict';sap.apf.core.odataRequestWrapper=function(m,r,s,e,b){function a(d,f){var M=sap.apf.core.utils.checkForTimeout(f);var E={};if(M){E.messageObject=M;e(E);}else{s(d,f);}}function c(E){var M=sap.apf.core.utils.checkForTimeout(E);if(M){E.messageObject=M;}e(E);}OData.request(r,a,c,b);};}());
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare("sap.ui.comp.smartmicrochart.SmartBulletMicroChartRenderer");
jQuery.sap.require("sap.ui.core.Renderer");
jQuery.sap.require("sap.suite.ui.microchart.BulletMicroChartRenderer");
/**
* @class SmartBulletMicroChart renderer.
* @version 1.36.12
* @experimental Since 1.34.0 This is currently under development. The API could be changed at any point in time.
* @static
*/
sap.ui.comp.smartmicrochart.SmartBulletMicroChartRenderer = sap.ui.core.Renderer.extend(sap.suite.ui.microchart.BulletMicroChartRenderer);<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
/*global jQuery, sap*/
jQuery.sap.require("sap.apf.modeler.ui.utils.nullObjectChecker");
jQuery.sap.require("sap.apf.modeler.ui.utils.optionsValueModelBuilder");
jQuery.sap.require("sap.apf.modeler.ui.utils.viewValidator");
/**
* @class requestOptions
* @name requestOptions
* @description General controller for VHR, FRR and navigation target
* The ViewData for this view needs the following parameters:
* getCalatogServiceUri()- api to fetch uri
* oConfigurationHandler - Handler for configuration
* oConfigurationEditor - manages the facet filter object
* oTextReader - Method to getText
* oParentObject - Object from which the controller gets instantiated
*/
sap.ui.define([ "sap/ui/core/mvc/Controller" ], function(Controller) {
"use strict";
var nullObjectChecker = new sap.apf.modeler.ui.utils.NullObjectChecker();
var optionsValueModelBuilder = new sap.apf.modeler.ui.utils.OptionsValueModelBuilder();
// Adds 'Auto Complete Feature' to the input field source in the view using sap.apf.modeler.ui.utils.TextPoolHelper
function _enableAutoComplete(oController) {
var oTextPoolHelper = new sap.apf.modeler.ui.utils.TextPoolHelper(oController.getView().getViewData().oConfigurationHandler.getTextPool());
//auto complete for source
var oDependenciesForService = {
oConfigurationEditor : oController.oConfigurationEditor,
type : "service"
};
oTextPoolHelper.setAutoCompleteOn(oController.byId("idSource"), oDependenciesForService);
}
// Sets source on init or change
function _setSource(oController) {
var sSource = oController.getSource();
// Default state
oController.byId("idSource").setValue("");
if (!nullObjectChecker.checkIsNotNullOrUndefinedOrBlank(sSource)) {
oController.addOrRemoveMandatoryFieldsAndRequiredFlag(false);
return;
}
// setValue
oController.byId("idSource").setValue(sSource);
oController.addOrRemoveMandatoryFieldsAndRequiredFlag(true);
}
// Sets entity set on init or change
function _setEntity(oController) {
var oModelForEntity, sSource, sEntitySet, aAllEntities;
sSource = oController.byId("idSource").getValue();
// Default State
oController.byId("idEntity").setModel(null);
oController.byId("idEntity").clearSelection();
if (!nullObjectChecker.checkIsNotNullOrUndefinedOrBlank(sSource)) {
return;
}
if (!oController.oConfigurationEditor.registerService(sSource)) {
return;
}
aAllEntities = oController.getAllEntities(sSource);
// setModel
oModelForEntity = optionsValueModelBuilder.convert(aAllEntities);
oController.byId("idEntity").setModel(oModelForEntity);
sEntitySet = oController.getEntity();
// setSelectedKey as 0th entity -> in case new parent object(no entity available for new parent object)/ in case of change of source(if old entity is not present in the entities of new source)
if (!nullObjectChecker.checkIsNotNullOrUndefinedOrBlank(sEntitySet) || aAllEntities.indexOf(sEntitySet) === -1) {
if (nullObjectChecker.checkIsNotNullOrUndefinedOrBlank(aAllEntities)) {
sEntitySet = oController.getAllEntities(sSource)[0];
}
}
oController.byId("idEntity").setSelectedKey(sEntitySet);
}
// Sets select properties on init or change
function _setSelectProperties(oController) {
var sSource, sEntitySet, aSelectProperties, aProperties, oModelForSelectProps, aCommonProps;
sSource = oController.byId("idSource").getValue();
// Default state
oController.byId("idSelectProperties").setModel(null);
oController.byId("idSelectProperties").setSelectedKeys([]);
// if no source nothing to set
if (!nullObjectChecker.checkIsNotNullOrUndefinedOrBlank(sSource)) {
return;
}
sEntitySet = oController.byId("idEntity").getSelectedKey();
// if no entity nothing to set
if (!nullObjectChecker.checkIsNotNullOrUndefinedOrBlank(sEntitySet)) {
return;
}
// setModel
aProperties = oController.getAllEntitySetProperties(sSource, sEntitySet);
oModelForSelectProps = optionsValueModelBuilder.convert(aProperties);
oController.byId("idSelectProperties").setModel(oModelForSelectProps);
// setSelectedKeys
// scenario:
// 1. common properties in case of existing filter, intersection between already available select properties on parent object and all properties on entity/source
// 2. common properties in case of new filter, intersection between already available select properties on parent object and all properties on entity/source is empty
// implies that there is nothing to set.
aSelectProperties = oController.getSelectProperties();
if (nullObjectChecker.checkIsNotNullOrUndefinedOrBlank(aSelectProperties)) {
aCommonProps = _getIntersection(aSelectProperties, aProperties);
aSelectProperties = aCommonProps;
}
oController.byId("idSelectProperties").setSelectedKeys(aSelectProperties);
}
// attaches events to the current view.
function _attachEvents(oController) {
oController.byId("idSource").attachEvent("selectService", oController.handleSelectionOfService.bind(oController));
}
// Determines and returns intersection of existing properties and total entity set
function _getIntersection(aExistingProps, aTotalSet) {
var resultedIntersection = [];
if (!nullObjectChecker.checkIsNotNullOrUndefinedOrBlank(aExistingProps) || !nullObjectChecker.checkIsNotNullOrUndefinedOrBlank(aTotalSet)) {
return resultedIntersection;
}
// intersection logic
aExistingProps.forEach(function(property) {
if (aTotalSet.indexOf(property) !== -1) {
resultedIntersection.push(property);
}
});
return resultedIntersection;
}
return Controller.extend("sap.apf.modeler.ui.controller.requestOptions", {
viewValidator : {},
oConfigurationEditor : {},
oParentObject : {},
// Called on initialization of the sub view and set the static texts and data for all controls in sub view
onInit : function() {
var oController = this;
oController.viewValidator = new sap.apf.modeler.ui.utils.ViewValidator(oController.getView());
oController.oConfigurationEditor = oController.getView().getViewData().oConfigurationEditor;
oController.oParentObject = oController.getView().getViewData().oParentObject;
_enableAutoComplete(oController);
oController.setDetailData();
oController.setDisplayText();
_attachEvents(oController);
},
// Called on initialization of the view to set data on fields of sub view
setDetailData : function() {
var oController = this;
_setSource(oController);
_setEntity(oController);
_setSelectProperties(oController);
},
// Called on reset of parent object in order to update parent object instance and configuration editor instance
updateSubViewInstancesOnReset : function(oEvent) {
var oController = this;
oController.oConfigurationEditor = oEvent.mParameters[0];
oController.oParentObject = oEvent.mParameters[1];
oController.setDetailData();
},
//Stub to be implemented in sub views to set display text of controls
setDisplayText : function() {
},
// Updates service of sub view and later entity and select properties if needed and fires relevant events if implemented by sub view
handleChangeForSource : function() {
var oController = this, sEntity, aSelectProperties;
var sSource = oController.byId("idSource").getValue().trim();
if (nullObjectChecker.checkIsNotNullOrUndefinedOrBlank(sSource) && oController.oConfigurationEditor.registerService(sSource)) {
oController.addOrRemoveMandatoryFieldsAndRequiredFlag(true);
oController.updateSource(sSource);
} else {
oController.clearSource();
oController.addOrRemoveMandatoryFieldsAndRequiredFlag(false);
}
_setEntity(oController);
sEntity = oController.byId("idEntity").getSelectedKey();
oController.updateEntity(sEntity);
_setSelectProperties(oController);
aSelectProperties = oController.byId("idSelectProperties").getSelectedKeys();
oController.updateSelectProperties(aSelectProperties);
oController.oConfigurationEditor.setIsUnsaved();
oController.fireRelevantEvents();
},
// Updates entity set of sub view and later select properties if needed and fires relevant events if implemented by sub view
handleChangeForEntity : function() {
var oController = this, sEntity, aSelectProperties;
sEntity = oController.byId("idEntity").getSelectedKey();
oController.updateEntity(sEntity);
_setSelectProperties(oController);
aSelectProperties = oController.byId("idSelectProperties").getSelectedKeys();
oController.updateSelectProperties(aSelectProperties);
oController.oConfigurationEditor.setIsUnsaved();
oController.fireRelevantEvents();
},
// Updates select properties of sub view and later fires relevant events if implemented by sub view
handleChangeForSelectProperty : function() {
var oController = this;
var aSelectProperties = oController.byId("idSelectProperties").getSelectedKeys();
oController.updateSelectProperties(aSelectProperties);
oController.oConfigurationEditor.setIsUnsaved();
oController.fireRelevantEvents();
},
//Stub to be implemented in sub views in case of any events to be handled on change of source, entity set or select properties
fireRelevantEvents : function() {
},
// Adds/removes required tag to entity set and select properties fields and accepts a boolean to determine required
addOrRemoveMandatoryFieldsAndRequiredFlag : function(bRequired) {
var oController = this;
oController.byId("idEntityLabel").setRequired(bRequired);
oController.byId("idSelectPropertiesLabel").setRequired(bRequired);
if (bRequired) {
oController.viewValidator.addFields([ "idEntity", "idSelectProperties" ]);
} else {
oController.viewValidator.removeFields([ "idEntity", "idSelectProperties" ]);
}
},
// Handles Service selection from the Select Dialog
handleSelectionOfService : function(oEvent) {
var selectedService = oEvent.getParameters()[0];
oEvent.getSource().setValue(selectedService);
// Event is getting trigered by service control
oEvent.getSource().fireEvent("change");
},
// Handles Opening of Value Help Request Dialog.
handleShowValueHelpRequest : function(oEvent) {
var oController = this;
var oViewData = {
oTextReader : oController.getView().getViewData().oTextReader,
// passing the source of control from which the event got triggered
parentControl : oEvent.getSource(),
getCalatogServiceUri : oController.getView().getViewData().getCalatogServiceUri
};
sap.ui.view({
id : oController.createId("idCatalogServiceView"),
viewName : "sap.apf.modeler.ui.view.catalogService",
type : sap.ui.core.mvc.ViewType.XML,
viewData : oViewData
});
},
// Stubs to be implemented in sub views depending on sub view logic
getSource : function() {
},
getAllEntities : function(sSource) {
},
getAllEntitySetProperties : function(sSource, sEntitySet) {
},
getEntity : function() {
},
clearSource : function() {
},
clearEntity : function() {
},
clearSelectProperties : function() {
},
updateSource : function(sSource) {
},
updateEntity : function(sEntity) {
},
updateSelectProperties : function(aSelectProperties) {
},
getSelectProperties : function() {
}
});
});
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.suite.ui.microchart.Example.
sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* Constructor for a new DeltaMicroChart control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Represents the delta of two values as a chart. This control replaces the deprecated sap.suite.ui.commons.DeltaMicroChart.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.DeltaMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var DeltaMicroChart = Control.extend("sap.suite.ui.microchart.DeltaMicroChart", /** @lends sap.suite.ui.microchart.DeltaMicroChart.prototype */ { metadata: {
library: "sap.suite.ui.microchart",
properties: {
/**
* The first value for delta calculation.
*/
value1: {type: "float", group: "Misc", defaultValue: null},
/**
* The second value for delta calculation.
*/
value2: {type: "float", group: "Misc", defaultValue: null},
/**
* The first value title.
*/
title1: {type: "string", group: "Misc", defaultValue: null},
/**
* The second value title.
*/
title2: {type: "string", group: "Misc", defaultValue: null},
/**
* If this property is set, it is rendered instead of value1.
*/
displayValue1: {type: "string", group: "Misc", defaultValue: null},
/**
* If this property is set, it is rendered instead of value2.
*/
displayValue2: {type: "string", group: "Misc", defaultValue: null},
/**
* If this property is set, it is rendered instead of a calculated delta.
*/
deltaDisplayValue: {type: "string", group: "Misc", defaultValue: null},
/**
* The semantic color of the delta value.
*/
color: {type: "sap.m.ValueColor", group: "Misc", defaultValue: "Neutral"},
/**
* The width of the chart.
*/
width: {type: "sap.ui.core.CSSSize", group: "Misc"},
/**
* The size of the chart. If is not set, the default size is applied based on the device type.
*/
size: {type: "sap.m.Size", group: "Misc", defaultValue: "Auto"}
},
events: {
/**
* The event is fired when the user chooses the delta micro chart.
*/
press: {}
}
}});
DeltaMicroChart.prototype.init = function() {
this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this.setTooltip("{AltText}");
};
DeltaMicroChart.prototype._calcChartData = function() {
var fVal1 = this.getValue1();
var fVal2 = this.getValue2();
var fMin = Math.min(fVal1, fVal2, 0);
var fMax = Math.max(fVal1, fVal2, 0);
var fTotal = fMax - fMin;
function calcPercent(fVal) {
return (fTotal === 0 ? 0 : Math.abs(fVal) / fTotal * 100).toFixed(2);
}
var oConf = {};
var fDelta = fVal1 - fVal2;
oConf.delta = {
left: fMax === 0,
width: calcPercent(fDelta),
isFirstStripeUp: fVal1 < fVal2,
isMax: (fVal1 < 0 && fVal2 >= 0) || (fVal1 >= 0 && fVal2 < 0),
isZero: fVal1 === 0 && fVal2 === 0,
isEqual: fDelta === 0
};
oConf.bar1 = {
left: fVal2 >= 0,
width: calcPercent(fVal1),
isSmaller: Math.abs(fVal1) < Math.abs(fVal2)
};
oConf.bar2 = {
left: fVal1 >= 0,
width: calcPercent(fVal2),
isSmaller: Math.abs(fVal2) < Math.abs(fVal1)
};
return oConf;
};
DeltaMicroChart.prototype._getLocalizedColorMeaning = function(sColor) {
return this._oRb.getText(("SEMANTIC_COLOR_" + sColor).toUpperCase());
};
/**
* Calculates the number of digits after the decimal point.
*
* @param {float} fValue float value
* @returns {int} number of digits after the decimal point in fValue.
* @private
*/
DeltaMicroChart.prototype._digitsAfterDecimalPoint = function(fValue) {
var sAfter = ("" + fValue).match(/[.,](\d+)/g);
return (sAfter) ? ("" + sAfter).length - 1 : 0;
};
DeltaMicroChart.prototype.getAltText = function() {
var sDv1 = this.getDisplayValue1();
var sDv2 = this.getDisplayValue2();
var sDdv = this.getDeltaDisplayValue();
var fVal1 = this.getValue1();
var fVal2 = this.getValue2();
var sAdv1ToShow = sDv1 ? sDv1 : "" + fVal1;
var sAdv2ToShow = sDv2 ? sDv2 : "" + fVal2;
var sAddvToShow = sDdv ? sDdv : "" + Math.abs(fVal1 - fVal2).toFixed(Math.max(this._digitsAfterDecimalPoint(fVal1), this._digitsAfterDecimalPoint(fVal2)));
var sMeaning = this._getLocalizedColorMeaning(this.getColor());
return this.getTitle1() + " " + sAdv1ToShow + "\n" + this.getTitle2() + " " + sAdv2ToShow + "\n" + this._oRb.getText("DELTAMICROCHART_DELTA_TOOLTIP", [sAddvToShow, sMeaning]);
};
DeltaMicroChart.prototype.getTooltip_AsString = function() {
var oTooltip = this.getTooltip();
var sTooltip = this.getAltText();
if (typeof oTooltip === "string" || oTooltip instanceof String) {
sTooltip = oTooltip.split("{AltText}").join(sTooltip).split("((AltText))").join(sTooltip);
return sTooltip;
}
return oTooltip ? oTooltip : "";
};
DeltaMicroChart.prototype._isCalcSupported = function() {
return jQuery.sap.byId(this.getId() + "-calc").css("max-width") == "11px";
};
DeltaMicroChart.prototype._isRoundingSupported = function() {
return jQuery.sap.byId(this.getId() + "-calc1").width() == 4;
};
DeltaMicroChart.prototype.onBeforeRendering = function() {
this._oChartData = this._calcChartData();
};
DeltaMicroChart.prototype.onAfterRendering = function() {
this._bCalc = this._isCalcSupported();
this._bRounding = this._isRoundingSupported();
if (!this._bCalc || !this._bRounding) {
if (this._sResizeHandlerId) {
sap.ui.core.ResizeHandler.deregister(this._sResizeHandlerId);
}
var oChart = jQuery.sap.domById(this.getId() + "-dmc-chart");
this._sResizeHandlerId = sap.ui.core.ResizeHandler.register(oChart, jQuery.proxy(this._adjust, this));
if (!this._bCalc) {
this._adjustCalc();
}
if (!this._bRounding) {
this._adjustRound();
}
}
};
DeltaMicroChart.prototype._adjust = function() {
if (!this._bCalc) {
this._adjustCalc();
}
if (!this._bRounding) {
this._adjustRound();
}
};
DeltaMicroChart.prototype._adjustRound = function() {
var iChartWidth = jQuery.sap.byId(this.getId() + "-dmc-chart").width();
var iDeltaWidth = Math.round(iChartWidth * this._oChartData.delta.width / 100);
jQuery.sap.byId(this.getId() + "-dmc-bar-delta").width(iDeltaWidth);
if (this._oChartData.bar1.isSmaller && !this._oChartData.delta.isMax) {
jQuery.sap.byId(this.getId() + "-dmc-bar1").width(iChartWidth - iDeltaWidth);
}
if (this._oChartData.bar2.isSmaller && !this._oChartData.delta.isMax) {
jQuery.sap.byId(this.getId() + "-dmc-bar2").width(iChartWidth - iDeltaWidth);
}
};
DeltaMicroChart.prototype._adjustCalc = function() {
var iChartWidth = jQuery.sap.byId(this.getId() + "-dmc-chart").width();
function adjustBar(oBar) {
oBar.css("max-width", iChartWidth - parseInt(oBar.css("max-width"), 10) + "px");
}
adjustBar(jQuery.sap.byId(this.getId() + "-dmc-bar1"));
adjustBar(jQuery.sap.byId(this.getId() + "-dmc-bar2"));
adjustBar(jQuery.sap.byId(this.getId() + "-dmc-bar-delta"));
};
DeltaMicroChart.prototype.attachEvent = function(sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData, fnFunction, oListener);
if (this.hasListeners("press")) {
this.$().attr("tabindex", 0).addClass("sapSuiteUiMicroChartPointer");
}
return this;
};
DeltaMicroChart.prototype.detachEvent = function(sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction, oListener);
if (!this.hasListeners("press")) {
this.$().removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer");
}
return this;
};
DeltaMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.internet_explorer) {
this.$().focus();
}
this.firePress();
};
DeltaMicroChart.prototype.onkeydown = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.SPACE) {
oEvent.preventDefault();
}
};
DeltaMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.ENTER || oEvent.which == jQuery.sap.KeyCodes.SPACE) {
this.firePress();
oEvent.preventDefault();
}
};
return DeltaMicroChart;
});
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define(['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* @class FieldList renderer.
* @static
*/
var FieldListRenderer = {};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
* @param {sap.ui.comp.smartform.flexibility.FieldList} oControl an object representation of the control that should be rendered
*/
FieldListRenderer.render = function(oRm, oControl) {
// write the HTML into the render manager
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapUiCompFieldList");
oRm.writeClasses();
oRm.write(">"); // span element
FieldListRenderer.renderNodes(oRm, oControl);
oRm.write("</div>");
};
/**
* Renders the child nodes from the aggregation nodes
*
* @param {sap.ui.core.RenderManager} oRm RenderManager
* @param {sap.ui.comp.smartform.flexibility.FieldList} oControl field list node
* @private
*/
FieldListRenderer.renderNodes = function(oRm, oControl) {
var aNodes, length, i;
aNodes = oControl.getNodes();
length = aNodes.length;
for (i = 0; i < length; i++) {
oRm.renderControl(aNodes[i]);
}
};
return FieldListRenderer;
}, /* bExport= */ true);
<file_sep>sap.ovp[version] = 1.36.12
sap.ovp[dependencies] = sap.ui.core,sap.ui.layout,sap.ui.generic.app,sap.m,sap.ui.comp
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides the Design Time Metadata for the sap.ui.comp.smartform.Group control
sap.ui.define([],
function() {
"use strict";
return {
aggregations : {
groupElements : {
ignore : true
},
formElements : {
domRef : ":sap-domref"
}
},
name: "{name}",
description: "{description}"
};
}, /* bExport= */ true);<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define(['jquery.sap.global'],function(q){"use strict";var F={};F.render=function(r,c){r.write("<div");r.writeControlData(c);r.addClass("sapUiCompFieldList");r.writeClasses();r.write(">");F.renderNodes(r,c);r.write("</div>");};F.renderNodes=function(r,c){var n,l,i;n=c.getNodes();l=n.length;for(i=0;i<l;i++){r.renderControl(n[i]);}};return F;},true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2015 SAP SE. All rights reserved
*/
sap.ui.define([
"sap/ui/core/Control", "sap/gantt/misc/Utility", "../misc/AxisTime", "sap/ui/thirdparty/d3"
], function (Control, Utility, AxisTime) {
"use strict";
var LegendBase = Control.extend("sap.gantt.legend.LegendBase", {
metadata: {
abstract: true,
properties: {
svgDefs: {type: "array"},
legendWidth: {type: "number", defaultValue: 32}, // width in pixels in compact mode
legendHeight: {type: "number", defaultValue: 32}, // height in pixels in compact mode
/**
* Font size of legend item texts.
*/
fontSize: {type: "number", defaultValue: 16} // font size for legend text
}
}
});
// timestamp to create a fake axistime.
LegendBase.prototype.TIME_RANGE = ["20160101000000", "20160103000000"];
// middle timestamp of the time axis.
LegendBase.prototype.TIME = "20160102000000";
LegendBase.prototype.init = function () {
this._aTimeRange = [d3.time.format("%Y%m%d%H%M%S").parse(this.TIME_RANGE[0]),
d3.time.format("%Y%m%d%H%M%S").parse(this.TIME_RANGE[1])];
};
LegendBase.prototype.getAxisTime = function () {
return this._oAxisTime;
};
LegendBase.prototype.onBeforeRendering = function () {
this._sUiSizeMode = Utility.findSapUiSizeClass();
this._aViewRange = [0, this._getScaledLegendWidth()];
this._oAxisTime = new AxisTime(this._aTimeRange, this._aViewRange);
// for calendar
// this._oStatusSet = {
// aViewBoundary: this._aViewRange
// };
};
LegendBase.prototype._getScaledLegendWidth = function () {
return Utility.scaleBySapUiSize(this.getSapUiSizeClass(), this.getLegendWidth());
};
LegendBase.prototype._getScaledLegendHeight = function () {
return Utility.scaleBySapUiSize(this.getSapUiSizeClass(), this.getLegendHeight());
};
LegendBase.prototype.getSapUiSizeClass = function () {
return this._sUiSizeMode;
};
return LegendBase;
}, true);<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.suite.ui.microchart.ComparisonMicroChart.
sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* Constructor for a new ComparisonMicroChart control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Illustrates values as colored bar charts with title, numeric value, and scaling factor in the content area. This control replaces the deprecated sap.suite.ui.commons.ComparisonChart.
* @extends sap.ui.core.Control
*
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.ComparisonMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ComparisonMicroChart = Control.extend("sap.suite.ui.microchart.ComparisonMicroChart", /** @lends sap.suite.ui.microchart.ComparisonMicroChart.prototype */ { metadata : {
library: "sap.suite.ui.microchart",
properties: {
/**
* The size of the microchart. If not set, the default size is applied based on the size of the device tile.
*/
size: {type: "sap.m.Size", group: "Misc", defaultValue: "Auto"},
/**
* The scaling suffix that is added to the actual and target values.
*/
scale: {type: "string", group: "Misc", defaultValue: ""},
/**
* The width of the chart. If it is not set, the size of the control is defined by the size property.
*/
width: {type: "sap.ui.core.CSSSize", group: "Misc"},
/**
* The view of the chart. If not set, the Normal view is used by default.
*/
view: {type: "sap.suite.ui.microchart.ComparisonMicroChartViewType", group: "Appearance", defaultValue: "Normal"},
/**
* The color palette for the chart. If this property is set, semantic colors defined in ComparisonData are ignored. Colors from the palette are assigned to each bar consequentially. When all the palette colors are used, assignment of the colors begins from the first palette color.
*/
colorPalette: {type: "string[]", group: "Appearance", defaultValue: []},
/**
* If it is set to true, the height of the control is defined by its content.
*/
shrinkable: {type: "boolean", group: "Misc", defaultValue: "false"},
/**
* Height of the chart.
*/
height: {type: "sap.ui.core.CSSSize", group: "Appearance"}
},
aggregations: {
/**
* The comparison chart bar data.
*/
data: {type: "sap.suite.ui.microchart.ComparisonMicroChartData", multiple: true}
},
events: {
/**
* The event is fired when the user chooses the comparison microchart.
*/
press : {}
}
}});
ComparisonMicroChart.prototype.init = function(){
this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this.setTooltip("{AltText}");
};
/**
* Calculates the width in percents of chart bars' elements accordingly with provided chart values.
*
* @returns {Array} array of calculated values for each chart bar.
* @private
*/
ComparisonMicroChart.prototype._calculateChartData = function() {
var aResult = [];
var aData = this.getData();
var iCount = aData.length;
var iMaxValue = 0;
var iMinValue = 0;
var iTotal;
var iMaxPercent;
var iMinPercent;
var i;
for (i = 0; i < iCount; i++) {
var iDataValue = isNaN(aData[i].getValue()) ? 0 : aData[i].getValue();
iMaxValue = Math.max(iMaxValue, iDataValue);
iMinValue = Math.min(iMinValue, iDataValue);
}
iTotal = iMaxValue - iMinValue;
iMaxPercent = (iTotal == 0) ? 0 : Math.round(iMaxValue * 100 / iTotal);
if (iMaxPercent == 0 && iMaxValue != 0) {
iMaxPercent = 1;
} else if (iMaxPercent == 100 && iMinValue != 0) {
iMaxPercent = 99;
}
iMinPercent = 100 - iMaxPercent;
for (i = 0; i < iCount; i++) {
var oItem = {};
var iDataVal = isNaN(aData[i].getValue()) ? 0 : aData[i].getValue();
oItem.value = (iTotal == 0) ? 0 : Math.round(iDataVal * 100 / iTotal);
if (oItem.value == 0 && iDataVal != 0) {
oItem.value = (iDataVal > 0) ? 1 : -1;
} else if (oItem.value == 100) {
oItem.value = iMaxPercent;
} else if (oItem.value == -100) {
oItem.value = -iMinPercent;
}
if (oItem.value >= 0) {
oItem.negativeNoValue = iMinPercent;
oItem.positiveNoValue = iMaxPercent - oItem.value;
} else {
oItem.value = -oItem.value;
oItem.negativeNoValue = iMinPercent - oItem.value;
oItem.positiveNoValue = iMaxPercent;
}
aResult.push(oItem);
}
return aResult;
};
ComparisonMicroChart.prototype.attachEvent = function(sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData, fnFunction, oListener);
if (this.hasListeners("press")) {
this.$().attr("tabindex", 0).addClass("sapSuiteUiMicroChartPointer");
}
return this;
};
ComparisonMicroChart.prototype.detachEvent = function(sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction, oListener);
if (!this.hasListeners("press")) {
this.$().removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer");
}
return this;
};
ComparisonMicroChart.prototype._getLocalizedColorMeaning = function(sColor) {
return this._oRb.getText(("SEMANTIC_COLOR_" + sColor).toUpperCase());
};
ComparisonMicroChart.prototype.getAltText = function() {
var sScale = this.getScale();
var sAltText = "";
for (var i = 0; i < this.getData().length; i++) {
var oBar = this.getData()[i];
var sMeaning = (this.getColorPalette().length) ? "" : this._getLocalizedColorMeaning(oBar.getColor());
sAltText += ((i == 0) ? "" : "\n") + oBar.getTitle() + " " + (oBar.getDisplayValue() ? oBar.getDisplayValue() : oBar.getValue()) + sScale + " " + sMeaning;
}
return sAltText;
};
ComparisonMicroChart.prototype.getTooltip_AsString = function() {
var oTooltip = this.getTooltip();
var sTooltip = this.getAltText();
if (typeof oTooltip === "string" || oTooltip instanceof String) {
sTooltip = oTooltip.split("{AltText}").join(sTooltip).split("((AltText))").join(sTooltip);
return sTooltip;
}
return oTooltip ? oTooltip : "";
};
ComparisonMicroChart.prototype._adjustBars = function() {
var iHeight = parseFloat(this.$().css("height"));
var iBarCount = this.getData().length;
var aBarContainers = this.$().find(".sapSuiteCmpChartItem");
var iMinH = parseFloat(aBarContainers.css("min-height"));
var iMaxH = parseFloat(aBarContainers.css("max-height"));
var iBarContHeight;
if (iBarCount != 0) {
iBarContHeight = iHeight / iBarCount;
if (iBarContHeight > iMaxH) {
iBarContHeight = iMaxH;
} else if (iBarContHeight < iMinH) {
iBarContHeight = iMinH;
}
aBarContainers.css("height", iBarContHeight);
if (this.getView() === "Wide" ) {
this.$().find(".sapSuiteCmpChartBar>div").css("height", (iBarContHeight * 79 / 42) + "%");
} else if (this.getView() === "Normal") {
this.$().find(".sapSuiteCmpChartBar>div").css("height", (iBarContHeight - 19) + "%");
}
var iChartsHeightDelta = (iHeight - iBarContHeight * iBarCount) / 2;
if (iChartsHeightDelta > 0) {
jQuery(aBarContainers[0]).css("margin-top", iChartsHeightDelta + 7 + "px");
}
}
};
ComparisonMicroChart.prototype.onAfterRendering = function() {
if (this.getHeight() != "") {
var that = this;
sap.ui.Device.media.attachHandler(function(){
that._adjustBars();
});
this._adjustBars();
}
};
ComparisonMicroChart.prototype._getBarAltText = function(iBarIndex) {
var sScale = this.getScale();
var oBar = this.getData()[iBarIndex];
var sMeaning = (this.getColorPalette().length) ? "" : this._getLocalizedColorMeaning(oBar.getColor());
return oBar.getTitle() + " " + (oBar.getDisplayValue() ? oBar.getDisplayValue() : oBar.getValue()) + sScale + " " + sMeaning;
};
ComparisonMicroChart.prototype.onsaptabnext = function(oEvent) {
var oLast = this.$().find(":focusable").last(); // last tabstop in the control
if (oLast) {
this._bIgnoreFocusEvt = true;
oLast.get(0).focus();
}
};
ComparisonMicroChart.prototype.onsaptabprevious = function(oEvent) {
if (oEvent.target.id != oEvent.currentTarget.id) {
var oFirst = this.$().find(":focusable").first(); // first tabstop in the control
if (oFirst) {
oFirst.get(0).focus();
}
}
};
ComparisonMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.edge) {
this.onclick(oEvent);
}
};
ComparisonMicroChart.prototype.onclick = function(oEvent) {
if (!this.fireBarPress(oEvent)) {
if (sap.ui.Device.browser.internet_explorer || sap.ui.Device.browser.edge) {
this.$().focus();
}
this.firePress();
}
};
ComparisonMicroChart.prototype.onkeydown = function(oEvent) {
switch (oEvent.keyCode) {
case jQuery.sap.KeyCodes.SPACE:
oEvent.preventDefault();
break;
case jQuery.sap.KeyCodes.ARROW_LEFT:
case jQuery.sap.KeyCodes.ARROW_UP:
var oFocusables = this.$().find(":focusable"); // all tabstops in the control
var iThis = oFocusables.index(oEvent.target); // focused element index
if (oFocusables.length > 0) {
oFocusables.eq(iThis - 1).get(0).focus(); // previous tab stop element
oEvent.preventDefault();
oEvent.stopPropagation();
}
break;
case jQuery.sap.KeyCodes.ARROW_DOWN:
case jQuery.sap.KeyCodes.ARROW_RIGHT:
var oFocusable = this.$().find(":focusable"); // all tabstops in the control
var iThisEl = oFocusable.index(oEvent.target); // focused element index
if (oFocusable.length > 0) {
oFocusable.eq((iThisEl + 1 < oFocusable.length) ? iThisEl + 1 : 0).get(0).focus(); // next tab stop element
oEvent.preventDefault();
oEvent.stopPropagation();
}
break;
default:
}
};
ComparisonMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.ENTER || oEvent.which == jQuery.sap.KeyCodes.SPACE) {
if (!this.fireBarPress(oEvent)) {
this.firePress();
oEvent.preventDefault();
}
}
};
ComparisonMicroChart.prototype.fireBarPress = function(oEvent) {
var oBar = jQuery(oEvent.target);
if (oBar && oBar.attr("data-bar-index")) {
var iIndex = parseInt(oBar.attr("data-bar-index"), 10);
var oComparisonData = this.getData()[iIndex];
if (oComparisonData) {
oComparisonData.firePress();
oEvent.preventDefault();
oEvent.stopPropagation();
if (sap.ui.Device.browser.internet_explorer) {
jQuery.sap.byId(this.getId() + "-chart-item-bar-" + iIndex).focus();
}
return true;
}
}
return false;
};
ComparisonMicroChart.prototype.setBarPressable = function(iBarIndex, bPressable) {
if (bPressable) {
var sBarAltText = this._getBarAltText(iBarIndex);
jQuery.sap.byId(this.getId() + "-chart-item-bar-" + iBarIndex).addClass("sapSuiteUiMicroChartPointer").attr("tabindex", 0).attr("title", sBarAltText).attr("role", "presentation").attr("aria-label", sBarAltText);
} else {
jQuery.sap.byId(this.getId() + "-chart-item-bar-" + iBarIndex).removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer").removeAttr("title").removeAttr("role").removeAttr("aria-label");
}
};
ComparisonMicroChart.prototype.onfocusin = function(oEvent) {
if (this._bIgnoreFocusEvt) {
this._bIgnoreFocusEvt = false;
return;
}
if (this.getId() + "-hidden" == oEvent.target.id) {
this.$().focus();
oEvent.preventDefault();
oEvent.stopPropagation();
}
};
return ComparisonMicroChart;
});
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
jQuery.sap.declare("sap.apf.core.ajax");
jQuery.sap.require("sap.apf.core.utils.checkForTimeout");
(function() {
'use strict';
/**
* @memberOf sap.apf.core
* @description Wraps a jQuery (jQuery.ajax) request in order to handle a server time-out.
* @param {object} oSettings Configuration of the jQuery.ajax request.
* @returns {object} jqXHR
*/
sap.apf.core.ajax = function(oSettings) {
var oAjaxSettings = jQuery.extend(true, {}, oSettings);
var fnBeforeSend = oAjaxSettings.beforeSend;
var fnSuccess = oAjaxSettings.success;
var fnError = oAjaxSettings.error;
oAjaxSettings.beforeSend = function(jqXHR, settings) {
if (fnBeforeSend) {
fnBeforeSend(jqXHR, settings);
}
};
oAjaxSettings.success = function(data, textStatus, jqXHR) {
var oMessage = sap.apf.core.utils.checkForTimeout(jqXHR);
if (oMessage) {
fnError(data, "error", undefined, oMessage);
} else {
fnSuccess(data, textStatus, jqXHR);
}
};
oAjaxSettings.error = function(jqXHR, textStatus, errorThrown) {
var oMessage = sap.apf.core.utils.checkForTimeout(jqXHR);
if (oMessage) {
fnError(jqXHR, textStatus, errorThrown, oMessage);
} else {
fnError(jqXHR, textStatus, errorThrown);
}
};
return jQuery.ajax(oAjaxSettings);
};
}());<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
sap.ui.define(["jquery.sap.global","sap/ui/fl/FlexController","sap/ui/fl/Utils"],function(q,F,U){"use strict";var a={};a._instanceCache={};a.create=function(c){var f=a._instanceCache[c];if(!f){f=new F(c);a._instanceCache[c]=f;}return f;};a.createForControl=function(c){var C=U.getComponentClassName(c);return a.create(C);};return a;},true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2015 SAP SE. All rights reserved
*/
sap.ui.define([
"sap/ui/core/Control", "sap/ui/layout/Splitter", "sap/ui/layout/SplitterLayoutData", "sap/ui/core/Orientation",
"./legend/LegendContainer", "./control/Toolbar", "./control/AssociateContainer",
"./config/TimeHorizon", "./misc/Utility"
], function (Control, Splitter, SplitterLayoutData, Orientation, LegendContainer, Toolbar, AssociateContainer,
TimeHorizon, Utility) {
"use strict";
/**
* Creates and initializes a new Gantt chart container.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* A container that holds one or more <code>GanttChartBase</code> instances.
*
* <p> This class has several built-in several controls to support <code>GanttChartBase</code> instances:
* <ul>
* <li>A toolbar above all Gantt Charts. Many built-in controls can be enabled or disabled using configuration property <code>toolbarScheme</code>. Built-in functions include:
* <ul>
* <li>ComboBox for container selection</li>
* <li>Buttons for Add View, Delete View, and Switch Splitter Orientation</li>
* <li>Expand/Collapse groups for expandable charts</li>
* <li>A zooming slider</li>
* <li>A legend button</li>
* <li>A Settings button</li>
* </ul>
* If nothing is added to the toolbar, the toolbar is hidden automatically. For more information about the functions and configuration,
* see the API documentation of <code>sap.gantt.config.ToolbarScheme.</code>
* </li>
* <li>A Splitter containing aggregation <code>ganttCharts</code></li>
* </ul>
* </p>
*
* @extend sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.8
*
* @constructor
* @public
* @alias sap.gantt.GanttChartContainer
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var GanttChartContainer = Control.extend("sap.gantt.GanttChartContainer", /** @lends sap.gantt.GanttChartContainer.prototype */ {
metadata: {
library: "sap.gantt",
properties: {
/**
* Width of the control
*/
width: {type: "sap.ui.core.CSSSize", defaultValue: "100%"},
/**
* Height of the control
*/
height: {type: "sap.ui.core.CSSSize", defaultValue: "100%"},
/**
* Switch to enable and disable scroll synchronization by time on instances of aggregation <code>ganttCharts</code>.
*/
enableTimeScrollSync: {type: "boolean", defaultValue: true},
/**
* Switch to enable and disable scroll synchronization by row on instances of aggregation <code>ganttCharts</code>.
*/
enableRowScrollSync: {type: "boolean", defaultValue: false},
/**
* Switch to enable and disable the cursor line that follows the cursor.
*
* When this value is set, it overrides the corresponding value on instances of aggregation <code>ganttCharts</code>.
*/
enableCursorLine: {type: "boolean", defaultValue: true},
/**
* Switch to enable and disable the present time indicator.
*
* When this value is set, it overrides the corresponding value on instances of aggregation <code>ganttCharts</code>.
*/
enableNowLine: {type: "boolean", defaultValue: true},
/**
* Switch to enable and disable vertical lines representing intervals along the time axis.
*
* When this value is set, it overrides the corresponding value on instances of aggregation <code>ganttCharts</code>.
*/
enableVerticalLine: {type: "boolean", defaultValue: true},
/**
* Definitions of paint servers used for advanced shape features around SVG fill, stroke, and filter attributes.
*
* If this property is provided, the paint server definition of the SVG is rendered. Method <code>getDefString()</code> should be
* implemented by all paint server classes that are passed in in this property. It is easier to assign a common paint server definition
* in this class instead of in separate instances of <code>sap.gantt.GanttChartBase</code>. Then the definition is
* rendered only once.
*/
svgDefs: {type: "sap.gantt.def.SvgDefs", defaultValue: null},
/**
* List of available modes. To apply modes to the toolbar and shapes, further configuration is needed. (specifically,
* in property <code>toolbarSchemes</code>, and properties <code>toolbarSchemes</code> and <code>shapes</code> in
* the <code>GanttChartBase</code> class)If not provided, a default configuration is provided.
*/
modes: {type: "array", defaultValue: sap.gantt.config.DEFAULT_MODES},
/**
* List of available toolbar schemes. If not provided, a default configuration is provided.
*/
toolbarSchemes: {type: "array", defaultValue: sap.gantt.config.DEFAULT_CONTAINER_TOOLBAR_SCHEMES},
/**
* List of available hierarchies. If not provided, a default configuration is provided.
*/
hierarchies: {type: "array", defaultValue: sap.gantt.config.DEFAULT_HIERARCHYS},
/**
* Configuration of container layouts.
*
* This configuration affects the data source selection ComboBox in the Container Toolbar. When the selection
* changes, the <code>ganttChartChangeRequested</code> event that is triggered includes the corresponding layout key.
*/
containerLayouts: {type: "array", defaultValue: sap.gantt.config.DEFAULT_CONTAINER_LAYOUTS},
/**
* Current container layout key.
*
* This is a key configured in configuration property <code>containerLayouts</code>.
*/
containerLayoutKey: {type: "string", defaultValue: sap.gantt.config.DEFAULT_CONTAINER_SINGLE_LAYOUT_KEY},
/**
* Define the amount of units to change the time zoom slider.
*
* See {@link sap.m.Slider#setStep}
*/
sliderStep: {type: "int", defaultValue: 10}
},
aggregations: {
/**
* Legend shown when the legend button is clicked.
*
* This aggregation is used only when the Legend button is configured to be shown in the container toolbar.
*/
legendContainer: {type: "sap.gantt.legend.LegendContainer", multiple: false, visibility: "public"},
/**
* Controls to be placed in the container toolbar.
*
* <p>This aggregation is used only when the custom toolbar item group is configured to be shown in the container toolbar.
* Different from the built-in buttons that are configured to be shown or hidden, these controls are free controls created
* by the application, but are only placed in the container toolbar by <code>sap.gantt.GanttChartContainer</code>.</p>
*
* <p>If the source selection group is enabled and you want your application to use a container layout pre-configured
* for a specific source, you can implement your custom toolbar items in the event handler of event <code>ganttChartChangeRequested</code>.</p>
*/
customToolbarItems: {type: "sap.ui.core.Control", multiple: true, visibility: "public",
singularName: "customToolbarItem", bindable: "bindable"},
/**
* Gantt chart instances.
*
* <p>If the source selection group is enabled and you want your application to use a container layout pre-configured
* for a specific source, you can implement your custom toolbar items in the event handler of event <code>ganttChartChangeRequested</code>.</p>
* <p>Provide a Gantt chart in compliance with the container layout setting.
* GanttChartContainer is designed to support Gantt chart layouts that include multiple views.</p>
*/
ganttCharts: {type: "sap.gantt.GanttChartBase", multiple: true, visibility: "public", singularName: "ganttChart", bindable: "bindable"},
_toolbar: {type: "sap.gantt.control.Toolbar", multiple: false, visibility: "hidden"}
},
events: {
/**
* Event fired when any change occurs in the toolbar that requests the application to change aggregation <code>ganttCharts</code>.
*
* <p>Possible triggers are:
* <ul>
* <li>The source selection group changes in the container toolbar.</li>
* <li>The layout group button is clicked in the container toolbar.</li>
* <li>The source selection group changes in the Gantt chart toolbar.</li>
* </ul>
* </p>
*/
ganttChartChangeRequested: {
parameters: {
/**
* Action that caused the change.
*
* <p>Possible action values are:
* <ul>
* <li><code>'switchGanttChart'</code>: The source selection group of one Gantt chart toolbar is changed.</li>
* <li><code>'addGanttChart'</code>: The Add Gantt chart dropdown menu is selected.</li>
* <li><code>'lessGanttChart'</code>: The Less Gantt chart dropdown menu is selected.</li>
* <li><code>'switchContainerLayout'</code>: The source selection group of the Container toolbar is changed.</li>
* </ul>
* </p>
*/
action: {type: "string"},
/**
* Provided for actions <code>'switchGanttChart'</code> and <code>'lessGanttChart'</code>.
*/
ganttChartIndex: {type: "int"},
/**
* Provided for actions <code>'switchGanttChart'</code>, <code>'addGanttChart'</code> and <code>'lessGanttChart'</code>.
*/
hierarchyKey: {type: "string"},
/**
* Provided for action <code>'switchGanttChart'</code>.
*/
oldHierarchyKey: {type: "string"},
/**
* Provided for action <code>'switchContainerLayout'</code>.
*/
containerLayoutKey: {type: "string"}
}
},
/**
* Event fired when the custom settings are changed.
*
* The Custom settings are application-injected settings that can be configured in the Settings dialog box. This event allows the application to handle these settings.
* Only check boxes are supported.
*/
customSettingChange: {
parameters: {
/**
* ID of the custom setting
*/
id: {type: "string"},
/**
* The value of the custom setting
*/
value: {type: "boolean"}
}
}
}
}
});
GanttChartContainer.prototype.init = function () {
jQuery.sap.measure.start("GanttChartContainer Init","GanttPerf:GanttChartContainer Init function");
this._bInitHorizonApplied = false;
this._oToolbar = new Toolbar({
type: sap.gantt.control.ToolbarType.Global,
sourceId: sap.gantt.config.DEFAULT_CONTAINER_SINGLE_LAYOUT_KEY
});
this._oToolbar.setSliderStep(this.getSliderStep());
this.setAggregation("_toolbar", this._oToolbar);
this._oToolbar.attachSourceChange(this._onToolbarSourceChange, this);
this._oToolbar.attachLayoutChange(this._onToolbarLayoutChange, this);
this._oToolbar.attachExpandChartChange(this._onToolbarExpandChartChange, this);
this._oToolbar.attachZoomRateChange(this._onToolbarZoomRateChange, this);
this._oToolbar.attachSettingsChange(this._onToolbarSettingsChange, this);
this._oToolbar.data("holder", this);
this._oSplitter = new Splitter({
width: "100%",
height: "100%",
orientation: Orientation.Vertical
});
this._oModesConfigMap = {};
this._oModesConfigMap[sap.gantt.config.DEFAULT_MODE_KEY] = sap.gantt.config.DEFAULT_MODE;
this._oToolbarSchemeConfigMap = {};
this._oToolbarSchemeConfigMap[sap.gantt.config.DEFAULT_CONTAINER_TOOLBAR_SCHEME_KEY] = sap.gantt.config.DEFAULT_CONTAINER_TOOLBAR_SCHEME;
this._oToolbarSchemeConfigMap[sap.gantt.config.DEFAULT_GANTTCHART_TOOLBAR_SCHEME_KEY] = sap.gantt.config.DEFAULT_GANTTCHART_TOOLBAR_SCHEME;
this._oToolbarSchemeConfigMap[sap.gantt.config.EMPTY_TOOLBAR_SCHEME_KEY] = sap.gantt.config.EMPTY_TOOLBAR_SCHEME;
this._oHierarchyConfigMap = {};
this._oHierarchyConfigMap[sap.gantt.config.DEFAULT_HIERARCHY_KEY] = sap.gantt.config.DEFAULT_HIERARCHY;
this._oContainerLayoutConfigMap = {};
this._oContainerLayoutConfigMap[sap.gantt.config.DEFAULT_CONTAINER_SINGLE_LAYOUT_KEY] = sap.gantt.config.DEFAULT_CONTAINER_SINGLE_LAYOUT;
this._oContainerLayoutConfigMap[sap.gantt.config.DEFAULT_CONTAINER_DUAL_LAYOUT_KEY] = sap.gantt.config.DEFAULT_CONTAINER_DUAL_LAYOUT;
jQuery.sap.measure.end("GanttChartContainer Init");
};
GanttChartContainer.prototype.applySettings = function (mSettings, oScope) {
var retVal = Control.prototype.applySettings.apply(this, arguments);
if (this.getContainerLayouts() && this.getContainerLayoutKey()) {
this.switchOrientation(null, true);
}
return retVal;
};
GanttChartContainer.prototype.setModes = function (aModes) {
this.setProperty("modes", aModes);
this._oToolbar.setModes(aModes);
// build a map for easy look up
this._oModesConfigMap = {};
if (aModes) {
for (var i = 0; i < aModes.length; i++) {
this._oModesConfigMap[aModes[i].getKey()] = aModes[i];
}
}
return this;
};
GanttChartContainer.prototype.setSliderStep = function (step) {
this.setProperty("sliderStep", step);
this._oToolbar.setSliderStep(step);
return this;
};
GanttChartContainer.prototype.setToolbarSchemes = function (aToolbarSchemes) {
this.setProperty("toolbarSchemes", aToolbarSchemes);
this._oToolbar.setToolbarSchemes(aToolbarSchemes);
// build a map for easy look up
this._oToolbarSchemeConfigMap = {};
if (aToolbarSchemes) {
for (var i = 0; i < aToolbarSchemes.length; i++) {
this._oToolbarSchemeConfigMap[aToolbarSchemes[i].getKey()] = aToolbarSchemes[i];
}
}
return this;
};
GanttChartContainer.prototype.setHierarchies = function (aHierarchies) {
this.setProperty("hierarchies", aHierarchies);
this._oToolbar.setHierarchies(aHierarchies);
// build a map for easy look up
this._oHierarchyConfigMap = {};
if (aHierarchies) {
for (var i = 0; i < aHierarchies.length; i++) {
this._oHierarchyConfigMap[aHierarchies[i].getKey()] = aHierarchies[i];
}
}
return this;
};
GanttChartContainer.prototype.setContainerLayouts = function (aContainerLayouts) {
this.setProperty("containerLayouts", aContainerLayouts);
this._oToolbar.setContainerLayouts(aContainerLayouts);
// build a map for easy look up
this._oContainerLayoutConfigMap = {};
if (aContainerLayouts) {
for (var i = 0; i < aContainerLayouts.length; i++) {
this._oContainerLayoutConfigMap[aContainerLayouts[i].getKey()] = aContainerLayouts[i];
}
}
if (this.getContainerLayoutKey()) {
this.switchOrientation(null, true);
}
return this;
};
GanttChartContainer.prototype.setEnableCursorLine = function (bEnableCursorLine) {
this.setProperty("enableCursorLine", bEnableCursorLine);
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++) {
aGanttCharts[i].setEnableCursorLine(bEnableCursorLine);
}
this.getAggregation("_toolbar").setEnableCursorLine(bEnableCursorLine);
return this;
};
GanttChartContainer.prototype.setEnableNowLine = function (bEnableNowLine) {
this.setProperty("enableNowLine", bEnableNowLine);
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++) {
aGanttCharts[i].setEnableNowLine(bEnableNowLine);
}
this.getAggregation("_toolbar").setEnableNowLine(bEnableNowLine);
return this;
};
GanttChartContainer.prototype.setEnableVerticalLine = function (bEnableVerticalLine) {
this.setProperty("enableVerticalLine", bEnableVerticalLine);
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++) {
aGanttCharts[i].setEnableVerticalLine(bEnableVerticalLine);
}
this.getAggregation("_toolbar").setEnableVerticalLine(bEnableVerticalLine);
return this;
};
GanttChartContainer.prototype.setEnableTimeScrollSync = function (bEnableTimeScrollSync) {
this.setProperty("enableTimeScrollSync", bEnableTimeScrollSync);
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++) {
aGanttCharts[i].detachHorizontalScroll(this._onGanttChartHSBScroll, this);
if (bEnableTimeScrollSync) {
aGanttCharts[i].attachHorizontalScroll(this._onGanttChartHSBScroll, this);
}
}
this.getAggregation("_toolbar").setEnableTimeScrollSync(bEnableTimeScrollSync);
return this;
};
GanttChartContainer.prototype.setEnableRowScrollSync = function (bEnableRowScrollSync) {
this.setProperty("enableRowScrollSync", bEnableRowScrollSync);
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++){
aGanttCharts[i].detachVerticalScroll(this._onGanttChartVSBScroll, this);
if (bEnableRowScrollSync) {
aGanttCharts[i].attachVerticalScroll(this._onGanttChartVSBScroll, this);
}
}
this.getAggregation("_toolbar").setEnableRowScrollSync(bEnableRowScrollSync);
return this;
};
GanttChartContainer.prototype.setContainerLayoutKey = function (sContainerLayoutKey) {
if (this.getProperty("containerLayoutKey") === sContainerLayoutKey) {
return this;
}
this.setProperty("containerLayoutKey", sContainerLayoutKey);
this._oToolbar.setSourceId(sContainerLayoutKey);
if (this.getContainerLayouts()) {
this.switchOrientation(null, true);
}
return this;
};
GanttChartContainer.prototype.setLegendContainer = function (oLegendContainer) {
this.setAggregation("legendContainer", oLegendContainer);
if (oLegendContainer){
this._oToolbar.setLegend(new AssociateContainer({
content: oLegendContainer.getId()
}));
}
return this;
};
GanttChartContainer.prototype.addCustomToolbarItem = function (oCustomToolbarItem) {
this._oToolbar.addCustomToolbarItem(oCustomToolbarItem);
};
GanttChartContainer.prototype.insertCustomToolbarItem = function (oCustomToolbarItem, iIndex) {
this._oToolbar.insertCustomToolbarItem(oCustomToolbarItem, iIndex);
};
GanttChartContainer.prototype.removeCustomToolbarItem = function (oCustomToolbarItem) {
this._oToolbar.removeCustomToolbarItem(oCustomToolbarItem);
};
GanttChartContainer.prototype.removeAllCustomToolbarItems = function () {
this._oToolbar.removeAllCustomToolbarItems();
};
GanttChartContainer.prototype.addGanttChart = function (oGanttChart) {
this.addAggregation("ganttCharts", oGanttChart);
if (oGanttChart) {
this._insertGanttChart(oGanttChart);
}
};
GanttChartContainer.prototype.insertGanttChart = function (oGanttChart, iIndex) {
this.insertAggregation("ganttCharts", oGanttChart, iIndex);
if (oGanttChart) {
this._insertGanttChart(oGanttChart, iIndex);
}
};
GanttChartContainer.prototype.removeGanttChart = function (vGanttChart) {
this._removeGanttChart(vGanttChart);
this.removeAggregation("ganttCharts", vGanttChart);
};
GanttChartContainer.prototype.removeAllGanttCharts = function () {
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++) {
this._removeGanttChart(aGanttCharts[i]);
}
this.removeAllAggregation("ganttCharts");
};
GanttChartContainer.prototype._insertGanttChart = function (oGanttChart, iIndex) {
jQuery.sap.measure.start("GanttChartContainer _insertGanttChart","GanttPerf:GanttChartContainer _insertGanttChart function");
if (!oGanttChart) {
return;
}
// wrap association container
var oAssociateContainer = new AssociateContainer({
content: oGanttChart.getId(),
layoutData: new SplitterLayoutData({
size: "auto"
})
});
if (iIndex !== 0 && !iIndex) {
this._oSplitter.addContentArea(oAssociateContainer);
} else {
this._oSplitter.insertContentArea(oAssociateContainer, iIndex);
}
// pass down properties
var oContainerLayoutConfig = this._oContainerLayoutConfigMap[this.getContainerLayoutKey()];
var sSelectionPanelSize = oContainerLayoutConfig.getSelectionPanelSize() ?
oContainerLayoutConfig.getSelectionPanelSize() : "Auto";
oGanttChart.setSelectionPanelSize(sSelectionPanelSize);
//oView.setTimeZoomRate(this._oToolbar.getZoomRate());
// attach events
if (this.getEnableTimeScrollSync()) {
oGanttChart.attachHorizontalScroll(this._onGanttChartHSBScroll, this);
}
//
if (this.getEnableRowScrollSync()){
oGanttChart.attachVerticalScroll(this._onGanttChartVSBScroll, this);
}
oGanttChart.attachSplitterResize(this._onViewSplitterResize, this);
oGanttChart.attachGanttChartSwitchRequested(this._onGanttChartSwitchRequested, this);
oGanttChart.attachChartDragEnter(this._onChartDragEnter, this);
oGanttChart.attachChartDragLeave(this._onChartDragLeave, this);
oGanttChart.attachShapeDragEnd(this._onChartDragEnd, this);
jQuery.sap.measure.end("GanttChartContainer _insertGanttChart");
};
GanttChartContainer.prototype._removeGanttChart = function (vGanttChart) {
var oGanttChart = vGanttChart;
if ((typeof vGanttChart) === "number") {
oGanttChart = this.getGanttCharts()[vGanttChart];
}
if (oGanttChart) {
// remove associated container
this._oSplitter.removeContentArea(oGanttChart._oAC);
// detach events
oGanttChart.detachHorizontalScroll(this._onGanttChartHSBScroll, this);
oGanttChart.detachVerticalScroll(this._onGanttChartVSBScroll, this);
oGanttChart.detachSplitterResize(this._onViewSplitterResize, this);
oGanttChart.detachGanttChartSwitchRequested(this._onGanttChartSwitchRequested, this);
oGanttChart.detachChartDragEnter(this._onChartDragEnter, this);
oGanttChart.detachChartDragLeave(this._onChartDragLeave, this);
oGanttChart.detachShapeDragEnd(this._onChartDragEnd, this);
}
};
GanttChartContainer.prototype.onBeforeRendering = function () {
this._detachEvents();
//View switch will initial global toolbar, need to reset the correct setting status to global toolbar
this._oToolbar.setEnableTimeScrollSync(this.getEnableTimeScrollSync());
this._oToolbar.setEnableRowScrollSync(this.getEnableRowScrollSync());
this._oToolbar.setEnableCursorLine(this.getEnableCursorLine());
this._oToolbar.setEnableNowLine(this.getEnableNowLine());
this._oToolbar.setEnableVerticalLine(this.getEnableVerticalLine());
var aGanttCharts = this.getGanttCharts();
// Views need to respect the setting in Gantt, especially when changing
// hierarchy layout, which triggered binding updated
for (var i = 0; i < aGanttCharts.length; i++) {
var oGanttChart = aGanttCharts[i];
oGanttChart.setEnableCursorLine(this.getEnableCursorLine());
oGanttChart.setEnableNowLine(this.getEnableNowLine());
oGanttChart.setEnableVerticalLine(this.getEnableVerticalLine());
}
};
GanttChartContainer.prototype._detachEvents = function () {};
GanttChartContainer.prototype.onAfterRendering = function () {
this._attachEvents();
};
GanttChartContainer.prototype._attachEvents = function () {
};
GanttChartContainer.prototype._detachToolbarEvents = function () {
this._oToolbar.detachSourceChange(this._onToolbarSourceChange, this);
this._oToolbar.detachLayoutChange(this._onToolbarLayoutChange, this);
this._oToolbar.detachExpandChartChange(this._onToolbarExpandChartChange, this);
this._oToolbar.detachZoomRateChange(this._onToolbarZoomRateChange, this);
this._oToolbar.detachSettingsChange(this._onToolbarSettingsChange, this);
};
GanttChartContainer.prototype._onGanttChartHSBScroll = function(oEvent){
var fLeftOffsetRate = oEvent.getParameters().leftOffsetRate;
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++){
if (oEvent.oSource.getId() === aGanttCharts[i].getId()){
continue;
}
aGanttCharts[i].jumpToPosition(fLeftOffsetRate);
}
};
GanttChartContainer.prototype._onGanttChartVSBScroll = function(oEvent){
var nScrollSteps = oEvent.getParameters().scrollSteps;
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++){
if (oEvent.oSource.getId() === aGanttCharts[i].getId()){
continue;
}
var oNowGanttChart = aGanttCharts[i]._oTC || aGanttCharts[i]._oTT;
oNowGanttChart._oVSb.setScrollPosition(nScrollSteps);
}
};
GanttChartContainer.prototype._onViewSplitterResize = function (oEvent) {
if (this._oSplitter.getOrientation() === Orientation.Vertical) {
this._syncSelectionPanelSizeBetweenViews(oEvent);
this._oToolbar.setZoomInfo(oEvent.getParameter("zoomInfo"));
}
};
GanttChartContainer.prototype._syncSelectionPanelSizeBetweenViews = function (oEvent) {
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++) {
if (oEvent.oSource.getId() === aGanttCharts[i].getId()) {
continue;
}
aGanttCharts[i].setSelectionPanelSize(oEvent.getParameter("newSizes")[0] + "px", true);
}
};
GanttChartContainer.prototype._onGanttChartSwitchRequested = function (oEvent) {
oEvent.getSource().notifySourceChange();
this.fireGanttChartChangeRequested({
action: "switchGanttChart",
hierarchyKey: oEvent.getParameter("hierarchyKey"),
oldHierarchyKey: oEvent.getParameter("oldHierarchyKey"),
ganttChartIndex: this.getGanttCharts().indexOf(oEvent.getSource())
});
};
GanttChartContainer.prototype._onToolbarLayoutChange = function (oEvent){
var sEventId = oEvent.getParameter("id");
var oEventValue = oEvent.getParameter("value");
switch (sEventId) {
case "orientation":
this.switchOrientation(oEventValue);
break;
case "add":
this.fireGanttChartChangeRequested({
action: "addGanttChart",
hierarchyKey: oEventValue.hierarchyKey
});
this._updateGanttChartSize();
break;
case "less":
this.fireGanttChartChangeRequested({
action: "lessGanttChart",
hierarchyKey: oEventValue.hierarchyKey,
ganttChartIndex: oEventValue.ganttChartIndex
});
this._updateGanttChartSize();
break;
default:
break;
}
};
GanttChartContainer.prototype._updateGanttChartSize = function() {
var aContents = this._oSplitter.getContentAreas();
for (var l = 0; l < aContents.length; l++) {
if (aContents[l].getLayoutData()) {
if (aContents[l].getLayoutData().getSize() === "auto") {
aContents[l].getLayoutData().setSize("100%");
}
aContents[l].getLayoutData().setSize("auto");
}
}
};
GanttChartContainer.prototype._onToolbarSourceChange = function (oEvent) {
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++) {
aGanttCharts[i].notifySourceChange();
}
this.setContainerLayoutKey(oEvent.getParameter("id"));
this.fireGanttChartChangeRequested({
action: "switchContainerLayout",
containerLayoutKey: oEvent.getParameter("id")
});
};
GanttChartContainer.prototype._onToolbarExpandChartChange = function (oEvent) {
var aGanttCharts = this.getGanttCharts();
for (var i = 0; i < aGanttCharts.length; i++) {
aGanttCharts[i].expandChartChange(oEvent);
}
};
GanttChartContainer.prototype._onToolbarZoomRateChange = function (oEvent) {
var aGanttCharts = this.getGanttCharts();
var i, oGanttChart;
for (i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
oGanttChart.setTimeZoomRate(oEvent.getParameter("zoomRate"));
}
if (this._bInitHorizonApplied) {
return;
}
this._bInitHorizonApplied = true;
for (i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
oGanttChart.jumpToPosition();
}
};
GanttChartContainer.prototype._onChartDragEnter = function (oEvent) {
//do the following only when the mouse is still down
var oSourceEvent = oEvent.getParameter("originEvent");
var oGanttChart = oEvent.getSource();
if (oSourceEvent.button == 0 && oSourceEvent.buttons !== 0 && this._oDraggingSource !== undefined) {
oGanttChart.setDraggingData(this._oDraggingSource);
this._oDraggingSource = undefined;
}else {
this._oDraggingSource = undefined;
oGanttChart.setDraggingData(this._oDraggingSource);
}
};
GanttChartContainer.prototype._onChartDragLeave = function (oEvent) {
var oParam = oEvent.getParameters();
if (oParam.draggingSource !== undefined) {
//drag out of chart
this._oDraggingSource = oParam.draggingSource;
}else {
this._oDraggingSource = undefined;
}
};
GanttChartContainer.prototype._onChartDragEnd = function (oEvent) {
this._oDraggingSource = undefined;
};
GanttChartContainer.prototype._onToolbarSettingsChange = function(oEvent){
var oParameters = oEvent.getParameters();
for (var i = 0; i < oParameters.length; i++) {
switch (oParameters[i].id) {
case sap.gantt.config.SETTING_ITEM_ENABLE_TIME_SCROLL_SYNC_KEY:
if (this.getEnableTimeScrollSync() !== oParameters[i].value) {
this.setEnableTimeScrollSync(oParameters[i].value);
}
break;
case sap.gantt.config.SETTING_ITEM_ROW_SCROLL_SYNC_KEY:
if (this.getEnableRowScrollSync() !== oParameters[i].value) {
this.setEnableRowScrollSync(oParameters[i].value);
}
break;
case sap.gantt.config.SETTING_ITEM_ENABLE_CURSOR_LINE_KEY:
if (this.getEnableCursorLine() !== oParameters[i].value) {
this.setEnableCursorLine(oParameters[i].value);
}
break;
case sap.gantt.config.SETTING_ITEM_ENABLE_NOW_LINE_KEY:
if (this.getEnableNowLine() !== oParameters[i].value) {
this.setEnableNowLine(oParameters[i].value);
}
break;
case sap.gantt.config.SETTING_ITEM_ENABLE_VERTICAL_LINE_KEY:
if (this.getEnableVerticalLine() !== oParameters[i].value) {
this.setEnableVerticalLine(oParameters[i].value);
}
break;
default:
this.fireCustomSettingChange(oParameters[i]);
}
}
};
/**
* Switches the splitter orientation.
*
* @param {string} [vOrientation] Target orientation. If not provided, this method inverts the orientation.
* @param {boolean} [bReadConfig] If this value is provided, it overrides the target orientation from the current configuration indicated by property <code>containerLayoutKey</code>.
* @returns {object} - <code>this</code>
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.switchOrientation = function (vOrientation, bReadConfig) {
// init target orientation by switch current orientation
var sOrientation = this._oSplitter.getOrientation() === Orientation.Horizontal ?
Orientation.Vertical :
Orientation.Horizontal;
// over-write target orientation by input
sOrientation = vOrientation ? vOrientation : sOrientation;
if (bReadConfig) { // if bReadConfig, over-write target orientation by config
var sContainerLayoutKey = this.getContainerLayoutKey();
if (this._oContainerLayoutConfigMap[sContainerLayoutKey]) {
sOrientation = this._oContainerLayoutConfigMap[sContainerLayoutKey].getOrientation();
}
} else { // else, reset view ratio to 'auto'
this._resetSplitterLayoutData(sOrientation);
}
this._oSplitter.setOrientation(sOrientation);
return this;
};
GanttChartContainer.prototype._resetSplitterLayoutData = function (orientation) {
var aSplitter;
var aGanttCharts = this.getGanttCharts();
var aContents = this._oSplitter.getContentAreas();
for (var l = 0; l < aContents.length; l++) {
if (aContents[l].getLayoutData()) {
// to trigger resize of gantt splitter first
if (aContents[l].getLayoutData().getSize() === "auto") {
aContents[l].getLayoutData().setSize("100%");
}
aContents[l].getLayoutData().setSize("auto");
}
}
for (var i = 0; i < aGanttCharts.length; i++) {
aSplitter = aGanttCharts[i]._oSplitter;
var contents = aSplitter.getContentAreas();
for (var j = 0;j < contents.length; j++) {
if (contents[j].getLayoutData()) {
if (orientation === Orientation.Vertical) {
if (j == 0 && contents.length > 1) {
contents[j].getLayoutData().setSize("30%");
} else {
contents[j].getLayoutData().setSize("auto");
}
} else {
contents[j].getLayoutData().setSize("auto");
}
}
}
}
};
/**
* Returns the current effective toolbar scheme key.
*
* @returns {string} - Toolbar scheme key.
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.getToolbarSchemeKey = function () {
return this._oToolbar.getToolbarSchemeKey();
};
/**
* Selects in-row shapes and returns a success code.
*
* @param {int} [iGanttChart] Index of the Gantt chart containing the shapes that you want to select
* @param {array} [aIds] L of the shape IDs that you want to select
* @param {boolean} [isExclusive] Whether all other selected shapes are to be deselected
* @returns {boolean} - If any selection change is applied, returns true.
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.selectShapes = function(iGanttChart, aIds, isExclusive) {
var aGanttCharts = this.getGanttCharts(),
bRetVal = false,
oGanttChart;
if (iGanttChart != undefined && iGanttChart < aGanttCharts.length) {
oGanttChart = aGanttCharts[iGanttChart];
bRetVal = oGanttChart.selectShapes(aIds, isExclusive);
}else {
for (var i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
if (oGanttChart.selectShapes(aIds, isExclusive)) {
bRetVal = true;
}
}
}
return bRetVal;
};
/**
* Deselects in-row shapes and returns a success code.
*
* @param {int} [iGanttChartIndex] Index of the Gantt chart containing the shapes that you want to deselect
* @param {array} [aIds] List of the shapes that you want to deselect
* @returns {boolean} - If any selection change is applied, returns true.
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.deselectShapes = function(iGanttChartIndex, aIds) {
var aGanttCharts = this.getGanttCharts(),
bRetVal = false,
oGanttChart;
if (iGanttChartIndex != undefined && iGanttChartIndex < this.getGanttCharts().length) {
oGanttChart = this.getGanttCharts()[iGanttChartIndex];
bRetVal = oGanttChart.deselectShapes(aIds);
}else {
for (var iGanttChart in aGanttCharts) {
oGanttChart = aGanttCharts[iGanttChart];
if (oGanttChart.deselectShapes(aIds)) {
bRetVal = true;
}
}
}
return bRetVal;
};
/**
* Selects relationships and returns a success code.
*
* @param {int} [iGanttChartIndex] Index of the Gantt chart containing the relationships that you want to select
* @param {array} [aIds] List of the relationships that you want to select
* @param {boolean} [isExclusive] Whether all other selected relationships are to be deselected
* @returns {boolean} - If any selection change is applied, returns true.
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.selectRelationships = function(iGanttChartIndex, aIds, isExclusive) {
var aGanttCharts = this.getGanttCharts(),
bRetVal = false,
oGanttChart;
if (iGanttChartIndex != undefined && iGanttChartIndex < aGanttCharts.length) {
oGanttChart = aGanttCharts[iGanttChartIndex];
bRetVal = oGanttChart.selectRelationships(aIds, isExclusive);
}else {
for (var i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
if (oGanttChart.selectRelationships(aIds, isExclusive)) {
bRetVal = true;
}
}
}
return bRetVal;
};
/**
* Deselects relationships and returns a success code.
*
* @param {int} [iGanttChartIndex] Index of the Gantt chart containing the relationships that you want to deselect
* @param {array} [aIds] List of the relationships that you want to deselect
* @returns {boolean} - If any selection change is applied, returns true.
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.deselectRelationships = function(iGanttChartIndex, aIds) {
var aGanttCharts = this.getGanttCharts(),
bRetVal = false,
oGanttChart;
if (iGanttChartIndex != undefined && iGanttChartIndex < aGanttCharts.length) {
oGanttChart = aGanttCharts[iGanttChartIndex];
bRetVal = oGanttChart.deselectRelationships(aIds);
}else {
for (var i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
if (oGanttChart.deselectRelationships(aIds)) {
bRetVal = true;
}
}
}
return bRetVal;
};
/**
* Selects rows and returns a success code.
*
* @param {int} [iGanttChartIndex] Index of the Gantt chart containing the rows that you want to select
* @param {array} [aIds] List of the rows that you want to select
* @param {boolean} [isExclusive] Whether all other selected rows are to be deselected
* @returns {boolean} - If any selection change is applied, returns true.
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.selectRows = function(iGanttChartIndex, aIds, isExclusive) {
var bRetVal = false,
aGanttCharts = this.getGanttCharts(),
oGanttChart;
if (iGanttChartIndex != undefined && iGanttChartIndex < aGanttCharts.length) {
oGanttChart = aGanttCharts[iGanttChartIndex];
bRetVal = oGanttChart.selectRows(aIds, isExclusive);
}else {
for (var i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
if (oGanttChart.selectRows(aIds, isExclusive)) {
bRetVal = true;
}
}
}
return bRetVal;
};
/**
* Deselects rows and returns a success code.
*
* @param {int} [iGanttChartIndex] Index of the Gantt chart containing the rows that you want to deselect
* @param {array} [aIds] List of the rows that you want to deselect
* @returns {boolean} - If any selection change is applied, returns true.
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.deselectRows = function(iGanttChartIndex, aIds) {
var bRetVal = false,
aGanttCharts = this.getGanttCharts(),
oGanttChart;
if (iGanttChartIndex != undefined && iGanttChartIndex < aGanttCharts.length) {
oGanttChart = aGanttCharts[iGanttChartIndex];
bRetVal = oGanttChart.deselectRows(aIds);
}else {
for (var i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
if (oGanttChart.deselectRows(aIds)) {
bRetVal = true;
}
}
}
return bRetVal;
};
/**
* Selects rows and all shapes contained in these rows.
*
* @param {int} [iGanttChartIndex] Index of the Gantt chart containing the rows and shapes that you want to select
* @param {array} [aIds] Row UIDs
* @param {boolean} [bIsExclusive] Whether reset all other selected rows and shapes are to be reset
* @returns {boolean} - If any selection change is applied, returns true.
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.selectRowsAndShapes = function(iGanttChartIndex, aIds, bIsExclusive) {
var bRetVal = false,
aGanttCharts = this.getGanttCharts(),
oGanttChart;
if (iGanttChartIndex != undefined && iGanttChartIndex < aGanttCharts.length) {
oGanttChart = aGanttCharts[iGanttChartIndex];
bRetVal = oGanttChart.selectRowsAndShapes(aIds, bIsExclusive);
}else {
for (var i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
if (oGanttChart.selectRowsAndShapes(aIds, bIsExclusive)) {
bRetVal = true;
}
}
}
return bRetVal;
};
/**
* Gets the selected in-row shapes.
*
* @param {int} [iGanttChartIndex] Index of the Gantt chart containing the selected shapes that you want to get
* @return {array} Returns all selected shapes in the chart
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.getSelectedShapes = function(iGanttChartIndex) {
var aRetVal = [],
aGanttCharts = this.getGanttCharts(),
oGanttChart,
oSelectedShapes;
if (iGanttChartIndex != undefined && iGanttChartIndex < aGanttCharts.length) {
oGanttChart = aGanttCharts[iGanttChartIndex];
oSelectedShapes = oGanttChart.getSelectedShapes();
if (oSelectedShapes !== undefined) {
aRetVal.push({"ganttChartIndex": iGanttChartIndex, "selectedShapes": oSelectedShapes});
}
}else {
for (var i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
oSelectedShapes = oGanttChart.getSelectedShapes();
if (oSelectedShapes !== undefined) {
aRetVal.push({"ganttChartIndex": i, "selectedShapes": oSelectedShapes});
}
}
}
return aRetVal;
};
/**
* Gets the selected rows.
*
* @param {int} [iGanttChartIndex] Index of the Gantt chart containing the selected rows that you want to get
* @return {array} Returns all selected rows
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.getSelectedRows = function(iGanttChartIndex) {
var aRetVal = [],
aGanttCharts = this.getGanttCharts(),
oGanttChart, aRows;
if (iGanttChartIndex != undefined && iGanttChartIndex < aGanttCharts.length) {
oGanttChart = aGanttCharts[iGanttChartIndex];
aRows = oGanttChart.getSelectedRows();
if (aRows !== undefined && aRows.length > 0) {
aRetVal.push({"ganttChartIndex": iGanttChartIndex, "selectedRows": aRows});
}
}else {
for (var i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
aRows = oGanttChart.getSelectedRows();
if (aRows !== undefined) {
aRetVal.push({"ganttChartIndex": i, "selectedRows": aRows});
}
}
}
return aRetVal;
};
/**
* Gets the selected relationships.
*
* @param {int} [iGanttChartIndex] Index of the Gantt chart containing the selected relationships that you want to get
* @return {array} Returns all selected relationships in the chart
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.getSelectedRelationships = function(iGanttChartIndex) {
var aRetVal = [],
aGanttCharts = this.getGanttCharts(),
oGanttChart, aRelationships;
if (iGanttChartIndex != undefined && iGanttChartIndex < aGanttCharts.length) {
oGanttChart = aGanttCharts[iGanttChartIndex];
aRelationships = oGanttChart.getSelectedRelationships();
if (aRelationships !== undefined) {
aRetVal.push({"ganttChartIndex": iGanttChartIndex, "selectedRelationships": aRelationships});
}
}else {
for (var i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
aRelationships = oGanttChart.getSelectedRelationships();
if (aRelationships !== undefined) {
aRetVal.push({"ganttChartIndex": i, "selectedRelationships": aRelationships});
}
}
}
return aRetVal;
};
/**
* Gets all selected rows and shapes, including relationships.
*
* @param {int} [iGanttChartIndex] Index of the Gantt chart containing that you want to get
* @return {object} The returned object contains "rows" for all selected rows, "shapes" for all selected shapes, and "relationships" for all selected relationships
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
GanttChartContainer.prototype.getAllSelections = function(iGanttChartIndex) {
var aRetVal = [],
aGanttCharts = this.getGanttCharts(),
oGanttChart, oSelections;
if (iGanttChartIndex != undefined && iGanttChartIndex < aGanttCharts.length) {
oGanttChart = aGanttCharts[iGanttChartIndex];
oSelections = oGanttChart.getAllSelections();
if (oSelections !== undefined) {
aRetVal.push({"ganttChartIndex": iGanttChartIndex, "allSelection": oSelections});
}
}else {
for (var i = 0; i < aGanttCharts.length; i++) {
oGanttChart = aGanttCharts[i];
oSelections = oGanttChart.getAllSelections();
if (oSelections !== undefined) {
aRetVal.push({"ganttChartIndex": i, "allSelection": oSelections});
}
}
}
return aRetVal;
};
GanttChartContainer.prototype.exit = function () {
this._detachEvents();
this._oToolbar.destroy();
this._oSplitter.destroy();
};
return GanttChartContainer;
}, true);
<file_sep>// This file has been generated by the SAPUI5 'AllInOne' Builder
jQuery.sap.declare('sap.suite.ui.microchart.library-all');
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.AreaMicroChartRenderer') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.suite.ui.microchart.AreaMicroChartRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/AreaMicroChartRenderer",['jquery.sap.global'],
function() {
"use strict";
/**
* AreaMicroChartRenderer renderer.
* @namespace
*/
var AreaMicroChartRenderer = {};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm
* the RenderManager that can be used for writing to
* the Render-Output-Buffer
* @param {sap.ui.core.Control} oControl
* the control to be rendered
*/
AreaMicroChartRenderer.render = function(oRm, oControl) {
function fnWriteLbl(oLabel, sId, sClass, sType) {
var sLabel = oLabel ? oLabel.getLabel() : "";
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + sId);
if (oLabel) {
oRm.addClass(oLabel.getColor());
}
oRm.addClass("sapSuiteAmcLbl");
oRm.addClass(sClass);
oRm.addClass(sType);
oRm.writeClasses();
oRm.write(">");
oRm.writeEscaped(sLabel);
oRm.write("</div>");
}
var sTooltip = oControl.getTooltip_AsString();
if (typeof sTooltip !== "string") {
sTooltip = "";
}
var sTopLblType = ((oControl.getView() == "Normal" && oControl.getFirstYLabel() && oControl.getFirstYLabel().getLabel()) ? "L" : "")
+ ((oControl.getMaxLabel() && oControl.getMaxLabel().getLabel()) ? "C" : "")
+ ((oControl.getView() == "Normal" && oControl.getLastYLabel() && oControl.getLastYLabel().getLabel()) ? "R" : "");
var sBtmLblType = ((oControl.getView() == "Normal" && oControl.getFirstXLabel() && oControl.getFirstXLabel().getLabel()) ? "L" : "")
+ ((oControl.getMinLabel() && oControl.getMinLabel().getLabel()) ? "C" : "")
+ ((oControl.getView() == "Normal" && oControl.getLastXLabel() && oControl.getLastXLabel().getLabel()) ? "R" : "");
var bLeftLbls, bRightLbls;
bRightLbls = bLeftLbls = oControl.getView() == "Wide";
oRm.write("<div");
oRm.writeControlData(oControl);
if (sTooltip) {
oRm.writeAttributeEscaped("title", sTooltip);
}
oRm.addStyle("width", oControl.getWidth());
oRm.addStyle("height", oControl.getHeight());
oRm.writeStyles();
oRm.writeAttribute("role", "presentation");
oRm.writeAttributeEscaped("aria-label", oControl.getAltText().replace(/\s/g, " ") + (sap.ui.Device.browser.firefox ? "" : " " + sTooltip ));
oRm.addClass("sapSuiteAmc");
if (oControl.hasListeners("press")) {
oRm.addClass("sapSuiteUiMicroChartPointer");
oRm.writeAttribute("tabindex", "0");
}
if (sTopLblType) {
oRm.addClass("topLbls");
}
if (sBtmLblType) {
oRm.addClass("btmLbls");
}
oRm.writeClasses();
oRm.write(">");
if (sTopLblType) {
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-top-labels");
oRm.addClass("sapSuiteAmcLabels");
oRm.addClass("Top");
oRm.writeClasses();
oRm.write(">");
fnWriteLbl(oControl.getFirstYLabel(), "-top-left-lbl", "Left", sTopLblType);
fnWriteLbl(oControl.getMaxLabel(), "-top-center-lbl", "Center", sTopLblType);
fnWriteLbl(oControl.getLastYLabel(), "-top-right-lbl", "Right", sTopLblType);
oRm.write("</div>");
}
if (bLeftLbls) {
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-left-labels");
oRm.addClass("sapSuiteAmcSideLabels");
oRm.addClass("Left");
oRm.writeClasses();
oRm.write(">");
fnWriteLbl(oControl.getFirstYLabel(), "-top-left-lbl", "Top", "Left");
fnWriteLbl(oControl.getFirstXLabel(), "-btm-left-lbl", "Btm", "Left");
oRm.write("</div>");
}
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-canvas-cont");
oRm.addClass("sapSuiteAmcCanvas");
oRm.writeClasses();
oRm.write(">");
oRm.write("<canvas");
oRm.writeAttribute("id", oControl.getId() + "-canvas");
oRm.addStyle("width", "100%");
oRm.addStyle("height", "100%");
oRm.writeStyles();
oRm.write("></canvas>");
oRm.write("</div>");
if (bRightLbls) {
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-right-labels");
oRm.addClass("sapSuiteAmcSideLabels");
oRm.addClass("Right");
oRm.writeClasses();
oRm.write(">");
fnWriteLbl(oControl.getLastYLabel(), "-top-right-lbl", "Top", "Right");
fnWriteLbl(oControl.getLastXLabel(), "-btm-right-lbl", "Btm", "Right");
oRm.write("</div>");
}
if (sBtmLblType) {
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-bottom-labels");
oRm.addClass("sapSuiteAmcLabels");
oRm.addClass("Btm");
oRm.writeClasses();
oRm.write(">");
fnWriteLbl(oControl.getFirstXLabel(), "-btm-left-lbl", "Left", sBtmLblType);
fnWriteLbl(oControl.getMinLabel(), "-btm-center-lbl", "Center", sBtmLblType);
fnWriteLbl(oControl.getLastXLabel(), "-btm-right-lbl", "Right", sBtmLblType);
oRm.write("</div>");
}
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-css-helper");
oRm.addStyle("display", "none");
oRm.writeStyles();
oRm.write("></div>");
oRm.write("</div>");
};
return AreaMicroChartRenderer;
}, /* bExport= */ true);
}; // end of sap/suite/ui/microchart/AreaMicroChartRenderer.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.BulletMicroChartRenderer') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.suite.ui.microchart.BulletMicroChartRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/BulletMicroChartRenderer",['jquery.sap.global'],
function() {
"use strict";
/**
* BulletMicroChart renderer.
* @namespace
*/
var BulletMicroChartRenderer = {};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm
* the RenderManager that can be used for writing to
* the Render-Output-Buffer
* @param {sap.ui.core.Control} oControl
* the control to be rendered
*/
BulletMicroChartRenderer.render = function(oRm, oControl) {
var oChartData = oControl._calculateChartData();
var fForecastValuePct = +oChartData.forecastValuePct;
var sSize = oControl.getSize();
var sScale = oControl.getScale();
var bRtl = sap.ui.getCore().getConfiguration().getRTL();
var sOrientation = bRtl ? "right" : "left";
var sMode = oControl.getMode();
var sDeltaValue = (sap.suite.ui.microchart.BulletMicroChartModeType.Delta == sMode) ? oControl._calculateDeltaValue() : 0;
var bIsActualSet = oControl.getActual() && oControl.getActual()._isValueSet;
var bShowActualValue = oControl.getShowActualValue() && (sap.m.Size.XS != sSize) && sap.suite.ui.microchart.BulletMicroChartModeType.Actual == sMode;
var bShowDeltaValue = oControl.getShowDeltaValue() && (sap.m.Size.XS != sSize) && sap.suite.ui.microchart.BulletMicroChartModeType.Delta == sMode;
var bShowTargetValue = oControl.getShowTargetValue() && (sap.m.Size.XS != sSize);
var sActualValueLabel = oControl.getActualValueLabel();
var sDeltaValueLabel = oControl.getDeltaValueLabel();
var sTargetValueLabel = oControl.getTargetValueLabel();
var aData = oControl.getThresholds();
var sTooltip = oControl.getTooltip_AsString();
if (typeof sTooltip !== "string") {
sTooltip = "";
}
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapSuiteBMCContent");
oRm.addClass(sSize);
if (oControl.hasListeners("press")) {
oRm.addClass("sapSuiteUiMicroChartPointer");
oRm.writeAttribute("tabindex", "0");
}
oRm.writeAttribute("role", "presentation");
oRm.writeAttributeEscaped("aria-label", oControl.getAltText().replace(/\s/g, " ") + (sap.ui.Device.browser.firefox ? "" : " " + sTooltip ));
oRm.writeClasses();
if (oControl.getWidth()) {
oRm.addStyle("width", oControl.getWidth());
oRm.writeStyles();
}
oRm.writeAttribute("id", oControl.getId() + "-bc-content");
oRm.writeAttributeEscaped("title", sTooltip);
oRm.write(">");
oRm.write("<div");
oRm.addClass("sapSuiteBMCChart");
oRm.addClass(sSize);
oRm.writeClasses();
oRm.writeAttribute("id", oControl.getId() + "-bc-chart");
oRm.write(">");
var sValScale = "";
if (bIsActualSet && bShowActualValue) {
var sAValToShow = (sActualValueLabel) ? sActualValueLabel : "" + oControl.getActual().getValue();
sValScale = sAValToShow + sScale;
oRm.write("<div");
oRm.addClass("sapSuiteBMCItemValue");
oRm.addClass(oControl.getActual().getColor());
oRm.addClass(sSize);
oRm.writeClasses();
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-bc-item-value");
oRm.write(">");
oRm.writeEscaped(sValScale);
oRm.write("</div>");
} else if (bIsActualSet && oControl._isTargetValueSet && bShowDeltaValue) {
var sDValToShow = (sDeltaValueLabel) ? sDeltaValueLabel : "" + sDeltaValue;
sValScale = sDValToShow + sScale;
oRm.write("<div");
oRm.addClass("sapSuiteBMCItemValue");
oRm.addClass(oControl.getActual().getColor());
oRm.addClass(sSize);
oRm.writeClasses();
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-bc-item-value");
oRm.write(">");
oRm.write("Δ");
oRm.writeEscaped(sValScale);
oRm.write("</div>");
}
for (var i = 0; i < oChartData.thresholdsPct.length; i++) {
if (aData[i]._isValueSet) {
this.renderThreshold(oRm, oControl, oChartData.thresholdsPct[i]);
}
}
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-chart-bar");
oRm.addClass("sapSuiteBMCBar");
oRm.addClass(sSize);
oRm.addClass(oControl.getScaleColor());
oRm.writeClasses();
oRm.write(">");
oRm.write("</div>");
if (oControl._isForecastValueSet && sMode == "Actual") {
oRm.write("<div");
oRm.addClass("sapSuiteBMCForecastBarValue");
oRm.addClass(oControl.getActual().getColor());
oRm.addClass(sSize);
oRm.writeClasses();
oRm.addStyle("width", fForecastValuePct + "%");
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-forecast-bar-value");
oRm.write("></div>");
}
if (bIsActualSet) {
oRm.write("<div");
oRm.addClass("sapSuiteBMCBarValueMarker");
oRm.addClass(sMode);
if (!oControl.getShowValueMarker()) {
oRm.addClass("sapSuiteBMCBarValueMarkerHidden");
}
oRm.addClass(oControl.getActual().getColor());
oRm.addClass(sSize);
oRm.writeClasses();
oRm.addStyle(sOrientation, parseFloat(oChartData.actualValuePct) + parseFloat(1) + "%");
if (sMode == "Delta" && oChartData.actualValuePct <= oChartData.targetValuePct) {
oRm.addStyle("margin", "0");
}
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-bc-bar-value-marker");
oRm.write("></div>");
if (sMode == "Actual") {
oRm.write("<div");
oRm.addClass("sapSuiteBMCBarValue");
oRm.addClass(oControl.getActual().getColor());
oRm.addClass(sSize);
if (oControl._isForecastValueSet) {
oRm.addClass("sapSuiteBMCForecast");
}
oRm.writeClasses();
oRm.addStyle("width", oChartData.actualValuePct + "%");
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-bc-bar-value");
oRm.write("></div>");
} else if (oControl._isTargetValueSet && sMode == "Delta") {
oRm.write("<div");
oRm.addClass("sapSuiteBMCBarValue");
oRm.addClass(oControl.getActual().getColor());
oRm.addClass(sSize);
oRm.writeClasses();
oRm.addStyle("width", Math.abs(oChartData.actualValuePct - oChartData.targetValuePct) + "%");
oRm.addStyle(sOrientation, 1 + Math.min(oChartData.actualValuePct, oChartData.targetValuePct) + "%");
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-bc-bar-value");
oRm.write("></div>");
}
}
if (oControl._isTargetValueSet) {
oRm.write("<div");
oRm.addClass("sapSuiteBMCTargetBarValue");
oRm.addClass(sSize);
oRm.writeClasses();
oRm.addStyle(sOrientation, parseFloat(oChartData.targetValuePct).toFixed(2) + "%");
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-bc-target-bar-value");
oRm.write("></div>");
if (bShowTargetValue) {
var sTValToShow = (sTargetValueLabel) ? sTargetValueLabel : "" + oControl.getTargetValue();
var sTValScale = sTValToShow + sScale;
oRm.write("<div");
oRm.addClass("sapSuiteBMCTargetValue");
oRm.addClass(sSize);
oRm.writeClasses();
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-bc-target-value");
oRm.write(">");
oRm.writeEscaped(sTValScale);
oRm.write("</div>");
}
}
oRm.write("</div>");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-info");
oRm.writeAttribute("aria-hidden", "true");
oRm.addStyle("display", "none");
oRm.writeStyles();
oRm.write(">");
oRm.writeEscaped(sTooltip);
oRm.write("</div>");
oRm.write("</div>");
};
/**
* Renders the HTML for the thresholds, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
* @param {sap.ui.core.Control} oControl an object representation of the control whose thresholds should be rendered
* @param {sap.ui.core.Control} oThreshold an object containing threshold values and colors
*/
BulletMicroChartRenderer.renderThreshold = function(oRm, oControl, oThreshold) {
var sOrientation = sap.ui.getCore().getConfiguration().getRTL() ? "right" : "left";
var fValuePct = 0.98 * oThreshold.valuePct + 1;
var sColor = oThreshold.color;
var sSize = oControl.getSize();
if (sap.m.ValueColor.Error == oThreshold.color) {
oRm.write("<div");
oRm.addClass("sapSuiteBMCDiamond");
oRm.addClass(sSize);
oRm.addClass(sColor);
oRm.writeClasses();
oRm.addStyle(sOrientation, fValuePct + "%");
oRm.writeStyles();
oRm.write("></div>");
}
oRm.write("<div");
oRm.addClass("sapSuiteBMCThreshold");
oRm.addClass(sSize);
oRm.addClass(sColor);
oRm.writeClasses();
oRm.addStyle(sOrientation, fValuePct + "%");
oRm.writeStyles();
oRm.write("></div>");
};
return BulletMicroChartRenderer;
}, /* bExport= */ true);
}; // end of sap/suite/ui/microchart/BulletMicroChartRenderer.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.ColumnMicroChartRenderer') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.suite.ui.microchart.ColumnMicroChartRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/ColumnMicroChartRenderer",['jquery.sap.global'],
function() {
"use strict";
/**
* ColumnMicroChartRenderer renderer.
* @namespace
*/
var ColumnMicroChartRenderer = {};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm
* the RenderManager that can be used for writing to
* the Render-Output-Buffer
* @param {sap.ui.core.Control} oControl
* the control to be rendered
*/
ColumnMicroChartRenderer.render = function(oRm, oControl) {
function fnWriteLbl(oLabel, sId, sClass, bWideBtmLbl) {
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + sId);
oRm.addClass("sapSuiteCmcLbl");
oRm.addClass(sClass);
oRm.addClass(oLabel.getColor());
if (bWideBtmLbl) {
oRm.addClass("W");
}
oRm.writeClasses();
oRm.write(">");
oRm.writeEscaped(oLabel.getLabel());
oRm.write("</div>");
}
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapSuiteCmc");
oRm.addClass(oControl.getSize());
var sTooltip = oControl.getTooltip_AsString();
if (typeof sTooltip !== "string") {
sTooltip = "";
}
oRm.writeAttributeEscaped("title", sTooltip);
if (oControl.hasListeners("press")) {
oRm.addClass("sapSuiteUiMicroChartPointer");
oRm.writeAttribute("tabindex", "0");
}
oRm.writeAttribute("role", "presentation");
oRm.writeAttributeEscaped("aria-label", oControl.getAltText().replace(/\s/g, " ") + (sap.ui.Device.browser.firefox ? "" : " " + sTooltip ));
oRm.writeClasses();
oRm.addStyle("width", oControl.getWidth());
oRm.addStyle("height", oControl.getHeight());
oRm.writeStyles();
oRm.write(">");
var bLeftTopLbl = oControl.getLeftTopLabel() && oControl.getLeftTopLabel().getLabel() != "";
var bRightTopLbl = oControl.getRightTopLabel() && oControl.getRightTopLabel().getLabel() != "";
var bLeftBtmLbl = oControl.getLeftBottomLabel() && oControl.getLeftBottomLabel().getLabel() != "";
var bRightBtmLbl = oControl.getRightBottomLabel() && oControl.getRightBottomLabel().getLabel() != "";
if (bLeftTopLbl || bRightTopLbl) {
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-top-lbls");
oRm.addClass("sapSuiteCmcLbls");
oRm.addClass("T");
oRm.writeClasses();
oRm.write(">");
var bWideTopLbl = bLeftTopLbl ^ bRightTopLbl;
if (bLeftTopLbl) {
fnWriteLbl(oControl.getLeftTopLabel(), "-left-top-lbl", "L", bWideTopLbl);
}
if (bRightTopLbl) {
fnWriteLbl(oControl.getRightTopLabel(), "-right-top-lbl", "R", bWideTopLbl);
}
oRm.write("</div>");
}
oRm.write("<div");
oRm.writeAttributeEscaped("id", oControl.getId() + "-content");
oRm.addClass("sapSuiteCmcCnt");
if (bLeftTopLbl || bRightTopLbl) {
oRm.addClass("T");
}
if (bLeftBtmLbl || bRightBtmLbl) {
oRm.addClass("B");
}
oRm.writeClasses();
oRm.write(">");
oRm.write("<div");
oRm.writeAttributeEscaped("id", oControl.getId() + "-bars");
oRm.addClass("sapSuiteCmcBars");
oRm.writeClasses();
oRm.write(">");
var iColumnsNum = oControl.getColumns().length;
for (var i = 0; i < iColumnsNum; i++) {
var oColumn = oControl.getColumns()[i];
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-bar-" + i);
oRm.writeAttribute("data-bar-index", i);
oRm.addClass("sapSuiteCmcBar");
oRm.addClass(oColumn.getColor());
if (oColumn.hasListeners("press")) {
oRm.writeAttribute("tabindex", "0");
oRm.writeAttribute("role", "presentation");
var sBarAltText = oControl._getBarAltText(i);
oRm.writeAttributeEscaped("title", sBarAltText);
oRm.writeAttributeEscaped("aria-label", sBarAltText);
oRm.addClass("sapSuiteUiMicroChartPointer");
}
oRm.writeClasses();
oRm.write(">");
oRm.write("</div>");
}
oRm.write("</div>");
oRm.write("</div>");
if (bLeftBtmLbl || bRightBtmLbl) {
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-btm-lbls");
oRm.addClass("sapSuiteCmcLbls");
oRm.addClass("B");
oRm.writeClasses();
oRm.write(">");
var bWideBtmLbl = bLeftBtmLbl ^ bRightBtmLbl;
if (bLeftBtmLbl) {
fnWriteLbl(oControl.getLeftBottomLabel(), "-left-btm-lbl", "L", bWideBtmLbl);
}
if (bRightBtmLbl) {
fnWriteLbl(oControl.getRightBottomLabel(), "-right-btm-lbl", "R", bWideBtmLbl);
}
oRm.write("</div>");
}
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-hidden");
oRm.writeAttribute("aria-hidden", "true");
oRm.writeAttribute("tabindex", "0");
oRm.writeStyles();
oRm.write(">");
oRm.write("</div>");
oRm.write("</div>");
};
return ColumnMicroChartRenderer;
}, /* bExport= */ true);
}; // end of sap/suite/ui/microchart/ColumnMicroChartRenderer.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.ComparisonMicroChartRenderer') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.suite.ui.microchart.ComparisonMicroChartRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/ComparisonMicroChartRenderer",['jquery.sap.global'],
function() {
"use strict";
/**
* ComparisonMicroChart renderer.
* @namespace
*/
var ComparisonMicroChartRenderer = {};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm
* the RenderManager that can be used for writing to
* the Render-Output-Buffer
* @param {sap.ui.core.Control} oControl
* the control to be rendered
*/
ComparisonMicroChartRenderer.render = function (oRm, oControl) {
var sTooltip = oControl.getTooltip_AsString();
if (typeof sTooltip !== "string") {
sTooltip = "";
}
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapSuiteCmpChartContent");
oRm.addClass(oControl.getSize());
if (oControl.hasListeners("press")) {
oRm.writeAttribute("tabindex", "0");
oRm.addClass("sapSuiteUiMicroChartPointer");
}
oRm.writeClasses();
oRm.writeAttribute("role", "presentation");
oRm.writeAttributeEscaped("aria-label", oControl.getAltText().replace(/\s/g, " ") + (sap.ui.Device.browser.firefox ? "" : " " + sTooltip ));
if (oControl.getShrinkable()) {
oRm.addStyle("min-height", "0px");
}
if (oControl.getWidth()) {
oRm.addStyle("width", oControl.getWidth());
}
if (oControl.getHeight()) {
oRm.addStyle("height", oControl.getHeight());
}
oRm.writeStyles();
oRm.writeAttributeEscaped("title", sTooltip);
oRm.write(">");
this._renderInnerContent(oRm, oControl);
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-info");
oRm.writeAttribute("aria-hidden", "true");
oRm.addStyle("display", "none");
oRm.writeStyles();
oRm.write(">");
oRm.writeEscaped(sTooltip);
oRm.write("</div>");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-hidden");
oRm.writeAttribute("aria-hidden", "true");
oRm.writeAttribute("tabindex", "-1");
oRm.writeStyles();
oRm.write(">");
oRm.write("</div>");
oRm.write("</div>");
};
ComparisonMicroChartRenderer._renderInnerContent = function(oRm, oControl) {
var iCPLength = oControl.getColorPalette().length;
var iCPIndex = 0;
var fnNextColor = function() {
if (iCPLength) {
if (iCPIndex == iCPLength) {
iCPIndex = 0;
}
return oControl.getColorPalette()[iCPIndex++];
}
};
var aChartData = oControl._calculateChartData();
for (var i = 0; i < aChartData.length; i++) {
this._renderChartItem(oRm, oControl, aChartData[i], i, fnNextColor());
}
};
ComparisonMicroChartRenderer._renderChartItem = function(oRm, oControl, oChartData, iIndex, sColor) {
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-chart-item-" + iIndex);
oRm.addClass("sapSuiteCmpChartItem");
oRm.addClass(oControl.getView());
oRm.addClass(oControl.getSize());
oRm.writeClasses();
oRm.write(">");
this._renderChartHeader(oRm, oControl, iIndex, sColor);
this._renderChartBar(oRm, oControl, oChartData, iIndex, sColor);
oRm.write("</div>");
};
ComparisonMicroChartRenderer._renderChartBar = function(oRm, oControl, oChartData, iIndex, sColor) {
var oData = oControl.getData()[iIndex];
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-chart-item-bar-" + iIndex);
oRm.addClass("sapSuiteCmpChartBar");
oRm.addClass(oControl.getView());
oRm.addClass(oControl.getSize());
if (oControl.getData()[iIndex].hasListeners("press")) {
oRm.writeAttribute("tabindex", "0");
oRm.writeAttribute("role", "presentation");
oRm.writeAttributeEscaped("title", oControl._getBarAltText(iIndex));
oRm.writeAttributeEscaped("aria-label", oControl._getBarAltText(iIndex));
oRm.writeAttribute("data-bar-index", iIndex);
oRm.addClass("sapSuiteUiMicroChartPointer");
}
oRm.writeClasses();
oRm.write(">");
if (oChartData.negativeNoValue > 0) {
oRm.write("<div");
oRm.writeAttribute("data-bar-index", iIndex);
oRm.addClass("sapSuiteCmpChartBarNegNoValue");
oRm.writeClasses();
oRm.addStyle("width", oChartData.negativeNoValue + "%");
oRm.writeStyles();
oRm.write("></div>");
}
if (oChartData.value > 0) {
oRm.write("<div");
oRm.writeAttribute("data-bar-index", iIndex);
oRm.addClass("sapSuiteCmpChartBarValue");
oRm.addClass(oData.getColor());
oRm.writeClasses();
oRm.addStyle("background-color", sColor);
oRm.addStyle("width", oChartData.value + "%");
oRm.writeStyles();
oRm.write("></div>");
}
if (oChartData.positiveNoValue > 0) {
oRm.write("<div");
oRm.writeAttribute("data-bar-index", iIndex);
oRm.addClass("sapSuiteCmpChartBarNoValue");
oRm.writeClasses();
oRm.addStyle("width", oChartData.positiveNoValue + "%");
oRm.writeStyles();
oRm.write("></div>");
}
oRm.write("</div>");
};
ComparisonMicroChartRenderer._renderChartHeader = function(oRm, oControl, iIndex, sColor) {
var oData = oControl.getData()[iIndex];
var sScale = oControl.getScale();
var sDisplayValue = oData.getDisplayValue();
var sAValToShow = sDisplayValue ? sDisplayValue : "" + oData.getValue();
var sValScale = sAValToShow + sScale;
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-chart-item-" + iIndex + "-header");
oRm.addClass("sapSuiteCmpChartItemHeader");
oRm.addClass(oControl.getView());
oRm.addClass(oControl.getSize());
oRm.writeClasses();
oRm.write(">");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-chart-item-" + iIndex + "-value");
oRm.addClass("sapSuiteCmpChartItemValue");
oRm.addClass(oControl.getSize());
oRm.addClass(oControl.getView());
if (!sColor) {
oRm.addClass(oData.getColor());
}
if (oData.getTitle()) {
oRm.addClass("T");
}
oRm.writeClasses();
oRm.write(">");
if (!isNaN(oData.getValue())) {
oRm.writeEscaped(sValScale);
}
oRm.write("</div>");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-chart-item-" + iIndex + "-title");
oRm.addClass("sapSuiteCmpChartItemTitle");
oRm.writeClasses();
oRm.write(">");
oRm.writeEscaped(oData.getTitle());
oRm.write("</div>");
oRm.write("</div>");
};
return ComparisonMicroChartRenderer;
}, /* bExport= */ true);
}; // end of sap/suite/ui/microchart/ComparisonMicroChartRenderer.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.DeltaMicroChartRenderer') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.suite.ui.microchart.DeltaMicroChartRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/DeltaMicroChartRenderer",['jquery.sap.global'],
function() {
"use strict";
/**
* DeltaMicroChart renderer.
* @namespace
*/
var DeltaMicroChartRenderer = {};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm
* the RenderManager that can be used for writing to
* the Render-Output-Buffer
* @param {sap.ui.core.Control} oControl
* the control to be rendered
*/
DeltaMicroChartRenderer.render = function(oRm, oControl) {
var sDv1 = oControl.getDisplayValue1();
var sDv2 = oControl.getDisplayValue2();
var fVal1 = oControl.getValue1();
var fVal2 = oControl.getValue2();
var sDdv = oControl.getDeltaDisplayValue();
var sAdv1ToShow = sDv1 ? sDv1 : "" + fVal1;
var sAdv2ToShow = sDv2 ? sDv2 : "" + fVal2;
var sAddvToShow = sDdv ? sDdv : "" + Math.abs(fVal1 - fVal2).toFixed(Math.max(oControl._digitsAfterDecimalPoint(fVal1), oControl._digitsAfterDecimalPoint(fVal2)));
var sColor = oControl.getColor();
var sTooltip = oControl.getTooltip_AsString();
if (typeof sTooltip !== "string") {
sTooltip = "";
}
var sSize = oControl.getSize();
var bNoTitles = (!oControl.getTitle1() && !oControl.getTitle2());
function getDir(bLeft) {
return bLeft ? "Left" : "Right";
}
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.addClass("sapSuiteDmc");
if (oControl.hasListeners("press")) {
oRm.addClass("sapSuiteUiMicroChartPointer");
oRm.writeAttribute("tabindex", "0");
}
oRm.addClass(sSize);
oRm.writeAttribute("role", "presentation");
oRm.writeAttributeEscaped("aria-label", oControl.getAltText().replace(/\s/g, " ") + (sap.ui.Device.browser.firefox ? "" : " " + sTooltip ));
oRm.writeAttributeEscaped("title", sTooltip);
oRm.writeClasses();
if (oControl.getWidth()) {
oRm.addStyle("width", oControl.getWidth());
oRm.writeStyles();
}
oRm.write(">");
oRm.write("<div");
oRm.addClass("sapSuiteDmcCnt");
oRm.addClass(sSize);
oRm.writeClasses();
oRm.write(">");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-title1");
oRm.addClass("sapSuiteDmcTitle");
oRm.addClass("Top");
oRm.writeClasses();
oRm.write(">");
oRm.writeEscaped(oControl.getTitle1());
oRm.write("</div>");
oRm.write("<div");
oRm.addClass("sapSuiteDmcChart");
oRm.addClass(sSize);
if (bNoTitles){
oRm.addClass("NoTitles");
}
oRm.writeClasses();
oRm.writeAttribute("id", oControl.getId() + "-dmc-chart");
oRm.write(">");
oRm.write("<div");
oRm.addClass("sapSuiteDmcBar");
oRm.addClass("Bar1");
oRm.addClass(sSize);
if (oControl._oChartData.delta.isMax) {
oRm.addClass("MaxDelta");
}
if (oControl._oChartData.bar1.isSmaller) {
oRm.addClass("Smaller");
}
oRm.addClass(getDir(oControl._oChartData.bar1.left));
oRm.writeClasses();
oRm.addStyle("width", oControl._oChartData.bar1.width + "%");
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-dmc-bar1");
oRm.write(">");
oRm.write("<div");
oRm.addClass("sapSuiteDmcBarInternal");
oRm.addClass(getDir(oControl._oChartData.bar2.left));
oRm.writeClasses();
oRm.write(">");
oRm.write("</div>");
oRm.write("</div>");
oRm.write("<div");
oRm.addClass("sapSuiteDmcBar");
oRm.addClass("Bar2");
oRm.addClass(sSize);
if (oControl._oChartData.delta.isMax) {
oRm.addClass("MaxDelta");
}
if (oControl._oChartData.bar2.isSmaller) {
oRm.addClass("Smaller");
}
oRm.addClass(getDir(oControl._oChartData.bar2.left));
oRm.writeClasses();
oRm.addStyle("width", oControl._oChartData.bar2.width + "%");
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-dmc-bar2");
oRm.write(">");
oRm.write("<div");
oRm.addClass("sapSuiteDmcBarInternal");
oRm.addClass(getDir(oControl._oChartData.bar1.left));
oRm.writeClasses();
oRm.write(">");
oRm.write("</div>");
oRm.write("</div>");
oRm.write("<div");
oRm.addClass("sapSuiteDmcBar");
oRm.addClass("Delta");
oRm.addClass(sSize);
if (!oControl._oChartData.delta.isMax) {
oRm.addClass("NotMax");
}
if (oControl._oChartData.delta.isZero) {
oRm.addClass("Zero");
}
if (oControl._oChartData.delta.isEqual) {
oRm.addClass("Equal");
}
oRm.addClass(getDir(oControl._oChartData.delta.left));
oRm.writeClasses();
oRm.addStyle("width", oControl._oChartData.delta.width + "%");
oRm.writeStyles();
oRm.writeAttribute("id", oControl.getId() + "-dmc-bar-delta");
oRm.write(">");
oRm.write("<div");
oRm.addClass(sColor);
oRm.addClass("sapSuiteDmcBarDeltaInt");
oRm.writeClasses();
oRm.write(">");
oRm.write("</div>");
oRm.write("<div");
oRm.addClass("sapSuiteDmcBarDeltaStripe");
oRm.addClass(getDir(true));
if (oControl._oChartData.delta.isEqual) {
oRm.addClass("Equal");
}
oRm.addClass(oControl._oChartData.delta.isFirstStripeUp ? "Up" : "Down");
oRm.writeClasses();
oRm.write(">");
oRm.write("</div>");
oRm.write("<div");
oRm.addClass("sapSuiteDmcBarDeltaStripe");
oRm.addClass(getDir(false));
oRm.addClass(oControl._oChartData.delta.isFirstStripeUp ? "Down" : "Up");
oRm.writeClasses();
oRm.write(">");
oRm.write("</div>");
oRm.write("</div>");
oRm.write("</div>");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-title2");
oRm.addClass("sapSuiteDmcTitle");
oRm.addClass("Btm");
oRm.writeClasses();
oRm.write(">");
oRm.writeEscaped(oControl.getTitle2());
oRm.write("</div>");
oRm.write("</div>");
oRm.write("<div");
oRm.addClass("sapSuiteDmcLbls");
oRm.addClass(sSize);
oRm.writeClasses();
oRm.write(">");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-value1");
oRm.addClass("sapSuiteDmcValue1");
oRm.writeClasses();
oRm.write(">");
oRm.writeEscaped(sAdv1ToShow);
oRm.write("</div>");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-delta");
oRm.addClass("sapSuiteDmcDelta");
oRm.addClass(sColor);
oRm.writeClasses();
oRm.write(">");
oRm.writeEscaped(sAddvToShow);
oRm.write("</div>");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-value2");
oRm.addClass("sapSuiteDmcValue2");
oRm.writeClasses();
oRm.write(">");
oRm.writeEscaped(sAdv2ToShow);
oRm.write("</div>");
oRm.write("</div>");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-calc");
oRm.addClass("sapSuiteDmcCalc");
oRm.writeClasses();
oRm.write(">");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-calc1");
oRm.addClass("sapSuiteDmcCalc1");
oRm.writeClasses();
oRm.write("></div>");
oRm.write("<div");
oRm.writeAttribute("id", oControl.getId() + "-calc2");
oRm.addClass("sapSuiteDmcCalc2");
oRm.writeClasses();
oRm.write("></div>");
oRm.write("</div>");
oRm.write("</div>");
};
return DeltaMicroChartRenderer;
}, /* bExport= */ true);
}; // end of sap/suite/ui/microchart/DeltaMicroChartRenderer.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.HarveyBallMicroChartRenderer') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.suite.ui.microchart.HarveyBallMicroChartRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
sap.ui.define("sap/suite/ui/microchart/HarveyBallMicroChartRenderer",[],
function() {
"use strict";
/**
* HarveyBallMicroChartRenderer renderer.
* @namespace
*/
var HarveyBallMicroChartRenderer = {};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the Render - Output - Buffer
* @param {sap.ui.core.Control} oControl the control to be rendered
*/
HarveyBallMicroChartRenderer.render = function(oRm, oControl) {
// write the HTML into the render manager
var bRtl = sap.ui.getCore().getConfiguration().getRTL();
var sTooltip = oControl.getTooltip_AsString();
if (typeof sTooltip !== "string") {
sTooltip = "";
}
var sTotalScale = "";
var sValueLabel = "";
var sValueScale = "";
var bFmtLabel = false;
var fValue = 0;
var sColor = "";
var sCpColor = false;
// support only value from first item
if (oControl.getItems().length) {
var oPieItem = oControl.getItems()[0];
fValue = oPieItem.getFraction();
sColor = oPieItem.getColor();
sValueLabel = oPieItem.getFractionLabel() ? oPieItem.getFractionLabel() : sValueLabel + oPieItem.getFraction();
sValueScale = oPieItem.getFractionScale() ? oPieItem.getFractionScale().substring(0, 3) : sValueScale;
bFmtLabel = oPieItem.getFormattedLabel();
}
if (bFmtLabel) {
var oFormattedValue = oControl._parseFormattedValue(sValueLabel);
sValueScale = oFormattedValue.scale.substring(0, 3);
sValueLabel = oFormattedValue.value;
}
var fTotal = oControl.getTotal();
var sTotalLabel = oControl.getTotalLabel() ? oControl.getTotalLabel() : "" + oControl.getTotal();
if (oControl.getTotalScale()) {
sTotalScale = oControl.getTotalScale().substring(0, 3);
}
if (oControl.getFormattedLabel()) {
var oFormattedTotal = oControl._parseFormattedValue(sTotalLabel);
sTotalScale = oFormattedTotal.scale.substring(0, 3);
sTotalLabel = oFormattedTotal.value;
}
var iTrunc = 5; // truncate values to 5 chars
if (sValueLabel) {
sValueLabel = (sValueLabel.length >= iTrunc && (sValueLabel[iTrunc - 1] === "." || sValueLabel[iTrunc - 1] === ","))
? sValueLabel.substring(0, iTrunc - 1)
: sValueLabel.substring(0, iTrunc);
}
if (sTotalLabel) {
sTotalLabel = (sTotalLabel.length >= iTrunc && (sTotalLabel[iTrunc - 1] === "." || sTotalLabel[iTrunc - 1] === ","))
? sTotalLabel.substring(0, iTrunc - 1)
: sTotalLabel.substring(0, iTrunc);
}
if (oControl.getColorPalette().length > 0) {
sCpColor = oControl.getColorPalette()[0];
}
var sSize = oControl.getSize();
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.writeAttributeEscaped("title", sTooltip);
oRm.addClass("suiteHBMC");
oRm.addClass(sSize);
if (oControl.hasListeners("press")) {
oRm.addClass("sapSuiteUiMicroChartPointer");
oRm.writeAttribute("tabindex", "0");
}
oRm.writeClasses();
if (oControl.getWidth()) {
oRm.addStyle("width", oControl.getWidth());
}
oRm.writeStyles();
oRm.write(">");
oRm.write("<div");
oRm.addClass("suiteHBMCChartCnt");
oRm.addClass(sSize);
oRm.writeClasses();
oRm.addStyle("display", "inline-block");
oRm.writeStyles();
oRm.writeAttribute("role", "presentation");
oRm.writeAttributeEscaped("aria - label", oControl.getAltText().replace(/\s/g, " ") + (sap.ui.Device.browser.firefox ? "" : " " + sTooltip));
oRm.write(">");
oRm.write("<svg");
oRm.writeAttribute("id", oControl.getId() + "-harvey-ball");
oRm.writeAttribute("width", oControl._oPath.size);
oRm.writeAttribute("height", oControl._oPath.size);
oRm.writeAttribute("focusable", false);
oRm.write(">");
oRm.write("<g>");
oRm.write("<circle");
oRm.writeAttribute("cx", oControl._oPath.center);
oRm.writeAttribute("cy", oControl._oPath.center);
oRm.writeAttribute("r", (sap.ui.getCore().getConfiguration().getTheme() === "sap_hcb")
? oControl._oPath.center - 1
: oControl._oPath.center);
oRm.addClass("suiteHBMCSBall");
oRm.writeClasses();
oRm.write("/>");
if (fValue && fValue >= fTotal) {
oRm.write("<circle");
oRm.writeAttribute("cx", oControl._oPath.center);
oRm.writeAttribute("cy", oControl._oPath.center);
oRm.writeAttribute("r", oControl._oPath.center - oControl._oPath.border);
oRm.addClass("suiteHBMCSgmnt");
oRm.addClass(sColor);
oRm.writeClasses();
if (oControl.getColorPalette().length > 0) {
oRm.addStyle("fill", jQuery.sap.encodeHTML(oControl.getColorPalette()[0]));
oRm.writeStyles();
}
oRm.write("/>");
} else if (fValue > 0) {
oRm.write("<path");
oRm.writeAttribute("id", oControl.getId() + "-segment");
oRm.addClass("suiteHBMCSgmnt");
oRm.addClass(sColor);
oRm.writeClasses();
oRm.writeAttribute("d", oControl.serializePieChart());
if (oControl.getColorPalette().length > 0) {
oRm.addStyle("fill", jQuery.sap.encodeHTML(oControl.getColorPalette()[0]));
oRm.writeStyles();
}
oRm.write("/>");
}
oRm.write("</g>");
oRm.write("</svg>");
oRm.write("</div>");
oRm.write("<div");
oRm.addClass("suiteHBMCValSclCnt");
oRm.addClass(sSize);
oRm.addClass(sColor);
if (sCpColor) {
oRm.addClass("CP");
}
oRm.writeClasses();
oRm.addStyle("display", oControl.getShowFractions() ? "inline - block" : "none");
oRm.writeStyles();
oRm.write(">");
oRm.write("<p");
oRm.write(">");
this.renderLabel(oRm, oControl, [sColor, sSize, "suiteHBMCVal"], sValueLabel, "-fraction");
this.renderLabel(oRm, oControl, [sColor, sSize, "suiteHBMCValScale"], sValueScale, "-fraction-scale");
oRm.write("</p>");
oRm.write("</div>");
oRm.write("<div");
oRm.addClass("suiteHBMCTtlSclCnt");
oRm.addClass(sSize);
oRm.writeClasses();
if (bRtl) {
oRm.addStyle("left", "0");
} else {
oRm.addStyle("right", "0");
}
oRm.addStyle("display", oControl.getShowTotal() ? "inline-block" : "none");
oRm.writeStyles();
oRm.write(">");
this.renderLabel(oRm, oControl, [sColor, sSize, "suiteHBMCTtl"], sTotalLabel, "-total");
this.renderLabel(oRm, oControl, [sColor, sSize, "suiteHBMCTtlScale"], sTotalScale, "-total-scale");
oRm.write("</div>");
oRm.write("</div>");
};
HarveyBallMicroChartRenderer.renderLabel = function(oRm, oControl, aClasses, sLabel, sId) {
oRm.write("<span");
oRm.writeAttribute("id", oControl.getId() + sId);
for (var i = 0; i < aClasses.length; i++) {
oRm.addClass(aClasses[i]);
}
oRm.writeClasses();
oRm.write(">");
if (sLabel) {
oRm.writeEscaped(sLabel);
}
oRm.write("</span>");
};
return HarveyBallMicroChartRenderer;
}, /* bExport */ true);
}; // end of sap/suite/ui/microchart/HarveyBallMicroChartRenderer.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.RadialMicroChartRenderer') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.suite.ui.microchart.RadialMicroChartRenderer'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/RadialMicroChartRenderer",["jquery.sap.global"],
function(jQuery) {
"use strict";
/**
* RadialMicroChartRenderer renderer.
* @namespace
* @since 1.36.0
*/
var RadialMicroChartRenderer = {};
//Constants
RadialMicroChartRenderer.FORM_RATIO = 1000; //Form ratio for the control, means the calculation base
RadialMicroChartRenderer.BACKGROUND_CIRCLE_BORDER_WIDTH = 1;
RadialMicroChartRenderer.BACKGROUND_CIRCLE_RADIUS = 500; //Calculated by: RadialMicroChartRenderer.FORM_RATIO * 0.5
RadialMicroChartRenderer.CIRCLE_BORDER_WIDTH = 87.5; //Calculated by: RadialMicroChartRenderer.BACKGROUND_CIRCLE_RADIUS * 0.175<WHEEL_WIDTH_FACTOR>
RadialMicroChartRenderer.CIRCLE_RADIUS = 441.75; //Calculated by: RadialMicroChartRenderer.BACKGROUND_CIRCLE_RADIUS * (1.0 - 0.029<EXTERNAL_OUTER_BORDER_WIDTH_FACTOR> - 0.175<WHEEL_WIDTH_FACTOR> / 2.0)
RadialMicroChartRenderer.SVG_VIEWBOX_CENTER_FACTOR = "50%";
RadialMicroChartRenderer.X_ROTATION = 0;
RadialMicroChartRenderer.SWEEP_FLAG = 1;
RadialMicroChartRenderer.NUMBER_FONT_SIZE = 235; //Calculated by: RadialMicroChartRenderer.BACKGROUND_CIRCLE_RADIUS * 0.47<NUMBER_FONT_SIZE_FACTOR>
RadialMicroChartRenderer.EDGE_CASE_SIZE_ACCESSIBLE_COLOR = 54;
RadialMicroChartRenderer.EDGE_CASE_SIZE_SHOW_TEXT = 46;
RadialMicroChartRenderer.EDGE_CASE_SIZE_MICRO_CHART = 24;
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the Render - Output - Buffer
* @param {sap.ui.core.Control} oControl the control to be rendered
*/
RadialMicroChartRenderer.render = function(oRm, oControl) {
// Write the HTML into the render manager
this._writeDivStartElement(oControl, oRm);
this._writeSVGStartElement(oRm);
this._writeBackground(oRm);
if (this._renderingOfInnerContentIsRequired(oControl)) {
this._writeBorders(oRm);
if (this._innerCircleRequired(oControl)) {
this._writeCircle(oControl, oRm);
} else {
this._writeCircleWithPathElements(oControl, oRm);
}
this._writeText(oControl, oRm);
}
oRm.write("</svg>");
oRm.write("</div>");
};
/* Rendering Write-Helpers */
/**
* Writes the start tag for the surrounding div-element incl. ARIA text and required classes
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @param {sap.ui.core.RenderManager} oRm the render manager
*/
RadialMicroChartRenderer._writeDivStartElement = function(control, oRm) {
oRm.write("<div");
oRm.writeControlData(control);
var sTooltip = control._getTooltipText();
if (sTooltip) {
oRm.writeAttributeEscaped("title", sTooltip);
}
oRm.writeAttribute("role", "img");
oRm.writeAttributeEscaped("aria-label", control._getAriaText());
if (control.hasListeners("press")) {
oRm.addClass("sapSuiteUiMicroChartPointer");
oRm.writeAttribute("tabindex", "0");
}
oRm.addClass("sapSuiteUiMicroChartRMC");
oRm.writeClasses();
oRm.writeStyles();
oRm.write(">");
};
/**
* Writes the start tag for the SVG element.
*
* @private
* @param {sap.ui.core.RenderManager} oRm the render manager
*/
RadialMicroChartRenderer._writeSVGStartElement = function(oRm) {
var sPreserveAspectRatio;
if (!sap.ui.getCore().getConfiguration().getRTL()) {
sPreserveAspectRatio = "xMaxYMid meet";
} else {
sPreserveAspectRatio = "xMinYMid meet";
}
oRm.write("<svg width=\"100%\" height=\"100%\" viewBox=\"0 0 " + RadialMicroChartRenderer.FORM_RATIO + ' ' + RadialMicroChartRenderer.FORM_RATIO + "\" preserveAspectRatio=\"" + sPreserveAspectRatio + "\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">");
};
/**
* Writes the background circle.
*
* @private
* @param {sap.ui.core.RenderManager} oRm the render manager
*/
RadialMicroChartRenderer._writeBackground = function(oRm) {
oRm.write("<circle class=\"sapSuiteUiMicroChartRMCCircleBackground\" cx=\"" + RadialMicroChartRenderer.SVG_VIEWBOX_CENTER_FACTOR + "\" cy=\"" + RadialMicroChartRenderer.SVG_VIEWBOX_CENTER_FACTOR + "\" r=\"" + RadialMicroChartRenderer.BACKGROUND_CIRCLE_RADIUS + "\" stroke-width=\"" + this.BACKGROUND_CIRCLE_BORDER_WIDTH + "\" />");
};
/**
* Writes the Borders, required for HCB.
* In case of other themes, they are also available to avoid issues during switching themes.
*
* @private
* @param {sap.ui.core.RenderManager} oRm the render manager
*/
RadialMicroChartRenderer._writeBorders = function(oRm) {
oRm.write("<circle class=\"sapSuiteUiMicroChartRMCHCBIncompleteBorder\" cx=\"" + RadialMicroChartRenderer.SVG_VIEWBOX_CENTER_FACTOR + "\" cy=\"" + RadialMicroChartRenderer.SVG_VIEWBOX_CENTER_FACTOR + "\" r=\"" + (RadialMicroChartRenderer.CIRCLE_RADIUS + RadialMicroChartRenderer.CIRCLE_BORDER_WIDTH / 2.0 - RadialMicroChartRenderer.BACKGROUND_CIRCLE_BORDER_WIDTH ) + "\" stroke-width=\"" + RadialMicroChartRenderer.BACKGROUND_CIRCLE_BORDER_WIDTH + "\" />");
oRm.write("<circle class=\"sapSuiteUiMicroChartRMCHCBIncompleteBorder\" cx=\"" + RadialMicroChartRenderer.SVG_VIEWBOX_CENTER_FACTOR + "\" cy=\"" + RadialMicroChartRenderer.SVG_VIEWBOX_CENTER_FACTOR + "\" r=\"" + (RadialMicroChartRenderer.CIRCLE_RADIUS - RadialMicroChartRenderer.CIRCLE_BORDER_WIDTH / 2.0 + RadialMicroChartRenderer.BACKGROUND_CIRCLE_BORDER_WIDTH ) + "\" stroke-width=\"" + RadialMicroChartRenderer.BACKGROUND_CIRCLE_BORDER_WIDTH + "\" />");
};
/**
* Writes the circle element, required for 0% and 100% cases.
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @param {sap.ui.core.RenderManager} oRm the render manager
*/
RadialMicroChartRenderer._writeCircle = function(control, oRm) {
oRm.write("<circle class=\"" + this._getSVGStringForColor(this._getFullCircleColor(control), control) + "\" cx=\"" + RadialMicroChartRenderer.SVG_VIEWBOX_CENTER_FACTOR + "\" cy=\"" + RadialMicroChartRenderer.SVG_VIEWBOX_CENTER_FACTOR + "\" r=\"" + RadialMicroChartRenderer.CIRCLE_RADIUS + "\" fill=\"transparent\" stroke-width=\"" + RadialMicroChartRenderer.CIRCLE_BORDER_WIDTH + "px\" />");
};
/**
* Writes the two path elements, required for all cases between 1% and 99%.
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @param {sap.ui.core.RenderManager} oRm the render manager
*/
RadialMicroChartRenderer._writeCircleWithPathElements = function(control, oRm) {
var iLargeArcFlag = control.getPercentage() > 50 ? 1 : 0;
var aPathCoordinates = this._calculatePathCoordinates(control);
this._writePath1(iLargeArcFlag, aPathCoordinates, control, oRm);
this._writePath2(iLargeArcFlag, aPathCoordinates, control, oRm);
};
/**
* Writes the first path element for cases between 1% and 99%.
*
* @private
* @param {integer} largeArcFlag for check of smaller or bigger than 180 degrees
* @param {float[]} pathCoordinates array containing specific coordinates for the path
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @param {sap.ui.core.RenderManager} oRm the render manager
*/
RadialMicroChartRenderer._writePath1 = function(largeArcFlag, pathCoordinates, control, oRm) {
var sPathData1 = "M" + pathCoordinates[0] + " " + pathCoordinates[1] + " A " + RadialMicroChartRenderer.CIRCLE_RADIUS + " " + RadialMicroChartRenderer.CIRCLE_RADIUS +
", " + RadialMicroChartRenderer.X_ROTATION + ", " + largeArcFlag + ", " + RadialMicroChartRenderer.SWEEP_FLAG + ", " + pathCoordinates[2] + " " + pathCoordinates[3];
oRm.write("<path class=\"sapSuiteUiMicroChartRadialMicroChartPath" + this._getSVGStringForColor(this._getPathColor(control), control) + "d=\"" + sPathData1 + "\" fill=\"transparent\" stroke-width=\"" + RadialMicroChartRenderer.CIRCLE_BORDER_WIDTH + "px\" />");
};
/**
* Writes the second path element for cases between 1% and 99%.
*
* @private
* @param {integer} largeArcFlag for check of smaller or bigger than 180 degrees
* @param {float[]} pathCoordinates array containing specific coordinates for the path
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @param {sap.ui.core.RenderManager} oRm the render manager
*/
RadialMicroChartRenderer._writePath2 = function(largeArcFlag, pathCoordinates, control, oRm) {
var sPathData2 = "M" + pathCoordinates[2] + " " + pathCoordinates[3] + " A " + RadialMicroChartRenderer.CIRCLE_RADIUS + " " + RadialMicroChartRenderer.CIRCLE_RADIUS +
", " + RadialMicroChartRenderer.X_ROTATION + ", " + (1 - largeArcFlag) + ", " + RadialMicroChartRenderer.SWEEP_FLAG + ", " + pathCoordinates[0] + " " + pathCoordinates[1];
oRm.write("<path class=\"sapSuiteUiMicroChartRadialMicroChartPath sapSuiteUiMicroChartRMCPathIncomplete\" d=\"" + sPathData2 + "\" fill=\"transparent\" stroke-width=\"" + RadialMicroChartRenderer.CIRCLE_BORDER_WIDTH + "px\" />");
};
/**
* Writes the text content inside the chart.
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @param {sap.ui.core.RenderManager} oRm the render manager
*/
RadialMicroChartRenderer._writeText = function(control, oRm) {
oRm.write("<text class=\"sapSuiteUiMicroChartRMCFont\" aria-hidden=\"true\" text-anchor=\"middle\" alignment-baseline=\"middle\"" + "\" font-size=\"" + RadialMicroChartRenderer.NUMBER_FONT_SIZE + "\" x=\"" + RadialMicroChartRenderer.SVG_VIEWBOX_CENTER_FACTOR + "\" y=\"" + this._getVerticalViewboxCenterFactorForText() + "\"> " + this._generateTextContent(control) + "</text>");
};
/* Helpers */
/**
* Checks if rendering of inner content (circle or path-elements) is required.
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @returns {boolean} true if rendering is required, false if rendering is not required
*/
RadialMicroChartRenderer._renderingOfInnerContentIsRequired = function(control) {
if (control._getPercentageMode() || (control.getTotal() !== 0)){
return true;
} else {
return false;
}
};
/**
* Since the property valueColor can be a CSSColor or ValueColor, we need to add this parameter in different way to the path statement.
* For CSSColor, it's added straight to the statement as stroke.
* For valueColor it's added as a CSSClass.
*
* @private
* @param {sap.m.ValueColor|sap.ui.core.CSSColor} color of the chart
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @returns {string} value to add to the SVG string
*/
RadialMicroChartRenderer._getSVGStringForColor = function(color, control){
if (control._isValueColorInstanceOfValueColor()) {
return " " + color + "\"";
} else if (color === "sapSuiteUiMicroChartRMCPathIncomplete"){
return " " + color + "\"";
} else {
return "\" stroke=\"" + color + "\"";
}
};
/**
* Returns the center factor for the text element.
* Since browsers interpret the text differently, the constant SVG_VIEWBOX_CENTER_FACTOR can not be used.
*
* @private
* @returns {string} factor for vertical center of text
*/
RadialMicroChartRenderer._getVerticalViewboxCenterFactorForText = function() {
if (sap.ui.Device.browser.msie) {
return "55%";
} else if (sap.ui.Device.browser.mozilla) {
return "56%";
} else {
return "51%";
}
};
/**
* Checks if the inner circle is required. This is valid for 0% or 100% scenarios.
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @returns {boolean} true if inner circle has to be rendered, false if inner circle is not required
*/
RadialMicroChartRenderer._innerCircleRequired = function(control) {
if (control.getPercentage() >= 100 || control.getPercentage() <= 0) {
return true;
} else {
return false;
}
};
/**
* Generates the coordinates needed for drawing the twho path elements.
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @returns {float[]} array with calculated coordinates
*/
RadialMicroChartRenderer._calculatePathCoordinates = function(control) {
var fPercentage = this._getPercentageForCircleRendering(control);
var aCoordinates = [];
aCoordinates.push(RadialMicroChartRenderer.FORM_RATIO / 2 + RadialMicroChartRenderer.CIRCLE_RADIUS * Math.cos(-Math.PI / 2.0));
aCoordinates.push(RadialMicroChartRenderer.FORM_RATIO / 2 + RadialMicroChartRenderer.CIRCLE_RADIUS * Math.sin(-Math.PI / 2.0));
aCoordinates.push(RadialMicroChartRenderer.FORM_RATIO / 2 + RadialMicroChartRenderer.CIRCLE_RADIUS * Math.cos(-Math.PI / 2.0 + fPercentage / 100 * 2 * Math.PI));
aCoordinates.push(RadialMicroChartRenderer.FORM_RATIO / 2 + RadialMicroChartRenderer.CIRCLE_RADIUS * Math.sin(-Math.PI / 2.0 + fPercentage / 100 * 2 * Math.PI));
return aCoordinates;
};
/**
* Generates percentage value for rendering the circle.
* For edge cases (99% and 1%) a specific handling is implemented.
* For values between 99.0% - 99.9%, 99% will be retrieved to make sure the circle is not completely filled setting thos big values.
* For values between 0.1% - 0.9%, 1% will be returned to make sure the circle is not completely empty settings those small values.
* This is only used for painting the circle by path elements. For the text area, the value of the percentage property can be used.
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @returns {float} the calculated percentage value for bar rendering
*/
RadialMicroChartRenderer._getPercentageForCircleRendering = function(control) {
var fPercentage = control.getPercentage();
var fPercentageForEdgeCases = fPercentage;
if (fPercentage > 99) {
fPercentageForEdgeCases = 99;
}
if (fPercentage < 1) {
fPercentageForEdgeCases = 1;
}
return fPercentageForEdgeCases;
};
/**
* Handles the UI specific stuff in onAfterRendering.
*
* @private
* @param {object} control instance of RadialMicroChart
*/
RadialMicroChartRenderer._handleOnAfterRendering = function(control) {
var sParentWidth;
// Within a Generic Tile max-width was applied instead min-width in Chrome and IE, that's why we forced min-width to be applied in this block.
if (control.getParent() instanceof sap.m.TileContent) {
this._adjustToTileContent(control);
} else {
//Apply fixed size of parent to make SVG work in all browsers.
if (control.getParent() !== undefined && control.getParent() !== null &&
control.getParent().getHeight !== undefined && control.getParent().getHeight !== null) {
// Two pixels are subtracted from the original value. Otherwise, there's not enough space for the outline and it won't render correctly.
var sParentHeight = parseFloat(control.getParent().$().height()) - 2;
control.$().height(sParentHeight); //Required for rendering in page element. Otherwise element is cutted at the top.
control.$().children("svg").height(sParentHeight);
}
if (control.getParent() !== undefined && control.getParent() !== null &&
control.getParent().getWidth !== undefined && control.getParent().getWidth !== null) {
// Two pixels are subtracted from the original value. Otherwise, there's not enough space for the outline and it won't render correctly.
sParentWidth = parseFloat(control.getParent().$().width()) - 2;
control.$().width(sParentWidth); //Required for rendering in page element. Otherwise element is cutted at the top.
control.$().children("svg").width(sParentWidth);
}
}
if (parseInt(control.$().children("svg").css("height"), 10) < RadialMicroChartRenderer.EDGE_CASE_SIZE_MICRO_CHART ||
parseInt(control.$().children("svg").css("width"), 10) < RadialMicroChartRenderer.EDGE_CASE_SIZE_MICRO_CHART) {
control.$().hide();
return;
}
//Hide text element for small elements (<46px)
var $text = control.$().find("text");
if (parseInt(control.$().children("svg").css("height"), 10) <= RadialMicroChartRenderer.EDGE_CASE_SIZE_SHOW_TEXT ||
parseInt(control.$().children("svg").css("width"), 10) <= RadialMicroChartRenderer.EDGE_CASE_SIZE_SHOW_TEXT) {
$text.hide();
} else {
var sCurrentClass = $text.attr("class"); // Gets all the classes applied to the SVG text element
if (sCurrentClass) {
var sTextColorClass = this._getTextColorClass(control); // Gets the correct color
if (sCurrentClass.indexOf(sTextColorClass) < 0) {
$text.attr("class", sCurrentClass + " " + sTextColorClass); // Writes a new class attribute with all the other classes and the new correct color
}
}
}
};
/**
* Performs the necessary adjustments in case of chart located iside of GenericTile.
*
* @private
* @param {object} control instance of RadialMicroChart
*/
RadialMicroChartRenderer._adjustToTileContent = function(control) {
var sParentWidth = control.getParent().$().css("min-width");
control.getParent().$().width(sParentWidth);
if (sap.ui.Device.browser.msie || sap.ui.Device.browser.edge) {
// 16 pixels are removed to compensate the margin and the padding. Needs to be done for IE in case it is rendered only once.
control.$().width(parseInt(sParentWidth, 10) - 16);
}
};
/**
* Returns the text color of the control. Also handles switch for accessibility features.
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @returns {string} value for CSS Text color class
*/
RadialMicroChartRenderer._getTextColorClass = function(control) {
var iSize = parseInt(jQuery.sap.byId(control.getId()).children("svg").css("height"), 10);
if (iSize <= RadialMicroChartRenderer.EDGE_CASE_SIZE_ACCESSIBLE_COLOR && (!control._isValueColorInstanceOfValueColor() || control.getValueColor() === sap.m.ValueColor.Neutral)){
return "sapSuiteUiMicroChartRMCAccessibleTextColor";
} else {
switch (control.getValueColor()){
case sap.m.ValueColor.Good:
return "sapSuiteUiMicroChartRMCGoodTextColor";
case sap.m.ValueColor.Error:
return "sapSuiteUiMicroChartRMCErrorTextColor";
case sap.m.ValueColor.Critical:
return "sapSuiteUiMicroChartRMCCriticalTextColor";
default:
return "sapSuiteUiMicroChartRMCNeutralTextColor";
}
}
};
/**
* Returns the color for full circles required for 100% or 0% charts.
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @returns {string} value for full circle CSS color class or css attribute
*/
RadialMicroChartRenderer._getFullCircleColor = function(control) {
if (control.getPercentage() >= 100) {
return this._getPathColor(control);
}
if (control.getPercentage() <= 0) {
return "sapSuiteUiMicroChartRMCPathIncomplete";
}
};
/**
* Gets the CSS class or CSS attribute to apply the right color to the circle path
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @returns {string} containing the name of the CSS class or the CSS value
*/
RadialMicroChartRenderer._getPathColor = function(control) {
var sValueColor = control.getValueColor();
if (control._isValueColorInstanceOfValueColor()) {
switch (sValueColor){
case sap.m.ValueColor.Good:
return "sapSuiteUiMicroChartRMCPathGood";
case sap.m.ValueColor.Error:
return "sapSuiteUiMicroChartRMCPathError";
case sap.m.ValueColor.Critical:
return "sapSuiteUiMicroChartRMCPathCritical";
default:
return "sapSuiteUiMicroChartRMCPathNeutral";
}
} else {
return sValueColor;
}
};
/**
* Generates the text content of the chart
*
* @private
* @param {sap.suite.ui.microchart.RadialMicroChart} control the current chart control
* @returns {string} value for text element in the chart
*/
RadialMicroChartRenderer._generateTextContent = function(control) {
if (control.getPercentage() === 100) {
return control._rb.getText("RADIALMICROCHART_PERCENTAGE_TEXT", [100]);
}
if (control.getPercentage() === 0) {
return control._rb.getText("RADIALMICROCHART_PERCENTAGE_TEXT", [0]);
}
if (control.getPercentage() >= 100) {
jQuery.sap.log.error("Values over 100%(" + control.getPercentage() + "%) are not supported");
return control._rb.getText("RADIALMICROCHART_PERCENTAGE_TEXT", [100]);
}
if (control.getPercentage() <= 0) {
jQuery.sap.log.error("Values below 0%(" + control.getPercentage() + "%) are not supported");
return control._rb.getText("RADIALMICROCHART_PERCENTAGE_TEXT", [0]);
}
return control._rb.getText("RADIALMICROCHART_PERCENTAGE_TEXT", [control.getPercentage()]);
};
return RadialMicroChartRenderer;
}, /* bExport */ true);
}; // end of sap/suite/ui/microchart/RadialMicroChartRenderer.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.library') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
/**
* Initialization Code and shared classes of library sap.suite.ui.microchart.
*/
jQuery.sap.declare('sap.suite.ui.microchart.library'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.library'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Core'); // unlisted dependency retained
jQuery.sap.require('sap.m.library'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/library",['jquery.sap.global', 'sap/ui/core/library', 'sap/ui/core/Core', 'sap/m/library'],
function(jQuery, coreLibrary, Core, mLibrary) {
"use strict";
/**
* UI5 library: sap.suite.ui.microchart.
*
* @namespace
* @name sap.suite.ui.microchart
* @public
*/
// delegate further initialization of this library to the Core
sap.ui.getCore().initLibrary({
name : "sap.suite.ui.microchart",
version: "1.36.12",
// library dependencies
dependencies : ["sap.ui.core", "sap.m"],
types: [
"sap.suite.ui.microchart.AreaMicroChartViewType",
"sap.suite.ui.microchart.BulletMicroChartModeType",
"sap.suite.ui.microchart.CommonBackgroundType",
"sap.suite.ui.microchart.ComparisonMicroChartViewType",
"sap.suite.ui.microchart.LoadStateType"
],
interfaces: [],
controls: [
"sap.suite.ui.microchart.AreaMicroChart",
"sap.suite.ui.microchart.BulletMicroChart",
"sap.suite.ui.microchart.ColumnMicroChart",
"sap.suite.ui.microchart.ComparisonMicroChart",
"sap.suite.ui.microchart.DeltaMicroChart",
"sap.suite.ui.microchart.HarveyBallMicroChart",
"sap.suite.ui.microchart.RadialMicroChart"
],
elements: [
"sap.suite.ui.microchart.AreaMicroChartPoint",
"sap.suite.ui.microchart.AreaMicroChartItem",
"sap.suite.ui.microchart.AreaMicroChartLabel",
"sap.suite.ui.microchart.BulletMicroChartData",
"sap.suite.ui.microchart.ColumnMicroChartData",
"sap.suite.ui.microchart.ColumnMicroChartLabel",
"sap.suite.ui.microchart.ComparisonMicroChartData",
"sap.suite.ui.microchart.HarveyBallMicroChartItem"
]
});
/**
* Enum of available views for the area micro chart concerning the position of the labels.
*
* @enum {string}
* @public
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
sap.suite.ui.microchart.AreaMicroChartViewType = {
/**
* The view with labels on the top and bottom.
* @public
*/
Normal : "Normal",
/**
* The view with labels on the left and right.
* @public
*/
Wide : "Wide"
};
/**
* Defines if the horizontal bar represents a current value only or if it represents the delta between a current value and a threshold value.
*
* @enum {string}
* @public
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
sap.suite.ui.microchart.BulletMicroChartModeType = {
/**
* Displays the Actual value.
* @public
*/
Actual: "Actual",
/**
* Displays delta between the Actual and Threshold values.
* @public
*/
Delta: "Delta"
};
/**
* Lists the available theme-specific background colors.
*
* @enum {string}
* @public
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
sap.suite.ui.microchart.CommonBackgroundType = {
/**
* The lightest background color.
* @public
*/
Lightest: "Lightest",
/**
* Extra light background color.
* @public
*/
ExtraLight: "ExtraLight",
/**
* Light background color.
* @public
*/
Light: "Light",
/**
* Medium light background color.
* @public
*/
MediumLight: "MediumLight",
/**
* Medium background color.
* @public
*/
Medium: "Medium",
/**
* Dark background color.
* @public
*/
Dark: "Dark",
/**
* Extra dark background color.
* @public
*/
ExtraDark: "ExtraDark",
/**
* The darkest background color.
* @public
*/
Darkest: "Darkest",
/**
* The transparent background color.
* @public
*/
Transparent: "Transparent"
};
/**
* Lists the views of the comparison micro chart concerning the position of titles and labels.
*
* @enum {string}
* @public
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
sap.suite.ui.microchart.ComparisonMicroChartViewType = {
/**
* Titles and values are displayed above the bars.
* @public
*/
Normal: "Normal",
/**
* Titles and values are displayed in the same line with the bars.
* @public
*/
Wide: "Wide"
};
sap.suite.ui.microchart.LoadStateType = {
/**
* LoadableView is loading the control.
* @public
*/
Loading: "Loading",
/**
* LoadableView has loaded the control.
* @public
*/
Loaded: "Loaded",
/**
* LoadableView failed to load the control.
* @public
*/
Failed: "Failed",
/**
* LoadableView disabled to load the control.
* @public
*/
Disabled: "Disabled"
};
return sap.suite.ui.microchart;
});
}; // end of sap/suite/ui/microchart/library.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.AreaMicroChart') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
jQuery.sap.declare('sap.suite.ui.microchart.AreaMicroChart'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/AreaMicroChart",['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* Constructor for a new AreaMicroChart control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Chart that displays the history of values and target values as segmented lines and shows thresholds as colored background. This control replaces the deprecated sap.suite.ui.commons.MicroAreaChart.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.AreaMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var AreaMicroChart = Control.extend("sap.suite.ui.microchart.AreaMicroChart", /** @lends sap.suite.ui.microchart.AreaMicroChart.prototype */ {
metadata: {
library: "sap.suite.ui.microchart",
properties: {
/**
* The width of the chart.
*/
width: {type: "sap.ui.core.CSSSize", group : "Misc", defaultValue : null},
/**
* The height of the chart.
*/
height: {type: "sap.ui.core.CSSSize", group : "Misc", defaultValue : null},
/**
* If this property is set it indicates the value X axis ends with.
*/
maxXValue: {type: "float", group : "Misc", defaultValue : null},
/**
* If this property is set it indicates the value X axis ends with.
*/
minXValue: {type : "float", group : "Misc", defaultValue : null},
/**
* If this property is set it indicates the value X axis ends with.
*/
maxYValue: {type: "float", group : "Misc", defaultValue : null},
/**
* If this property is set it indicates the value X axis ends with.
*/
minYValue: {type: "float", group : "Misc", defaultValue : null},
/**
* The view of the chart.
*/
view: {type: "sap.suite.ui.microchart.AreaMicroChartViewType", group : "Appearance", defaultValue : "Normal"},
/**
* The color palette for the chart. If this property is set,
* semantic colors defined in AreaMicroChartItem are ignored.
* Colors from the palette are assigned to each line consequentially.
* When all the palette colors are used, assignment of the colors begins
* from the first palette color.
*/
colorPalette: {type: "string[]", group : "Appearance", defaultValue : [] }
},
events : {
/**
* The event is fired when the user chooses the micro area chart.
*/
press: {}
},
aggregations: {
/**
* The configuration of the actual values line.
* The color property defines the color of the line.
* Points are rendered in the same sequence as in this aggregation.
*/
chart: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The configuration of the max threshold area. The color property defines the color of the area above the max threshold line. Points are rendered in the same sequence as in this aggregation.
*/
maxThreshold: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The configuration of the upper line of the inner threshold area. The color property defines the color of the area between inner thresholds. For rendering of the inner threshold area, both innerMaxThreshold and innerMinThreshold aggregations must be defined. Points are rendered in the same sequence as in this aggregation.
*/
innerMaxThreshold: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The configuration of the bottom line of the inner threshold area. The color property is ignored. For rendering of the inner threshold area, both innerMaxThreshold and innerMinThreshold aggregations must be defined. Points are rendered in the same sequence as in this aggregation.
*/
innerMinThreshold: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The configuration of the min threshold area. The color property defines the color of the area below the min threshold line. Points are rendered in the same sequence as in this aggregation.
*/
minThreshold: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The configuration of the target values line. The color property defines the color of the line. Points are rendered in the same sequence as in this aggregation.
*/
target: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The label on X axis for the first point of the chart.
*/
firstXLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The label on Y axis for the first point of the chart.
*/
firstYLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The label on X axis for the last point of the chart.
*/
lastXLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The label on Y axis for the last point of the chart.
*/
lastYLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The label for the maximum point of the chart.
*/
maxLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The label for the minimum point of the chart.
*/
minLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The set of lines.
*/
lines: { multiple: true, type: "sap.suite.ui.microchart.AreaMicroChartItem" }
}
}
});
AreaMicroChart.prototype.init = function(){
this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this.setTooltip("{AltText}");
};
AreaMicroChart.prototype._getCssValues = function() {
this._cssHelper.className = Array.prototype.slice.call(arguments).join(" ");
var oCsses = window.getComputedStyle(this._cssHelper);
if (oCsses.backgroundColor == undefined) {
oCsses.backgroundColor = oCsses["background-color"];
}
if (oCsses.outlineStyle == undefined) {
oCsses.outlineStyle = oCsses["outline-style"];
}
if (oCsses.outlineWidth == undefined) {
oCsses.outlineWidth = oCsses["outline-width"];
}
return oCsses;
};
AreaMicroChart.prototype.__fillThresholdArea = function(c, aPoints1, aPoints2, color) {
c.beginPath();
c.moveTo(aPoints1[0].x, aPoints1[0].y);
for (var i = 1, length = aPoints1.length; i < length; i++) {
c.lineTo(aPoints1[i].x, aPoints1[i].y);
}
for (var j = aPoints2.length - 1; j >= 0 ; j--) {
c.lineTo(aPoints2[j].x, aPoints2[j].y);
}
c.closePath();
c.fillStyle = "white";
c.fill();
c.fillStyle = color;
c.fill();
c.lineWidth = 1;
c.strokeStyle = "white";
c.stroke();
c.strokeStyle = color;
c.stroke();
};
AreaMicroChart.prototype._renderDashedLine = function(c, aPoints, d, aDashes) {
if (c.setLineDash) {
c.setLineDash(aDashes);
this._renderLine(c, aPoints, d);
c.setLineDash([]);
} else {
c.beginPath();
for (var i = 0, length = aPoints.length - 1; i < length; i++) {
c._dashedLine(aPoints[i].x, aPoints[i].y, aPoints[i + 1].x, aPoints[i + 1].y, aDashes);
}
c.stroke();
}
};
AreaMicroChart.prototype._renderLine = function(c, aPoints, d) {
c.beginPath();
c.moveTo(aPoints[0].x, aPoints[0].y);
for (var i = 1, length = aPoints.length; i < length; i++) {
c.lineTo(aPoints[i].x, aPoints[i].y);
}
c.stroke();
};
AreaMicroChart.prototype._renderTarget = function(c, d) {
if (d.target.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcTarget", this.getTarget().getColor());
c.strokeStyle = oCsses.color;
c.lineWidth = parseFloat(oCsses.width);
if (oCsses.outlineStyle == "dotted") {
this._renderDashedLine(c, d.target, d, [parseFloat(oCsses.outlineWidth), 3]);
} else {
this._renderLine(c, d.target, d);
}
} else if (d.target.length == 1) {
jQuery.sap.log.warning("Target is not rendered because only 1 point was given");
}
};
AreaMicroChart.prototype._renderThresholdLine = function(c, aPoints, d) {
if (aPoints && aPoints.length) {
var oCsses = this._getCssValues("sapSuiteAmcThreshold");
c.strokeStyle = oCsses.color;
c.lineWidth = oCsses.width;
this._renderLine(c, aPoints, d);
}
};
AreaMicroChart.prototype._fillMaxThreshold = function(c, d) {
if (d.maxThreshold.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcThreshold", this.getMaxThreshold().getColor());
this.__fillThresholdArea(c, d.maxThreshold, [
{x: d.maxThreshold[0].x, y: d.minY},
{x: d.maxThreshold[d.maxThreshold.length - 1].x, y: d.minY}
], oCsses.backgroundColor);
this._renderThresholdLine(c, d.maxThreshold, d);
} else if (d.maxThreshold.length == 1) {
jQuery.sap.log.warning("Max Threshold is not rendered because only 1 point was given");
}
};
AreaMicroChart.prototype._fillMinThreshold = function(c, d) {
if (d.minThreshold.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcThreshold", this.getMinThreshold().getColor());
this.__fillThresholdArea(c, d.minThreshold, [
{x: d.minThreshold[0].x, y: d.maxY},
{x: d.minThreshold[d.minThreshold.length - 1].x, y: d.maxY}
], oCsses.backgroundColor);
} else if (d.minThreshold.length == 1) {
jQuery.sap.log.warning("Min Threshold is not rendered because only 1 point was given");
}
};
AreaMicroChart.prototype._fillThresholdArea = function(c, d) {
if (d.minThreshold.length > 1 && d.maxThreshold.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcThreshold", "Critical");
this.__fillThresholdArea(c, d.maxThreshold, d.minThreshold, oCsses.backgroundColor);
}
};
AreaMicroChart.prototype._fillInnerThresholdArea = function(c, d) {
if (d.innerMinThreshold.length > 1 && d.innerMaxThreshold.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcThreshold", this.getInnerMaxThreshold().getColor());
this.__fillThresholdArea(c, d.innerMaxThreshold, d.innerMinThreshold, oCsses.backgroundColor);
} else if (d.innerMinThreshold.length || d.innerMaxThreshold.length) {
jQuery.sap.log.warning("Inner threshold area is not rendered because inner min and max threshold were not correctly set");
}
};
AreaMicroChart.prototype._renderChart = function(c, d) {
if (d.chart.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcChart", this.getChart().getColor());
c.strokeStyle = oCsses.color;
c.lineWidth = parseFloat(oCsses.width);
this._renderLine(c, d.chart, d);
} else if (d.chart.length == 1) {
jQuery.sap.log.warning("Actual values are not rendered because only 1 point was given");
}
};
AreaMicroChart.prototype._renderLines = function(c, d) {
var iCpLength = this.getColorPalette().length;
var iCpIndex = 0;
var that = this;
var fnNextColor = function() {
if (iCpLength) {
if (iCpIndex == iCpLength) {
iCpIndex = 0;
}
return that.getColorPalette()[iCpIndex++];
}
};
var oCsses = this._getCssValues("sapSuiteAmcLine");
c.lineWidth = parseFloat(oCsses.width);
var iLength = d.lines.length;
for (var i = 0; i < iLength; i++) {
if (d.lines[i].length > 1) {
if (iCpLength) {
c.strokeStyle = fnNextColor();
} else {
oCsses = this._getCssValues("sapSuiteAmcLine", this.getLines()[i].getColor());
c.strokeStyle = oCsses.color;
}
this._renderLine(c, d.lines[i], d);
}
}
};
AreaMicroChart.prototype._renderCanvas = function() {
this._cssHelper = document.getElementById(this.getId() + "-css-helper");
var sLabelsWidth = this.$().find(".sapSuiteAmcSideLabels").css("width");
this.$().find(".sapSuiteAmcCanvas, .sapSuiteAmcLabels").css("right", sLabelsWidth).css("left", sLabelsWidth);
var canvas = document.getElementById(this.getId() + "-canvas");
var canvasSettings = window.getComputedStyle(canvas);
var fWidth = parseFloat(canvasSettings.width);
canvas.setAttribute("width", fWidth ? fWidth : 360);
var fHeight = parseFloat(canvasSettings.height);
canvas.setAttribute("height", fHeight ? fHeight : 242);
var c = canvas.getContext("2d");
c.lineJoin = "round";
c._dashedLine = function(x, y, x2, y2, dashArray) {
var dashCount = dashArray.length;
this.moveTo(x, y);
var dx = (x2 - x), dy = (y2 - y);
var slope = dx ? dy / dx : 1e15;
var distRemaining = Math.sqrt(dx * dx + dy * dy);
var dashIndex = 0, draw = true;
while (distRemaining >= 0.1) {
var dashLength = dashArray[dashIndex++ % dashCount];
if (dashLength > distRemaining) {
dashLength = distRemaining;
}
var xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope));
if (dx < 0) {
xStep = -xStep;
}
x += xStep;
y += slope * xStep;
this[draw ? 'lineTo' : 'moveTo'](x, y);
distRemaining -= dashLength;
draw = !draw;
}
};
var d = this._calculateDimensions(canvas.width, canvas.height);
this._fillMaxThreshold(c, d);
this._fillMinThreshold(c, d);
this._fillThresholdArea(c, d);
this._renderThresholdLine(c, d.minThreshold, d);
this._renderThresholdLine(c, d.maxThreshold, d);
this._fillInnerThresholdArea(c, d);
this._renderThresholdLine(c, d.innerMinThreshold, d);
this._renderThresholdLine(c, d.innerMaxThreshold, d);
this._renderTarget(c, d);
this._renderChart(c, d);
this._renderLines(c, d);
};
/**
*
*
* @param fWidth
* @param fHeight
* @returns {object}
*/
AreaMicroChart.prototype._calculateDimensions = function(fWidth, fHeight) {
var maxX, maxY, minX, minY;
maxX = maxY = minX = minY = undefined;
var that = this;
function calculateExtremums() {
if (!that._isMinXValue || !that._isMaxXValue || !that._isMinYValue || !that._isMaxYValue) {
var lines = that.getLines();
if (that.getMaxThreshold()) {
lines.push(that.getMaxThreshold());
}
if (that.getMinThreshold()) {
lines.push(that.getMinThreshold());
}
if (that.getChart()) {
lines.push(that.getChart());
}
if (that.getTarget()) {
lines.push(that.getTarget());
}
if (that.getInnerMaxThreshold()) {
lines.push(that.getInnerMaxThreshold());
}
if (that.getInnerMinThreshold()) {
lines.push(that.getInnerMinThreshold());
}
for (var i = 0, numOfLines = lines.length; i < numOfLines; i++) {
var aPoints = lines[i].getPoints();
for (var counter = 0, a = aPoints.length; counter < a; counter++) {
var tmpVal = aPoints[counter].getXValue();
if (tmpVal > maxX || maxX === undefined) {
maxX = tmpVal;
}
if (tmpVal < minX || minX === undefined) {
minX = tmpVal;
}
tmpVal = aPoints[counter].getYValue();
if (tmpVal > maxY || maxY === undefined) {
maxY = tmpVal;
}
if (tmpVal < minY || minY === undefined) {
minY = tmpVal;
}
}
}
}
if (that._isMinXValue) {
minX = that.getMinXValue();
}
if (that._isMaxXValue) {
maxX = that.getMaxXValue();
}
if (that._isMinYValue) {
minY = that.getMinYValue();
}
if (that._isMaxYValue) {
maxY = that.getMaxYValue();
}
}
calculateExtremums();
var oResult = {
minY: 0,
minX: 0,
maxY: fHeight,
maxX: fWidth,
lines: []
};
var kx;
var fDeltaX = maxX - minX;
if (fDeltaX > 0) {
kx = fWidth / fDeltaX;
} else if (fDeltaX == 0) {
kx = 0;
oResult.maxX /= 2;
} else {
jQuery.sap.log.warning("Min X is more than max X");
}
var ky;
var fDeltaY = maxY - minY;
if (fDeltaY > 0) {
ky = fHeight / (maxY - minY);
} else if (fDeltaY == 0) {
ky = 0;
oResult.maxY /= 2;
} else {
jQuery.sap.log.warning("Min Y is more than max Y");
}
function calculateCoordinates(line) {
var bRtl = sap.ui.getCore().getConfiguration().getRTL();
var fnCalcX = function(fValue) {
var x = kx * (fValue - minX);
if (bRtl) {
x = oResult.maxX - x;
}
return x;
};
var fnCalcY = function(fValue) {
return oResult.maxY - ky * (fValue - minY);
};
var aResult = [];
if (line && kx != undefined && ky != undefined) {
var aPoints = line.getPoints();
var iLength = aPoints.length;
var xi, yi, tmpXValue, tmpYValue;
if (iLength == 1) {
tmpXValue = aPoints[0].getXValue();
tmpYValue = aPoints[0].getYValue();
if (tmpXValue == undefined ^ tmpYValue == undefined) {
var xn, yn;
if (tmpXValue == undefined) {
yn = yi = fnCalcY(tmpYValue);
xi = oResult.minX;
xn = oResult.maxX;
} else {
xn = xi = fnCalcX(tmpXValue);
yi = oResult.minY;
yn = oResult.maxY;
}
aResult.push({x: xi, y: yi}, {x: xn, y: yn});
} else {
jQuery.sap.log.warning("Point with coordinates [" + tmpXValue + " " + tmpYValue + "] ignored");
}
} else {
for (var i = 0; i < iLength; i++) {
tmpXValue = aPoints[i].getXValue();
tmpYValue = aPoints[i].getYValue();
if (tmpXValue != undefined && tmpYValue != undefined) {
xi = fnCalcX(tmpXValue);
yi = fnCalcY(tmpYValue);
aResult.push({x: xi, y: yi});
} else {
jQuery.sap.log.warning("Point with coordinates [" + tmpXValue + " " + tmpYValue + "] ignored");
}
}
}
}
return aResult;
}
oResult.maxThreshold = calculateCoordinates(that.getMaxThreshold());
oResult.minThreshold = calculateCoordinates(that.getMinThreshold());
oResult.chart = calculateCoordinates(that.getChart());
oResult.target = calculateCoordinates(that.getTarget());
oResult.innerMaxThreshold = calculateCoordinates(that.getInnerMaxThreshold());
oResult.innerMinThreshold = calculateCoordinates(that.getInnerMinThreshold());
var iLength = that.getLines().length;
for (var i = 0; i < iLength; i++) {
oResult.lines.push(calculateCoordinates(that.getLines()[i]));
}
return oResult;
};
/**
* Property setter for the Min X value
*
* @param {int} value - new value Min X
* @param {boolean} bSuppressInvalidate - Suppress in validate
* @returns {void}
* @public
*/
AreaMicroChart.prototype.setMinXValue = function(value, bSuppressInvalidate) {
this._isMinXValue = this._isNumber(value);
return this.setProperty("minXValue", this._isMinXValue ? value : NaN, bSuppressInvalidate);
};
/**
* Property setter for the Max X value
*
* @param {int} value - new value Max X
* @param {boolean} bSuppressInvalidate - Suppress in validate
* @returns {void}
* @public
*/
AreaMicroChart.prototype.setMaxXValue = function(value, bSuppressInvalidate) {
this._isMaxXValue = this._isNumber(value);
return this.setProperty("maxXValue", this._isMaxXValue ? value : NaN, bSuppressInvalidate);
};
/**
* Property setter for the Min Y value
*
* @param {value} value - new value Min Y
* @param {boolean} bSuppressInvalidate - Suppress in validate
* @returns {void}
* @public
*/
AreaMicroChart.prototype.setMinYValue = function(value, bSuppressInvalidate) {
this._isMinYValue = this._isNumber(value);
return this.setProperty("minYValue", this._isMinYValue ? value : NaN, bSuppressInvalidate);
};
/**
* Property setter for the Max Y valye
*
* @param {string} value - new value Max Y
* @param {boolean} bSuppressInvalidate - Suppress in validate
* @returns {void}
* @public
*/
AreaMicroChart.prototype.setMaxYValue = function(value, bSuppressInvalidate) {
this._isMaxYValue = this._isNumber(value);
return this.setProperty("maxYValue", this._isMaxYValue ? value : NaN, bSuppressInvalidate);
};
AreaMicroChart.prototype._isNumber = function(n) {
return typeof n === 'number' && !isNaN(n) && isFinite(n);
};
AreaMicroChart.prototype.onAfterRendering = function() {
this._renderCanvas();
};
AreaMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.internet_explorer) {
this.$().focus();
}
this.firePress();
};
AreaMicroChart.prototype.onkeydown = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.SPACE) {
oEvent.preventDefault();
}
};
AreaMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.ENTER || oEvent.which == jQuery.sap.KeyCodes.SPACE) {
this.firePress();
oEvent.preventDefault();
}
};
AreaMicroChart.prototype.attachEvent = function(sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData, fnFunction, oListener);
if (this.hasListeners("press")) {
this.$().attr("tabindex", 0).addClass("sapSuiteUiMicroChartPointer");
}
return this;
};
AreaMicroChart.prototype.detachEvent = function(sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction, oListener);
if (!this.hasListeners("press")) {
this.$().removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer");
}
return this;
};
AreaMicroChart.prototype._getLocalizedColorMeaning = function(sColor) {
return this._oRb.getText(("SEMANTIC_COLOR_" + sColor).toUpperCase());
};
AreaMicroChart.prototype.getAltText = function() {
var sAltText = "";
var oFirstXLabel = this.getFirstXLabel();
var oFirstYLabel = this.getFirstYLabel();
var oLastXLabel = this.getLastXLabel();
var oLastYLabel = this.getLastYLabel();
var oMinLabel = this.getMinLabel();
var oMaxLabel = this.getMaxLabel();
var oActual = this.getChart();
var oTarget = this.getTarget();
var bIsFirst = true;
if (oFirstXLabel && oFirstXLabel.getLabel() || oFirstYLabel && oFirstYLabel.getLabel()) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_START")) + ": " + (oFirstXLabel ? oFirstXLabel.getLabel() : "") + " " + (oFirstYLabel ? oFirstYLabel.getLabel() + " " + this._getLocalizedColorMeaning(oFirstYLabel.getColor()) : "");
bIsFirst = false;
}
if (oLastXLabel && oLastXLabel.getLabel() || oLastYLabel && oLastYLabel.getLabel()) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_END")) + ": " + (oLastXLabel ? oLastXLabel.getLabel() : "") + " " + (oLastYLabel ? oLastYLabel.getLabel() + " " + this._getLocalizedColorMeaning(oLastYLabel.getColor()) : "");
bIsFirst = false;
}
if (oMinLabel && oMinLabel.getLabel()) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_MINIMAL_VALUE")) + ": " + oMinLabel.getLabel() + " " + this._getLocalizedColorMeaning(oMinLabel.getColor());
bIsFirst = false;
}
if (oMaxLabel && oMaxLabel.getLabel()) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_MAXIMAL_VALUE")) + ": " + oMaxLabel.getLabel() + " " + this._getLocalizedColorMeaning(oMaxLabel.getColor());
bIsFirst = false;
}
if (oActual && oActual.getPoints() && oActual.getPoints().length > 0) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_ACTUAL_VALUES")) + ":";
bIsFirst = false;
var aActual = oActual.getPoints();
for (var i = 0; i < aActual.length; i++) {
sAltText += " " + aActual[i].getY();
}
}
if (oTarget && oTarget.getPoints() && oTarget.getPoints().length > 0) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_TARGET_VALUES")) + ":";
var aTarget = oTarget.getPoints();
for (var j = 0; j < aTarget.length; j++) {
sAltText += " " + aTarget[j].getY();
}
}
for (var k = 0; k < this.getLines().length; k++) {
var oLine = this.getLines()[k];
if (oLine.getPoints() && oLine.getPoints().length > 0) {
sAltText += (bIsFirst ? "" : "\n") + oLine.getTitle() + ":";
var aLine = oLine.getPoints();
for (var y = 0; y < aLine.length; y++) {
sAltText += " " + aLine[y].getY();
}
if (this.getColorPalette().length == 0) {
sAltText += " " + this._getLocalizedColorMeaning(oLine.getColor());
}
}
}
return sAltText;
};
AreaMicroChart.prototype.getTooltip_AsString = function() {
var oTooltip = this.getTooltip();
var sTooltip = this.getAltText();
if (typeof oTooltip === "string" || oTooltip instanceof String) {
sTooltip = oTooltip.split("{AltText}").join(sTooltip).split("((AltText))").join(sTooltip);
return sTooltip;
}
return oTooltip ? oTooltip : "";
};
AreaMicroChart.prototype.clone = function(sIdSuffix, aLocalIds, oOptions) {
var oClone = sap.ui.core.Control.prototype.clone.apply(this, arguments);
oClone._isMinXValue = this._isMinXValue;
oClone._isMaxXValue = this._isMaxXValue;
oClone._isMinYValue = this._isMinYValue;
oClone._isMaxYValue = this._isMaxYValue;
return oClone;
};
return AreaMicroChart;
});
}; // end of sap/suite/ui/microchart/AreaMicroChart.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.AreaMicroChartItem') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// This control displays the history of values as a line mini chart or an area mini chart.
jQuery.sap.declare('sap.suite.ui.microchart.AreaMicroChartItem'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/AreaMicroChartItem",['jquery.sap.global', './library', 'sap/ui/core/Element'],
function(jQuery, library, Element) {
"use strict";
/**
* The configuration of the graphic element on the chart.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Graphical representation of the area micro chart regarding the value lines, the thresholds, and the target values.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.AreaMicroChartItem
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var AreaMicroChartItem = Element.extend("sap.suite.ui.microchart.AreaMicroChartItem", /** @lends sap.suite.ui.microchart.AreaMicroChartItem.prototype */ {
metadata: {
library: "sap.suite.ui.microchart",
properties: {
/**
* The graphic element color.
*/
color: { group: "Misc", type: "sap.m.ValueColor", defaultValue: "Neutral" },
/**
* The line title.
*/
title: { type: "string", group: "Misc", defaultValue: null}
},
aggregations: {
/**
* The set of points for this graphic element.
*/
"points": { multiple: true, type: "sap.suite.ui.microchart.AreaMicroChartPoint" }
}
}
});
return AreaMicroChartItem;
});
}; // end of sap/suite/ui/microchart/AreaMicroChartItem.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.AreaMicroChartLabel') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// This control displays the history of values as a line mini chart or an area mini chart.
jQuery.sap.declare('sap.suite.ui.microchart.AreaMicroChartLabel'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/AreaMicroChartLabel",['jquery.sap.global', './library', 'sap/ui/core/Element'],
function(jQuery, library, Element) {
"use strict";
/**
* Constructor for a new AreaMicroChart control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Displays or hides the labels for start and end dates, start and end values, and minimum and maximum values.
* @extends sap.ui.core.Control
*
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.AreaMicroChartLabel
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var AreaMicroChartLabel = Element.extend("sap.suite.ui.microchart.AreaMicroChartLabel", /** @lends sap.suite.ui.microchart.AreaMicroChartLabel.prototype */ {
metadata : {
library : "sap.suite.ui.microchart",
properties : {
/**
* The graphic element color.
*/
color: { group: "Misc", type: "sap.m.ValueColor", defaultValue: "Neutral" },
/**
* The line title.
*/
label: {type : "string", group : "Misc", defaultValue : "" }
}
}
});
return AreaMicroChartLabel;
});
}; // end of sap/suite/ui/microchart/AreaMicroChartLabel.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.AreaMicroChartPoint') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// This control displays the history of values as a line mini chart or an area mini chart.
jQuery.sap.declare('sap.suite.ui.microchart.AreaMicroChartPoint'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/AreaMicroChartPoint",['jquery.sap.global', './library', 'sap/ui/core/Element'],
function(jQuery, library, Element) {
"use strict";
/**
* This control contains data for the point.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Contains the data for the point.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.AreaMicroChartPoint
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var AreaMicroChartPoint = Element.extend("sap.suite.ui.microchart.AreaMicroChartPoint", /** @lends sap.suite.ui.microchart.AreaMicroChartPoint.prototype */ {
metadata : {
library : "sap.suite.ui.microchart",
properties : {
/**
* X value for the given point.
*/
x: { type : "float", group : "Misc", defaultValue : null },
/**
* Y value for the given point.
*/
y: { type : "float", group : "Misc", defaultValue : null }
}
}
});
AreaMicroChartPoint.prototype.setX = function(value, bSuppressInvalidate) {
this._isXValue = this._isNumber(value);
return this.setProperty("x", this._isXValue ? value : NaN, bSuppressInvalidate);
};
AreaMicroChartPoint.prototype.setY = function(value, bSuppressInvalidate) {
this._isYValue = this._isNumber(value);
return this.setProperty("y", this._isYValue ? value : NaN, bSuppressInvalidate);
};
//
/**
* Returns the x value. It returns 'undefined', if the x property was not set or an invalid number was set.
*
* @public
* @returns {string}
*/
AreaMicroChartPoint.prototype.getXValue = function() {
return this._isXValue ? this.getX() : undefined;
};
/**
* Returns the y value. It returns 'undefined', if the y property was not set or an invalid number was set.
*
* @public
* @returns {float}
*/
AreaMicroChartPoint.prototype.getYValue = function() {
return this._isYValue ? this.getY() : undefined;
};
AreaMicroChartPoint.prototype._isNumber = function(n) {
return typeof n == 'number' && !isNaN(n) && isFinite(n);
};
/**
* Overrides Control.clone to clone additional internal state.
*
* @param {string} sIdSuffix? a suffix to be appended to the cloned element id
* @param {string[]} aLocalIds? an array of local IDs within the cloned hierarchy (internally used)
* @param {object} oOptions
* @returns {sap.ui.core.Control} reference to the newly created clone
*/
AreaMicroChartPoint.prototype.clone = function(sIdSuffix, aLocalIds, oOptions) {
var oClone = sap.ui.core.Control.prototype.clone.apply(this, arguments);
oClone._isXValue = this._isXValue;
oClone._isYValue = this._isYValue;
return oClone;
};
return AreaMicroChartPoint;
});
}; // end of sap/suite/ui/microchart/AreaMicroChartPoint.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.BulletMicroChart') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.suite.ui.microchart.BulletMicroChart.
jQuery.sap.declare('sap.suite.ui.microchart.BulletMicroChart'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/BulletMicroChart",['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* Constructor for a new BulletMicroChart control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Displays a colored horizontal bar representing a current value on top of a background bar representing the compared value. The vertical bars can represent the numeric values, the scaling factors, the thresholds, and the target values. This control replaces the deprecated sap.suite.ui.commons.BulletChart.
* @extends sap.ui.core.Control
*
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.BulletMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var BulletMicroChart = Control.extend("sap.suite.ui.microchart.BulletMicroChart", /** @lends sap.suite.ui.microchart.BulletMicroChart.prototype */ { metadata : {
library: "sap.suite.ui.microchart",
properties: {
/**
* The size of the microchart. If not set, the default size is applied based on the size of the device tile.
*/
size: {type: "sap.m.Size", group: "Misc", defaultValue: "Auto"},
/**
* The mode of displaying the actual value itself or the delta between the actual value and the target value. If not set, the actual value is displayed.
*/
mode: {type: "sap.suite.ui.microchart.BulletMicroChartModeType", group: "Misc", defaultValue: "Actual"},
/**
* The scaling suffix that is added to the actual and target values.
*/
scale: {type: "string", group: "Misc", defaultValue: ""},
/**
* The forecast value that is displayed in Actual mode only. If set, the forecast value bar appears in the background of the actual value bar.
*/
forecastValue: {type: "float", group: "Misc", defaultValue: null},
/**
* The target value that is displayed as a black vertical bar.
*/
targetValue: {type: "float", group: "Misc", defaultValue: null},
/**
* The minimum scale value for the bar chart used for defining a fixed size of the scale in different instances of this control.
*/
minValue: {type: "float", group: "Misc", defaultValue: null},
/**
* The maximum scale value for the bar chart used for defining a fixed size of the scale in different instances of this control.
*/
maxValue: {type: "float", group: "Misc", defaultValue: null},
/**
* If set to true, shows the numeric actual value. This property works in Actual mode only.
*/
showActualValue: {type: "boolean", group: "Misc", defaultValue: "true"},
/**
* If set to true, shows the calculated delta value instead of the numeric actual value regardless of the showActualValue setting. This property works in Delta mode only.
*/
showDeltaValue: {type: "boolean", group: "Misc", defaultValue: "true"},
/**
* If set to true, shows the numeric target value.
*/
showTargetValue: {type: "boolean", group: "Misc", defaultValue: "true"},
/**
* If set to true, shows the value marker.
*/
showValueMarker: {type: "boolean", group: "Misc", defaultValue: "false"},
/**
* If set, displays a specified label instead of the numeric actual value.
*/
actualValueLabel: {type: "string", group: "Misc", defaultValue: ""},
/**
* If set, displays a specified label instead of the calculated numeric delta value.
*/
deltaValueLabel: {type: "string", group: "Misc", defaultValue: ""},
/**
* If set, displays a specified label instead of the numeric target value.
*/
targetValueLabel: {type: "string", group: "Misc", defaultValue: ""},
/**
* The width of the chart. If it is not set, the size of the control is defined by the size property.
*/
width: {type: "sap.ui.core.CSSSize", group: "Misc"},
/**
* The background color of the scale.
*/
scaleColor: {type: "sap.suite.ui.microchart.CommonBackgroundType", group: "Misc", defaultValue: "MediumLight"}
},
aggregations: {
/**
* The bullet chart actual data.
*/
actual: {type: "sap.suite.ui.microchart.BulletMicroChartData", multiple: false},
/**
* The bullet chart thresholds data.
*/
thresholds: {type: "sap.suite.ui.microchart.BulletMicroChartData", multiple: true, singularName: "threshold"}
},
events: {
/**
* The event is fired when the user chooses the bullet microchart.
*/
press : {}
}
}});
BulletMicroChart.prototype.init = function() {
this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this.setTooltip("{AltText}");
};
/**
* Calculates the width in percents of chart elements in accordance with provided chart values.
*
* @returns {Object} object that contains calculated values for actual value, target value, thresholds and their colors.
* @private
*/
BulletMicroChart.prototype._calculateChartData = function() {
var fScaleWidthPct = 98;
var aData = this.getThresholds();
var aThresholds = [];
var fTarget = this.getTargetValue();
var fForecast = this.getForecastValue();
var fActual = this.getActual() && this.getActual().getValue() ? this.getActual().getValue() : 0;
var aValues = [];
var fLowestValue = 0;
var fHighestValue = 0;
if (this.getActual() && this.getActual()._isValueSet) {
aValues.push(fActual);
}
if (this._isForecastValueSet) {
aValues.push(fForecast);
}
if (this._isTargetValueSet) {
aValues.push(fTarget);
}
if (this._isMinValueSet) {
aValues.push(this.getMinValue());
}
if (this._isMaxValueSet) {
aValues.push(this.getMaxValue());
}
for (var iData = 0; iData < aData.length; iData++) {
aValues.push(aData[iData].getValue());
}
var fTotal = 0;
if (aValues.length > 0) {
fLowestValue = fHighestValue = aValues[0];
for (var j = 0; j < aValues.length; j++){
if (aValues[j] < fLowestValue) {
fLowestValue = aValues[j];
}
if (aValues[j] > fHighestValue) {
fHighestValue = aValues[j];
}
}
fHighestValue = (fHighestValue < 0 && fHighestValue < 3 * (fLowestValue - fHighestValue)) ? 0 : fHighestValue;
fLowestValue = (fLowestValue > 0 && fLowestValue > 3 * (fHighestValue - fLowestValue)) ? 0 : fLowestValue;
fTotal = fHighestValue - fLowestValue;
for (var iThr = 0; iThr < aData.length; iThr++) {
aThresholds[iThr] = {color: aData[iThr].getColor(), valuePct: (!aData[iThr]._isValueSet || fTotal == 0) ? 0 : ((aData[iThr].getValue() - fLowestValue) * fScaleWidthPct / fTotal).toFixed(2)};
}
}
return {
actualValuePct: (!this.getActual() || !this.getActual()._isValueSet || fTotal == 0) ? 0 : (0.05 + (fActual - fLowestValue) * fScaleWidthPct / fTotal).toFixed(2),
targetValuePct: (!this._isTargetValueSet || fTotal == 0) ? 0 : ((fTarget - fLowestValue) * fScaleWidthPct / fTotal).toFixed(2),
forecastValuePct: (!this._isForecastValueSet || fTotal == 0) ? 0 : ((fForecast - fLowestValue) * fScaleWidthPct / fTotal).toFixed(2),
thresholdsPct: aThresholds,
fScaleWidthPct: fScaleWidthPct
};
};
/**
* Calculates the number of digits after the decimal point.
*
* @param {float} fValue float value
* @returns {int} number of digits after the decimal point in fValue.
* @private
*/
BulletMicroChart.prototype._digitsAfterDecimalPoint = function(fValue) {
var sAfter = ("" + fValue).match(/[.,](\d+)/g);
return (sAfter) ? ("" + sAfter).length - 1 : 0;
};
/**
* Calculates the delta between actual value and threshold.
*
* @returns {float} value of delta between actual value and threshold.
* @private
*/
BulletMicroChart.prototype._calculateDeltaValue = function() {
if (!this.getActual()._isValueSet || !this._isTargetValueSet) {
return 0;
} else {
var fActual = this.getActual().getValue();
var fTarget = this.getTargetValue();
return Math.abs(fActual - fTarget).toFixed(Math.max(this._digitsAfterDecimalPoint(fActual), this._digitsAfterDecimalPoint(fTarget)));
}
};
BulletMicroChart.prototype.setMinValue = function(fMinValue, bSuppressInvalidate) {
this._isMinValueSet = this._fnIsNumber(fMinValue);
return this.setProperty("minValue", this._isMinValueSet ? fMinValue : NaN, bSuppressInvalidate);
};
BulletMicroChart.prototype.setMaxValue = function(fMaxValue, bSuppressInvalidate) {
this._isMaxValueSet = this._fnIsNumber(fMaxValue);
return this.setProperty("maxValue", this._isMaxValueSet ? fMaxValue : NaN, bSuppressInvalidate);
};
BulletMicroChart.prototype.setTargetValue = function(fTargetValue, bSuppressInvalidate) {
this._isTargetValueSet = this._fnIsNumber(fTargetValue);
return this.setProperty("targetValue", this._isTargetValueSet ? fTargetValue : NaN, bSuppressInvalidate);
};
BulletMicroChart.prototype.setForecastValue = function(fForecastValue, bSuppressInvalidate) {
this._isForecastValueSet = this._fnIsNumber(fForecastValue);
return this.setProperty("forecastValue", this._isForecastValueSet ? fForecastValue : NaN, bSuppressInvalidate);
};
BulletMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.internet_explorer) {
this.$().focus();
}
this.firePress();
};
BulletMicroChart.prototype.onkeydown = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.SPACE) {
oEvent.preventDefault();
}
};
BulletMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.ENTER || oEvent.which == jQuery.sap.KeyCodes.SPACE) {
this.firePress();
oEvent.preventDefault();
}
};
BulletMicroChart.prototype._fnIsNumber = function(n) {
return typeof n == 'number' && !isNaN(n) && isFinite(n);
};
BulletMicroChart.prototype.attachEvent = function(sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData, fnFunction, oListener);
if (this.hasListeners("press")) {
this.$().attr("tabindex", 0).addClass("sapSuiteUiMicroChartPointer");
}
return this;
};
BulletMicroChart.prototype.detachEvent = function(sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction, oListener);
if (!this.hasListeners("press")) {
this.$().removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer");
}
return this;
};
BulletMicroChart.prototype.onAfterRendering = function() {
if (this._sBarResizeHandlerId) {
sap.ui.core.ResizeHandler.deregister(this._sBarResizeHandlerId);
}
var oHeader = jQuery.sap.domById(this.getId() + "-chart-bar");
this._sBarResizeHandlerId = sap.ui.core.ResizeHandler.register(oHeader, jQuery.proxy(this._adjustLabelsPos, this));
this._adjustLabelsPos();
if (this.getShowValueMarker()) {
this._adjustValueToMarker();
}
};
BulletMicroChart.prototype.exit = function() {
sap.ui.core.ResizeHandler.deregister(this._sBarResizeHandlerId);
};
BulletMicroChart.prototype._adjustLabelsPos = function() {
var bRtl = sap.ui.getCore().getConfiguration().getRTL();
var oTBarVal = jQuery.sap.byId(this.getId() + "-bc-target-bar-value");
var oChartBar = jQuery.sap.byId(this.getId() + "-chart-bar");
var fFullWidth = oChartBar.width();
if (fFullWidth) {
var fTValWidth = 0;
if (oTBarVal && oTBarVal.offset()) {
fTValWidth = oTBarVal.offset().left - oChartBar.offset().left;
if (bRtl) {
fTValWidth = fFullWidth - fTValWidth;
}
this._adjustLabelPos(jQuery.sap.byId(this.getId() + "-bc-target-value"), fFullWidth, fTValWidth, bRtl);
}
var oValMarker = jQuery.sap.byId(this.getId() + "-bc-bar-value-marker");
if (oValMarker && oValMarker.offset()) {
var fAValWidth = oValMarker.offset().left - oChartBar.offset().left;
if (bRtl) {
fAValWidth = fFullWidth - fAValWidth;
}
if ((sap.suite.ui.microchart.BulletMicroChartModeType.Delta == this.getMode())) {
fAValWidth = (fAValWidth + fTValWidth) / 2;
}
this._adjustLabelPos(jQuery.sap.byId(this.getId() + "-bc-item-value"), fFullWidth, fAValWidth, bRtl);
}
}
};
BulletMicroChart.prototype._adjustLabelPos = function(oLabel, fFullWidth, fOffset, bRtl) {
var sOrientation = bRtl ? "right" : "left";
var fLabelWidth = oLabel.width();
if (fLabelWidth > fFullWidth) {
oLabel.css("width", "" + fFullWidth + "px");
oLabel.css(sOrientation, "0");
} else {
var fLabelLeft = fOffset - 0.5 * fLabelWidth;
if (fLabelLeft < 0) {
fLabelLeft = 0;
}
if (fLabelLeft + fLabelWidth > fFullWidth) {
fLabelLeft = fFullWidth - fLabelWidth;
}
oLabel.css(sOrientation, fLabelLeft);
oLabel.css("width", "" + (parseInt(fLabelWidth, 10) + 1) + "px");
}
};
BulletMicroChart.prototype._adjustValueToMarker = function() {
var oValue = jQuery.sap.byId(this.getId() + "-bc-bar-value");
var oMarker = jQuery.sap.byId(this.getId() + "-bc-bar-value-marker");
if (oValue.offset() && oMarker.offset()) {
var fValueWidth = oValue.width();
var fValueLeft = oValue.offset().left;
var fMarkerWidth = oMarker.width();
var fMarkerLeft = oMarker.offset().left;
if (sap.ui.getCore().getConfiguration().getRTL()) {
if (fMarkerLeft < fValueLeft) { // browser's subpixel problem fix
oMarker.css("right", "");
oMarker.offset({left: fValueLeft});
}
if (fMarkerLeft + fMarkerWidth > fValueLeft + fValueWidth) { // bar value is less than marker min-width
oMarker.css("right", "");
oMarker.offset({left: fValueLeft + fValueWidth - fMarkerWidth});
}
} else {
if (fMarkerLeft < fValueLeft) { // bar value is less than marker min-width
oMarker.offset({left: fValueLeft});
}
if (fMarkerLeft + fMarkerWidth > fValueLeft + fValueWidth) { // browser's subpixel problem fix
oValue.width(fMarkerLeft + fMarkerWidth - fValueLeft);
}
}
}
};
BulletMicroChart.prototype._getLocalizedColorMeaning = function(sColor) {
return this._oRb.getText(("SEMANTIC_COLOR_" + sColor).toUpperCase());
};
BulletMicroChart.prototype.getAltText = function() {
var bIsActualSet = this.getActual() && this.getActual()._isValueSet;
var sScale = this.getScale();
var sTargetValueLabel = this.getTargetValueLabel();
var sMeaning = !this.getActual() || !this.getActual().getColor() ? "" : this._getLocalizedColorMeaning(this.getActual().getColor());
var sAltText = "";
if (bIsActualSet) {
var sActualValueLabel = this.getActualValueLabel();
var sAValToShow = (sActualValueLabel) ? sActualValueLabel : "" + this.getActual().getValue();
sAltText += this._oRb.getText("BULLETMICROCHART_ACTUAL_TOOLTIP", [sAValToShow + sScale, sMeaning]);
}
if (this.getMode() == "Delta") {
if (this._isTargetValueSet && bIsActualSet) {
var sDeltaValueLabel = this.getDeltaValueLabel();
var sDValToShow = (sDeltaValueLabel) ? sDeltaValueLabel : "" + this._calculateDeltaValue();
sAltText += "\n" + this._oRb.getText("BULLETMICROCHART_DELTA_TOOLTIP", [sDValToShow + sScale, sMeaning]);
}
} else {
if (this._isForecastValueSet) {
sAltText += (this._isForecastValueSet) ? "\n" + this._oRb.getText("BULLETMICROCHART_FORECAST_TOOLTIP", [this.getForecastValue() + sScale, sMeaning]) : "";
}
}
if (this._isTargetValueSet) {
var sTValToShow = (sTargetValueLabel) ? sTargetValueLabel : "" + this.getTargetValue();
sAltText += "\n" + this._oRb.getText("BULLETMICROCHART_TARGET_TOOLTIP", [sTValToShow + sScale]);
}
var aThresholds = this.getThresholds().sort(function(oFirst, oSecond) { return oFirst.getValue() - oSecond.getValue(); });
for (var i = 0; i < aThresholds.length; i++) {
var oThreshold = aThresholds[i];
sAltText += "\n" + this._oRb.getText("BULLETMICROCHART_THRESHOLD_TOOLTIP", [oThreshold.getValue() + this.getScale(), this._getLocalizedColorMeaning(oThreshold.getColor())]);
}
return sAltText;
};
BulletMicroChart.prototype.getTooltip_AsString = function() {
var oTooltip = this.getTooltip();
var sTooltip = this.getAltText();
if (typeof oTooltip === "string" || oTooltip instanceof String) {
sTooltip = oTooltip.split("{AltText}").join(sTooltip).split("((AltText))").join(sTooltip);
return sTooltip;
}
return oTooltip ? oTooltip : "";
};
BulletMicroChart.prototype.clone = function(sIdSuffix, aLocalIds, oOptions) {
var oClone = sap.ui.core.Control.prototype.clone.apply(this, arguments);
oClone._isMinValueSet = this._isMinValueSet;
oClone._isMaxValueSet = this._isMaxValueSet;
oClone._isForecastValueSet = this._isForecastValueSet;
oClone._isTargetValueSet = this._isTargetValueSet;
return oClone;
};
return BulletMicroChart;
});
}; // end of sap/suite/ui/microchart/BulletMicroChart.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.BulletMicroChartData') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.suite.ui.microchart.BulletMicroChartData.
jQuery.sap.declare('sap.suite.ui.microchart.BulletMicroChartData'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/BulletMicroChartData",['jquery.sap.global', './library', 'sap/ui/core/Element'],
function(jQuery, library, Element) {
"use strict";
/**
* Constructor for a new BulletMicroChartData.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Contains the thresholds data.
* @extends sap.ui.core.Element
*
* @version 1.36.12
*
* @constructor
* @public
* @alias sap.suite.ui.microchart.BulletMicroChartData
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var BulletMicroChartData = Element.extend("sap.suite.ui.microchart.BulletMicroChartData", /** @lends sap.suite.ui.microchart.BulletMicroChartData.prototype */ { metadata : {
library: "sap.suite.ui.microchart",
properties: {
/**
* The actual value.
*/
value: {type: "float", group: "Misc", defaultValue: "0"},
/**
* The semantic color of the actual value.
*/
color: {type: "sap.m.ValueColor", group: "Misc", defaultValue: "Neutral"}
}
}});
BulletMicroChartData.prototype.setValue = function(fValue, bSuppressInvalidate) {
this._isValueSet = this._fnIsNumber(fValue);
return this.setProperty("value", this._isValueSet ? fValue : NaN, bSuppressInvalidate);
};
BulletMicroChartData.prototype._fnIsNumber = function(n) {
return typeof n == 'number' && !isNaN(n) && isFinite(n);
};
BulletMicroChartData.prototype.clone = function(sIdSuffix, aLocalIds, oOptions) {
var oClone = sap.ui.core.Control.prototype.clone.apply(this, arguments);
oClone._isValueSet = this._isValueSet;
return oClone;
};
return BulletMicroChartData;
});
}; // end of sap/suite/ui/microchart/BulletMicroChartData.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.ColumnMicroChart') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.suite.ui.microchart.Example.
jQuery.sap.declare('sap.suite.ui.microchart.ColumnMicroChart'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/ColumnMicroChart",['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* Constructor for a new ColumnMicroChart control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Compares different values which are represented as vertical bars. This control replaces the deprecated sap.suite.ui.commons.ColumnMicroChart.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.ColumnMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ColumnMicroChart = Control.extend("sap.suite.ui.microchart.ColumnMicroChart", /** @lends sap.suite.ui.microchart.ColumnMicroChart.prototype */ {
metadata: {
library: "sap.suite.ui.microchart",
properties: {
/**
* Updates the size of the chart. If not set then the default size is applied based on the device tile.
*/
size: {group: "Misc", type: "sap.m.Size", defaultValue: "Auto"},
/**
* The width of the chart. If it is not set, the width of the control is defined by the size property.
*/
width: {group: "Misc", type: "sap.ui.core.CSSSize"},
/**
* The height of the chart. If it is not set, the height of the control is defined by the size property.
*/
height: {group: "Misc", type: "sap.ui.core.CSSSize"}
},
events : {
/**
* The event is fired when the user chooses the column chart.
*/
press : {}
},
aggregations: {
/**
* The column chart data.
*/
columns: { multiple: true, type: "sap.suite.ui.microchart.ColumnMicroChartData", defaultValue : null},
/**
* The label on the left top corner of the chart.
*/
leftTopLabel: { multiple: false, type: "sap.suite.ui.microchart.ColumnMicroChartLabel", defaultValue : null},
/**
* The label on the right top corner of the chart.
*/
rightTopLabel: { multiple: false, type: "sap.suite.ui.microchart.ColumnMicroChartLabel", defaultValue : null},
/**
* The label on the left bottom corner of the chart.
*/
leftBottomLabel: { multiple: false, type: "sap.suite.ui.microchart.ColumnMicroChartLabel", defaultValue: null},
/**
* The label on the right bottom corner of the chart.
*/
rightBottomLabel: { multiple: false, type: "sap.suite.ui.microchart.ColumnMicroChartLabel", defaultValue : null}
}
}
});
ColumnMicroChart.prototype.init = function(){
this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this.setTooltip("{AltText}");
};
ColumnMicroChart.prototype.onAfterRendering = function() {
if (this._sChartResizeHandlerId) {
sap.ui.core.ResizeHandler.deregister(this._sChartResizeHandlerId);
}
this._sChartResizeHandlerId = sap.ui.core.ResizeHandler.register(jQuery.sap.domById(this.getId()), jQuery.proxy(this._calcColumns, this));
this._fChartWidth = undefined;
this._fChartHeight = undefined;
this._aBars = [];
var iColumnsNum = this.getColumns().length;
for (var i = 0; i < iColumnsNum; i++) {
this._aBars.push({});
}
this._calcColumns();
};
ColumnMicroChart.prototype.exit = function() {
sap.ui.core.ResizeHandler.deregister(this._sChartResizeHandlerId);
};
ColumnMicroChart.prototype._calcColumns = function() {
var iColumnsNum = this.getColumns().length;
if (iColumnsNum) {
var fChartWidth = parseFloat(this.$().css("width"));
if (fChartWidth != this._fChartWidth) {
this._fChartWidth = fChartWidth;
var iColumnMargin = 0;
var oBar;
if (iColumnsNum > 1) {
oBar = jQuery.sap.byId(this.getId() + "-bar-1");
var bRtl = sap.ui.getCore().getConfiguration().getRTL();
iColumnMargin = parseInt(oBar.css("margin-" + (bRtl ? "right" : "left")), 10);
} else {
oBar = jQuery.sap.byId(this.getId() + "-bar-0");
}
var iColumMinWidth = parseInt(oBar.css("min-width"), 10);
this._calcColumnsWidth(iColumnMargin, iColumMinWidth, fChartWidth, this._aBars);
}
var fChartHeight = parseFloat(this.$().css("height"));
if (fChartHeight != this._fChartHeight) {
this._fChartHeight = fChartHeight;
this._calcColumnsHeight(fChartHeight, this._aBars);
}
for (var i = 0; i < iColumnsNum; i++) {
jQuery.sap.byId(this.getId() + "-bar-" + i).css(this._aBars[i]);
}
if (this._aBars.overflow) {
jQuery.sap.log.warning(this.toString() + " Chart overflow", "Some columns were not rendered");
}
}
};
ColumnMicroChart.prototype._calcColumnsWidth = function(iColumnMargin, iColumMinWidth, fChartWidth, aBars) {
var iColumnsNum = this.getColumns().length;
var iVisibleColumnsNum = Math.floor((fChartWidth + iColumnMargin) / (iColumMinWidth + iColumnMargin));
var iColumnWidth = Math.floor((fChartWidth + iColumnMargin) / Math.min(iVisibleColumnsNum, iColumnsNum)) - iColumnMargin;
var sColumnWidth = iColumnWidth + "px";
for (var i = 0; i < iColumnsNum; i++) {
if (i < iVisibleColumnsNum) {
aBars[i].width = sColumnWidth;
aBars[i].display = "inline-block";
} else {
aBars[i].display = "none";
}
}
aBars.overflow = iVisibleColumnsNum != iColumnsNum;
};
ColumnMicroChart.prototype._calcColumnsHeight = function(fChartHeight, aBars) {
var iClmnsNum = this.getColumns().length;
var fMaxVal, fMinVal, fValue;
fMaxVal = fMinVal = 0;
for (var i = 0; i < iClmnsNum; i++) {
var oClmn = this.getColumns()[i];
if (fMaxVal < oClmn.getValue()) {
fMaxVal = oClmn.getValue();
} else if (fMinVal > oClmn.getValue()) {
fMinVal = oClmn.getValue();
}
}
var fDelta = fMaxVal - fMinVal;
var fOnePxVal = fDelta / fChartHeight;
var fDownShift, fTopShift;
fDownShift = fTopShift = 0;
for (var iCl = 0; iCl < iClmnsNum; iCl++) {
fValue = this.getColumns()[iCl].getValue();
if (Math.abs(fValue) < fOnePxVal) {
if (fValue >= 0) {
if (fValue == fMaxVal) {
fTopShift = fOnePxVal - fValue;
}
} else if (fValue == fMinVal) {
fDownShift = fOnePxVal + fValue;
}
}
}
if (fTopShift) {
fMaxVal += fTopShift;
fMinVal -= fTopShift;
}
if (fDownShift) {
fMaxVal -= fDownShift;
fMinVal += fDownShift;
}
var fNegativeOnePxVal = 0 - fOnePxVal;
for (var iClmn = 0; iClmn < iClmnsNum; iClmn++) {
fValue = this.getColumns()[iClmn].getValue();
var fCalcVal = fValue;
if (fValue >= 0) {
fCalcVal = Math.max(fCalcVal + fTopShift - fDownShift, fOnePxVal);
} else {
fCalcVal = Math.min(fCalcVal + fTopShift - fDownShift, fNegativeOnePxVal);
}
aBars[iClmn].value = fCalcVal;
}
function calcPersent(fValue) {
return (fValue / fDelta * 100).toFixed(2) + "%";
}
var fZeroLine = calcPersent(fMaxVal);
for (var iCol = 0; iCol < iClmnsNum; iCol++) {
fValue = aBars[iCol].value;
aBars[iCol].top = (fValue < 0) ? fZeroLine : calcPersent(fMaxVal - fValue);
aBars[iCol].height = calcPersent(Math.abs(fValue));
}
};
ColumnMicroChart.prototype.attachEvent = function(sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData, fnFunction, oListener);
if (this.hasListeners("press")) {
this.$().attr("tabindex", 0).addClass("sapSuiteUiMicroChartPointer");
}
return this;
};
ColumnMicroChart.prototype.detachEvent = function(sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction, oListener);
if (!this.hasListeners("press")) {
this.$().removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer");
}
return this;
};
ColumnMicroChart.prototype.getLocalizedColorMeaning = function(sColor) {
if (sColor) {
return this._oRb.getText(("SEMANTIC_COLOR_" + sColor).toUpperCase());
}
};
ColumnMicroChart.prototype.getAltText = function() {
var sAltText = "";
var bIsFirst = true;
var oLeftTopLabel = this.getLeftTopLabel();
var oRightTopLabel = this.getRightTopLabel();
var oLeftBtmLabel = this.getLeftBottomLabel();
var oRightBtmLabel = this.getRightBottomLabel();
var sColor;
if (oLeftTopLabel && oLeftTopLabel.getLabel() || oLeftBtmLabel && oLeftBtmLabel.getLabel()) {
if (oLeftTopLabel) {
sColor = oLeftTopLabel.getColor();
} else if (oLeftBtmLabel){
sColor = oLeftBtmLabel.getColor();
} else {
sColor = "";
}
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("COLUMNMICROCHART_START")) + ": " + (oLeftBtmLabel ? oLeftBtmLabel.getLabel() + " " : "")
+ (oLeftTopLabel ? oLeftTopLabel.getLabel() + " " : "") + this.getLocalizedColorMeaning(sColor);
bIsFirst = false;
}
if (oRightTopLabel && oRightTopLabel.getLabel() || oRightBtmLabel && oRightBtmLabel.getLabel()) {
if (oRightTopLabel) {
sColor = oRightTopLabel.getColor();
} else if (oRightBtmLabel){
sColor = oRightBtmLabel.getColor();
} else {
sColor = "";
}
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("COLUMNMICROCHART_END")) + ": " + (oRightBtmLabel ? oRightBtmLabel.getLabel() + " " : "")
+ (oRightTopLabel ? oRightTopLabel.getLabel() + " " : "") + this.getLocalizedColorMeaning(sColor);
bIsFirst = false;
}
var aColumns = this.getColumns();
for (var i = 0; i < aColumns.length; i++) {
var oBar = aColumns[i];
var sMeaning = this.getLocalizedColorMeaning(oBar.getColor());
sAltText += ((!bIsFirst || i != 0) ? "\n" : "") + oBar.getLabel() + " " + oBar.getValue() + " " + sMeaning;
}
return sAltText;
};
ColumnMicroChart.prototype.getTooltip_AsString = function() {
var oTooltip = this.getTooltip();
var sTooltip = this.getAltText();
if (typeof oTooltip === "string" || oTooltip instanceof String) {
sTooltip = oTooltip.split("{AltText}").join(sTooltip).split("((AltText))").join(sTooltip);
return sTooltip;
}
return oTooltip ? oTooltip : "";
};
ColumnMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.edge) {
this.onclick(oEvent);
}
};
ColumnMicroChart.prototype.onclick = function(oEvent) {
if (!this.fireBarPress(oEvent)) {
if (sap.ui.Device.browser.internet_explorer || sap.ui.Device.browser.edge) {
this.$().focus();
}
this.firePress();
}
};
ColumnMicroChart.prototype.onkeydown = function(oEvent) {
var iThis, oFocusables;
switch (oEvent.keyCode) {
case jQuery.sap.KeyCodes.SPACE:
oEvent.preventDefault();
break;
case jQuery.sap.KeyCodes.ARROW_LEFT:
case jQuery.sap.KeyCodes.ARROW_UP:
oFocusables = this.$().find(":focusable"); // all tabstops in the control
iThis = oFocusables.index(oEvent.target); // focused element index
if (oFocusables.length > 0) {
oFocusables.eq(iThis - 1).get(0).focus(); // previous tab stop element
oEvent.preventDefault();
oEvent.stopPropagation();
}
break;
case jQuery.sap.KeyCodes.ARROW_DOWN:
case jQuery.sap.KeyCodes.ARROW_RIGHT:
oFocusables = this.$().find(":focusable"); // all tabstops in the control
iThis = oFocusables.index(oEvent.target); // focused element index
if (oFocusables.length > 0) {
oFocusables.eq((iThis + 1 < oFocusables.length) ? iThis + 1 : 0).get(0).focus(); // next tab stop element
oEvent.preventDefault();
oEvent.stopPropagation();
}
break;
default:
}
};
ColumnMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.ENTER || oEvent.which == jQuery.sap.KeyCodes.SPACE) {
if (!this.fireBarPress(oEvent)) {
this.firePress();
oEvent.preventDefault();
}
}
};
ColumnMicroChart.prototype.fireBarPress = function(oEvent) {
var oBar = jQuery(oEvent.target);
if (oBar && oBar.attr("data-bar-index")) {
var iIndex = parseInt(oBar.attr("data-bar-index"), 10);
var oCmcData = this.getColumns()[iIndex];
if (oCmcData) {
oCmcData.firePress();
oEvent.preventDefault();
oEvent.stopPropagation();
if (sap.ui.Device.browser.internet_explorer) {
oBar.focus();
}
return true;
}
}
return false;
};
ColumnMicroChart.prototype._getBarAltText = function(iBarIndex) {
var oBar = this.getColumns()[iBarIndex];
var sMeaning = this.getLocalizedColorMeaning(oBar.getColor());
return oBar.getLabel() + " " + oBar.getValue() + " " + sMeaning;
};
ColumnMicroChart.prototype.setBarPressable = function(iBarIndex, bPressable) {
if (bPressable) {
var sBarAltText = this._getBarAltText(iBarIndex);
jQuery.sap.byId(this.getId() + "-bar-" + iBarIndex).addClass("sapSuiteUiMicroChartPointer").attr("tabindex", 0).attr("title", sBarAltText).attr("role", "presentation").attr("aria-label", sBarAltText);
} else {
jQuery.sap.byId(this.getId() + "-bar-" + iBarIndex).removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer").removeAttr("title").removeAttr("role").removeAttr("aria-label");
}
};
ColumnMicroChart.prototype.onsaptabnext = function(oEvent) {
var oLast = this.$().find(":focusable").last(); // last tabstop in the control
if (oLast) {
this._bIgnoreFocusEvt = true;
oLast.get(0).focus();
}
};
ColumnMicroChart.prototype.onsaptabprevious = function(oEvent) {
if (oEvent.target.id != oEvent.currentTarget.id) {
var oFirst = this.$().find(":focusable").first(); // first tabstop in the control
if (oFirst) {
oFirst.get(0).focus();
}
}
};
ColumnMicroChart.prototype.onfocusin = function(oEvent) {
if (this._bIgnoreFocusEvt) {
this._bIgnoreFocusEvt = false;
return;
}
if (this.getId() + "-hidden" == oEvent.target.id) {
this.$().focus();
oEvent.preventDefault();
oEvent.stopPropagation();
}
};
return ColumnMicroChart;
});
}; // end of sap/suite/ui/microchart/ColumnMicroChart.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.ColumnMicroChartData') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// This control displays the history of values as a line mini chart or an area mini chart.
jQuery.sap.declare('sap.suite.ui.microchart.ColumnMicroChartData'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/ColumnMicroChartData",['jquery.sap.global', './library', 'sap/ui/core/Element'],
function(jQuery, library, Element) {
"use strict";
/**
* Constructor for a new ColumnMicroChartData control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Defines the column chart data.
* @extends sap.ui.core.Control
*
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.ColumnMicroChartData
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ColumnMicroChartData = Element.extend("sap.suite.ui.microchart.ColumnMicroChartData", /** @lends sap.suite.ui.microchart.ColumnMicroChartData.prototype */ {
metadata : {
library : "sap.suite.ui.microchart",
properties : {
/**
* The graphic element color.
*/
color: { group: "Misc", type: "sap.m.ValueColor", defaultValue: "Neutral" },
/**
* The line title.
*/
label: {type : "string", group : "Misc", defaultValue : "" },
/**
* The actual value.
*/
value: {type: "float", group : "Misc"}
},
events: {
/**
* The event is fired when the user chooses the column data.
*/
press: {}
}
}
});
ColumnMicroChartData.prototype.attachEvent = function(sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData, fnFunction, oListener);
if (this.getParent()) {
this.getParent().setBarPressable(this.getParent().getColumns().indexOf(this), true);
}
return this;
};
ColumnMicroChartData.prototype.detachEvent = function(sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction, oListener);
if (this.getParent()) {
this.getParent().setBarPressable(this.getParent().getColumns().indexOf(this), false);
}
return this;
};
return ColumnMicroChartData;
});
}; // end of sap/suite/ui/microchart/ColumnMicroChartData.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.ColumnMicroChartLabel') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// This control displays the history of values as a line mini chart or an area mini chart.
jQuery.sap.declare('sap.suite.ui.microchart.ColumnMicroChartLabel'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/ColumnMicroChartLabel",['jquery.sap.global', './library', 'sap/ui/core/Element'],
function(jQuery, library, Element) {
"use strict";
/**
* Constructor for a new ColumnMicroChartLabel control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Displays or hides the labels of a column micro chart.
* @extends sap.ui.core.Control
*
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.ColumnMicroChartLabel
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ColumnMicroChartLabel = Element.extend("sap.suite.ui.microchart.ColumnMicroChartLabel", /** @lends sap.suite.ui.microchart.ColumnMicroChartLabel.prototype */ {
metadata : {
library : "sap.suite.ui.microchart",
properties : {
/**
* The graphic element color.
*/
color: { group: "Misc", type: "sap.m.ValueColor", defaultValue: "Neutral" },
/**
* The line title.
*/
label: { type : "string", group : "Misc", defaultValue : "" }
}
}
});
return ColumnMicroChartLabel;
});
}; // end of sap/suite/ui/microchart/ColumnMicroChartLabel.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.ComparisonMicroChart') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.suite.ui.microchart.ComparisonMicroChart.
jQuery.sap.declare('sap.suite.ui.microchart.ComparisonMicroChart'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/ComparisonMicroChart",['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* Constructor for a new ComparisonMicroChart control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Illustrates values as colored bar charts with title, numeric value, and scaling factor in the content area. This control replaces the deprecated sap.suite.ui.commons.ComparisonChart.
* @extends sap.ui.core.Control
*
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.ComparisonMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ComparisonMicroChart = Control.extend("sap.suite.ui.microchart.ComparisonMicroChart", /** @lends sap.suite.ui.microchart.ComparisonMicroChart.prototype */ { metadata : {
library: "sap.suite.ui.microchart",
properties: {
/**
* The size of the microchart. If not set, the default size is applied based on the size of the device tile.
*/
size: {type: "sap.m.Size", group: "Misc", defaultValue: "Auto"},
/**
* The scaling suffix that is added to the actual and target values.
*/
scale: {type: "string", group: "Misc", defaultValue: ""},
/**
* The width of the chart. If it is not set, the size of the control is defined by the size property.
*/
width: {type: "sap.ui.core.CSSSize", group: "Misc"},
/**
* The view of the chart. If not set, the Normal view is used by default.
*/
view: {type: "sap.suite.ui.microchart.ComparisonMicroChartViewType", group: "Appearance", defaultValue: "Normal"},
/**
* The color palette for the chart. If this property is set, semantic colors defined in ComparisonData are ignored. Colors from the palette are assigned to each bar consequentially. When all the palette colors are used, assignment of the colors begins from the first palette color.
*/
colorPalette: {type: "string[]", group: "Appearance", defaultValue: []},
/**
* If it is set to true, the height of the control is defined by its content.
*/
shrinkable: {type: "boolean", group: "Misc", defaultValue: "false"},
/**
* Height of the chart.
*/
height: {type: "sap.ui.core.CSSSize", group: "Appearance"}
},
aggregations: {
/**
* The comparison chart bar data.
*/
data: {type: "sap.suite.ui.microchart.ComparisonMicroChartData", multiple: true}
},
events: {
/**
* The event is fired when the user chooses the comparison microchart.
*/
press : {}
}
}});
ComparisonMicroChart.prototype.init = function(){
this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this.setTooltip("{AltText}");
};
/**
* Calculates the width in percents of chart bars' elements accordingly with provided chart values.
*
* @returns {Array} array of calculated values for each chart bar.
* @private
*/
ComparisonMicroChart.prototype._calculateChartData = function() {
var aResult = [];
var aData = this.getData();
var iCount = aData.length;
var iMaxValue = 0;
var iMinValue = 0;
var iTotal;
var iMaxPercent;
var iMinPercent;
var i;
for (i = 0; i < iCount; i++) {
var iDataValue = isNaN(aData[i].getValue()) ? 0 : aData[i].getValue();
iMaxValue = Math.max(iMaxValue, iDataValue);
iMinValue = Math.min(iMinValue, iDataValue);
}
iTotal = iMaxValue - iMinValue;
iMaxPercent = (iTotal == 0) ? 0 : Math.round(iMaxValue * 100 / iTotal);
if (iMaxPercent == 0 && iMaxValue != 0) {
iMaxPercent = 1;
} else if (iMaxPercent == 100 && iMinValue != 0) {
iMaxPercent = 99;
}
iMinPercent = 100 - iMaxPercent;
for (i = 0; i < iCount; i++) {
var oItem = {};
var iDataVal = isNaN(aData[i].getValue()) ? 0 : aData[i].getValue();
oItem.value = (iTotal == 0) ? 0 : Math.round(iDataVal * 100 / iTotal);
if (oItem.value == 0 && iDataVal != 0) {
oItem.value = (iDataVal > 0) ? 1 : -1;
} else if (oItem.value == 100) {
oItem.value = iMaxPercent;
} else if (oItem.value == -100) {
oItem.value = -iMinPercent;
}
if (oItem.value >= 0) {
oItem.negativeNoValue = iMinPercent;
oItem.positiveNoValue = iMaxPercent - oItem.value;
} else {
oItem.value = -oItem.value;
oItem.negativeNoValue = iMinPercent - oItem.value;
oItem.positiveNoValue = iMaxPercent;
}
aResult.push(oItem);
}
return aResult;
};
ComparisonMicroChart.prototype.attachEvent = function(sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData, fnFunction, oListener);
if (this.hasListeners("press")) {
this.$().attr("tabindex", 0).addClass("sapSuiteUiMicroChartPointer");
}
return this;
};
ComparisonMicroChart.prototype.detachEvent = function(sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction, oListener);
if (!this.hasListeners("press")) {
this.$().removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer");
}
return this;
};
ComparisonMicroChart.prototype._getLocalizedColorMeaning = function(sColor) {
return this._oRb.getText(("SEMANTIC_COLOR_" + sColor).toUpperCase());
};
ComparisonMicroChart.prototype.getAltText = function() {
var sScale = this.getScale();
var sAltText = "";
for (var i = 0; i < this.getData().length; i++) {
var oBar = this.getData()[i];
var sMeaning = (this.getColorPalette().length) ? "" : this._getLocalizedColorMeaning(oBar.getColor());
sAltText += ((i == 0) ? "" : "\n") + oBar.getTitle() + " " + (oBar.getDisplayValue() ? oBar.getDisplayValue() : oBar.getValue()) + sScale + " " + sMeaning;
}
return sAltText;
};
ComparisonMicroChart.prototype.getTooltip_AsString = function() {
var oTooltip = this.getTooltip();
var sTooltip = this.getAltText();
if (typeof oTooltip === "string" || oTooltip instanceof String) {
sTooltip = oTooltip.split("{AltText}").join(sTooltip).split("((AltText))").join(sTooltip);
return sTooltip;
}
return oTooltip ? oTooltip : "";
};
ComparisonMicroChart.prototype._adjustBars = function() {
var iHeight = parseFloat(this.$().css("height"));
var iBarCount = this.getData().length;
var aBarContainers = this.$().find(".sapSuiteCmpChartItem");
var iMinH = parseFloat(aBarContainers.css("min-height"));
var iMaxH = parseFloat(aBarContainers.css("max-height"));
var iBarContHeight;
if (iBarCount != 0) {
iBarContHeight = iHeight / iBarCount;
if (iBarContHeight > iMaxH) {
iBarContHeight = iMaxH;
} else if (iBarContHeight < iMinH) {
iBarContHeight = iMinH;
}
aBarContainers.css("height", iBarContHeight);
if (this.getView() === "Wide" ) {
this.$().find(".sapSuiteCmpChartBar>div").css("height", (iBarContHeight * 79 / 42) + "%");
} else if (this.getView() === "Normal") {
this.$().find(".sapSuiteCmpChartBar>div").css("height", (iBarContHeight - 19) + "%");
}
var iChartsHeightDelta = (iHeight - iBarContHeight * iBarCount) / 2;
if (iChartsHeightDelta > 0) {
jQuery(aBarContainers[0]).css("margin-top", iChartsHeightDelta + 7 + "px");
}
}
};
ComparisonMicroChart.prototype.onAfterRendering = function() {
if (this.getHeight() != "") {
var that = this;
sap.ui.Device.media.attachHandler(function(){
that._adjustBars();
});
this._adjustBars();
}
};
ComparisonMicroChart.prototype._getBarAltText = function(iBarIndex) {
var sScale = this.getScale();
var oBar = this.getData()[iBarIndex];
var sMeaning = (this.getColorPalette().length) ? "" : this._getLocalizedColorMeaning(oBar.getColor());
return oBar.getTitle() + " " + (oBar.getDisplayValue() ? oBar.getDisplayValue() : oBar.getValue()) + sScale + " " + sMeaning;
};
ComparisonMicroChart.prototype.onsaptabnext = function(oEvent) {
var oLast = this.$().find(":focusable").last(); // last tabstop in the control
if (oLast) {
this._bIgnoreFocusEvt = true;
oLast.get(0).focus();
}
};
ComparisonMicroChart.prototype.onsaptabprevious = function(oEvent) {
if (oEvent.target.id != oEvent.currentTarget.id) {
var oFirst = this.$().find(":focusable").first(); // first tabstop in the control
if (oFirst) {
oFirst.get(0).focus();
}
}
};
ComparisonMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.edge) {
this.onclick(oEvent);
}
};
ComparisonMicroChart.prototype.onclick = function(oEvent) {
if (!this.fireBarPress(oEvent)) {
if (sap.ui.Device.browser.internet_explorer || sap.ui.Device.browser.edge) {
this.$().focus();
}
this.firePress();
}
};
ComparisonMicroChart.prototype.onkeydown = function(oEvent) {
switch (oEvent.keyCode) {
case jQuery.sap.KeyCodes.SPACE:
oEvent.preventDefault();
break;
case jQuery.sap.KeyCodes.ARROW_LEFT:
case jQuery.sap.KeyCodes.ARROW_UP:
var oFocusables = this.$().find(":focusable"); // all tabstops in the control
var iThis = oFocusables.index(oEvent.target); // focused element index
if (oFocusables.length > 0) {
oFocusables.eq(iThis - 1).get(0).focus(); // previous tab stop element
oEvent.preventDefault();
oEvent.stopPropagation();
}
break;
case jQuery.sap.KeyCodes.ARROW_DOWN:
case jQuery.sap.KeyCodes.ARROW_RIGHT:
var oFocusable = this.$().find(":focusable"); // all tabstops in the control
var iThisEl = oFocusable.index(oEvent.target); // focused element index
if (oFocusable.length > 0) {
oFocusable.eq((iThisEl + 1 < oFocusable.length) ? iThisEl + 1 : 0).get(0).focus(); // next tab stop element
oEvent.preventDefault();
oEvent.stopPropagation();
}
break;
default:
}
};
ComparisonMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.ENTER || oEvent.which == jQuery.sap.KeyCodes.SPACE) {
if (!this.fireBarPress(oEvent)) {
this.firePress();
oEvent.preventDefault();
}
}
};
ComparisonMicroChart.prototype.fireBarPress = function(oEvent) {
var oBar = jQuery(oEvent.target);
if (oBar && oBar.attr("data-bar-index")) {
var iIndex = parseInt(oBar.attr("data-bar-index"), 10);
var oComparisonData = this.getData()[iIndex];
if (oComparisonData) {
oComparisonData.firePress();
oEvent.preventDefault();
oEvent.stopPropagation();
if (sap.ui.Device.browser.internet_explorer) {
jQuery.sap.byId(this.getId() + "-chart-item-bar-" + iIndex).focus();
}
return true;
}
}
return false;
};
ComparisonMicroChart.prototype.setBarPressable = function(iBarIndex, bPressable) {
if (bPressable) {
var sBarAltText = this._getBarAltText(iBarIndex);
jQuery.sap.byId(this.getId() + "-chart-item-bar-" + iBarIndex).addClass("sapSuiteUiMicroChartPointer").attr("tabindex", 0).attr("title", sBarAltText).attr("role", "presentation").attr("aria-label", sBarAltText);
} else {
jQuery.sap.byId(this.getId() + "-chart-item-bar-" + iBarIndex).removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer").removeAttr("title").removeAttr("role").removeAttr("aria-label");
}
};
ComparisonMicroChart.prototype.onfocusin = function(oEvent) {
if (this._bIgnoreFocusEvt) {
this._bIgnoreFocusEvt = false;
return;
}
if (this.getId() + "-hidden" == oEvent.target.id) {
this.$().focus();
oEvent.preventDefault();
oEvent.stopPropagation();
}
};
return ComparisonMicroChart;
});
}; // end of sap/suite/ui/microchart/ComparisonMicroChart.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.ComparisonMicroChartData') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.suite.ui.microchart.ComparisonMicroChartData.
jQuery.sap.declare('sap.suite.ui.microchart.ComparisonMicroChartData'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/ComparisonMicroChartData",['jquery.sap.global', './library', 'sap/ui/core/Element'],
function(jQuery, library, Element) {
"use strict";
/**
* Constructor for a new ComparisonMicroChartData.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Contains the values of the comparison chart.
* @extends sap.ui.core.Element
*
* @version 1.36.12
*
* @constructor
* @public
* @alias sap.suite.ui.microchart.ComparisonMicroChartData
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ComparisonMicroChartData = Element.extend("sap.suite.ui.microchart.ComparisonMicroChartData", /** @lends sap.suite.ui.microchart.ComparisonMicroChartData.prototype */ {
metadata : {
library: "sap.suite.ui.microchart",
properties: {
/**
* The value for comparison.
*/
value: {type: "float", group: "Misc", defaultValue: "0"},
/**
* The semantic color of the value.
*/
color: {type: "sap.m.ValueColor", group: "Misc", defaultValue: "Neutral"},
/**
* The comparison bar title.
*/
title: {type: "string", group: "Misc", defaultValue: ""},
/**
* If this property is set then it will be displayed instead of value.
*/
displayValue: {type: "string", group: "Misc", defaultValue: ""}
},
events: {
/**
* The event is fired when the user chooses the comparison chart bar.
*/
press : {}
}
}
});
ComparisonMicroChartData.prototype.setValue = function(fValue, bSuppressInvalidate) {
this._isValueSet = this._fnIsNumber(fValue);
return this.setProperty("value", this._isValueSet ? fValue : NaN, bSuppressInvalidate);
};
ComparisonMicroChartData.prototype._fnIsNumber = function(n) {
return typeof n == 'number' && !isNaN(n) && isFinite(n);
};
ComparisonMicroChartData.prototype.clone = function(sIdSuffix, aLocalIds, oOptions) {
var oClone = sap.ui.core.Control.prototype.clone.apply(this, arguments);
oClone._isValueSet = this._isValueSet;
return oClone;
};
ComparisonMicroChartData.prototype.attachEvent = function(sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData, fnFunction, oListener);
if (this.getParent()) {
this.getParent().setBarPressable(this.getParent().getData().indexOf(this), true);
}
return this;
};
ComparisonMicroChartData.prototype.detachEvent = function(sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction, oListener);
if (this.getParent()) {
this.getParent().setBarPressable(this.getParent().getData().indexOf(this), false);
}
return this;
};
return ComparisonMicroChartData;
});
}; // end of sap/suite/ui/microchart/ComparisonMicroChartData.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.DeltaMicroChart') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.suite.ui.microchart.Example.
jQuery.sap.declare('sap.suite.ui.microchart.DeltaMicroChart'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/DeltaMicroChart",['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* Constructor for a new DeltaMicroChart control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Represents the delta of two values as a chart. This control replaces the deprecated sap.suite.ui.commons.DeltaMicroChart.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.DeltaMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var DeltaMicroChart = Control.extend("sap.suite.ui.microchart.DeltaMicroChart", /** @lends sap.suite.ui.microchart.DeltaMicroChart.prototype */ { metadata: {
library: "sap.suite.ui.microchart",
properties: {
/**
* The first value for delta calculation.
*/
value1: {type: "float", group: "Misc", defaultValue: null},
/**
* The second value for delta calculation.
*/
value2: {type: "float", group: "Misc", defaultValue: null},
/**
* The first value title.
*/
title1: {type: "string", group: "Misc", defaultValue: null},
/**
* The second value title.
*/
title2: {type: "string", group: "Misc", defaultValue: null},
/**
* If this property is set, it is rendered instead of value1.
*/
displayValue1: {type: "string", group: "Misc", defaultValue: null},
/**
* If this property is set, it is rendered instead of value2.
*/
displayValue2: {type: "string", group: "Misc", defaultValue: null},
/**
* If this property is set, it is rendered instead of a calculated delta.
*/
deltaDisplayValue: {type: "string", group: "Misc", defaultValue: null},
/**
* The semantic color of the delta value.
*/
color: {type: "sap.m.ValueColor", group: "Misc", defaultValue: "Neutral"},
/**
* The width of the chart.
*/
width: {type: "sap.ui.core.CSSSize", group: "Misc"},
/**
* The size of the chart. If is not set, the default size is applied based on the device type.
*/
size: {type: "sap.m.Size", group: "Misc", defaultValue: "Auto"}
},
events: {
/**
* The event is fired when the user chooses the delta micro chart.
*/
press: {}
}
}});
DeltaMicroChart.prototype.init = function() {
this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this.setTooltip("{AltText}");
};
DeltaMicroChart.prototype._calcChartData = function() {
var fVal1 = this.getValue1();
var fVal2 = this.getValue2();
var fMin = Math.min(fVal1, fVal2, 0);
var fMax = Math.max(fVal1, fVal2, 0);
var fTotal = fMax - fMin;
function calcPercent(fVal) {
return (fTotal === 0 ? 0 : Math.abs(fVal) / fTotal * 100).toFixed(2);
}
var oConf = {};
var fDelta = fVal1 - fVal2;
oConf.delta = {
left: fMax === 0,
width: calcPercent(fDelta),
isFirstStripeUp: fVal1 < fVal2,
isMax: (fVal1 < 0 && fVal2 >= 0) || (fVal1 >= 0 && fVal2 < 0),
isZero: fVal1 === 0 && fVal2 === 0,
isEqual: fDelta === 0
};
oConf.bar1 = {
left: fVal2 >= 0,
width: calcPercent(fVal1),
isSmaller: Math.abs(fVal1) < Math.abs(fVal2)
};
oConf.bar2 = {
left: fVal1 >= 0,
width: calcPercent(fVal2),
isSmaller: Math.abs(fVal2) < Math.abs(fVal1)
};
return oConf;
};
DeltaMicroChart.prototype._getLocalizedColorMeaning = function(sColor) {
return this._oRb.getText(("SEMANTIC_COLOR_" + sColor).toUpperCase());
};
/**
* Calculates the number of digits after the decimal point.
*
* @param {float} fValue float value
* @returns {int} number of digits after the decimal point in fValue.
* @private
*/
DeltaMicroChart.prototype._digitsAfterDecimalPoint = function(fValue) {
var sAfter = ("" + fValue).match(/[.,](\d+)/g);
return (sAfter) ? ("" + sAfter).length - 1 : 0;
};
DeltaMicroChart.prototype.getAltText = function() {
var sDv1 = this.getDisplayValue1();
var sDv2 = this.getDisplayValue2();
var sDdv = this.getDeltaDisplayValue();
var fVal1 = this.getValue1();
var fVal2 = this.getValue2();
var sAdv1ToShow = sDv1 ? sDv1 : "" + fVal1;
var sAdv2ToShow = sDv2 ? sDv2 : "" + fVal2;
var sAddvToShow = sDdv ? sDdv : "" + Math.abs(fVal1 - fVal2).toFixed(Math.max(this._digitsAfterDecimalPoint(fVal1), this._digitsAfterDecimalPoint(fVal2)));
var sMeaning = this._getLocalizedColorMeaning(this.getColor());
return this.getTitle1() + " " + sAdv1ToShow + "\n" + this.getTitle2() + " " + sAdv2ToShow + "\n" + this._oRb.getText("DELTAMICROCHART_DELTA_TOOLTIP", [sAddvToShow, sMeaning]);
};
DeltaMicroChart.prototype.getTooltip_AsString = function() {
var oTooltip = this.getTooltip();
var sTooltip = this.getAltText();
if (typeof oTooltip === "string" || oTooltip instanceof String) {
sTooltip = oTooltip.split("{AltText}").join(sTooltip).split("((AltText))").join(sTooltip);
return sTooltip;
}
return oTooltip ? oTooltip : "";
};
DeltaMicroChart.prototype._isCalcSupported = function() {
return jQuery.sap.byId(this.getId() + "-calc").css("max-width") == "11px";
};
DeltaMicroChart.prototype._isRoundingSupported = function() {
return jQuery.sap.byId(this.getId() + "-calc1").width() == 4;
};
DeltaMicroChart.prototype.onBeforeRendering = function() {
this._oChartData = this._calcChartData();
};
DeltaMicroChart.prototype.onAfterRendering = function() {
this._bCalc = this._isCalcSupported();
this._bRounding = this._isRoundingSupported();
if (!this._bCalc || !this._bRounding) {
if (this._sResizeHandlerId) {
sap.ui.core.ResizeHandler.deregister(this._sResizeHandlerId);
}
var oChart = jQuery.sap.domById(this.getId() + "-dmc-chart");
this._sResizeHandlerId = sap.ui.core.ResizeHandler.register(oChart, jQuery.proxy(this._adjust, this));
if (!this._bCalc) {
this._adjustCalc();
}
if (!this._bRounding) {
this._adjustRound();
}
}
};
DeltaMicroChart.prototype._adjust = function() {
if (!this._bCalc) {
this._adjustCalc();
}
if (!this._bRounding) {
this._adjustRound();
}
};
DeltaMicroChart.prototype._adjustRound = function() {
var iChartWidth = jQuery.sap.byId(this.getId() + "-dmc-chart").width();
var iDeltaWidth = Math.round(iChartWidth * this._oChartData.delta.width / 100);
jQuery.sap.byId(this.getId() + "-dmc-bar-delta").width(iDeltaWidth);
if (this._oChartData.bar1.isSmaller && !this._oChartData.delta.isMax) {
jQuery.sap.byId(this.getId() + "-dmc-bar1").width(iChartWidth - iDeltaWidth);
}
if (this._oChartData.bar2.isSmaller && !this._oChartData.delta.isMax) {
jQuery.sap.byId(this.getId() + "-dmc-bar2").width(iChartWidth - iDeltaWidth);
}
};
DeltaMicroChart.prototype._adjustCalc = function() {
var iChartWidth = jQuery.sap.byId(this.getId() + "-dmc-chart").width();
function adjustBar(oBar) {
oBar.css("max-width", iChartWidth - parseInt(oBar.css("max-width"), 10) + "px");
}
adjustBar(jQuery.sap.byId(this.getId() + "-dmc-bar1"));
adjustBar(jQuery.sap.byId(this.getId() + "-dmc-bar2"));
adjustBar(jQuery.sap.byId(this.getId() + "-dmc-bar-delta"));
};
DeltaMicroChart.prototype.attachEvent = function(sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData, fnFunction, oListener);
if (this.hasListeners("press")) {
this.$().attr("tabindex", 0).addClass("sapSuiteUiMicroChartPointer");
}
return this;
};
DeltaMicroChart.prototype.detachEvent = function(sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction, oListener);
if (!this.hasListeners("press")) {
this.$().removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer");
}
return this;
};
DeltaMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.internet_explorer) {
this.$().focus();
}
this.firePress();
};
DeltaMicroChart.prototype.onkeydown = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.SPACE) {
oEvent.preventDefault();
}
};
DeltaMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.ENTER || oEvent.which == jQuery.sap.KeyCodes.SPACE) {
this.firePress();
oEvent.preventDefault();
}
};
return DeltaMicroChart;
});
}; // end of sap/suite/ui/microchart/DeltaMicroChart.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.HarveyBallMicroChart') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// This file defines behavior for the control.
jQuery.sap.declare('sap.suite.ui.microchart.HarveyBallMicroChart'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/HarveyBallMicroChart",['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* The configuration of the graphic element on the chart.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Displays parts of a whole as highlighted sectors in a pie chart.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.HarveyBallMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var HarveyBallMicroChart = Control.extend("sap.suite.ui.microchart.HarveyBallMicroChart", /** @lends sap.suite.ui.microchart.HarveyBallMicroChart.prototype */ {
metadata : {
library: "sap.suite.ui.microchart",
properties: {
/**
* The total value. This is taken as 360 degrees value on the chart.
*/
total: {group:"Misc", type:"float", defaultValue: null},
/**
* The total label. If specified, it is displayed instead of the total value.
*/
totalLabel: {group:"Misc", type:"string"},
/**
The scaling factor that is displayed next to the total value.
*/
totalScale: {group:"Misc", type:"string"},
/**
If set to true, the totalLabel parameter is considered as the combination of the total value and its scaling factor. The default value is false. It means that the total value and the scaling factor are defined separately by the total and the totalScale properties accordingly.
*/
formattedLabel: {group:"Misc", type:"boolean", defaultValue:false},
/**
If it is set to true, the total value is displayed next to the chart. The default setting is true.
*/
showTotal: {group:"Misc", type:"boolean", defaultValue:true},
/**
If it is set to true, the fraction values are displayed next to the chart. The default setting is true.
*/
showFractions: {group:"Misc", type:"boolean", defaultValue:true},
/**
The size of the chart. If it is not set, the default size is applied based on the device type.
*/
size: {group:"Misc", type:"sap.m.Size", defaultValue:"Auto"},
/**
The color palette for the chart. If this property is set, semantic colors defined in HarveyBallMicroChart are ignored. Colors from the palette are assigned to each slice consequentially. When all the palette colors are used, assignment of the colors begins from the first palette color.
*/
colorPalette: {type: "string[]", group : "Appearance", defaultValue : [] },
/**
The width of the chart. If it is not set, the size of the control is defined by the size property.
*/
width: {group:"Misc", type:"sap.ui.core.CSSSize"}
},
events: {
/**
* The event is fired when the user chooses the control.
*/
press: {}
},
aggregations: {
/**
* The set of points for this graphic element.
*/
"items": { multiple: true, type: "sap.suite.ui.microchart.HarveyBallMicroChartItem" }
}
}
});
///**
// * This file defines behavior for the control,
// */
HarveyBallMicroChart.prototype.getAltText = function() {
var sAltText = "";
var bIsFirst = true;
var aItems = this.getItems();
for (var i = 0; i < aItems.length; i++) {
var oItem = aItems[i];
var sColor = (this.getColorPalette().length === 0) ? this._rb.getText(("SEMANTIC_COLOR_" + oItem.getColor()).toUpperCase()) : "";
var sLabel = oItem.getFractionLabel();
var sScale = oItem.getFractionScale();
if (!sLabel && sScale) {
sLabel = oItem.getFormattedLabel() ? oItem.getFraction() : oItem.getFraction() + oItem.getFractionScale().substring(0,3);
} else if (!oItem.getFormattedLabel() && oItem.getFractionLabel()) {
sLabel += oItem.getFractionScale().substring(0,3);
}
sAltText += (bIsFirst ? "" : "\n") + sLabel + " " + sColor;
bIsFirst = false;
}
if (this.getTotal()) {
var sTLabel = this.getTotalLabel();
if (!sTLabel) {
sTLabel = this.getFormattedLabel() ? this.getTotal() : this.getTotal() + this.getTotalScale().substring(0,3);
} else if (!this.getFormattedLabel()) {
sTLabel += this.getTotalScale().substring(0,3);
}
sAltText += (bIsFirst ? "" : "\n") + this._rb.getText("HARVEYBALLMICROCHART_TOTAL_TOOLTIP") + " " + sTLabel;
}
return sAltText;
};
HarveyBallMicroChart.prototype.getTooltip_AsString = function() {
var oTooltip = this.getTooltip();
var sTooltip = this.getAltText();
if (typeof oTooltip === "string" || oTooltip instanceof String) {
sTooltip = oTooltip.split("{AltText}").join(sTooltip).split("((AltText))").join(sTooltip);
return sTooltip;
}
return oTooltip ? oTooltip : "";
};
HarveyBallMicroChart.prototype.init = function() {
this._rb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this.setTooltip("{AltText}");
sap.ui.Device.media.attachHandler(this.rerender, this, sap.ui.Device.media.RANGESETS.SAP_STANDARD);
};
HarveyBallMicroChart.prototype._calculatePath = function() {
var oSize = this.getSize();
var fTot = this.getTotal();
var fFrac = 0;
if (this.getItems().length) {
fFrac = this.getItems()[0].getFraction();
}
var bIsPhone = false;
if (oSize == "Auto") {
bIsPhone = jQuery("html").hasClass("sapUiMedia-Std-Phone");
}
if (oSize == "S" || oSize == "XS") {
bIsPhone = true;
}
var iMeadiaSize = bIsPhone ? 56 : 72;
var iCenter = iMeadiaSize / 2;
// var iBorder = bIsPhone? 3 : 4;
var iBorder = 4;
this._oPath = {
initial : {
x : iCenter,
y : iCenter,
x1 : iCenter,
y1 : iCenter
},
lineTo : {
x : iCenter,
y : iBorder
},
arc : {
x1 : iCenter - iBorder,
y1 : iCenter - iBorder,
xArc : 0,
largeArc : 0,
sweep : 1,
x2 : "",
y2 : ""
},
size : iMeadiaSize,
border : iBorder,
center : iCenter
};
var fAngle = fFrac / fTot * 360;
if (fAngle < 10) {
this._oPath.initial.x -= 1.5;
this._oPath.initial.x1 += 1.5;
this._oPath.arc.x2 = this._oPath.initial.x1;
this._oPath.arc.y2 = this._oPath.lineTo.y;
} else if (fAngle > 350 && fAngle < 360) {
this._oPath.initial.x += 1.5;
this._oPath.initial.x1 -= 1.5;
this._oPath.arc.x2 = this._oPath.initial.x1;
this._oPath.arc.y2 = this._oPath.lineTo.y;
} else {
var fRad = Math.PI / 180.0;
var fRadius = this._oPath.center - this._oPath.border;
var ix = fRadius * Math.cos((fAngle - 90) * fRad) + this._oPath.center;
var iy = this._oPath.size - (fRadius * Math.sin((fAngle + 90) * fRad) + this._oPath.center);
this._oPath.arc.x2 = ix.toFixed(2);
this._oPath.arc.y2 = iy.toFixed(2);
}
var iLargeArc = fTot / fFrac < 2 ? 1 : 0;
this._oPath.arc.largeArc = iLargeArc;
};
HarveyBallMicroChart.prototype.onBeforeRendering = function() {
this._calculatePath();
};
HarveyBallMicroChart.prototype.serializePieChart = function() {
var p = this._oPath;
return ["M", p.initial.x, ",", p.initial.y, " L", p.initial.x, ",", p.lineTo.y, " A", p.arc.x1, ",", p.arc.y1,
" ", p.arc.xArc, " ", p.arc.largeArc, ",", p.arc.sweep, " ", p.arc.x2, ",", p.arc.y2, " L", p.initial.x1,
",", p.initial.y1, " z"].join("");
};
HarveyBallMicroChart.prototype._parseFormattedValue = function(
sValue) {
return {
scale: sValue.replace(/.*?([^+-.,\d]*)$/g, "$1").trim(),
value: sValue.replace(/(.*?)[^+-.,\d]*$/g, "$1").trim()
};
};
HarveyBallMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.internet_explorer) {
this.$().focus();
}
this.firePress();
};
HarveyBallMicroChart.prototype.onkeydown = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.SPACE) {
oEvent.preventDefault();
}
};
HarveyBallMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.ENTER
|| oEvent.which == jQuery.sap.KeyCodes.SPACE) {
this.firePress();
oEvent.preventDefault();
}
};
HarveyBallMicroChart.prototype.attachEvent = function(
sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData,
fnFunction, oListener);
if (this.hasListeners("press")) {
this.$().attr("tabindex", 0).addClass("sapSuiteUiMicroChartPointer");
}
return this;
};
HarveyBallMicroChart.prototype.detachEvent = function(
sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction,
oListener);
if (!this.hasListeners("press")) {
this.$().removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer");
}
return this;
};
HarveyBallMicroChart.prototype.exit = function(oEvent) {
sap.ui.Device.media.detachHandler(this.rerender, this, sap.ui.Device.media.RANGESETS.SAP_STANDARD);
};
return HarveyBallMicroChart;
});
}; // end of sap/suite/ui/microchart/HarveyBallMicroChart.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.HarveyBallMicroChartItem') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// This control displays the history of values as a line mini chart or an area mini chart.
jQuery.sap.declare('sap.suite.ui.microchart.HarveyBallMicroChartItem'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Element'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/HarveyBallMicroChartItem",['jquery.sap.global', './library', 'sap/ui/core/Element'],
function(jQuery, library, Element) {
"use strict";
/**
* The configuration of the graphic element on the chart.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Configures the slices of the pie chart.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.HarveyBallMicroChartItem
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var HarveyBallMicroChartItem = Element.extend("sap.suite.ui.microchart.HarveyBallMicroChartItem", /** @lends sap.suite.ui.microchart.HarveyBallMicroChartItem.prototype */ {
metadata : {
library: "sap.suite.ui.microchart",
properties: {
/**
*The slice color.
*/
color: {group:"Misc", type:"sap.m.ValueColor", defaultValue:"Neutral"},
/**
*The fraction value.
*/
fraction: {group:"Misc", type:"float", defaultValue:"0"},
/**
*The fraction label. If specified, it is displayed instead of the fraction value.
*/
fractionLabel: {group:"Misc", type:"string"},
/**
*The scaling factor that is displayed after the fraction value.
*/
fractionScale: {group:"Misc", type:"string"},
/**
*If set to true, the fractionLabel parameter is considered as the combination of the fraction value and scaling factor. The default value is false. It means that the fraction value and the scaling factor are defined separately by the fraction and the fractionScale properties accordingly.
*/
formattedLabel: {group:"Misc", type:"boolean", defaultValue:"false"}
}
}
});
return HarveyBallMicroChartItem;
});
}; // end of sap/suite/ui/microchart/HarveyBallMicroChartItem.js
if ( !jQuery.sap.isDeclared('sap.suite.ui.microchart.RadialMicroChart') ) {
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// This file defines the behavior for the control.
jQuery.sap.declare('sap.suite.ui.microchart.RadialMicroChart'); // unresolved dependency added by SAPUI5 'AllInOne' Builder
jQuery.sap.require('jquery.sap.global'); // unlisted dependency retained
jQuery.sap.require('sap.ui.core.Control'); // unlisted dependency retained
sap.ui.define("sap/suite/ui/microchart/RadialMicroChart",['jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/suite/ui/microchart/RadialMicroChartRenderer'],
function(jQuery, library, Control, Renderer) {
"use strict";
/**
* Describes the configuration of the graphic element on the chart.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Displays a ring chart highlighting a current status. The status is displayed with a semantically colored radial bar and a percentage value.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
* @since 1.36.0
*
* @constructor
* @public
* @alias sap.suite.ui.microchart.RadialMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var RadialMicroChart = Control.extend("sap.suite.ui.microchart.RadialMicroChart", /** @lends sap.suite.ui.microchart.RadialMicroChart.prototype */ {
constructor : function(sId, mSettings) {
var bPercentageMode;
if (mSettings && typeof mSettings.percentage === "number"){
bPercentageMode = true;
} else if (sId && typeof sId.percentage === "number") {
bPercentageMode = true;
} else {
bPercentageMode = false;
}
try {
Control.apply(this, arguments);
this._bPercentageMode = bPercentageMode;
} catch (e) {
this.destroy();
throw e;
}
},
metadata : {
library: "sap.suite.ui.microchart",
properties: {
/**
* The total value. This is taken as 360 degrees value on the chart.
*/
total: {group:"Data", type:"float", defaultValue: null},
/**
* The fraction of the total value that is displayed.
*/
fraction: {group:"Data", type:"float", defaultValue: null},
/**
* The percentage that is displayed.
* When a percentage is set, properties total and fraction are not considered.
*/
percentage: {group:"Data", type:"float", defaultValue: null},
/**
* The color shown in the completed path.
*/
valueColor: {group: "Appearance", type: "sap.m.ValueCSSColor", defaultValue: "Neutral"}
},
events: {
/**
* The event is fired when the user chooses the control.
*/
press: {}
}
}
});
/* --- Lifecycle Handling --- */
/**
* Init function for the control
*/
RadialMicroChart.prototype.init = function() {
this._rb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this._bPercentageMode; // Flag for tracking if the application is using percentage or fraction and total
};
/**
* Handler for before rendering
*/
RadialMicroChart.prototype.onBeforeRendering = function() {
if (!this._bPercentageMode) {
if (this.getTotal() === 0) {
jQuery.sap.log.error("Total can not be 0, please add a valid total value");
} else {
this.setProperty("percentage", Math.round((this.getFraction() * 100 / this.getTotal()) * 10) / 10, true);
}
}
};
RadialMicroChart.prototype.onAfterRendering = function() {
Renderer._handleOnAfterRendering(this);
};
/* --- Event Handling --- */
RadialMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.internet_explorer) {
this.$().focus();
}
this.firePress();
};
RadialMicroChart.prototype.onkeydown = function(oEvent) {
if (oEvent.which === jQuery.sap.KeyCodes.SPACE) {
oEvent.preventDefault();
}
};
RadialMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which === jQuery.sap.KeyCodes.ENTER || oEvent.which === jQuery.sap.KeyCodes.SPACE) {
this.firePress();
oEvent.preventDefault();
}
};
RadialMicroChart.prototype.attachEvent = function(eventId, data, functionToCall, listener) {
sap.ui.core.Control.prototype.attachEvent.call(this, eventId, data, functionToCall, listener);
if (eventId === "press") {
this.rerender();
}
return this;
};
RadialMicroChart.prototype.detachEvent = function(eventId, functionToCall, listener) {
sap.ui.core.Control.prototype.detachEvent.call(this, eventId, functionToCall, listener);
if (eventId === "press") {
this.rerender();
}
return this;
};
/* --- Getters and Setters --- */
/**
* Getter for internal property _bPercentageMode.
* Percentage mode is configured by setting a percentage value on definition of the control.
* If Fraction and Total is used, this property is false since percentage gets calculated automatically by the control.
*
* @private
* @returns {boolean} true if chart is in percentage mode, false if not.
*/
RadialMicroChart.prototype._getPercentageMode = function() {
return this._bPercentageMode;
};
RadialMicroChart.prototype.setPercentage = function(percentage) {
if (percentage) {
if (percentage !== this.getPercentage()) {
this._bPercentageMode = true;
this.setProperty("percentage", percentage);
}
} else {
this._bPercentageMode = false;
this.setProperty("percentage", null);
}
};
/* --- Helpers --- */
/**
* Check if the valueColor property is an instance of sap.m.ValueColor
* @returns {boolean} True if valueColor property is an instance of sap.m.ValueColor, false otherwise.
* @private
*/
RadialMicroChart.prototype._isValueColorInstanceOfValueColor = function() {
var sValue = this.getValueColor();
for (var sValueColor in sap.m.ValueColor){
if (sValueColor === sValue) {
return true;
}
}
return false;
};
/**
* Returns the tooltip for the given chart.
* If tooltip was set to an empty string (using whitespaces) by the application,
* the tooltip will be set to an empty string. If tooltip was not set (null/undefined),
* a tooltip gets generated by the control.
*
* @private
* @returns {string} tooltip for the given control
*/
RadialMicroChart.prototype._getTooltipText = function() {
var sTooltip = this.getTooltip_Text();
if (!sTooltip) { //Tooltip will be set by control
sTooltip = this._getAriaAndTooltipText();
} else if (this._isTooltipSuppressed()) {
sTooltip = null;
}
return sTooltip;
};
/**
* Returns text for ARIA label.
* If tooltip was set to an empty string (using whitespaces) by the application or
* the tooltip was not set (null/undefined), the ARIA text gets generated by the control.
* Otherwise, the given tooltip will also be set as ARIA text.
*
* @private
* @returns {String} ARIA text for the given control
*/
RadialMicroChart.prototype._getAriaText = function() {
var sAriaText = this.getTooltip_Text();
if (!sAriaText || this._isTooltipSuppressed()) { //ARIA label will be set by control. Otherwise (else), version generated by control will be used.
sAriaText = this._getAriaAndTooltipText();
}
return sAriaText;
};
/**
* Returns value that indicates if the tooltip was configured as empty string (e.g. one whitespace).
*
* @private
* @returns {boolean} value that indicates true, if whitespace was set, false in any other case, also null/undefined
*/
RadialMicroChart.prototype._isTooltipSuppressed = function() {
var sTooltip = this.getTooltip_Text();
if (sTooltip && jQuery.trim(sTooltip).length === 0) {
return true;
} else {
return false;
}
};
/**
* Returns the part of the tooltip and ARIA text which is equal.
*
* @private
* @returns {string} value containing the tooltip and ARIA text
*/
RadialMicroChart.prototype._getAriaAndTooltipText = function() {
var sTextValue;
var fPercentage = this.getPercentage();
if (fPercentage > 100) {
fPercentage = 100;
} else if (fPercentage < 0) {
fPercentage = 0;
}
if (this._isValueColorInstanceOfValueColor()) {
sTextValue = this._rb.getText("RADIALMICROCHART_ARIA_LABEL", [this.getPercentage(), this._getStatusText()]);
} else {
sTextValue = this._rb.getText("RADIALMICROCHART_ARIA_LABEL", [fPercentage, sap.m.ValueColor.Neutral]);
}
return sTextValue;
};
/**
* Returns the status text based on color value (to be available for other languages also)
*
* @private
* @returns {string} value containing the status text
*/
RadialMicroChart.prototype._getStatusText = function() {
var sValueColor = this.getValueColor();
switch (sValueColor) {
case sap.m.ValueColor.Error:
return this._rb.getText("SEMANTIC_COLOR_ERROR");
case sap.m.ValueColor.Critical:
return this._rb.getText("SEMANTIC_COLOR_CRITICAL");
case sap.m.ValueColor.Good:
return this._rb.getText("SEMANTIC_COLOR_GOOD");
default:
return this._rb.getText("SEMANTIC_COLOR_NEUTRAL");
}
};
return RadialMicroChart;
});
}; // end of sap/suite/ui/microchart/RadialMicroChart.js
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
jQuery.sap.declare("sap.apf.core.messageDefinition");
sap.apf.core.messageDefinition = [ {
code : "3001",
severity : "technError",
text : "Text is not available for the following key: {0}"
}, {
code : "5001",
severity : "technError",
text : "Request {3} to server failed with http status code {0}, http error message {1}, and server response {2}."
}, {
code : "5002",
severity : "error",
description : "Error in OData request; update of analysis step {0} failed.",
key : "5002"
}, {
code : "5004",
severity : "fatal",
description : "Request with ID {0} does not exist in the analytical content configuration.",
key : "5004"
}, {
code : "5005",
severity : "technError",
text : "Required property {1} is missing in the filter of the OData request for entity type {0}."
}, {
code : "5006",
severity : "technError",
text : "Inconsistency in data model; non-filterable property {1} is set as required filter for entity type {0}."
}, {
code : "5015",
severity : "fatal",
description : "Service for request {0} is not defined in the analytical content configuration.",
key : "5015"
}, {
code : "5016",
severity : "technError",
text : "Mandatory parameter key property {0} is missing in filter."
}, {
code : "5018",
severity : "fatal",
description : "Metadata request {0} failed.",
key : "5018"
}, {
code : "5019",
severity : "technError",
text : "System query option $orderby for property {1} removed from OData request for entity type {0}."
}, {
code : "5020",
severity : "fatal",
description : "Analytical content configuration is not available.",
key : "5020"
}, {
code : "5021",
severity : "error",
description : "Error during server request; session timeout occurred.",
key : "5021"
}, {
code : "5022",
severity : "fatal",
description : "Analytical configuration with ID {0} is not available.",
key : "5022"
}, {
code : "5023",
severity : "fatal",
description : "Texts could not be loaded for Analytical configuration with ID {0}.",
key : "5023"
}, {
code : "5024",
severity : "fatal",
description : "URL Parameter for Analytical Configuration ID must contain the ID of the application and the ID of the Analytical configuration seperated by a dot.",
key : "5024"
}, {
code : "5025",
severity : "fatal",
description : "Value for SAP client has not been provided at startup of the application.",
key : "5025"
}, {
code : "5026",
severity : "fatal",
description : "Logical system cannot be determined for SAP client {0}. ",
key : "5026"
}, {
code : "5027",
severity : "technError",
text : "Inconsistent parameters; analysis path cannot be saved. Path ID: {0}, path name: {1}, callback function {2}"
}, {
code : "5028",
severity : "technError",
text : "Binding with ID {0} contains a representation without ID."
}, {
code : "5029",
severity : "technError",
text : "Binding with ID {0} contains a duplicated representation ID."
}, {
code : "5030",
severity : "technError",
text : "Constructor property of representation type ID {0} does not contain a module path to a valid function."
}, {
code : "5031",
severity : "technError",
text : "Argument for method 'setApplicationMessageCallback' is not a function."
}, {
code : "5032",
severity : "technError",
text : "System query option {1} unknown in request for entity type {0}."
}, {
code : "5033",
severity : "technError",
text : "Unsupported type {0} in configuration object provided."
}, {
code : "5034",
severity : "technError",
text : "Facet filter configuration attribute 'property' missing."
}, {
code : "5035",
severity : "technError",
text : "Function module path contained in property preselectionFuntion of facet filter ID {0} does not contain a valid function."
}, {
code : "5036",
severity : "technError",
text : "Start paramater step id {0} is not existing."
}, {
code : "5037",
severity : "technError",
text : "Start paramater representation id {0} is not existing."
}, {
code : "5038",
severity : "technError",
text : "Environment for sap.ushell.Container is not existing."
}, {
code : "5039",
severity : "technError",
text : "Error while pushing content to the ushell container"
}, {
code : "5040",
severity : "technError",
text : "Error while fetching content from the ushell container"
}, {
code : "5100",
severity : "fatal",
description : "Unexpected internal error: {0}. Contact SAP.",
key : "5100"
}, {
code : "5101",
severity : "technError",
text : "Unexpected internal error: {0}. Contact SAP."
}, {
code : "5102",
severity : "fatal",
description : "Wrong definition in analytical content configuration: {0}",
key : "5102"
}, {
code : "5103",
severity : "technError",
text : "Wrong definition in analytical content configuration: {0}"
}, {
code : "5104",
severity : "technError",
text : "Wrong filter mapping definition in analytical content configuration"
}, {
code : "5200",
severity : "technError",
text : "Server error during processing of path: {0} {1}"
}, {
code : "5201",
severity : "error",
description : "Unknown server error.",
key : "5201"
}, {
code : "5202",
severity : "technError",
text : "Persistence service call returned '405 - Method not allowed'."
}, {
code : "5203",
severity : "technError",
text : "Bad request; data is structured incorrectly."
}, {
code : "5204",
severity : "error",
description : "Error during server request; maximum number of analysis steps exceeded.",
key : "5204"
}, {
code : "5205",
severity : "error",
description : "Error during server request; maximum number of analysis paths exceeded.",
key : "5205"
}, {
code : "5206",
severity : "error",
description : "Access forbidden; insufficient privileges",
key : "5206"
}, {
code : "5207",
severity : "error",
description : "Inserted value too large; probably maximum length of analysis path name exceeded",
key : "5207"
}, {
code : "5208",
severity : "error",
description : "Error during path persistence; request to server can not be proceed due to invalid ID.",
key : "5208"
}, {
code : "5210",
severity : "error",
description : "Error during opening of analysis path; see log.",
key : "5210"
}, {
code : "5211",
severity : "error",
description : "Server response contains undefined path objects.",
key : "5211"
}, {
code : "5212",
severity : "error",
description : "Metadata file of application {0} could not be accessed.",
key : "5212"
}, {
code : "5213",
severity : "error",
description : "Text file of application {0} could not be accessed.",
key : "5213"
}, {
code : "5300",
severity : "fatal",
description : "You must log out of the application due to a critical error.",
key : "5300"
}, {
code : "5301",
severity : "warning",
description : "Add or update path filter API method called with unsupported filter; See sap.apf.api documentation",
key : "5301"
}, {
code : "6001",
severity : "fatal",
description : "Missing {0} in the configuration; contact your administrator.",
key : "6001"
}, {
code : "6000",
severity : "error",
description : "Data is not available for the {0} step.",
key : "6000"
}, {
code : "6002",
severity : "error",
description : "Missing {0} for {1} in the configuration; contact your administrator.",
key : "6002"
}, {
code : "6003",
severity : "error",
description : "Missing {0} in the configuration; contact your administrator.",
key : "6001"
}, {
code : "6004",
severity : "technError",
text : "Metadata not available for step {0}."
}, {
code : "6005",
severity : "error",
description : "Server request failed. Unable to read paths.",
key : "6005"
}, {
code : "6006",
severity : "error",
description : "Server request failed. Unable to save path {0}.",
key : "6006"
}, {
code : "6007",
severity : "error",
description : "Server request failed. Unable to update path {0}.",
key : "6007"
}, {
code : "6008",
severity : "error",
description : "Server request failed. Unable to open path {0}.",
key : "6008"
}, {
code : "6009",
severity : "error",
description : "Server request failed. Unable to delete path {0}.",
key : "6009"
}, {
code : "6010",
severity : "technError",
description : "Data is not available for filter {0}",
key : "6010"
}, {
code : "6011",
severity : "fatal",
description : "Smart Business service failed.Please try later",
key : "6011"
}, {
code : "7000",
severity : "error",
description : "Missing {0} in the configuration; contact your administrator.",
key : "6001"
} ];
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
jQuery.sap.require('sap.apf.modeler.ui.utils.nullObjectChecker');jQuery.sap.declare('sap.apf.modeler.ui.utils.staticValuesBuilder');(function(){'use strict';sap.apf.modeler.ui.utils.staticValuesBuilder=function(t){sap.apf.modeler.ui.utils.staticValuesBuilder.prototype.getNavTargetTypeData=function(){var a=[t("globalNavTargets"),t("stepSpecific")];return a;};};})();
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2015 SAP SE. All rights reserved
*/
sap.ui.define([
"sap/gantt/shape/Rectangle", "sap/gantt/misc/Utility", "sap/ui/core/Core"
], function(Rectangle, Utility, Core){
"use strict";
/**
* Creates and initializes a new RowBackgroundRectangle class.
*
* @param {string} [sId] ID of the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings of the new control
*
* @class
* RowBackgroundRectangle shape class using SVG tag 'rect'. It's used to represent rows' background rectangle in the tree table of a Gantt chart.
*
* @extends sap.gantt.shape.Rectangle
*
* @author SAP SE
* @version 1.36.8
*
* @constructor
* @public
* @alias sap.gantt.shape.ext.RowBackgroundRectangle
*/
var RowBackgroundRectangle = Rectangle.extend("sap.gantt.shape.ext.RowBackgroundRectangle", /** @lends sap.gantt.shape.ext.RowBackgroundRectangle.prototype */ {
metadata: {
properties: {
isBulk: {type: "boolean", defaultValue: true},
enableSelection: {type: "boolean", defaultValue: false}
}
}
});
/**
* Gets the value of property <code>isBulk</code>.
*
* <p>
* For performance reasons, Gantt charts perform filtering of data using timestamp. For a background rectangle shape which only needs to draw once in visible areas, set this flag to true.
* </p>
*
* @name sap.gantt.shape.ext.RowBackgroundRectangle.prototype.getIsBulk
* @function
*
* @param {object} oData Shape data.
* @param {object} oRowInfo Information about the row and row data.
* @return {boolean} Value of property <code>isBulk</code>.
* @public
*/
/**
* Gets the value of property <code>fill</code>.
*
* <p>
* Standard SVG 'fill' attribute.
* See {@link http://www.w3.org/TR/SVG/painting.html#FillProperty SVG 1.1 specification for 'fill'}.
* <b>Note:</b> You can provide fill with HTML colors and the URL reference to a paint server. Paint server definitions can be retrieved from paint servers rendered by
* {@link sap.gantt.GanttChartContainer}, {@link sap.gantt.GanttChartWithTable}, or {@link sap.gantt.GanttChart}.
* </p>
*
* @param {object} oData Shape data.
* @param {object} oRowInfo Information about the row and row data.
* @return {string} Value of property <code>fill</code>.
* @public
*/
RowBackgroundRectangle.prototype.getFill = function(oData, oRowInfo) {
if (this.mShapeConfig.hasShapeProperty("fill")){
return this._configFirst("fill", oData);
}
var oChartSchemeMap = this.mChartInstance._oChartSchemesConfigMap;
var oChartScheme = (oChartSchemeMap && oChartSchemeMap[oRowInfo.chartScheme]) ? oChartSchemeMap[oRowInfo.chartScheme] : undefined;
if (oChartScheme && oChartScheme.getBackgroundColor()) {
return oChartScheme.getBackgroundColor();
}
return "none";
};
/**
* Gets the value of property <code>strokeWidth</code>.
*
* <p>
* Standard SVG 'stroke-width' attribute.
* See {@link http://www.w3.org/TR/SVG/painting.html#StrokeWidthProperty SVG 1.1 specification for 'stroke-width'}.
* </p>
* <p>The default value is 0.</p>
*
* @param {object} oData Shape data.
* @param {object} oRowInfo Information about the row and row data.
* @return {number} Value of property <code>strokeWidth</code>.
* @public
*/
RowBackgroundRectangle.prototype.getStrokeWidth = function(oData, oRowInfo) {
if (this.mShapeConfig.hasShapeProperty("strokeWidth")) {
return this._configFirst("strokeWidth", oData);
}
return 0;
};
/**
* Gets the value of property <code>x</code>.
*
* <p>
* x coordinate of the top-left point of a rectangle.
* See {@link http://www.w3.org/TR/SVG/shapes.html#RectElementXAttribute SVG 1.1 specification for the 'x' attribute of 'rect'}.
*
* Your application should not configure this value. Instead, the getter calculates the value of x by using the initial coordinate
* of the view boundary for visible areas in a Gantt chart.
* </p>
*
* @param {object} oData Shape data.
* @param {object} oRowInfo Information about the row and row data.
* @return {number} Value of property <code>x</code>.
* @public
*/
RowBackgroundRectangle.prototype.getX = function(oData, oRowInfo) {
if (this.mShapeConfig.hasShapeProperty("x")) {
return this._configFirst("x", oData);
}
var aViewRange = this.getShapeViewBoundary();
if (aViewRange){
return aViewRange[0];
}
return 0;
};
/**
* Gets the value of property <code>y</code>.
*
* <p>
* y coordinate of the top-left point of a rectangle.
* See {@link http://www.w3.org/TR/SVG/shapes.html#RectElementYAttribute SVG 1.1 specification for the 'y' attribute of 'rect'}.
*
* Your application should not configure this value. Instead, the getter calculates the value of y by using parameter <code>oRowInfo</code>.
* </p>
* <p>The default value is the y coordinate of the row plus 1px, which is the width of the stroke.</p>
*
* @param {object} oData Shape data.
* @param {object} oRowInfo Information about the row and row data.
* @return {number} Value of property <code>y</code>.
* @public
*/
RowBackgroundRectangle.prototype.getY = function(oData, oRowInfo) {
if (this.mShapeConfig.hasShapeProperty("y")) {
return this._configFirst("y", oData);
}
return oRowInfo.y + 1;
};
/**
* Gets the value of property <code>width</code>.
*
* <p>
* Width of a rectangle.
* See {@link http://www.w3.org/TR/SVG/shapes.html#RectElementWidthAttribute SVG 1.1 specification for the 'width' attribute of 'rect'}.
*
* Your application should not configure this value. Instead, the getter calculates the value of width by using the view boundary for visible areas in a Gantt chart.
* If your application overwrites the getter using configuration or code, accurate results cannot be guaranteed.
* </p>
*
* @param {object} oData Shape data.
* @param {object} oRowInfo Information about the row and row data.
* @return {number} Value of property <code>width</code>.
* @public
*/
RowBackgroundRectangle.prototype.getWidth = function(oData, oRowInfo) {
if (this.mShapeConfig.hasShapeProperty("width")) {
return this._configFirst("width", oData);
}
var aViewRange = this.getShapeViewBoundary();
if (aViewRange){
return aViewRange[1] - aViewRange[0];
}
return 0;
};
/**
* Gets the value of property <code>height</code>.
*
* <p>
* Height of a rectangle.
* See {@link http://www.w3.org/TR/SVG/shapes.html#RectElementHeightAttribute SVG 1.1 specification for the 'height' attribute of 'rect'}.
* </p>
* <p>The default value is the height of the row minus 1px, which is the width of stroke.</p>
*
* @param {object} oData Shape data.
* @param {object} oRowInfo Information about the row and row data.
* @return {number} Value of property <code>height</code>.
* @public
*/
RowBackgroundRectangle.prototype.getHeight = function(oData, oRowInfo) {
if (this.mShapeConfig.hasShapeProperty("height")) {
return this._configFirst("height", oData);
}
return oRowInfo.rowHeight - 1;
};
/**
* Filter all data in visible areas to get valid rows' data, only these valid rows must have a background rectangle drawn,
* which is filled in a certain color.
*
* @param {array} aRowDatas data of all rows in visible areas.
* @return {array} data of valid rows that must have a background rectangle drawn.
* @public
*/
RowBackgroundRectangle.prototype.filterValidData = function(aRowDatas) {
if (aRowDatas.length > 0){
var oChart = this.mChartInstance;
var oChartSchemeMap = oChart._oChartSchemesConfigMap;
var oObjectTypeMap = oChart._oObjectTypesConfigMap;
return $.grep(aRowDatas, function(oValue, iIndex) {
var oChartScheme;
if (oValue.__group) {
oChartScheme = (oChartSchemeMap && oChartSchemeMap[oValue.__group]) ? oChartSchemeMap[oValue.__group] : undefined;
} else {
var oObjectType = (oObjectTypeMap && oObjectTypeMap[oValue.type]) ? oObjectTypeMap[oValue.type] : undefined;
if (oObjectType) {
oChartScheme = (oChartSchemeMap && oChartSchemeMap[oObjectType.getMainChartSchemeKey()]) ? oChartSchemeMap[oObjectType.getMainChartSchemeKey()] : undefined;
}
}
if (oChartScheme && oChartScheme.getBackgroundColor()) {
return oValue;
}
});
}
return aRowDatas;
};
/**
* Indicates whether your application must use HtmlClass to decide the color of background.
* If the theme is sap_bluecrystal, the application can use custom configuration value for fill property, but if the theme is sap_hcb,
* the application must use HtmlClass instead.
*
* @param {object} oData Shape data.
* @param {object} oRowInfo Information about the row and row data.
* @return {boolean} Value indicates whether HtmlClass must be used to decide the color of the background.
*/
RowBackgroundRectangle.prototype.getHtmlClass = function(oData, oRowInfo) {
if (Core.getConfiguration().getTheme() === "sap_hcb") {
return true;
}
return false;
};
return RowBackgroundRectangle;
}, true);
<file_sep>/*
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
/**
* @public
* @name sap.ui.comp.transport.TransportSelection
* @author SAP SE
* @version 1.36.12
* @since 1.26.0
* Helper object to select an ABAP transport for an LREP object. This is not a generic utility to select a transport request, but part
* of the SmartVariant control.
* @param {jquery.sap.global} jQuery a reference to the jQuery implementation.
* @param {sap.ui.fl.Utils} Utils a reference to the flexibility utilities implementation.
* @param {sap.ui.fl.Transports} Transports a reference to the transport service implementation.
* @param {sap.ui.comp.transport.TransportDialog} TransportDialog a reference to the transport dialog implementation.
* @param {sap.ui.fl.registry.Settings} FlexSettings a reference to the settings implementation
* @returns {sap.ui.comp.transport.TransportSelection} a new instance of <code>sap.ui.comp.transport.TransportSelection</code>.
*/
sap.ui.define([ "jquery.sap.global", "sap/ui/fl/Utils", "sap/ui/fl/Transports", "sap/ui/comp/transport/TransportDialog", "sap/ui/fl/registry/Settings" ], function(jQuery, Utils, Transports, TransportDialog, FlexSettings) {
"use strict";
/**
* @public
* @constructor
*/
var TransportSelection = function() {
this.oTransports = new sap.ui.fl.Transports();
this.oUtils = sap.ui.fl.Utils;
};
/**
* Selects a transport request for a given LREP object.
* First checks if the Adaptation Transport Organizer (ATO) is enabled
* If ATO is enabled and LREP object is in CUSTOMER layer the request 'ATO_NOTIFICATION' has to be used which in the backend triggers that the change is added to an ATO collection
* If ATO is not enabled or LREP object not in CUSTOMER layer:
* If the LREP object is already assigned to an open transport request or the LREP object is
* assigned to a local ABAP package, no dialog to select a transport is started. Instead the success callback is invoked directly. The transport
* dialog is shown if a package or a transport request has still to be selected, so if more than one transport request is available for the
* current user and the LREP object is not locked in an open transport request.
*
* @param {object} oObjectInfo the LREP object, which has the attributes name, name space, type, layer and package.
* @param {function} fOkay call-back to be invoked when a transport request has successfully been selected.
* @param {function} fError call-back to be invoked when an error occurred during selection of a transport request.
* @param {boolean} bCompactMode flag indicating whether the transport dialog should be opened in compact mode.
* @param {object} oControl Control instance
* @public
*/
TransportSelection.prototype.selectTransport = function(oObjectInfo, fOkay, fError, bCompactMode, oControl) {
var sComponentName, mPropertyBag;
var that = this;
if (oObjectInfo) {
var sLayerType = Utils.getCurrentLayer(false);
if (oControl) {
sComponentName = Utils.getComponentClassName(oControl);
var mPropertyBag = {
appDescriptor: Utils.getAppDescriptor(oControl),
siteId: Utils.getSiteId(oControl)
};
}
// if component name and object layer are known and layer is CUSTOMER
// check in settings if the adaptation transport organizer (ATO) is enabled
if (sComponentName && sLayerType && sLayerType === 'CUSTOMER') {
// retrieve the settings and check if ATO is enabled
FlexSettings.getInstance(sComponentName, mPropertyBag).then(function(oSettings) {
// ATO is enabled - signal that change is to be added to an ATO collection
// instead of a transport
if (oSettings.isAtoEnabled()) {
var oTransport = { transportId: "ATO_NOTIFICATION" };
fOkay(that._createEventObject(oObjectInfo, oTransport));
// ATO is not enabled - use CTS
} else {
that._selectTransport(oObjectInfo, fOkay, fError, bCompactMode);
}
});
// do not have the required info to check for ATO or not CUSTOMER layer - use CTS
} else {
that._selectTransport(oObjectInfo, fOkay, fError, bCompactMode);
}
}
};
/**
* Selects a transport request for a given LREP object. If the LREP object is already assigned to an open transport request or the LREP object is
* assigned to a local ABAP package, no dialog to select a transport is started. Instead the success callback is invoked directly. The transport
* dialog is shown if a package or a transport request has still to be selected, so if more than one transport request is available for the
* current user and the LREP object is not locked in an open transport request.
*
* @param {object} oObjectInfo the LREP object, which has the attributes name, name space, type, layer and package.
* @param {function} fOkay call-back to be invoked when a transport request has successfully been selected.
* @param {function} fError call-back to be invoked when an error occurred during selection of a transport request.
* @param {boolean} bCompactMode flag indicating whether the transport dialog should be opened in compact mode.
* @private
*/
TransportSelection.prototype._selectTransport = function(oObjectInfo, fOkay, fError, bCompactMode) {
var oPromise, that = this;
if (oObjectInfo) {
oPromise = this.oTransports.getTransports(oObjectInfo);
oPromise.then(function(oResult) {
var oTransport;
if (that._checkDialog(oResult)) {
that._openDialog({
hidePackage: !that.oUtils.doesSharedVariantRequirePackage(),
pkg: oObjectInfo["package"],
transports: oResult.transports,
lrepObject: that._toLREPObject(oObjectInfo)
}, fOkay, fError, bCompactMode);
} else {
oTransport = that._getTransport(oResult);
fOkay(that._createEventObject(oObjectInfo, oTransport));
}
}, function(oResult) {
fError(oResult);
});
}
};
/**
* Creates an event object similar to the UI5 event object.
*
* @param {object} oObjectInfo identifies the LREP object.
* @param {object} oTransport the transport request that has been selected.
* @return {object} event object.
* @private
*/
TransportSelection.prototype._createEventObject = function(oObjectInfo, oTransport) {
return {
mParameters: {
selectedTransport: oTransport.transportId,
selectedPackage: oObjectInfo["package"],
dialog: false
},
getParameters: function() {
return this.mParameters;
},
getParameter: function(sName) {
return this.mParameters[sName];
}
};
};
/**
* Creates an LREP object description for the transport dialog.
*
* @param {object} oObjectInfo identifies the LREP object.
* @return {object} LREP object description for the transport dialog.
* @private
*/
TransportSelection.prototype._toLREPObject = function(oObjectInfo) {
var oObject = {};
if (oObjectInfo.namespace) {
oObject.namespace = oObjectInfo.namespace;
}
if (oObjectInfo.name) {
oObject.name = oObjectInfo.name;
}
if (oObjectInfo.type) {
oObject.type = oObjectInfo.type;
}
return oObject;
};
/**
* Opens the dialog to select a transport request.
*
* @param {object} oConfig configuration for the dialog, e.g. package and transports.
* @param {function} fOkay call-back to be invoked when a transport request has successfully been selected.
* @param {function} fError call-back to be invoked when an error occurred during selection of a transport request.
* @param {boolean} bCompactMode flag indicating whether the transport dialog should be opened in compact mode.
* @returns {sap.ui.comp.transport.TransportDialog} the dialog.
* @private
*/
TransportSelection.prototype._openDialog = function(oConfig, fOkay, fError, bCompactMode) {
var oDialog = new TransportDialog(oConfig);
oDialog.attachOk(fOkay);
oDialog.attachCancel(fError);
// toggle compact style.
if (bCompactMode) {
oDialog.addStyleClass("sapUiSizeCompact");
} else {
oDialog.removeStyleClass("sapUiSizeCompact");
}
oDialog.open();
return oDialog;
};
/**
* Returns a transport to assign an LREP object to.
*
* @param {object} oTransports the available transports.
* @returns {object} a transport to assign an LREP object to, can be <code>null</code>.
* @private
*/
TransportSelection.prototype._getTransport = function(oTransports) {
var oTransport;
if (!oTransports.localonly) {
oTransport = this._hasLock(oTransports.transports);
} else {
oTransport = {
transportId: ""
};
}
return oTransport;
};
/**
* Returns whether the dialog to select a transport should be started.
*
* @param {object} oTransports the available transports.
* @returns {boolean} <code>true</code>, if the LREP object is already locked in one of the transports, <code>false</code> otherwise.
* @private
*/
TransportSelection.prototype._checkDialog = function(oTransports) {
if (oTransports) {
if (oTransports.localonly || this._hasLock(oTransports.transports)) {
return false;
}
}
return true;
};
/**
* Returns whether the LREP object is already locked in one of the transports.
*
* @param {array} aTransports the available transports.
* @returns {object} the transport, if the LREP object is already locked in one of the transports, <code>null</code> otherwise.
* @private
*/
TransportSelection.prototype._hasLock = function(aTransports) {
var oTransport, len = aTransports.length;
while (len--) {
oTransport = aTransports[len];
if (oTransport.locked) {
return oTransport;
}
}
return false;
};
return TransportSelection;
}, true);
<file_sep>/* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP SE. All rights reserved
*/
jQuery.sap.declare("sap.apf.ui.representations.table");
jQuery.sap.require("sap.apf.core.constants");
jQuery.sap.require('sap.apf.ui.utils.formatter');
jQuery.sap.require("sap.apf.ui.representations.BaseUI5ChartRepresentation");
(function() {
'use strict';
//select the items in the table which are passed as parameter
function _selectItemsInTable(aSelectedItems) {
oTableWithoutHeaders.removeSelections();// remove all the selections , so that older values are not retained
aSelectedItems.forEach(function(item) {
oTableWithoutHeaders.setSelectedItem(item);
});
}
//clear the filters from the UI5Charthelper and also from APF filters
function _clearFilters(oTableInstance) {
oTableInstance.UI5ChartHelper.filterValues = [];
oTableInstance.setFilter(oTableInstance.oApi.createFilter());
}
//creates the filter values from the filters
function _getFilterTremsFromTableSelection(oTableInstance) {
var sRequiredFilterProperty = oTableInstance.getFilter().getInternalFilter().getProperties()[0]; // read the required property in the table
var aFilterTerms = oTableInstance.getFilter().getInternalFilter().getFilterTermsForProperty(sRequiredFilterProperty); //read the filter terms
var aFilterValues = aFilterTerms.map(function(term) {
return term.getValue();
});
return aFilterValues;
}
//read the filters and select the rows in table. Also read the selected items where selection is enabled, creates the filters from selections
function _drawSelection(oEvent) {
var aFilterValues = [], sRequiredFilterProperty;
var aCurrentSelectedItem = oEvent.getParameters("listItems").listItems; // store the current selected item for which selection event is triggered
if (this.UI5ChartHelper) { // if the UI5ChartHelper is available , then only filters would be present
var aInternalFilters = this.getFilter().getInternalFilter().getProperties();
aFilterValues = aInternalFilters.length > 0 ? _getFilterTremsFromTableSelection(this) : []; // if there are filters then get the filters or it will be an empty array
sRequiredFilterProperty = aInternalFilters[0]; // read the required property in the table
aFilters = aFilterValues; //update the filters for the table , for the selection count. In case of selection coming from charts
}
//enable the selection mode in the table based on the required filter availability
var selectionMode = this.oParameter.requiredFilters.length > 0 ? "MultiSelect" : "None";
oTableWithoutHeaders.setMode(selectionMode);
if (oEvent.getId() === "selectionChange") { //if the explicit selection is made on the table, selectionChanged event is triggered
var isSelectionChanged = true;// boolean to indicate if the selection changed API is triggered just once
var newAddedFilters = [];
sRequiredFilterProperty = aInternalFilters[0] || this.parameter.requiredFilters[0]; //read the required filter from the internal filter or the required filters (when table is created, the internal filter wont be available)
var sCurrentRequiredFilter = aCurrentSelectedItem[0].getBindingContext().getProperty(this.parameter.requiredFilters[0]);//required filter from current selected item
//toggle the selection in table
if (aCurrentSelectedItem[0].isSelected()) {
newAddedFilters.push(sCurrentRequiredFilter); // if new item is selected, add it to the new added filter array
} else {
var indexOfToggledItem = aFilterValues.indexOf(sCurrentRequiredFilter);
if (indexOfToggledItem !== -1) { // if item is deselected, find the index of item and remove it from array
aFilterValues.splice(indexOfToggledItem, 1);
}
}
aFilterValues = aFilterValues.concat(newAddedFilters.filter(function(item) { // merge the unique filters into an array
return aFilterValues.indexOf(item) < 0;
}));
aFilters = aFilterValues;//update the filters for the table , for the selection count. In case of selection event
if (isSelectionChanged) { // if the selection has changed and selectionChanged event has to be triggered
_clearFilters(this); // clear the filters first, so that older values are not retained on the UI5ChartHelper filetr values
this.filter = this.UI5ChartHelper.getFilterFromSelection(aFilterValues);
this.oApi.getActiveStep().getSelectedRepresentation().UI5ChartHelper.filterValues = this.UI5ChartHelper.filterValues; // assign the filter values from table to the selected representation
this.oApi.selectionChanged(); // trigger the selection change event
} else {
isSelectionChanged = true;// make the boolean true, so that the selectionChanges API is triggered
}
}
//read the filter directly in case of updateFinished event
var aAllSelectionInTable = oEvent.getSource().getItems().filter(function(item) { // selection in table which are based on the result filter values
var reqFilterValue = item.getBindingContext().getProperty(sRequiredFilterProperty);
return aFilterValues.indexOf(reqFilterValue) !== -1;
});
_selectItemsInTable(aAllSelectionInTable);
}
//reads the filters and selects the rows in print of table
function _drawSelectionForPrint(oTableInstance) {
var aFilterValues = _getFilterTremsFromTableSelection(oTableInstance);
var sRequiredFilterProperty = oTableInstance.getFilter().getInternalFilter().getProperties()[0]; // read the required property in the table
var aSelectedListItems = oPrintTable.getItems().filter(function(item) {
var reqFilterValue = item.getBindingContext().getProperty(sRequiredFilterProperty);
return aFilterValues.indexOf(reqFilterValue) !== -1;
});
var selectionMode = oTableInstance.oParameter.requiredFilters.length > 0 ? "MultiSelect" : "None";
oPrintTable.setMode(selectionMode);
return aSelectedListItems;
}
var oFormatter, aFilters, tableFields, tableColumns, isAlternateRepresentation, oTableWithoutHeaders, oTableWithHeaders, oPrintTable, aTableData = [];
var eventsFired, skipAction, skip, topValue, triggerBool;
var oTableDataModel = new sap.ui.model.json.JSONModel();
oTableDataModel.setSizeLimit(10000);
/**
* @class table constructor.
* @param oApi,oParameters
* defines parameters required for chart such as Dimension/Measures.
* @returns table object
*/
sap.apf.ui.representations.table = function(oApi, oParameters) {
this.oParameter = oParameters;
sap.apf.ui.representations.BaseUI5ChartRepresentation.apply(this, [ oApi, oParameters ]);
isAlternateRepresentation = oParameters.isAlternateRepresentation;
this.alternateRepresentation = oParameters.defaultListConfigurationTypeID;
this.type = sap.apf.ui.utils.CONSTANTS.representationTypes.TABLE_REPRESENTATION; //the type is read from step toolbar and step container
triggerBool = false;
eventsFired = 0;
skipAction = 0;
skip = 0;
topValue = 10;
aFilters = [];
this.aDataResponse = [];// getData in the base class reads the value of data response from this
};
sap.apf.ui.representations.table.prototype = Object.create(sap.apf.ui.representations.BaseUI5ChartRepresentation.prototype);
sap.apf.ui.representations.table.prototype.constructor = sap.apf.ui.representations.table;// Set the "constructor" property to refer to table
/**
* @method setData
* @param aDataResponse - Response from oData service
* @param metadata - Metadata of the oData service
* @description Public API which Fetches the data from oData service and updates the selection if present
*/
sap.apf.ui.representations.table.prototype.setData = function(aDataResponse, metadata) {
var self = this;
if (skipAction === 0) {
if (triggerBool) { //if pagination is triggered
aDataResponse.map(function(dataRow) {
self.aDataResponse.push(dataRow);// for pagination , append the data to the existing data set
});
skipAction++;
} else { //if the data is being loaded for first time
skip = 0;
topValue = 100;//initially 100 records should be fetched
aTableData = [];
self.aDataResponse = aDataResponse; // For new table, read only 100 data set
}
}
aTableData = self.aDataResponse || [];
if (!metadata) {
this.oMessageObject = this.oApi.createMessageObject({
code : "6004",
aParameters : [ this.oApi.getTextNotHtmlEncoded("step") ]
});
this.oApi.putMessage(this.oMessageObject);
} else { //if metadata is available
this.metadata = metadata; // assign the metadata to be used in the table representation
oFormatter = new sap.apf.ui.utils.formatter({ // formatter for the value formatting
getEventCallback : this.oApi.getEventCallback.bind(this.oApi),
getTextNotHtmlEncoded : this.oApi.getTextNotHtmlEncoded
}, metadata, aDataResponse);
this.UI5ChartHelper.metadata = metadata;
}
};
/**
* @method createDataset
* @description Intantiates the dataset to be consumed by the table
* Also formats the column value which has to be displayed in the table
*/
sap.apf.ui.representations.table.prototype.createDataset = function() {
tableFields = [];
tableColumns = {
name : [],
value : []
};
tableFields = this.oParameter.dimensions.concat(this.oParameter.measures).length ? this.oParameter.dimensions.concat(this.oParameter.measures) : this.oParameter.properties; // read the table properties if available , else Concatenate dimensions & measures
aTableData = this.getData();
if (aTableData.length !== 0) {
for(var i = 0; i < tableFields.length; i++) {
tableColumns.value[i] = tableFields[i].fieldName;
var name = "";
var defaultLabel = this.metadata.getPropertyMetadata(tableFields[i].fieldName).label || this.metadata.getPropertyMetadata(tableFields[i].fieldName).name;
var sUnitValue = "";
if (this.metadata !== undefined && this.metadata.getPropertyMetadata(tableFields[i].fieldName).unit !== undefined) {
var sUnitReference = this.metadata.getPropertyMetadata(tableFields[i].fieldName).unit;
sUnitValue = this.getData()[0][sUnitReference]; // take value of unit from firts data set
name = tableFields[i].fieldDesc === undefined || !this.oApi.getTextNotHtmlEncoded(tableFields[i].fieldDesc).length ? defaultLabel + " (" + sUnitValue + ")" : this.oApi.getTextNotHtmlEncoded(tableFields[i].fieldDesc) + " ("
+ sUnitValue + ")";
tableColumns.name[i] = name;
} else {
tableColumns.name[i] = tableFields[i].fieldDesc === undefined || !this.oApi.getTextNotHtmlEncoded(tableFields[i].fieldDesc).length ? defaultLabel : this.oApi.getTextNotHtmlEncoded(tableFields[i].fieldDesc);
}
}
}
};
/**
* @method getSelectionFromChart
* @returns the selected items in the table.
*/
sap.apf.ui.representations.table.prototype.getSelectionFromChart = function() {
var aSelection = oTableWithoutHeaders.getSelectedItems();
return aSelection;
};
/**
* @method getSelections
* @description This method helps in determining the selection count, text and id of selected data of a representation
* @returns the filter selections of the current representation.
*/
sap.apf.ui.representations.table.prototype.getSelections = function() {
var aSelection = [];
if (aFilters) {
aFilters.forEach(function(filter) {
aSelection.push({
id : filter,
text : filter
});
});
}
return aSelection;
};
/**
* @method getRequestOptions
* @description provide optional filter properties for odata request URL such as pagging, sorting etc
*/
sap.apf.ui.representations.table.prototype.getRequestOptions = function() {
if (!triggerBool) {
topValue = 100;
skip = 0;
skipAction = 0;
}
var requestObj = {
paging : {
top : topValue,
skip : skip,
inlineCount : true
}
};
var orderByArray;
if (this.sortProperty !== undefined) {
orderByArray = [ {
property : this.sortProperty,
descending : this.sortOrderIsDescending
} ];
requestObj.orderby = orderByArray;
} else {
if (this.getParameter().orderby && this.getParameter().orderby.length) {
var aOrderbyProps = this.getParameter().orderby.map(function(oOrderby) {
return {
property : oOrderby.property,
descending : !oOrderby.ascending
};
});
requestObj.orderby = aOrderbyProps;
}
}
return requestObj;
};
/**
* @method getMainContent
* @param oStepTitle - title of the main chart
* @param width - width of the main chart
* @param height - height of the main chart
* @description draws Main chart into the Chart area
*/
sap.apf.ui.representations.table.prototype.getMainContent = function(oStepTitle, height, width) {
var self = this;
this.createDataset();
var oMessageObject;
if (!oStepTitle) {
oMessageObject = this.oApi.createMessageObject({
code : "6002",
aParameters : [ "title", this.oApi.getTextNotHtmlEncoded("step") ]
});
this.oApi.putMessage(oMessageObject);
}
if (tableFields.length === 0) {
oMessageObject = this.oApi.createMessageObject({
code : "6002",
aParameters : [ "dimensions", oStepTitle ]
});
this.oApi.putMessage(oMessageObject);
}
if (!aTableData || aTableData.length === 0) {
oMessageObject = this.oApi.createMessageObject({
code : "6000",
aParameters : [ oStepTitle ]
});
this.oApi.putMessage(oMessageObject);
}
var chartWidth = (width || 1000) + "px";
var columnCells = [];
var indexForColumn;
var fnCellValue = function(index) {
return function(columnValue) {
if (self.metadata === undefined) {
return columnValue;
} else {
var formatedColumnValue;
if (tableColumns.value[index] && columnValue) {
formatedColumnValue = oFormatter.getFormattedValue(tableColumns.value[index], columnValue);
}
if (formatedColumnValue !== undefined) {
return formatedColumnValue;
} else {
return columnValue;
}
}
};
};
var tableCellValues;
for(indexForColumn = 0; indexForColumn < tableColumns.name.length; indexForColumn++) {
tableCellValues = new sap.m.Text().bindText(tableColumns.value[indexForColumn], fnCellValue(indexForColumn), sap.ui.model.BindingMode.OneWay);
columnCells.push(tableCellValues);
}
var columnsWithHeaders = [], columnsWithoutHeaders = [];
var columnNameWithHeaders, columnNameWithoutHeaders;
var indexTableColumn;
for(indexTableColumn = 0; indexTableColumn < tableColumns.name.length; indexTableColumn++) {
columnNameWithHeaders = new sap.m.Column({
header : new sap.m.Text({
text : tableColumns.name[indexTableColumn]
})
});
columnsWithHeaders.push(columnNameWithHeaders);
columnNameWithoutHeaders = new sap.m.Column();
columnsWithoutHeaders.push(columnNameWithoutHeaders);
}
// Table with Headers
oTableWithHeaders = new sap.m.Table({
headerText : oStepTitle,
showNoData : false,
columns : columnsWithHeaders
}).addStyleClass("tableWithHeaders");
// Table without Headers (built to get scroll only on the data part)
oTableWithoutHeaders = new sap.m.Table({
columns : columnsWithoutHeaders,
items : {
path : "/tableData",
template : new sap.m.ColumnListItem({
cells : columnCells
})
},
selectionChange : _drawSelection.bind(self)
});
oTableDataModel.setData({
tableData : aTableData
});
oTableWithHeaders.setModel(oTableDataModel);
oTableWithoutHeaders.setModel(oTableDataModel);
oTableWithoutHeaders.attachUpdateFinished(_drawSelection.bind(self));
var handleConfirm = function(oEvent) {
var param = oEvent.getParameters();
oTableWithoutHeaders.setBusy(true);
skipAction = 0;
self.sortProperty = param.sortItem.getKey();
self.orderby = self.sortOrderIsDescending = param.sortDescending;
topValue = 100;
skip = 0;
var sorter = [];
if (param.sortItem) {
if (isAlternateRepresentation) {
var oTableBinding = oTableWithoutHeaders.getBinding("items");
sorter.push(new sap.ui.model.Sorter(self.sortProperty, self.sortOrderIsDescending));
oTableBinding.sort(sorter);
oTableWithoutHeaders.setBusy(false);
return;
}
self.oApi.updatePath(function(oStep, bStepChanged) {
if (oStep === self.oApi.getActiveStep()) {
oTableDataModel.setData({
tableData : aTableData
});
oTableWithoutHeaders.rerender();
oTableWithoutHeaders.setBusy(false);
}
});
}
};
this.viewSettingsDialog = new sap.m.ViewSettingsDialog({// sort of table using ViewSettingsDialog
confirm : handleConfirm
});
var columnIndex;
for(columnIndex = 0; columnIndex < oTableWithHeaders.getColumns().length; columnIndex++) {
var oItem = new sap.m.ViewSettingsItem({
text : tableColumns.name[columnIndex],
key : tableColumns.value[columnIndex]
});
this.viewSettingsDialog.addSortItem(oItem);
}
var sortItemIndex;
if (this.sortProperty === undefined && this.sortOrderIsDescending === undefined) {// Set default values of radio buttons in view settings dialog
if (this.getParameter().orderby && this.getParameter().orderby.length) {
for(sortItemIndex = 0; sortItemIndex < this.viewSettingsDialog.getSortItems().length; sortItemIndex++) {
if (this.getParameter().orderby[0].property === this.viewSettingsDialog.getSortItems()[sortItemIndex].getKey()) {
this.viewSettingsDialog.setSelectedSortItem(this.viewSettingsDialog.getSortItems()[sortItemIndex]);
this.viewSettingsDialog.setSortDescending(!this.getParameter().orderby[0].ascending);
}
}
} else {
this.viewSettingsDialog.setSelectedSortItem(this.viewSettingsDialog.getSortItems()[0]);// by default set the first value in sort field and sort order
this.viewSettingsDialog.setSortDescending(false);
}
} else {
for(sortItemIndex = 0; sortItemIndex < this.viewSettingsDialog.getSortItems().length; sortItemIndex++) {
if (this.sortProperty === this.viewSettingsDialog.getSortItems()[sortItemIndex].getKey()) {
this.viewSettingsDialog.setSelectedSortItem(this.viewSettingsDialog.getSortItems()[sortItemIndex]);
}
}
this.viewSettingsDialog.setSortDescending(this.sortOrderIsDescending);
var sorter = [];
if (isAlternateRepresentation) {
var oTableBinding = oTableWithoutHeaders.getBinding("items");
sorter.push(new sap.ui.model.Sorter(this.sortProperty, this.sortOrderIsDescending));
oTableBinding.sort(sorter);
}
}
var fieldIndex;
if (this.metadata !== undefined) {// aligning amount fields
for(fieldIndex = 0; fieldIndex < tableColumns.name.length; fieldIndex++) {
var oMetadata = this.metadata.getPropertyMetadata(tableColumns.value[fieldIndex]);
if (oMetadata.unit) {
var amountCol = oTableWithoutHeaders.getColumns()[fieldIndex];
amountCol.setHAlign(sap.ui.core.TextAlign.Right);
}
}
}
var scrollContainer = new sap.m.ScrollContainer({// Scroll container for table without headers(to get vertical scroll on data part used for pagination
content : oTableWithoutHeaders,
height : "480px",
horizontal : false,
vertical : true
}).addStyleClass("tableWithoutHeaders");
var loadMoreLink = new sap.m.Link({
text : "More"
}).addStyleClass("loadMoreLink");
var scrollContainer1 = new sap.m.ScrollContainer({// Scroll container to hold table with headers and scroll container containing table without headers
content : [ oTableWithHeaders, scrollContainer ],
width : chartWidth,
horizontal : true,
vertical : false
}).addStyleClass("scrollContainer");
oTableDataModel.setSizeLimit(10000); // Set the size of data response to 10000 records
oTableWithHeaders.addEventDelegate({//Event delegate to bind pagination action
onAfterRendering : function() {
jQuery(".scrollContainer > div:first-child").css({// For IE-Full width for alternate representation
"display" : "table",
"width" : "inherit"
});
var scrollContainerHeight;
if (this.offsetTop === undefined) {
this.offsetTop = jQuery(".tableWithoutHeaders").offset().top;
}
if (jQuery(".tableWithoutHeaders").offset().top !== this.offsetTop) {// fullscreen
scrollContainerHeight = ((window.innerHeight - jQuery('.tableWithoutHeaders').offset().top)) + "px";
} else {
scrollContainerHeight = ((window.innerHeight - jQuery('.tableWithoutHeaders').offset().top) - (jQuery(".applicationFooter").height()) - 20) + "px";
}
document.querySelector('.tableWithoutHeaders').style.cssText += "height : " + scrollContainerHeight;
var dLoadMoreLink = sap.ui.getCore().getRenderManager().getHTML(loadMoreLink);
sap.ui.Device.orientation.attachHandler(function() {// TODO for height issue on orientation change
scrollContainer1.rerender();
});
var oActiveStep = self.oApi.getActiveStep();
if (oActiveStep.getSelectedRepresentation().bIsAlternateView === undefined || oActiveStep.getSelectedRepresentation().bIsAlternateView === false) {// Check if alternate representation else don't paginate
if (sap.ui.Device.browser.mobile) {
if (aTableData.length > 0) {// Add More Button for Mobile Device for
jQuery(jQuery(".tableWithoutHeaders > div:first-child")).append(dLoadMoreLink);
}
loadMoreLink.attachPress(function() {
if (!jQuery(".openToggleImage").length && (aTableData.length > 0)) {
if (eventsFired === 0) {
triggerPagination();
skipAction = 0;
eventsFired++;
jQuery(".loadMoreLink").remove();
jQuery(jQuery(".tableWithoutHeaders > div:first-child")).append(dLoadMoreLink);
}
} else {
jQuery(".loadMoreLink").remove();
}
});
} else {
jQuery('.tableWithoutHeaders').on("scroll", function() {// Mouse scroll, Mouse Down and Mouse Up Events for desktop
var self = jQuery(this);
var scrollTop = self.prop("scrollTop");
var scrollHeight = self.prop("scrollHeight");
var offsetHeight = self.prop("offsetHeight");
var contentHeight = scrollHeight - offsetHeight - 5;
if ((contentHeight <= scrollTop) && !jQuery(".openToggleImage").length && (aTableData.length > 0)) {
if (eventsFired === 0) {
triggerPagination();
skipAction = 0;
eventsFired++;
}
}
});
}
}
var triggerPagination = function() {
oTableWithoutHeaders.setBusy(true);
sap.ui.getCore().applyChanges();
var oData = oTableDataModel.getData();
skip = oData.tableData.length; // already fetched data should be skipped
topValue = 10;
triggerBool = true;
self.oApi.updatePath(function(oStep, bStepChanged) {
if (oStep === self.oApi.getActiveStep()) {
oTableDataModel.setData(oData);
oTableWithoutHeaders.rerender();
oTableWithoutHeaders.setBusy(false);
eventsFired = 0;
}
});
};
}
});
return new sap.ui.layout.VerticalLayout({
content : [ scrollContainer1 ]
});
};
/**
* @method getThumbnailContent
* @description draws Thumbnail for the current chart and returns to the calling object
* @returns thumbnail object for column
*/
sap.apf.ui.representations.table.prototype.getThumbnailContent = function() {
var oThumbnailContent;
if (this.aDataResponse !== undefined && this.aDataResponse.length !== 0) {
var image = new sap.ui.core.Icon({
src : "sap-icon://table-chart",
size : "70px"
}).addStyleClass('thumbnailTableImage');
oThumbnailContent = image;
} else {
var noDataText = new sap.m.Text({
text : this.oApi.getTextNotHtmlEncoded("noDataText")
}).addStyleClass('noDataText');
oThumbnailContent = new sap.ui.layout.VerticalLayout({
content : noDataText
});
}
return oThumbnailContent;
};
/**
* @method removeAllSelection
* @description removes all Selection from Chart
*/
sap.apf.ui.representations.table.prototype.removeAllSelection = function() {
_clearFilters(this);
aFilters = [];//clear the filters
oTableWithoutHeaders.removeSelections();
this.oApi.getActiveStep().getSelectedRepresentation().UI5ChartHelper.filterValues = []; // reset the filter values from table to the selected representation
this.oApi.selectionChanged();
};
/**
* @method getPrintContent
* @param oStepTitle
* title of the step
* @description gets the printable content of the representation
*/
sap.apf.ui.representations.table.prototype.getPrintContent = function(oStepTitle) {
var self = this;
this.createDataset();
var oPrintTableModel = new sap.ui.model.json.JSONModel();
oPrintTableModel.setData({
tableData : aTableData
});
var i;
var columns = [];
for(i = 0; i < tableColumns.name.length; i++) {
this.columnName = new sap.m.Column({
width : "75px",
header : new sap.m.Label({
text : tableColumns.name[i]
})
});
columns.push(this.columnName);
}
var columnCells = [];
var fnColumnValue = function(index) {
return function(columnValue) {
if (self.metadata === undefined) {
return columnValue;
} else {
var oMetadata = self.metadata.getPropertyMetadata(tableColumns.value[index]);
if (oMetadata.dataType.type === "Edm.DateTime") {
if (columnValue === null) {
return "-";
}
var dateFormat = new Date(parseInt(columnValue.slice(6, columnValue.length - 2), 10));
dateFormat = dateFormat.toLocaleDateString();
if (dateFormat === "Invalid Date") {
return "-";
}
return dateFormat;
}
if (oMetadata.unit) {
if (columnValue === null) {
return "-";
}
var currencyMetadata = self.metadata.getPropertyMetadata(oMetadata.unit);
if (currencyMetadata.semantics === "currency-code") {
var precision = aTableData[0][oMetadata.scale];
columnValue = parseFloat(columnValue, 10).toFixed(precision).toString();
var store = columnValue.split(".");
var amountValue = parseFloat(store[0]).toLocaleString();
var sample = 0.1;
sample = sample.toLocaleString();
if (amountValue.split(sample.substring(1, 2)).length > 1) {
amountValue = amountValue.split(sample.substring(1, 2))[0];
}
amountValue = amountValue.concat(sample.substring(1, 2), store[1]);
return amountValue;
}
} else {
return columnValue;
}
}
};
};
var tableCellValues;
for(i = 0; i < tableColumns.name.length; i++) {
tableCellValues = new sap.m.Text().bindText(tableColumns.value[i], fnColumnValue(i), sap.ui.model.BindingMode.OneWay);
columnCells.push(tableCellValues);
}
oPrintTable = new sap.m.Table({
headerText : oStepTitle,
headerDesign : sap.m.ListHeaderDesign.Standard,
columns : columns,
items : {
path : "/tableData",
template : new sap.m.ColumnListItem({
cells : columnCells
})
}
});
if (this.metadata !== undefined) {// aligning amount fields
for(i = 0; i < tableColumns.name.length; i++) {
var oMetadata = this.metadata.getPropertyMetadata(tableColumns.value[i]);
if (oMetadata.unit) {
var amountCol = oPrintTable.getColumns()[i];
amountCol.setHAlign(sap.ui.core.TextAlign.Right);
}
}
}
oPrintTable.setModel(oPrintTableModel);
var aSelectedListItems = _drawSelectionForPrint(this);// set the selections on table
return {
oTableForPrint : new sap.ui.layout.VerticalLayout({
content : [ oPrintTable ]
}),
aSelectedListItems : aSelectedListItems
};
};
}());<file_sep>/*
* ! SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.ui.comp.navpopover.NavigationPopover.
sap.ui.define([
'jquery.sap.global', 'sap/m/CustomListItem', 'sap/m/Link', 'sap/m/Popover', 'sap/ui/core/Title', 'sap/ui/layout/form/SimpleForm', 'sap/m/VBox', 'sap/m/PopoverRenderer'
], function(jQuery, CustomListItem, Link, Popover, Title, SimpleForm, VBox, PopoverRenderer) {
"use strict";
/**
* Constructor for a new navpopover/NavigationPopover.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
* @class The NavigationPopover allows navigating to different destinations by providing links on a popover.<br>
* The links are fetched using the {@link sap.ushell.services.CrossApplicationNavigation CrossApplicationNavigation} service of the unified
* shell.<br>
* This class gets instantiated by {@link sap.ui.comp.navpopover.SmartLink SmartLink}. It is recommended to use
* {@link sap.ui.comp.navpopover.SmartLink SmartLink} instead of creating NavigationPopover manually.
* @extends sap.m.Popover
* @constructor
* @public
* @alias sap.ui.comp.navpopover.NavigationPopover
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var NavigationPopover = Popover.extend("sap.ui.comp.navpopover.NavigationPopover", /** @lends sap.ui.comp.navpopover.NavigationPopover.prototype */
{
metadata: {
library: "sap.ui.comp",
properties: {
/**
* popover title
*
* @since 1.28.0
*/
title: {
type: "string",
group: "Misc",
defaultValue: null
},
/**
* the name of the semantic object
*
* @since 1.28.0
*/
semanticObjectName: {
type: "string",
group: "Misc",
defaultValue: null
},
/**
* describes the semantic attributes. The attribute has to be a map
*
* @since 1.28.0
*/
semanticAttributes: {
type: "object",
group: "Misc",
defaultValue: null
},
/**
* The application state key passed to retrieve the navigation targets.
*
* @since 1.28.0
*/
appStateKey: {
type: "string",
group: "Misc",
defaultValue: null
},
/**
* Sets the visible text for the main navigation. If empty, the navigationPopover will try to get the Id from the given sourceObject.
*/
mainNavigationId: {
type: "string",
group: "Misc",
defaultValue: null
}
},
aggregations: {
/**
* A list of available actions shown to the user.
*
* @since 1.28.0
*/
availableActions: {
type: "sap.ui.comp.navpopover.LinkData",
multiple: true,
singularName: "availableAction"
},
/**
* The main navigation displayed first on the popover.
*
* @since 1.28.0
*/
mainNavigation: {
type: "sap.ui.comp.navpopover.LinkData",
multiple: false
},
/**
* The navigation taking the user back to the source application.
*
* @since 1.28.0
*/
ownNavigation: {
type: "sap.ui.comp.navpopover.LinkData",
multiple: false
}
},
associations: {
/**
* Source control for which the popover is displayed.
*
* @since 1.28.0
*/
source: {
type: "sap.ui.core.Control",
multiple: false
},
/**
* ExtraContent is displayed between the main navigation and the additional available links.
*
* @since 1.28.0
*/
extraContent: {
type: "sap.ui.core.Control",
multiple: false
},
/**
* The parent component.
*/
component: {
type: "sap.ui.core.Element",
multiple: false
}
},
events: {
/**
* The navigation targets that are shown.
*
* @since 1.28.0
*/
targetsObtained: {},
/**
* Event is triggered when a link is pressed.
*
* @since 1.28.0
*/
navigate: {}
}
},
renderer: PopoverRenderer.render
});
NavigationPopover.prototype.init = function() {
Popover.prototype.init.call(this);
this.addStyleClass("navigationPopover");
this.setContentWidth("380px");
this.setHorizontalScrolling(false);
this.setPlacement(sap.m.PlacementType.Auto);
this._oHeaderForm = new SimpleForm({
maxContainerCols: 1,
visible: true
});
this._oMainNavigationText = new Title();
this._oMainNavigationLink = new Link();
this._oMainNavigationLink.attachPress(jQuery.proxy(this._onLinkPress, this));
this._oHeaderForm.addContent(this._oMainNavigationText);
this._oHeaderForm.addContent(this._oMainNavigationLink);
this._oForm = new SimpleForm({
maxContainerCols: 1,
visible: false
});
this._oNavigationLinkContainer = new VBox();
this._oForm.addContent(new Title({
text: sap.ui.getCore().getLibraryResourceBundle("sap.ui.comp").getText("POPOVER_LINKLIST_TEXT")
}));
this._oForm.addContent(this._oNavigationLinkContainer);
this.addContent(this._oHeaderForm);
this.addContent(this._oForm);
};
NavigationPopover.prototype.addAvailableAction = function(oLinkData) {
this.addAggregation("availableActions", oLinkData);
};
NavigationPopover.prototype._getSemanticObjectValue = function() {
var oSemanticAttributes = this.getSemanticAttributes();
if (oSemanticAttributes) {
var sSemanticalObject = this.getSemanticObjectName();
return oSemanticAttributes[sSemanticalObject];
}
return null;
};
/**
* creates the link controls and sets them into the popover's content
*
* @private
*/
NavigationPopover.prototype._createLinks = function() {
var i;
var oLink;
var sValue;
var sHref;
var oLinkData;
var oComponent = this._getComponent();
var oXApplNavigation = this._getNavigationService();
this._oNavigationLinkContainer.removeAllItems();
sValue = this.getMainNavigationId();
if (!sValue) {
var oSmartLink = this._getSourceControl();
if (oSmartLink) {
if (oSmartLink.getSemanticObjectValue) {
sValue = oSmartLink.getSemanticObjectValue();
} else {
sValue = this._getSemanticObjectValue();
}
}
}
this._oMainNavigationText.setText(sValue);
var oMainNav = this.getMainNavigation();
if (oMainNav) {
sHref = oMainNav.getHref();
if (sHref) {
this._oHeaderForm.removeStyleClass("navpopoversmallheader");
this._oMainNavigationLink.setText(oMainNav.getText());
if (oXApplNavigation) {
sHref = oXApplNavigation.hrefForExternal({
target: {
shellHash: sHref
}
}, oComponent);
}
this._oMainNavigationLink.setHref(sHref);
this._oMainNavigationLink.setTarget(oMainNav.getTarget());
this._oMainNavigationLink.setVisible(true);
} else {
this._oHeaderForm.addStyleClass("navpopoversmallheader");
this._oMainNavigationLink.setText("");
this._oMainNavigationLink.setVisible(false);
}
}
var aActions = this.getAvailableActions();
if (aActions) {
for (i = 0; i < aActions.length; i++) {
oLink = new Link();
oLinkData = aActions[i];
if (oLinkData) {
oLink.setText(oLinkData.getText());
oLink.attachPress(jQuery.proxy(this._onLinkPress, this));
sHref = oLinkData.getHref();
if (oXApplNavigation && sHref) {
sHref = oXApplNavigation.hrefForExternal({
target: {
shellHash: sHref
}
}, oComponent);
}
oLink.setHref(sHref);
oLink.setTarget(oLinkData.getTarget());
}
this._oNavigationLinkContainer.addItem(oLink);
}
}
this._setListVisibility();
};
NavigationPopover.prototype.insertAvailableAction = function(oLinkData, iIndex) {
this.insertAggregation("availableActions", oLinkData, iIndex);
};
NavigationPopover.prototype.removeAvailableAction = function(oLinkData) {
var iIndexOfRemovedItem;
if (typeof (oLinkData) === "number") { // oLinkData can also be an index to be removed
iIndexOfRemovedItem = oLinkData;
} else {
iIndexOfRemovedItem = this.getAvailableActions().indexOf(oLinkData);
}
if (iIndexOfRemovedItem >= 0) {
this._oNavigationLinkContainer.removeItem(iIndexOfRemovedItem);
}
var oReturnValue = this.removeAggregation("availableActions", oLinkData);
this._setListVisibility();
return oReturnValue;
};
NavigationPopover.prototype.removeAllAvailableActions = function() {
this._oNavigationLinkContainer.removeAllItems();
this.removeAllAggregation("availableActions");
this._setListVisibility();
};
/**
* sets the visibility of the link list depending on the number of available links (0 = invisible)
*
* @private
*/
NavigationPopover.prototype._setListVisibility = function() {
var iAvailableActions = this.getAvailableActions().length;
this._oForm.setVisible(iAvailableActions > 0);
};
/**
* EventHandler for all link press on this popover
*
* @param {object} oEvent - the event parameters
* @private
*/
NavigationPopover.prototype._onLinkPress = function(oEvent) {
var oSource = oEvent.getSource();
this.fireNavigate({
text: oSource.getText(),
href: oSource.getHref()
});
};
NavigationPopover.prototype.setSemanticObjectName = function(sSemanticalObject) {
this.setProperty("semanticObjectName", sSemanticalObject);
this.removeAllAvailableActions();
this.setMainNavigation(null);
};
/**
* retrieve the navigation service
*
* @private
* @returns {object} the navigation service
*/
NavigationPopover.prototype._getNavigationService = function() {
return sap.ushell && sap.ushell.Container && sap.ushell.Container.getService("CrossApplicationNavigation");
};
/**
* retrieve the url service
*
* @private
* @returns {object} the url service
*/
NavigationPopover.prototype._getUrlService = function() {
return sap.ushell && sap.ushell.Container && sap.ushell.Container.getService("URLParsing");
};
/**
* determines the potential navigation targets for the semantical object and visualize the popover
*
* @public
* @param {string} sSemanticalObject name of the semantical object
*/
NavigationPopover.prototype.retrieveNavTargets = function() {
var sSemanticalObject = this.getSemanticObjectName();
var mSemanticAttributes = this.getSemanticAttributes();
var sAppStateKey = this.getAppStateKey();
this._retrieveNavTargets(sSemanticalObject, mSemanticAttributes, sAppStateKey);
};
/**
* determines the potential navigation targets for the semantical object and visualize the popover
*
* @private
* @param {string} sSemanticalObject name of the semantical object
* @param {map} mSemanticAttributes map of (name, values) pair for to fine-tune the result
* @param {string} sAppStateKey Application state key
*/
NavigationPopover.prototype._retrieveNavTargets = function(sSemanticalObject, mSemanticAttributes, sAppStateKey) {
var that = this;
this.setMainNavigation(null);
this.removeAllAvailableActions();
var oXApplNavigation = this._getNavigationService();
if (!oXApplNavigation) {
jQuery.sap.log.error("Service 'CrossApplicationNavigation' could not be obtained");
// still fire targetsObtained event: easier for testing and the eventhandlers still could provide static links
this.fireTargetsObtained();
return;
}
var bIgnoreFormFactor = false;
var oComponent = this._getComponent();
var oPromise = oXApplNavigation.getSemanticObjectLinks(sSemanticalObject, mSemanticAttributes, bIgnoreFormFactor, oComponent, sAppStateKey);
oPromise.fail(jQuery.proxy(function() {
// Reset actions
jQuery.sap.log.error("'getSemanticObjectLinks' failed");
}, this));
oPromise.done(jQuery.proxy(function(aLinks) {
var i, sId, sText;
var oURLParsing, oShellHash;
var oLinkData;
var bHasFactSheet = false;
if (aLinks && aLinks.length) {
oURLParsing = that._getUrlService();
var sCurrentHash = oXApplNavigation.hrefForExternal();
if (sCurrentHash && sCurrentHash.indexOf("?") !== -1) { // sCurrentHash can contain query string, cut it off!
sCurrentHash = sCurrentHash.split("?")[0];
}
for (i = 0; i < aLinks.length; i++) {
sId = aLinks[i].intent;
sText = aLinks[i].text;
oLinkData = new sap.ui.comp.navpopover.LinkData({
text: sText,
href: sId
});
if (sId.indexOf(sCurrentHash) === 0) {
// Prevent current app from being listed
// NOTE: If the navigation target exists in
// multiple contexts (~XXXX in hash) they will all be skipped
this.setOwnNavigation(oLinkData);
continue;
}
// Check if a FactSheet exists for this SemanticObject (to skip the first one found)
oShellHash = oURLParsing.parseShellHash(sId);
if (oShellHash.action && (oShellHash.action === 'displayFactSheet') && !bHasFactSheet) {
// Prevent this first FactSheet from being listed --> TODO why ?
oLinkData.setText(sap.ui.getCore().getLibraryResourceBundle("sap.ui.comp").getText("POPOVER_FACTSHEET"));
that.setMainNavigation(oLinkData);
bHasFactSheet = true;
} else {
that.addAvailableAction(oLinkData);
}
}
}
that.fireTargetsObtained();
}, this));
};
/**
* returns the component object
*
* @private
* @returns {object} the component
*/
NavigationPopover.prototype._getComponent = function() {
var oComponent = this.getComponent();
if (typeof oComponent === "string") {
oComponent = sap.ui.getCore().getComponent(oComponent);
}
return oComponent;
};
/**
* displays the popover. This method should be called, once all navigation targets are adapted by the application
*
* @public
*/
NavigationPopover.prototype.show = function() {
var oSourceControl = this._getSourceControl();
if (!oSourceControl) {
jQuery.sap.log.error("no source assigned");
return;
}
var oMainNav = this.getMainNavigation();
var aActions = this.getAvailableActions();
if (!(oMainNav && (oMainNav.getHref())) && !(aActions && (aActions.length > 0))) { // if no fact sheet exists and no actions and no extra
// content, then do not show popover
jQuery.sap.log.error("no navigation targets found");
if (!this.getExtraContent()) {
jQuery.sap.log.error("NavigationPopover is empty");
jQuery.sap.require("sap.m.MessageBox");
var MessageBox = sap.ui.require("sap/m/MessageBox");
MessageBox.show(sap.ui.getCore().getLibraryResourceBundle("sap.ui.comp").getText("POPOVER_DETAILS_NAV_NOT_POSSIBLE"), {
icon: MessageBox.Icon.ERROR,
title: sap.ui.getCore().getLibraryResourceBundle("sap.ui.comp").getText("POPOVER_MSG_NAV_NOT_POSSIBLE"),
styleClass: (this.$() && this.$().closest(".sapUiSizeCompact").length) ? "sapUiSizeCompact" : ""
});
return;
}
}
this._createLinks();
this.openBy(oSourceControl);
};
/**
* retrieves the control for which the popover should be displayed
*
* @private
* @returns { sap.ui.core.Control} returns the source control
*/
NavigationPopover.prototype._getSourceControl = function() {
var oSourceControl = null;
var sControlId = this.getSource();
if (sControlId) {
oSourceControl = sap.ui.getCore().byId(sControlId);
}
return oSourceControl;
};
NavigationPopover.prototype.setExtraContent = function(oControl) {
var oOldContent = this.getExtraContent();
if (oOldContent && oControl && oOldContent === oControl.getId()) {
return;
}
if (oOldContent) {
var oOldControl = sap.ui.getCore().byId(oOldContent);
this.removeContent(oOldControl);
}
this.setAssociation("extraContent", oControl);
if (oControl) {
this.insertContent(oControl, 1);
}
};
return NavigationPopover;
}, /* bExport= */true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define(['jquery.sap.global','sap/ui/fl/changeHandler/Base'],function(q,B){"use strict";var R=function(){};R.prototype=q.sap.newObject(B.prototype);R.prototype.applyChange=function(c,f){if(f.getParent){var g=f.getParent();if(g.removeGroupElement){g.removeGroupElement(f);}}else{throw new Error("no GroupElement control provided for removing the field");}};R.prototype.completeChangeContent=function(c,s){var C=c.getDefinition();if(!C.content){C.content={};}};return R;},true);
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
sap.ui.jsview("sap.apf.ui.reuse.view.messageHandler",{initializeHandler:function(m){this.getController().showMessage(m);},getControllerName:function(){return"sap.apf.ui.reuse.controller.messageHandler";},createContent:function(c){jQuery.sap.require("sap.m.MessageToast");jQuery.sap.require("sap.ca.ui.message.message");}});
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2015 SAP SE. All rights reserved
*/
/*global jQuery, sap */
(function() {
'use strict';
jQuery.sap.declare("sap.apf.base.Component");
jQuery.sap.require("sap.ui.core.UIComponent");
jQuery.sap.require("sap.apf.api");
/**
* @public
* @class Base Component for all APF based applications.
* @name sap.apf.base.Component
* @extends sap.ui.core.UIComponent
* @since SAP UI5 1.30.0.
*/
sap.ui.core.UIComponent.extend("sap.apf.base.Component", {
metadata : {
"manifest" : "json",
"publicMethods" : [ "getApi" ]
},
oApi : null,
init : function() {
var baseManifest;
var manifest;
if (!this.oApi) {
baseManifest = sap.apf.base.Component.prototype.getMetadata().getManifest();
manifest = jQuery.extend({}, true, this.getMetadata().getManifest());
this.oApi = new sap.apf.Api(this, undefined, {
manifest : manifest,
baseManifest : baseManifest
});
} else {
return;
}
sap.ui.core.UIComponent.prototype.init.apply(this, arguments);
},
/**
* @public
* @description Creates the content of the component. A component that extends this component shall call this method.
* @function
* @name sap.apf.base.Component.prototype.createContent
* @returns {sap.ui.core.Control} the content
*/
createContent : function() {
sap.ui.core.UIComponent.prototype.createContent.apply(this, arguments);
return this.oApi.startApf();
},
/**
* @public
* @description Cleanup the Component instance. The component that extends this component should call this method.
* @function
* @name sap.apf.base.Component.prototype.exit
*/
exit : function() {
this.oApi.destroy();
},
/**
* @public
* @function
* @name sap.apf.base.Component#getApi
* @description Returns the instance of the APF API.
* @returns {sap.apf.Api}
*/
getApi : function() {
return this.oApi;
}
});
}());
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
jQuery.sap.require("sap.apf.modeler.ui.utils.textPoolHelper");
/**
* @class step
* @memberOf sap.apf.modeler.ui.controller
* @name step
* @description controller for view.step
*/
sap.ui.controller("sap.apf.modeler.ui.controller.step", {
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#onInit
* @description Called on initialization of the view.
* Sets the static texts for all controls in UI.
* Sets the scroll height for the container.
* Adds style classes to all UI controls.
* Prepares dependecies.
* Sets dynamic text for input controls
* */
onInit : function() {
this.getView().addStyleClass("sapUiSizeCompact");//For non touch devices- compact style class increases the information density on the screen by reducing control dimensions
this.oViewData = this.getView().getViewData();
this.getText = this.oViewData.getText;
this.params = this.oViewData.oParams;
this.oConfigurationHandler = this.oViewData.oConfigurationHandler;
this.oConfigurationEditor = this.oViewData.oConfigurationEditor;
this.oTextPool = this.oConfigurationHandler.getTextPool();
this.getNavigationTargetName = this.oViewData.getNavigationTargetName;
var self = this;
if (!this.oConfigurationEditor) {
this.oConfigurationHandler.loadConfiguration(this.params.arguments.configId, function(configurationEditor) {
self.oConfigurationEditor = configurationEditor;
});
}
this.oTextPool = this.oConfigurationHandler.getTextPool();
//this._getDependencies(); //get dependencies from router
this._setDisplayText();
this.setDetailData();
//Set Mandatory Fields
var mandatoryFields = [];
mandatoryFields.push(this.byId("idstepTitle"));
mandatoryFields.push(this.byId("idSourceSelect"));
mandatoryFields.push(this.byId("idSelectPropCombo"));
mandatoryFields.push(this.byId("idCategorySelect"));
mandatoryFields.push(this.byId("idFilterMapEntitySelect")); //filter map entity,select properties and target filter are mandatory when service is selected
mandatoryFields.push(this.byId("idFilterMapTargetFilterCombo"));
mandatoryFields.push(this.byId("idCustomRecordValue"));//mandatory custom value in data record for top N
this._setMandatoryFields(mandatoryFields);
this._attachEvents();
if (this.step.getFilterMappingService() === undefined || this.step.getFilterMappingService() === "") { // if the filter mapping field is not available
this._removeMandatoryFromFilterMap(); //initially filter mapping fields should not be mandatory
}
if (!this.step.getTopN()) { // if the top N is not available
this.byId("idCustomRecordValue").isMandatory = false; // remove input field from mandatory fields
}
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_setDisplayText
* @description Sets static texts in UI
* */
_setDisplayText : function() {
this.byId("idStepBasicData").setTitle(this.getText("stepBasicData"));
this.byId("idStepTitleLabel").setText(this.getText("stepTitle"));
this.byId("idStepTitleLabel").setRequired(true);
this.byId("idstepTitle").setPlaceholder(this.getText("newStep"));
this.byId("idStepLongTitleLabel").setText(this.getText("stepLongTitle"));
this.byId("idstepLongTitle").setPlaceholder(this.getText("stepLongTitle"));
this.byId("idCategoryTitleLabel").setText(this.getText("categoryAssignments"));
this.byId("idCategoryTitleLabel").setRequired(true);
this.byId("idGlobalLabel").setText(this.getText("globalNavTargets"));
this.byId("idStepSpecificLabel").setText(this.getText("stepSpecificNavTargets"));
this.byId("idSourceSelectLabel").setText(this.getText("source"));
this.byId("idSourceSelectLabel").setRequired(true);
this.byId("idEntitySelectLabel").setText(this.getText("entity"));
this.byId("idEntitySelectLabel").setRequired(true);
this.byId("idSelectPropComboLabel").setText(this.getText("selectProperties"));
this.byId("idSelectPropComboLabel").setRequired(true);
this.byId("idReqFilterSelectLabel").setText(this.getText("requiredFilters"));
this.byId("idDataRequest").setTitle(this.getText("dataRequest"));
this.byId("idNavigationTarget").setTitle(this.getText("navigationTargetAssignment"));
this.byId("idCornerTextLabel").setTitle(this.getText("cornerTextLabel"));
this.byId("idLeftTop").setPlaceholder(this.getText("leftTop"));
this.byId("idRightTop").setPlaceholder(this.getText("rightTop"));
this.byId("idLeftBottom").setPlaceholder(this.getText("leftBottom"));
this.byId("idRightBottom").setPlaceholder(this.getText("rightBottom"));
//Data Reduction labels
this.byId("idDataReduction").setTitle(this.getText("dataReduction"));
this.byId("idDataReductionLabel").setText(this.getText("dataReductionType"));
this.byId("idNoDataReduction").setText(this.getText("noDataReduction"));
this.byId("idTopN").setText(this.getText("topN"));
this.byId("idDataRecordsLabel").setText(this.getText("recordNumber"));
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_addAutoCompleteFeatureOnInputs
* @description Adds 'Auto Complete Feature' to the input fields in the view
* using sap.apf.modeler.ui.utils.TextPoolHelper.
* */
_addAutoCompleteFeatureOnInputs : function() {
if (this.oConfigurationHandler) {
var oTextPoolHelper = new sap.apf.modeler.ui.utils.TextPoolHelper(this.oTextPool);
var oStepTitleControl = this.byId("idstepTitle");
var oTranslationFormatForStepTitle = sap.apf.modeler.ui.utils.TranslationFormatMap.STEP_TITLE;
var oDependenciesForStepTitle = {
oTranslationFormat : oTranslationFormatForStepTitle,
type : "text"
};
oTextPoolHelper.setAutoCompleteOn(oStepTitleControl, oDependenciesForStepTitle);
var oStepLongTitleControl = this.byId("idstepLongTitle");
var oTranslationFormatForStepLongTitle = sap.apf.modeler.ui.utils.TranslationFormatMap.STEP_LONG_TITLE;
var oDependenciesForStepLongTitle = {
oTranslationFormat : oTranslationFormatForStepLongTitle,
type : "text"
};
oTextPoolHelper.setAutoCompleteOn(oStepLongTitleControl, oDependenciesForStepLongTitle);
var oStepLeftTop = this.byId("idLeftTop");
var oStepRightTop = this.byId("idRightTop");
var oStepLeftBottom = this.byId("idLeftBottom");
var oStepRightBottom = this.byId("idRightBottom");
var oTranslationFormatForStepCornerText = sap.apf.modeler.ui.utils.TranslationFormatMap.STEP_CORNER_TEXT;
var oDependenciesForStepCornerText = {
oTranslationFormat : oTranslationFormatForStepCornerText,
type : "text"
};
oTextPoolHelper.setAutoCompleteOn(oStepLeftTop, oDependenciesForStepCornerText);
oTextPoolHelper.setAutoCompleteOn(oStepRightTop, oDependenciesForStepCornerText);
oTextPoolHelper.setAutoCompleteOn(oStepLeftBottom, oDependenciesForStepCornerText);
oTextPoolHelper.setAutoCompleteOn(oStepRightBottom, oDependenciesForStepCornerText);
//autocomplete for source
var oDependenciesForService = {
oConfigurationEditor : this.oConfigurationEditor,
type : "service"
};
var oSource = this.byId("idSourceSelect");
oTextPoolHelper.setAutoCompleteOn(oSource, oDependenciesForService);
var oSourceForFilterMapping = this.byId("idFilterMapSourceSelect");
oTextPoolHelper.setAutoCompleteOn(oSourceForFilterMapping, oDependenciesForService);
}
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_prepareStepSpecificList
* @description Prepares the model for step specific targets and sets the step specific targets
* */
_prepareStepSpecificList : function() {
var self = this;
var aModifiedStepSpecificTargets = [];
var aAllNavTarget = this.oConfigurationEditor.getNavigationTargets();//Get all the navigation targets in a configuration
var aStepSpecificNavTargets = this.step.getNavigationTargets();//Get all the navigation targets assigned to the current step
var aAllStepSpecificNavTargets = aAllNavTarget.filter(function(oNavTarget) {//Filter aAllNavTarget to get only step specific navigation targets
return oNavTarget.isStepSpecific();
});
//If configuration has step specific navigation targets set a busy indicator on the control until texts are read
if (aAllStepSpecificNavTargets.length !== 0) {
this.byId("idStepSpecificCombo").setBusy(true);
}
aAllStepSpecificNavTargets.forEach(function(oStepSpecificNavTarget) {
var oNavTarget = {};
oNavTarget.navTargetKey = oStepSpecificNavTarget.getId();
self.getNavigationTargetName(oStepSpecificNavTarget.getId()).then(function(value) {
oNavTarget.navTargetName = value;
aModifiedStepSpecificTargets.push(oNavTarget);//Push modified step specific target into array
if (aModifiedStepSpecificTargets.length === aAllStepSpecificNavTargets.length) {
var stepSpecificModel = new sap.ui.model.json.JSONModel();
var oStepSpecificData = {
stepSpecific : aModifiedStepSpecificTargets
};
stepSpecificModel.setData(oStepSpecificData);
self.byId("idStepSpecificCombo").setModel(stepSpecificModel);
self.byId("idStepSpecificCombo").setSelectedKeys(aStepSpecificNavTargets);//Set navigation targets assigned to the step as selected
//Remove busy indicator once the model is set on the control
self.byId("idStepSpecificCombo").setBusy(false);
}
});
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_prepareGlobalList
* @description Prepares the model for global targets and sets the global targets
* */
_prepareGlobalList : function() {
var self = this;
var aModifiedGlobalTargets = [];
var aAllNavTarget = this.oConfigurationEditor.getNavigationTargets();//Get all the navigation targets in a configuration
var aGlobalNavTargets = aAllNavTarget.filter(function(oNavTarget) {//Filter aAllNavTarget to get only global navigation targets
return oNavTarget.isGlobal();
});
//If configuration has global navigation targets set a busy indicator on the control until texts are read
if (aGlobalNavTargets.length !== 0) {
this.byId("idGlobalCombo").setBusy(true);
}
aGlobalNavTargets = aGlobalNavTargets.map(function(oGlobalNavTarget) {
return oGlobalNavTarget.getId();
});
aGlobalNavTargets.forEach(function(oGlobalTarget) {
var oGlobalNavTarget = {};
oGlobalNavTarget.navTargetKey = oGlobalTarget;
self.getNavigationTargetName(oGlobalTarget).then(function(value) {
oGlobalNavTarget.navTargetName = value;
aModifiedGlobalTargets.push(oGlobalNavTarget);//Push modified global target into array
if (aModifiedGlobalTargets.length === aGlobalNavTargets.length) {
var globalModel = new sap.ui.model.json.JSONModel();
var oGlobalData = {
global : aModifiedGlobalTargets
};
globalModel.setData(oGlobalData);
self.byId("idGlobalCombo").setModel(globalModel);
self.byId("idGlobalCombo").setSelectedKeys(aGlobalNavTargets);//Set all global targets as selected
//Remove busy indicator once the model is set on the control
self.byId("idGlobalCombo").setBusy(false);
}
});
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#setDetailData
* @description Sets dynamic texts for controls
* */
setDetailData : function() {
var self = this;
if (this.params && this.params.arguments && this.params.arguments.stepId) {
this.step = this.oConfigurationEditor.getStep(this.params.arguments.stepId);
}
var Categories = [];
this.oTextPool = this.oConfigurationHandler.getTextPool();
var aAllCategories = this.oConfigurationEditor.getCategories();
aAllCategories.forEach(function(oCategory) {
var oCatOb = {};
oCatOb.CategoryId = oCategory.getId();
oCatOb.CategoryTitle = self.oTextPool.get(oCategory.labelKey) ? self.oTextPool.get(oCategory.labelKey).TextElementDescription : oCategory.labelKey;
Categories.push(oCatOb);
});
var oData = {
Categories : Categories
};
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(oData);
this.byId("idCategorySelect").setModel(oModel);
var oProp = {
propertyKey : this.getText("none"),
propertyName : this.getText("none")
};
var oDataForPropertiesSel = {
Properties : [ oProp ]
};
var oModelForSelectables = new sap.ui.model.json.JSONModel();
oModelForSelectables.setSizeLimit(500);
oModelForSelectables.setData(oDataForPropertiesSel);
this.byId("idReqFilterSelect").setModel(oModelForSelectables);
var aSelectPropertiesForTargetFilter = [];
var oSelectedPropertiesForTargetFilter = this.byId("idFilterMapTargetFilterCombo") ? this.byId("idFilterMapTargetFilterCombo").getSelectedKeys() : [];
oSelectedPropertiesForTargetFilter.forEach(function(property) { //selected properties from the combo box
var oProp = {};
oProp.propertyKey = property;
oProp.propertyName = property;
aSelectPropertiesForTargetFilter.push(oProp);
});
var oModelForTargetFilter = new sap.ui.model.json.JSONModel();
oModelForTargetFilter.setSizeLimit(500);
oModelForTargetFilter.setData(aSelectPropertiesForTargetFilter);
//all the selected properties will be displayed in the target filter property dropdown, none will not be displayed as one property has to be selected
this.byId("idFilterMapTargetFilterCombo").setModel(oModelForTargetFilter);
if (this.step) { //for existing step
var sNone = this.getText("none");
var noneProperties = [ sNone ];
//Setting the value for title for a step
if (this.step.getTitleId && this.step.getTitleId() !== undefined && this.step.getTitleId() !== null && self.oTextPool.get(this.step.getTitleId())) {
this.byId("idstepTitle").setValue(self.oTextPool.get(this.step.getTitleId()).TextElementDescription);
} else {
this.byId("idstepTitle").setValue(this.params.arguments.stepId);
}
//Setting the value for long title for a step
if (this.step.getLongTitleId && this.step.getLongTitleId() !== undefined && this.step.getLongTitleId() !== null && self.oTextPool.get(this.step.getLongTitleId())) {
this.byId("idstepLongTitle").setValue(self.oTextPool.get(this.step.getLongTitleId()).TextElementDescription);
} else {
this.byId("idstepLongTitle").setValue("");
}
//Setting the value for data source for a step
if (this.step.getService && this.step.getService() !== undefined && this.step.getService() !== null) {
this.byId("idSourceSelect").setValue(this.step.getService());
var sSource = this.step.getService();
var aAllEntitySets = [];
var aAllEntitySetsForControll = [];
aAllEntitySets = this.oConfigurationEditor.getAllEntitySetsOfService(sSource);
aAllEntitySets.forEach(function(entiset) {
var oEntitySet = {};
oEntitySet.entityKey = entiset;
oEntitySet.entityName = entiset;
aAllEntitySetsForControll.push(oEntitySet);
});
var oDataForEntitySets = {
Entities : aAllEntitySetsForControll
};
var oModelForEntitySet = new sap.ui.model.json.JSONModel();
oModelForEntitySet.setSizeLimit(500);
oModelForEntitySet.setData(oDataForEntitySets);
this.byId("idEntitySelect").setModel(oModelForEntitySet);
}
//Setting the value for entity sets for a step
if (this.step.getEntitySet && this.step.getEntitySet() !== undefined && this.step.getEntitySet() !== null) {
this.byId("idEntitySelect").setSelectedKey(this.step.getEntitySet());
var sEntity = this.step.getEntitySet();
var sServiceRoot = this.step.getService();
var aProperties = [], aPropertiesForControl = [];
if (sServiceRoot && sServiceRoot !== null && sServiceRoot !== "") {
aProperties = this.oConfigurationEditor.getAllPropertiesOfEntitySet(sServiceRoot, sEntity);
aProperties.forEach(function(property) {
var oProp = {};
oProp.propertyKey = property;
oProp.propertyName = property;
aPropertiesForControl.push(oProp);
});
var oDataForProperties = {
Properties : aPropertiesForControl
};
var oModelForSelProp = new sap.ui.model.json.JSONModel();
oModelForSelProp.setSizeLimit(500);
oModelForSelProp.setData(oDataForProperties);
this.byId("idSelectPropCombo").setModel(oModelForSelProp);
}
}
//Setting the value for select properties for a step
if (this.step.getSelectProperties && this.step.getSelectProperties() !== undefined && this.step.getSelectProperties().length !== 0) {
this.byId("idSelectPropCombo").setSelectedKeys(this.step.getSelectProperties());
aProperties = noneProperties.concat(this.step.getSelectProperties());
aPropertiesForControl = [];
aProperties.forEach(function(property) {
var oProp = {};
oProp.propertyKey = property;
oProp.propertyName = property;
aPropertiesForControl.push(oProp);
});
oDataForPropertiesSel = {
Properties : aPropertiesForControl
};
oModelForSelectables = new sap.ui.model.json.JSONModel();
oModelForSelectables.setSizeLimit(500);
oModelForSelectables.setData(oDataForPropertiesSel);
this.byId("idReqFilterSelect").setModel(oModelForSelectables);
}
//Setting the value for required filter for a step
if (this.step.getFilterProperties && this.step.getFilterProperties() !== undefined && this.step.getFilterProperties().length !== 0) {
this.byId("idReqFilterSelect").setSelectedKey(this.step.getFilterProperties()[0]);
this._showFilterMappingField();
} else {
this.byId("idReqFilterSelect").setSelectedKey(this.getText("none"));
this._hideFilterMapField();// Hides filter mapping fields
this._resetFilterMappingFields();//reset the values from the filter mapping properties and clears the selected keys in control
}
this._setTopNValue();//set the top N values
//Setting the value for data source for filter mapping of a step
if (this.step.getFilterMappingService && this.step.getFilterMappingService() !== undefined && this.step.getFilterMappingService().length !== 0) {
this.byId("idFilterMapSourceSelect").setValue(this.step.getFilterMappingService());
var sFilterMapSource = this.step.getFilterMappingService();
var aFilterMapAllEntitySets = [];
var aFilterMapAllEntitySetsForControl = [];
var aRequiredProperties = this.step.getFilterProperties();
aFilterMapAllEntitySets = this.oConfigurationEditor.getAllEntitySetsOfServiceWithGivenProperties(sFilterMapSource, aRequiredProperties);
aFilterMapAllEntitySets.forEach(function(entity) {
var oEntitySetFilterMap = {};
oEntitySetFilterMap.entityKey = entity;
oEntitySetFilterMap.entityName = entity;
aFilterMapAllEntitySetsForControl.push(oEntitySetFilterMap);
});
var oDataForFilterMapEntitySets = {
Entities : aFilterMapAllEntitySetsForControl
};
var oModelForFilterMapEntitySet = new sap.ui.model.json.JSONModel();
oModelForFilterMapEntitySet.setSizeLimit(500);
oModelForFilterMapEntitySet.setData(oDataForFilterMapEntitySets);
this.byId("idFilterMapEntitySelect").setModel(oModelForFilterMapEntitySet);
this._addMandatoryfromFilterMap(); //valid service selected, make other fields in filter mapping mandatory
} else {// if the service was not saved then reset the filter mapping fields
this._removeMandatoryFromFilterMap(); // removes the mandatory tag
this._resetFilterMappingFields();//reset the values from the filter mapping properties and clears the selected keys in control
}
//Setting the value for entity sets for filter mapping of a step
if (this.step.getFilterMappingEntitySet && this.step.getFilterMappingEntitySet() !== undefined && this.step.getFilterMappingEntitySet().length !== 0) {
this.byId("idFilterMapEntitySelect").setSelectedKey(this.step.getFilterMappingEntitySet());
var sFilterMapEntity = this.step.getFilterMappingEntitySet();
var sFilterMapServiceRoot = this.step.getFilterMappingService();
var aFilterMapProperties = [], aPropertiesForFilterMapControl = [];
if (sFilterMapServiceRoot && sFilterMapServiceRoot !== null && sFilterMapServiceRoot !== "") {
aFilterMapProperties = this.oConfigurationEditor.getAllPropertiesOfEntitySet(sFilterMapServiceRoot, sFilterMapEntity);
aFilterMapProperties.forEach(function(property) {
var oProp = {};
oProp.propertyKey = property;
oProp.propertyName = property;
aPropertiesForFilterMapControl.push(oProp);
});
var oDataForFilterMapProperties = {
Properties : aPropertiesForFilterMapControl
};
var oModelForFilterMapSelProp = new sap.ui.model.json.JSONModel();
oModelForFilterMapSelProp.setSizeLimit(500);
oModelForFilterMapSelProp.setData(oDataForFilterMapProperties);
this.byId("idFilterMapTargetFilterCombo").setModel(oModelForFilterMapSelProp);
}
}
//Setting the value for target property for filter mapping of a step
if (this.step.getFilterMappingTargetProperties && this.step.getFilterMappingTargetProperties() !== undefined && this.step.getFilterMappingTargetProperties().length !== 0) {
this.byId("idFilterMapTargetFilterCombo").setSelectedKeys(this.step.getFilterMappingTargetProperties());
}
//Setting the value for keep source checkbox for filter mapping of a step
if (this.step.getFilterMappingKeepSource && this.step.getFilterMappingKeepSource() !== undefined) {
this.byId("idFilterKeepSourceCheckBox").setSelected(this.step.getFilterMappingKeepSource());
}
//Setting the value of categories of a step
var aSelectedCategories = self.oConfigurationEditor.getCategoriesForStep(this.step.getId());
if (aSelectedCategories && aSelectedCategories.length !== 0) {
this.byId("idCategorySelect").setSelectedKeys(aSelectedCategories);
}
//Setting the value of left lower corner text of a step
if (this.step.getLeftLowerCornerTextKey() && self.oTextPool.get(this.step.getLeftLowerCornerTextKey())) {
this.byId("idLeftBottom").setValue(self.oTextPool.get(this.step.getLeftLowerCornerTextKey()).TextElementDescription);
} else {
this.byId("idLeftBottom").setValue(this.step.getLeftLowerCornerTextKey());
}
//Setting the value of left upper corner text of a step
if (this.step.getLeftUpperCornerTextKey() && self.oTextPool.get(this.step.getLeftUpperCornerTextKey())) {
this.byId("idLeftTop").setValue(self.oTextPool.get(this.step.getLeftUpperCornerTextKey()).TextElementDescription);
} else {
this.byId("idLeftTop").setValue(this.step.getLeftUpperCornerTextKey());
}
//Setting the value of right upper corner text of a step
if (this.step.getRightUpperCornerTextKey() && self.oTextPool.get(this.step.getRightUpperCornerTextKey())) {
this.byId("idRightTop").setValue(self.oTextPool.get(this.step.getRightUpperCornerTextKey()).TextElementDescription);
} else {
this.byId("idRightTop").setValue(this.step.getRightUpperCornerTextKey());
}
//Setting the value of right lower corner text of a step
if (this.step.getRightLowerCornerTextKey() && self.oTextPool.get(this.step.getRightLowerCornerTextKey())) {
this.byId("idRightBottom").setValue(self.oTextPool.get(this.step.getRightLowerCornerTextKey()).TextElementDescription);
} else {
this.byId("idRightBottom").setValue(this.step.getRightLowerCornerTextKey());
}
} else { //for new step
this._changeVisibilityDataReductionField(false);// Hide the data reduction as well for new step
this._changeVisibilityOfTopN(false);//hide the top N fields for new step
this._hideFilterMapField();//hide the filter mapping fields for new step
var sCategoryId = this.params.arguments.categoryId;
var sStepId = self.oConfigurationEditor.createStep(sCategoryId);
this.step = self.oConfigurationEditor.getStep(sStepId);
var selectedCategory = [ sCategoryId ];
this.byId("idCategorySelect").setSelectedKeys(selectedCategory);
var stepInfo = {
id : sStepId,
icon : "sap-icon://BusinessSuiteInAppSymbols/icon-phase"
};
this.oViewData.updateSelectedNode(stepInfo);
}
this._addAutoCompleteFeatureOnInputs();
this._prepareGlobalList();
this._prepareStepSpecificList();
},
_setTopNValue : function() {
//Setting the "Top N" to the step
this._setSortDataForStep();
var hasTopNValue; //boolean to check if the Top N settings are available
if (this.step.getTopN()) { //if the top N is set on the step
hasTopNValue = true;
var nDataRecod = this.step.getTopN().top;
this.byId("idDataReductionRadioGroup").setSelectedButton(this.byId("idDataReductionRadioGroup").getButtons()[1]); //select the "Top N" radio button and show the top N fields
this.byId("idCustomRecordValue").setValue(nDataRecod); //set the value on the input field
} else {
this.byId("idDataReductionRadioGroup").setSelectedButton(this.byId("idDataReductionRadioGroup").getButtons()[0]);
hasTopNValue = false;
}
this._changeVisibilityOfTopN(hasTopNValue); //change the visibility of the Top N fields based on the boolean
},
handleChangeDetailValueForTree : function(oEvent) {
this.oConfigurationEditor.setIsUnsaved();
var self = this;
var aStepCategories = this.oConfigurationEditor.getCategoriesForStep(this.step.getId());
var oTranslationFormat = sap.apf.modeler.ui.utils.TranslationFormatMap.STEP_TITLE;
var sStepTitle = this.byId("idstepTitle").getValue().trim();
var sStepTitleId = self.oTextPool.setText(sStepTitle, oTranslationFormat);
if (sStepTitle !== "" && sStepTitle !== null) {
this.step.setTitleId(sStepTitleId);
}
var stepInfo = {};
stepInfo.name = sStepTitle;
stepInfo.id = this.step.getId();
if (sStepTitle !== "" && sStepTitle !== null) {
if (aStepCategories.length > 1) {//In case the step is only assigned to one category
this.oViewData.updateTree();
} else {//In case the step is assigned to multiple categories, context of step and the list of categories is passed
this.oViewData.updateSelectedNode(stepInfo);
}
var sTitle = this.getText("step") + ": " + sStepTitle;
this.oViewData.updateTitleAndBreadCrumb(sTitle);
}
},
handleChangeForLongTitle : function() {
this.oConfigurationEditor.setIsUnsaved();
var sStepLongTitle = this.byId("idstepLongTitle").getValue().trim();
var oTranslationFormat = sap.apf.modeler.ui.utils.TranslationFormatMap.STEP_LONG_TITLE;
var sStepLongTitleId = this.oTextPool.setText(sStepLongTitle, oTranslationFormat);
this.step.setLongTitleId(sStepLongTitleId);
},
/**
* @function
* @name sap.apf.modeler.ui.controller.step# handleChangeForStepSpecific
* @description handler for the step specific navigation target control
* Assigns the selected step specific navigation targets to the step
* */
handleChangeForStepSpecific : function() {
var self = this;
this.oConfigurationEditor.setIsUnsaved();
var selectedNavTargets = this.byId("idStepSpecificCombo").getSelectedKeys();
var prevNavTargets = this.step.getNavigationTargets();
prevNavTargets.forEach(function(navTargetId) { //Remove the old assigned navigation targets from the step it was assigned to and are unselected now
if (selectedNavTargets.indexOf(navTargetId) === -1) {
self.step.removeNavigationTarget(navTargetId);
}
});
selectedNavTargets.forEach(function(navTargetId) {
if (prevNavTargets.indexOf(navTargetId) === -1) { //Add the selected navigation targets to the step
self.step.addNavigationTarget(navTargetId);
}
});
},
_attachEvents : function() {
var oController = this;
oController.byId("idSourceSelect").attachEvent("selectService", oController.handleSelectionOfService.bind(oController));
oController.byId("idFilterMapSourceSelect").attachEvent("selectService", oController.handleSelectionOfService.bind(oController));
},
handleShowValueHelpRequest : function(oEvent) {
var oController = this;
var oViewData = {
oTextReader : oController.getView().getViewData().getText,
parentView : oController.getView(),
parentControl : oEvent.getSource(),
getCalatogServiceUri : oController.getView().getViewData().getCalatogServiceUri
};
sap.ui.view({
id : oController.createId("idCatalogServiceView"),
viewName : "sap.apf.modeler.ui.view.catalogService",
type : sap.ui.core.mvc.ViewType.XML,
viewData : oViewData
});
},
handleSelectionOfService : function(oEvent) {
var selectedService = oEvent.getParameters()[0];
oEvent.getSource().setValue(selectedService);
oEvent.getSource().fireEvent("change");
},
/**
* @function
* @name sap.apf.modeler.ui.controller.step# handleChangeForService
* @description handler for the "service" property of the step request or filter mapping based on the event
* Checks the id of the source control and sets the value for request service or filter mapping service
* Reads all the entity set for the given source.
* Also , retrieves all the entities based on the required filters from the given source for filter mapping.
* Checks if all the properties (entity, properties etc ) are valid for a given service and empties these properties if the service is invalid.
* */
handleChangeForService : function(oEvent) {
this.oConfigurationEditor.setIsUnsaved();
var sSource, aAllEntitySets = [], aAllEntitySetsForControl = [], aProperties = [], aSelectPropertiesForControl = [], aRequiredProperties;
var sSelectedRequiredFilter = this.byId("idReqFilterSelect").getSelectedKey();
if (sSelectedRequiredFilter !== this.getText("none")) {
aRequiredProperties = [ sSelectedRequiredFilter ]; // required filter from the step
} else {
aRequiredProperties = this.step.getFilterProperties();
}
var sourceControlId = oEvent ? oEvent.getParameter("id") : "";
var bIsfilterMapControl = sourceControlId.search("FilterMap") !== -1 ? true : false;
var bServiceRegistered;
if (bIsfilterMapControl) {
sSource = this.byId("idFilterMapSourceSelect").getValue().trim();
bServiceRegistered = this.oConfigurationEditor.registerService(sSource);
if (bServiceRegistered) {
this._addMandatoryfromFilterMap(); //valid service selected, make other fields in filter mapping mandatory
aAllEntitySets = this.oConfigurationEditor.getAllEntitySetsOfServiceWithGivenProperties(sSource, aRequiredProperties);
} else {
this._removeMandatoryFromFilterMap(); //remove mandatory tag from the filter mapping fields
}
} else {
this._resetStepRequestProperties();//reset all the request fields when service is changed in case of select source
if (sSelectedRequiredFilter === this.getText("none") || sSelectedRequiredFilter === "") {//hide the filter mapping field on change of service when required filter is empty or none
this._hideFilterMapField();// Hide the filter mapping fields
} else { // reset the filter mapping
this._removeMandatoryFromFilterMap(); // removes the mandatory tag
}
this._resetFilterMappingFields();//reset the values from the filter mapping properties and clears the selected keys in control
sSource = this.byId("idSourceSelect").getValue().trim();
bServiceRegistered = this.oConfigurationEditor.registerService(sSource);
aAllEntitySets = this.oConfigurationEditor.getAllEntitySetsOfService(sSource);
}
aAllEntitySets.forEach(function(entitySet) {
var oEntitySet = {};
oEntitySet.entityKey = entitySet;
oEntitySet.entityName = entitySet;
aAllEntitySetsForControl.push(oEntitySet);
});
var oEntitySetData = {
Entities : aAllEntitySetsForControl
};
var oEntitySetModel = new sap.ui.model.json.JSONModel();
oEntitySetModel.setSizeLimit(500);
oEntitySetModel.setData(oEntitySetData);
var sEntitySet;
if (aAllEntitySets.length >= 1) { //set default entity set
if (bIsfilterMapControl) { //for filter mapping entity set
if (this.step.getFilterMappingEntitySet()) {
sEntitySet = this.step.getFilterMappingEntitySet();
aProperties = this.oConfigurationEditor.getAllPropertiesOfEntitySet(sSource, sEntitySet);
} else {
aProperties = this.oConfigurationEditor.getAllPropertiesOfEntitySet(sSource, aAllEntitySets[0]);
}
this.step.setFilterMappingEntitySet(aAllEntitySets[0]);
this.byId("idFilterMapEntitySelect").setSelectedKey(aAllEntitySets[0]);
} else {
if (this.step.getEntitySet()) { //for data source entity set
sEntitySet = this.step.getEntitySet();
aProperties = this.oConfigurationEditor.getAllPropertiesOfEntitySet(sSource, sEntitySet);
} else {
aProperties = this.oConfigurationEditor.getAllPropertiesOfEntitySet(sSource, aAllEntitySets[0]);
}
this.step.setEntitySet(aAllEntitySets[0]);
this.byId("idEntitySelect").setSelectedKey(aAllEntitySets[0]);
}
aProperties.forEach(function(property) {
var oProp = {};
oProp.propertyKey = property;
oProp.propertyName = property;
aSelectPropertiesForControl.push(oProp);
});
}
var oSelectPropertiesData = {
Properties : aSelectPropertiesForControl
};
var oSelectPropertiesModel = new sap.ui.model.json.JSONModel();
oSelectPropertiesModel.setSizeLimit(500);
oSelectPropertiesModel.setData(oSelectPropertiesData);
var aSelectPropertiesForRequiredFilter = [], aSelectPropertiesForTargetFilter = [];
var oSelectedPropertiesForRequiredFilter = this.byId("idSelectPropCombo").getSelectedKeys();
oSelectedPropertiesForRequiredFilter.forEach(function(property) { //selected properties from the combo box
var oProp = {};
oProp.propertyKey = property;
oProp.propertyName = property;
aSelectPropertiesForRequiredFilter.push(oProp);
});
var noneTextobj = {
propertyKey : this.getText("none"),
propertyName : this.getText("none")
};
var aNoneTextObject = [ noneTextobj ];
aNoneTextObject = aNoneTextObject.concat(aSelectPropertiesForRequiredFilter);
var oRequiredFilterMapProertyModel = new sap.ui.model.json.JSONModel();
oRequiredFilterMapProertyModel.setSizeLimit(500);
var oDataForReqFilter = {
Properties : aNoneTextObject
};
oRequiredFilterMapProertyModel.setData(oDataForReqFilter);
var oSelectedPropertiesForTargetFilter = this.byId("idFilterMapTargetFilterCombo") ? this.byId("idFilterMapTargetFilterCombo").getSelectedKeys() : [];
oSelectedPropertiesForTargetFilter.forEach(function(property) { //selected properties from the combo box
var oProp = {};
oProp.propertyKey = property;
oProp.propertyName = property;
aSelectPropertiesForTargetFilter.push(oProp);
});
if (bIsfilterMapControl) {
this.byId("idFilterMapEntitySelect").setModel(oEntitySetModel);
this.byId("idFilterMapTargetFilterCombo").setModel(oSelectPropertiesModel);
} else {
this.byId("idEntitySelect").setModel(oEntitySetModel);
this.byId("idSelectPropCombo").setModel(oSelectPropertiesModel);
this.byId("idReqFilterSelect").setModel(oRequiredFilterMapProertyModel);
}
this._checkValidationStateForService("source", sourceControlId);
},
/**
* @function
* @private
* @name sap.apf.modeler.ui.controller.step# _addMandatoryfromFilterMap
* @description add the mandatory tags to all the fields in the filter mapping if the service is valid
* */
_addMandatoryfromFilterMap : function() {
this.byId("idFilterMapEntitySelect").isMandatory = true;
this.byId("idFilterMapTargetFilterCombo").isMandatory = true;
this.byId("idFilterMapEntityLabel").setText(this.getText("entity"));
this.byId("idFilterMapEntityLabel").setRequired(true);
this.byId("idFilterMapTargetFilterLabel").setText(this.getText("filterMapTarget"));
this.byId("idFilterMapTargetFilterLabel").setRequired(true);
this.byId("idFilterMapKeepSourceLabel").setText(this.getText("filterMapKeepSource"));
this.byId("idFilterMapKeepSourceLabel").setRequired(true);
},
/**
* @function
* @private
* @name sap.apf.modeler.ui.controller.step# _removeMandatoryFromFilterMap
* @description removes the mandatory tags to all the fields in the filter mapping if the service is invalid
* */
_removeMandatoryFromFilterMap : function() {
this.byId("idFilterMapEntitySelect").isMandatory = false;
this.byId("idFilterMapTargetFilterCombo").isMandatory = false;
this.byId("idFilterMapEntityLabel").setText(this.getText("entity"));
this.byId("idFilterMapEntityLabel").setRequired(false);
this.byId("idFilterMapTargetFilterLabel").setText(this.getText("filterMapTarget"));
this.byId("idFilterMapTargetFilterLabel").setRequired(false);
this.byId("idFilterMapKeepSourceLabel").setText(this.getText("filterMapKeepSource"));
this.byId("idFilterMapKeepSourceLabel").setRequired(false);
},
/**
* @function
* @private
* @name sap.apf.modeler.ui.controller.step# _resetFilterMappingFields
* Resets all the values for the filter mapping properties (service, entitySet, select properties, target filter and keep source)
* and clears all the data and selected values from the controls
* */
_resetFilterMappingFields : function() {
var self = this;
this.step.setFilterMappingService("");
this.step.setFilterMappingEntitySet(undefined);
this.step.setFilterMappingKeepSource(undefined);
var aOldFilterMapTargetProperty = this.step.getFilterMappingTargetProperties();
aOldFilterMapTargetProperty.forEach(function(property) {
self.step.removeFilterMappingTargetProperty(property);
});
//set an empty model to the controls on the UI
var oEmptyModelForControlOnReset = new sap.ui.model.json.JSONModel();
var oEmptyDateSetForControlOnReset = {
NoData : []
};
oEmptyModelForControlOnReset.setData(oEmptyDateSetForControlOnReset);
this.byId("idFilterMapSourceSelect").setValue("");
this.byId("idFilterMapEntitySelect").setModel(oEmptyModelForControlOnReset);
this.byId("idFilterMapEntitySelect").setSelectedKey();
this.byId("idFilterMapTargetFilterCombo").setModel(oEmptyModelForControlOnReset);
var aSelectedKeys = this.byId("idFilterMapTargetFilterCombo").getSelectedKeys();
this.byId("idFilterMapTargetFilterCombo").removeSelectedKeys(aSelectedKeys);
},
/**
* @function
* @name sap.apf.modeler.ui.controller.step# handleChangeForEntity
* @description handler for the "entity" property of the step request or filter mapping based on the event
* Checks the id of the source control and sets the value for request entity or filter mapping entity
* Reads all the properties for the given source and entity and updates the select properties based on entity.
* */
handleChangeForEntity : function(oEvent) {
this.oConfigurationEditor.setIsUnsaved();
var sEntity, sService, aProperties = [], aPropertiesForControl = [];
var sourceControlId = oEvent.getParameter("id");
var bIsfilterMapControl = sourceControlId.search("FilterMap") !== -1 ? true : false;
if (bIsfilterMapControl) {
sEntity = this.byId("idFilterMapEntitySelect").getSelectedKey();
sService = this.byId("idFilterMapSourceSelect").getValue().trim();
aProperties = this.oConfigurationEditor.getAllPropertiesOfEntitySet(sService, sEntity);
} else {
sEntity = this.byId("idEntitySelect").getSelectedKey();
sService = this.byId("idSourceSelect").getValue().trim();
aProperties = this.oConfigurationEditor.getAllPropertiesOfEntitySet(sService, sEntity);
}
aProperties.forEach(function(property) {
var oProp = {};
oProp.propertyKey = property;
oProp.propertyName = property;
aPropertiesForControl.push(oProp);
});
var oSelectPropertiesData = {
Properties : aPropertiesForControl
};
var oSelectPropertyModel = new sap.ui.model.json.JSONModel();
oSelectPropertyModel.setSizeLimit(500);
oSelectPropertyModel.setData(oSelectPropertiesData);
var noneTextobj = {
propertyKey : this.getText("none"),
propertyName : this.getText("none")
};
var aRequiredPropertiesControl = [ noneTextobj ];
aRequiredPropertiesControl = aRequiredPropertiesControl.concat(aPropertiesForControl);
var oRequiredFilterMapProertyModel = new sap.ui.model.json.JSONModel();
oRequiredFilterMapProertyModel.setSizeLimit(500);
var oDataForReqFilter = {
Properties : aRequiredPropertiesControl
};
oRequiredFilterMapProertyModel.setData(oDataForReqFilter);
var oTargetFilterMapProertyModel = new sap.ui.model.json.JSONModel();
oTargetFilterMapProertyModel.setSizeLimit(500);
oTargetFilterMapProertyModel.setData(aPropertiesForControl);
if (bIsfilterMapControl) {
this.byId("idFilterMapTargetFilterCombo").setModel(oSelectPropertyModel);
} else {
this.byId("idSelectPropCombo").setModel(oSelectPropertyModel);
this.byId("idReqFilterSelect").setModel(oRequiredFilterMapProertyModel);
}
this._checkValidationStateForService("entitySet", sourceControlId);
var sRequiredFilter = this.byId("idReqFilterSelect").getSelectedKey();
if (sRequiredFilter === this.getText("none")) {
this._hideFilterMapField();// Hides filter mapping fields
this._resetFilterMappingFields();//reset the values from the filter mapping properties and clears the selected keys in control
}
},
/**
* @function
* @name sap.apf.modeler.ui.controller.step# handleChangeForSelectProperty
* @description handler for the "select property" of the step request or filter mapping based on the event
* Checks the id of the source control and sets the value for request select property or filter mapping select property
* Also updates the properties in the required filter list
* */
handleChangeForSelectProperty : function(oEvent) {
var self = this;
var bHasSelectProperty;
this.oConfigurationEditor.setIsUnsaved();
var aSelectProperty, aSelectPropertiesForControl = [];
var sourceControlId = oEvent.getParameter("id");
var aOldSelProp = this.step.getSelectProperties();
aOldSelProp.forEach(function(property) {
self.step.removeSelectProperty(property);
}); // clearing the old properties from core and ui as well
aSelectProperty = this.byId("idSelectPropCombo").getSelectedKeys();
if (aSelectProperty.length > 0) { //if there is select property
aSelectProperty.forEach(function(property) {
self.step.addSelectProperty(property);
var oProp = {};
oProp.propertyKey = property;
oProp.propertyName = property;
aSelectPropertiesForControl.push(oProp);
});
var noneTextobj = {
propertyKey : this.getText("none"),
propertyName : this.getText("none")
};
var aRequiredPropertiesControl = [ noneTextobj ];
aRequiredPropertiesControl = aRequiredPropertiesControl.concat(aSelectPropertiesForControl);
var oRequiredFilterMapProertyModel = new sap.ui.model.json.JSONModel();
oRequiredFilterMapProertyModel.setSizeLimit(500);
var oDataForReqFilter = {
Properties : aRequiredPropertiesControl
};
oRequiredFilterMapProertyModel.setData(oDataForReqFilter);
var oTargetFilterMapProertyModel = new sap.ui.model.json.JSONModel();
oTargetFilterMapProertyModel.setSizeLimit(500);
oTargetFilterMapProertyModel.setData(aSelectPropertiesForControl);
this.byId("idReqFilterSelect").setModel(oRequiredFilterMapProertyModel);
this._checkValidationStateForService("selectProperties", sourceControlId);
var sRequiredFilter = this.step.getFilterProperties() ? this.step.getFilterProperties()[0] : undefined;
if (sRequiredFilter) {
var bRequiredFilterPresentInProperties = this.step.getSelectProperties().indexOf(sRequiredFilter) === -1 ? false : true;
if (bRequiredFilterPresentInProperties) {
this.byId("idReqFilterSelect").setSelectedKey(sRequiredFilter);
} else {
this.byId("idReqFilterSelect").setSelectedKey(this.getText("none"));
}
}
if (this.byId("idReqFilterSelect").getSelectedKey() === this.getText("none")) {
this._hideFilterMapField();
this._resetFilterMappingFields();//reset the values from the filter mapping properties and clears the selected keys in control
}
this._setSortDataForStep();
bHasSelectProperty = true;
} else { // if no select property
bHasSelectProperty = false;
this._changeVisibilityOfTopN(bHasSelectProperty);// hide the topN fields
this.byId("idDataReductionRadioGroup").setSelectedButton(this.byId("idDataReductionRadioGroup").getButtons()[0]);
this._resetTopNFields(); //reset the Top N when no select property is there
}
this._changeVisibilityDataReductionField(bHasSelectProperty);// change the visibility of data reduction field
},
_changeVisibilityDataReductionField : function(bHasSelectProperty) {
this.byId("idDataReduction").setVisible(bHasSelectProperty);
this.byId("idDataReductionLabel").setVisible(bHasSelectProperty);
this.byId("idDataReductionRadioButton").setVisible(bHasSelectProperty);
this.byId("idDataReductionRadioGroup").setVisible(bHasSelectProperty);
},
/**
* @function
* @name sap.apf.modeler.ui.controller.step# handleChangeForRequiredFilter
* @description handler for the "Required filter" of the step request
* Shows and hides the filter mapping field based on required filter availibility in the step
* Updates the entity sets present in the filter mapping based on the required filters
* */
handleChangeForRequiredFilter : function(oEvent) {
var self = this;
var sourceControlId = oEvent.getParameter("id");
this.oConfigurationEditor.setIsUnsaved();
var aOldSelProp = this.step.getFilterProperties();
aOldSelProp.forEach(function(property) {
self.step.removeFilterProperty(property);
});
var sRequiredFilter = this.byId("idReqFilterSelect").getSelectedKey();
if (sRequiredFilter !== this.getText("none")) {
this.step.addFilterProperty(sRequiredFilter);
this._showFilterMappingField();//show filter mapping field on UI if there is a required filter
} else {
this._hideFilterMapField();//hide filter mapping field from UI if there is no required filter
this._resetFilterMappingFields();//reset the values from the filter mapping properties and clears the selected keys in control
}
this._checkValidationStateForService("requiredFilter", sourceControlId);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step# _showFilterMappingField
* @description shows the filter mapping field from UI if the required filter is available in the step
* */
_showFilterMappingField : function() {
this.byId("idFilterMapping").setVisible(true);
this.byId("idFilterMapSourceLabel").setVisible(true);
this.byId("idFilterMapSourceSelect").setVisible(true);
this.byId("idFilterMapEntityLabel").setVisible(true);
this.byId("idFilterMapEntitySelect").setVisible(true);
this.byId("idFilterMapTargetFilterLabel").setVisible(true);
this.byId("idFilterMapTargetFilterCombo").setVisible(true);
this.byId("idFilterMapKeepSourceLabel").setVisible(true);
this.byId("idFilterKeepSourceCheckBox").setVisible(true);
this.byId("idFilterMapping").setTitle(this.getText("filterMap"));
this.byId("idFilterMapSourceLabel").setText(this.getText("source"));
this.byId("idFilterMapSourceLabel").setRequired(false);
this.byId("idFilterMapEntityLabel").setText(this.getText("entity"));
this.byId("idFilterMapEntityLabel").setRequired(false);
this.byId("idFilterMapTargetFilterLabel").setText(this.getText("filterMapTarget"));
this.byId("idFilterMapTargetFilterLabel").setRequired(false);
this.byId("idFilterMapKeepSourceLabel").setText(this.getText("filterMapKeepSource"));
this.byId("idFilterMapKeepSourceLabel").setRequired(false);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step# _hideFilterMapField
* @description hides the filter mapping field from UI if the required filter is not available in the step
* */
_hideFilterMapField : function() {
this.byId("idFilterMapping").setVisible(false);
this.byId("idFilterMapSourceLabel").setVisible(false);
this.byId("idFilterMapSourceSelect").setVisible(false);
this.byId("idFilterMapEntityLabel").setVisible(false);
this.byId("idFilterMapEntitySelect").setVisible(false);
this.byId("idFilterMapTargetFilterLabel").setVisible(false);
this.byId("idFilterMapTargetFilterCombo").setVisible(false);
this.byId("idFilterMapKeepSourceLabel").setVisible(false);
this.byId("idFilterKeepSourceCheckBox").setVisible(false);
this._removeMandatoryFromFilterMap(); // removes the mandatory tag
},
/**
* @function
* @name sap.apf.modeler.ui.controller.step# handleChangeForTargetFilter
* @description handler for the "target property" of the filter mapping
* sets the value of target filter on the step object
* */
handleChangeForTargetFilter : function(oEvent) {
var self = this;
var sourceControlId = oEvent.getParameter("id");
this.oConfigurationEditor.setIsUnsaved();
var aTargetFilterMapProp = this.byId("idFilterMapTargetFilterCombo").getSelectedKeys();
if (aTargetFilterMapProp.length > 0) { // if any value is selected then clear the previous value and add the new one , else retain the old values
var aOldTargetProp = this.step.getFilterMappingTargetProperties();
aOldTargetProp.forEach(function(property) {
self.step.removeFilterMappingTargetProperty(property);
});
aTargetFilterMapProp.forEach(function(property) {
self.step.addFilterMappingTargetProperty(property);
});
}
this._checkValidationStateForService("targetProperties", sourceControlId);
},
/**
* @function
* @name sap.apf.modeler.ui.controller.step# handleFilterMapKeepSource
* @description handler for the "keep source" property of the filter mapping
* sets the boolean value of the property on the step object
* */
handleFilterMapKeepSource : function() {
var bIsKeepSourceSelected = this.byId("idFilterKeepSourceCheckBox").getSelected();
this.oConfigurationEditor.setIsUnsaved();
this.step.setFilterMappingKeepSource(bIsKeepSourceSelected);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_checkValidationStateForService
* @param param - to determine which property has to be to validated ( e.g. source, entitySet etc) and based on it the other properties has to be checked and updated
* @param sourceControlId - id of the control to determine if the property are being read from a request or filter mapping
* @description chceks if the filter mapping of the step has all mandatory fields( i.e. entitySet, service, select properties and target filter are available in the step)
* and sets the values on the step object
* */
_checkValidationStateForService : function(param, sourceControlId) {
var self = this;
var oValidStep = {
source : undefined,
entitySet : undefined,
selectProperty : undefined,
requiredFilter : undefined,
targetFilter : undefined
};
var sSource, aRequiredProperties, aAllEntitySets = [], aAllEntitySetsForControll = [];
var bIsfilterMapControl = sourceControlId.search("FilterMap") !== -1 ? true : false;
sSource = bIsfilterMapControl ? this.byId("idFilterMapSourceSelect").getValue().trim() : this.byId("idSourceSelect").getValue().trim();
var bServiceRegistered = this.oConfigurationEditor.registerService(sSource);
if (bServiceRegistered) {
oValidStep.source = sSource;
var sSelectedRequiredFilter = this.byId("idReqFilterSelect").getSelectedKey();
if (sSelectedRequiredFilter !== this.getText("none")) {
aRequiredProperties = [ sSelectedRequiredFilter ]; // required filter from the step
} else {
aRequiredProperties = this.step.getFilterProperties();
}
aAllEntitySets = bIsfilterMapControl ? this.oConfigurationEditor.getAllEntitySetsOfServiceWithGivenProperties(sSource, aRequiredProperties) : this.oConfigurationEditor.getAllEntitySetsOfService(sSource);
var sSelectedEntity;
if (param === "entitySet" || param === "selectProperties" || param === "targetProperties" || param === "requiredFilter") {
sSelectedEntity = bIsfilterMapControl ? this.byId("idFilterMapEntitySelect").getSelectedKey() : this.byId("idEntitySelect").getSelectedKey();
} else {
sSelectedEntity = bIsfilterMapControl ? this.step.getFilterMappingEntitySet() : this.step.getEntitySet();
}
if (sSelectedEntity) {
aAllEntitySets.forEach(function(entitySet) {
if (sSelectedEntity === entitySet) {
oValidStep.entitySet = sSelectedEntity;
if (param === "source") {
if (bIsfilterMapControl) {
self.byId("idFilterMapEntitySelect").setSelectedKey(sSelectedEntity);
} else {
self.byId("idEntitySelect").setSelectedKey(sSelectedEntity);
}
}
}
});
var aSelectProperties, aCommonProperty = [];
if (param === "selectProperties") {
aSelectProperties = this.byId("idSelectPropCombo").getSelectedKeys();
} else {
aSelectProperties = this.step.getSelectProperties();
}
var aProperties = this.oConfigurationEditor.getAllPropertiesOfEntitySet(sSource, sSelectedEntity); //TODO check
var aPropertiesForControl = [];
aProperties.forEach(function(propertyFromEntity) {
var oProp = {};
oProp.propertyKey = propertyFromEntity;
oProp.propertyName = propertyFromEntity;
aPropertiesForControl.push(oProp);
});
var oDataForProperties = {
Properties : aPropertiesForControl
};
var oModelForSelProp = new sap.ui.model.json.JSONModel();
oModelForSelProp.setSizeLimit(500);
oModelForSelProp.setData(oDataForProperties);
if (!bIsfilterMapControl) {
this.byId("idSelectPropCombo").setModel(oModelForSelProp);
} else {
this.byId("idFilterMapTargetFilterCombo").setModel(oModelForSelProp);
}
aProperties.forEach(function(propertyFromEntity) {
aSelectProperties.forEach(function(propertyFromControl) {
if (propertyFromControl === propertyFromEntity) {
aCommonProperty.push(propertyFromControl);
}
});
});
var aPropertiesMapControl = [];
var objNoneText = [ {
propertyKey : this.getText("none"),
propertyName : this.getText("none")
} ];
if (this.step.getFilterMappingTargetProperties().length === 0) {
this.byId("idFilterMapTargetFilterCombo").setSelectedKeys([]);// if the target filter is not available then clear the selected items from the control
}
if (aCommonProperty.length > 0) {
oValidStep.selectProperty = aCommonProperty;
if (param !== "selectProperties" && !bIsfilterMapControl) {
this.byId("idSelectPropCombo").setSelectedKeys(aCommonProperty);
}
aCommonProperty.forEach(function(property) {
var oProp = {};
oProp.propertyKey = property;
oProp.propertyName = property;
aPropertiesMapControl.push(oProp);
});
} else { //clear the selected keys from the control if there is no common properties
var selectedProperties;
if (!bIsfilterMapControl) {
selectedProperties = this.byId("idSelectPropCombo").getSelectedKeys();
this.byId("idSelectPropCombo").removeSelectedKeys(selectedProperties);
this.byId("idReqFilterSelect").setSelectedKey(this.getText("none"));
}
}
objNoneText = objNoneText.concat(aPropertiesMapControl);
var oRequiredOrFilterProperties = {
Properties : objNoneText
};
var oRequiredOrFilterPropertyModel = new sap.ui.model.json.JSONModel();
oRequiredOrFilterPropertyModel.setData(oRequiredOrFilterProperties);
var aTargetProperties = [], aRequiredFilters = [];
if (param === "targetProperties") {
aTargetProperties = this.byId("idFilterMapTargetFilterCombo").getSelectedKeys();
} else {
aTargetProperties = this.step.getFilterMappingTargetProperties();
}
if (aTargetProperties.length > 0) {
oValidStep.targetFilter = aTargetProperties;
this.byId("idFilterMapTargetFilterCombo").setSelectedKeys(aTargetProperties);
}
if (param === "requiredFilter") {
aRequiredFilters.push(this.byId("idReqFilterSelect").getSelectedKey());
} else {
aRequiredFilters = this.step.getFilterProperties();
}
var aRequiredFilterForValidStep = [];
aRequiredFilters.forEach(function(requiredFilter) {
if (requiredFilter !== self.getText("none")) {
aPropertiesMapControl.forEach(function(oProperty) {
if (oProperty.propertyKey === requiredFilter) {
aRequiredFilterForValidStep.push(requiredFilter);
}
});
}
});
if (aRequiredFilterForValidStep.length !== 0) {
oValidStep.requiredFilter = aRequiredFilterForValidStep; //required filters from dropdown - not none text
} else {
if (!bIsfilterMapControl) {
this.byId("idReqFilterSelect").setSelectedKey(this.getText("none"));
}
}
//all the selected properties will be displayed in the target filter property dropdown, none will not be displayed as one property has to be selected
var oTargetFilterProperties = {
Properties : aPropertiesMapControl
};
var oTargetFilterMapProertyModel = new sap.ui.model.json.JSONModel();
oTargetFilterMapProertyModel.setSizeLimit(500);
oTargetFilterMapProertyModel.setData(oTargetFilterProperties);
if (!bIsfilterMapControl) { //set the model for required filter /target filter
this.byId("idReqFilterSelect").setModel(oRequiredOrFilterPropertyModel);
}
}
if (bIsfilterMapControl) {
this._validateStepServiceForFilterMapping(oValidStep);
} else {
this._validateStepServiceForDataSource(oValidStep);
}
} else { // if service is invalid , reset all the request properties
if (bIsfilterMapControl) {
this._resetFilterMappingFields(); //resets the filter mapping target property
} else {
this._resetStepRequestProperties();
}
}
},
/**
* @function
* @private
* @name sap.apf.modeler.ui.controller.step# _resetStepRequestProperties
* Resets all the values for the step request properties (service, entitySet, select properties, required filter)
* */
_resetStepRequestProperties : function() {
var self = this;
this.step.setEntitySet(undefined);
var aOldSelectProperty = this.step.getSelectProperties();
aOldSelectProperty.forEach(function(property) {
self.step.removeSelectProperty(property);
});
var aOldRequiredFilterProperty = this.step.getFilterProperties();
aOldRequiredFilterProperty.forEach(function(property) {
self.step.removeFilterProperty(property);
});
this.byId("idEntitySelect").setSelectedKey();
this.byId("idReqFilterSelect").setSelectedKey();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_validateStepServiceForDataSource
* @param {Step} - step object
* @description chceks if the data source of the step is has all mandatory fields (i.e. entitySet, service, select properties are available in the step)
* and sets the values on the step object
* */
_validateStepServiceForDataSource : function(oValidStep) {
var self = this;
if (oValidStep.selectProperty && oValidStep.entitySet && oValidStep.source) {
this.step.setService(oValidStep.source);
this.step.setEntitySet(oValidStep.entitySet);
var aOldSelProp = this.step.getSelectProperties();
aOldSelProp.forEach(function(property) {
self.step.removeSelectProperty(property);
});
oValidStep.selectProperty.forEach(function(property) {
self.step.addSelectProperty(property);
});
var aOldRequiredProp = this.step.getFilterProperties();
aOldRequiredProp.forEach(function(property) {
self.step.removeFilterProperty(property);
});
if (oValidStep.requiredFilter) {
oValidStep.requiredFilter.forEach(function(property) {
self.step.addFilterProperty(property);
});
}
}
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_validateStepServiceForFilterMapping
* @param {Step} - step object
* @description chceks if the filter mapping of the step has all mandatory fields( i.e. entitySet, service, select properties and target filter are available in the step)
* and sets the values on the step object
* */
_validateStepServiceForFilterMapping : function(oValidStep) {
var self = this;
if (oValidStep.entitySet && oValidStep.source && oValidStep.targetFilter) {
this.step.setFilterMappingService(oValidStep.source);
this.step.setFilterMappingEntitySet(oValidStep.entitySet);
var aOldFilterMapTargetProp = this.step.getFilterMappingTargetProperties();
aOldFilterMapTargetProp.forEach(function(property) {
self.step.removeFilterMappingTargetProperty(property);
});
oValidStep.targetFilter.forEach(function(property) {
self.step.addFilterMappingTargetProperty(property);
});
}
},
handleChangeForCategory : function() {
this.oConfigurationEditor.setIsUnsaved();
var self = this;
var stepId = self.step.getId();
var currentCategoryId = this.params.arguments.categoryId;
var aPreCat = this.oConfigurationEditor.getCategoriesForStep(this.step.getId());
var sSelCategory = this.byId("idCategorySelect").getSelectedKeys();
var currentCategoryChange = sSelCategory.indexOf(currentCategoryId);
var aStepContexts = [];
var unselectedCategories = [];
var i, j;
for(i = 0; i < aPreCat.length; i++) {
var match = false;
for(j = 0; j < sSelCategory.length; j++) {
if (aPreCat[i] === sSelCategory[j]) {
match = true;
break;
}
}
if (!match) {
unselectedCategories.push(aPreCat[i]);
}
}
if (sSelCategory.length !== 0) {
sSelCategory.forEach(function(category) {
self.oConfigurationEditor.addCategoryStepAssignment(category, stepId); //Add the step to the categories selected
var oStepContext = {
oldContext : {
name : self.params.name,
arguments : {
configId : self.params.arguments.configId,
categoryId : currentCategoryId,
stepId : stepId
}
},
newContext : {
arguments : {
configId : self.params.arguments.configId,
categoryId : category
}
}
};
if (category !== currentCategoryId) {
aStepContexts.push(oStepContext);
}
});
aPreCat.forEach(function(sCatId) { //Remove the step from all the old categories it was present in
if (sSelCategory.indexOf(sCatId) === -1) { // ... and that are not selected any more
self.oConfigurationEditor.removeCategoryStepAssignment(sCatId, self.step.getId());
}
});
if (unselectedCategories.length !== 0) {//Prepare context for unselected categories, to be removed from the model
var newContext = jQuery.extend(true, {}, self.params);
unselectedCategories.forEach(function(unselectedCategory) {
var oStepContext = {
oldContext : {
name : self.params.name,
arguments : {
configId : self.params.arguments.configId,
categoryId : currentCategoryId,
stepId : stepId
}
},
newContext : {
arguments : {
configId : self.params.arguments.configId,
categoryId : unselectedCategory
}
},
removeStep : true
};
if (currentCategoryChange === -1 && unselectedCategory === currentCategoryId) {//Prepare context for category change, if the current category is removed from the step
var categoryChangeContext = {
arguments : {
appId : self.params.arguments.appId,
configId : self.params.arguments.configId,
categoryId : sSelCategory[0],
stepId : stepId
}
};
oStepContext.categoryChangeContext = categoryChangeContext;
oStepContext.changeCategory = true;
}
aStepContexts.push(oStepContext);
});
}
}
if (aStepContexts.length !== 0) {
this.oViewData.updateConfigTree(aStepContexts);//When the categories in the step is changed
}
},
handleChangeForLeftTop : function() {
this.oConfigurationEditor.setIsUnsaved();
var sStepLeftTop = this.byId("idLeftTop").getValue().trim();
var oTranslationFormat = sap.apf.modeler.ui.utils.TranslationFormatMap.STEP_CORNER_TEXT;
var sStepLeftTopTextId = this.oTextPool.setText(sStepLeftTop, oTranslationFormat);
this.step.setLeftUpperCornerTextKey(sStepLeftTopTextId);
},
handleChangeForRightTop : function() {
this.oConfigurationEditor.setIsUnsaved();
var sStepRightTop = this.byId("idRightTop").getValue().trim();
var oTranslationFormat = sap.apf.modeler.ui.utils.TranslationFormatMap.STEP_CORNER_TEXT;
var sStepRightTopTextId = this.oTextPool.setText(sStepRightTop, oTranslationFormat);
this.step.setRightUpperCornerTextKey(sStepRightTopTextId);
},
handleChangeForLeftBottom : function() {
this.oConfigurationEditor.setIsUnsaved();
var sStepLeftBottom = this.byId("idLeftBottom").getValue().trim();
var oTranslationFormat = sap.apf.modeler.ui.utils.TranslationFormatMap.STEP_CORNER_TEXT;
var sStepLeftBottomTextId = this.oTextPool.setText(sStepLeftBottom, oTranslationFormat);
this.step.setLeftLowerCornerTextKey(sStepLeftBottomTextId);
},
handleChangeForRightBottom : function() {
this.oConfigurationEditor.setIsUnsaved();
var sStepRightBottom = this.byId("idRightBottom").getValue().trim();
var oTranslationFormat = sap.apf.modeler.ui.utils.TranslationFormatMap.STEP_CORNER_TEXT;
var sStepRightBottomTextId = this.oTextPool.setText(sStepRightBottom, oTranslationFormat);
this.step.setRightLowerCornerTextKey(sStepRightBottomTextId);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_setSortDataForStep
* @description Returns the data set to be bound to sort data layout.
* Also checks if it is default sorting property, in this case creates the sort row from the first select property
* creates {Object} Data set for sort data layout of the form:
* {
aSortRows : [
{
aAllProperties : [
{
sName - Name of the property.
}
],
property - Name of the selected sort property.
ascending- Translated text for 'ascending' and 'descending'.
}
]
* }
* Sets the data on the sort layout and also on the sort model
* */
_setSortDataForStep : function() {
var oSelf = this;
var aSelectProperties = this.step.getSelectProperties().map(function(sProperty) {
return {
property : sProperty
};
});
var aSortRows;
var oTopNSettingsForStep = this.step.getTopN();
if (oTopNSettingsForStep && oTopNSettingsForStep.orderby) { // if Top N for step exists
var aSortRowsForStep = oTopNSettingsForStep.orderby.map(function(oSortProperty) {
var sOrderByProperty = oSortProperty.property;
var sOrderByDirection = oSortProperty.ascending !== undefined && !oSortProperty.ascending ? oSelf.getText("descending") : oSelf.getText("ascending");
return {
property : sOrderByProperty,
ascending : sOrderByDirection,
aAllProperties : aSelectProperties
};
});
aSortRows = aSortRowsForStep;
} else {
aSortRows = [ {
property : aSelectProperties[0].property,
ascending : true,
aAllProperties : aSelectProperties
} ];
}
var oSortModelForStep = new sap.ui.model.json.JSONModel({
aSortRows : aSortRows
});
this.byId("idStepSortLayout").setModel(oSortModelForStep);
this._bindSortLayoutDataForStep();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_bindSortLayoutDataForStep
* @description Binds sap.apf.modeler.ui.controller.step#oSortModelForStep to Sort layout.
* Iteratively binds the data to all the controls in Sort Data Layout.
* */
_bindSortLayoutDataForStep : function() {
var oSelf = this;
var oSortLayout = this.byId("idStepSortLayout");
var oSortRowTemplate = new sap.ui.layout.Grid({ // add the select box controls to the grid.
width : "100%"
});
var oSortFieldLabel = new sap.m.Label({// "Sort Label" Label
width : "100%",
textAlign : "End",
layoutData : new sap.ui.layout.GridData({
span : "L3 M3 S3"
}),
text : this.getText("sortingField")
}).addStyleClass("sortFieldLabel");
oSortRowTemplate.addContent(oSortFieldLabel);
var oSortPropertySelectBox = new sap.m.Select({// "Sort Fields" Select Box
width : "100%",
layoutData : new sap.ui.layout.GridData({
span : "L2 M3 S3"
}),
items : {
path : "aAllProperties",
template : new sap.ui.core.ListItem({
key : "{property}",
text : "{property}"
})
},
selectedKey : "{property}",
change : oSelf._handleChangeForSortData.bind(this)
// the current context should be bound to the event handler
});
oSortRowTemplate.addContent(oSortPropertySelectBox);
var oDirectionLabel = new sap.m.Label({
layoutData : new sap.ui.layout.GridData({// "Direction" Label
span : "L2 M2 S2"
}),
width : "100%",
textAlign : "End",
text : this.getText("direction")
}).addStyleClass("directionLabel");
oSortRowTemplate.addContent(oDirectionLabel);
var oDirectionSelectBox = new sap.m.Select({ // "Direction" Select Box
width : "100%",
layoutData : new sap.ui.layout.GridData({
span : "L2 M2 S2"
}),
items : [ {
key : this.getText("ascending"),
text : this.getText("ascending")
}, {
key : this.getText("descending"),
text : this.getText("descending")
} ],
selectedKey : "{ascending}",
change : oSelf._handleChangeForSortData.bind(this)
// the current context should be bound to the event handler
});
oSortRowTemplate.addContent(oDirectionSelectBox);// Add Icon
var oAddIcon = new sap.ui.core.Icon({
width : "100%",
src : "sap-icon://add",
tooltip : this.getText("addButton"),
visible : true,
press : oSelf._handleChangeForAddSortRow.bind(this)
// the current context should be bound to the event handler
}).addStyleClass("addIconRepresentation");
var oRemoveIcon = new sap.ui.core.Icon({// Remove Icon
width : "100%",
src : "sap-icon://less",
tooltip : this.getText("deleteButton"),
visible : {
path : "/",
formatter : function() {
var oBindingContext = this.getBindingContext();
var nCurrentIndex = parseInt(oBindingContext.getPath().split("/").pop(), 10);
return !!nCurrentIndex;
}
},
press : oSelf._handleChangeForDeleteSortRow.bind(this)
// the current context should be bound to the event handler
}).addStyleClass("lessIconRepresentation");
var oIconLayout = new sap.m.HBox({// Layout to hold the add/less icons
layoutData : new sap.ui.layout.GridData({
span : "L2 M2 S2"
}),
items : [ oAddIcon, oRemoveIcon ]
});
oSortRowTemplate.addContent(oIconLayout);
oSortLayout.bindAggregation("items", "/aSortRows", function(sId) {
return oSortRowTemplate.clone(sId);
});
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_handleChangeForSortData
* @description handles the change in the sort property or dort direction and sets the data on the step
* */
_handleChangeForSortData : function() {
this._setSortFieldsFromCurrentDataset();
this.oConfigurationEditor.setIsUnsaved();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_handleChangeForAddSortRow
* @param {oAddRowEvent}
* @description Handler for the "+" icon in the sort property row
* adds a new sort property row in the representation sort data and also sets the corresponding properties on the step object.
* */
_handleChangeForAddSortRow : function(oAddRowEvent) {
var oUpdatedSortRow = this._getUpdatedSortRow(oAddRowEvent);
var oBindingContext = oAddRowEvent.getSource().getBindingContext();
var oCurrentObjectClone = jQuery.extend(true, {}, oBindingContext.getObject());
delete oCurrentObjectClone.property;
delete oCurrentObjectClone.ascending;
oUpdatedSortRow.aSortRows.splice(oUpdatedSortRow.nCurrentIndex + 1, 0, oCurrentObjectClone);
this._updateModelForSortData();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_handleChangeForDeleteSortRow
* @param {oDeleteRowEvent}
* @description Handler for the "-" icon in the sort property row
* removes a sort property row from the representation sort data and also sets the corresponding properties on the step object.
* */
_handleChangeForDeleteSortRow : function(oDeleteRowEvent) {
var oUpdatedSortRow = this._getUpdatedSortRow(oDeleteRowEvent);
oUpdatedSortRow.aSortRows.splice(oUpdatedSortRow.nCurrentIndex, 1);
this._updateModelForSortData();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_getUpdatedSortRow
* @param {oSortRowEvent} - event from the add/delete row in sort data
* returns the information about the added/deleted row in the sort data
* {
* nCurrentIndex : nCurrentIndex,
aSortRows : aSortRows
* }
*
* */
_getUpdatedSortRow : function(oSortRowEvent) {
var oBindingContext = oSortRowEvent.getSource().getBindingContext();
var nCurrentIndex = parseInt(oBindingContext.getPath().split("/").pop(), 10);
var aSortRows = this.byId("idStepSortLayout").getModel().getData().aSortRows;
return {
nCurrentIndex : nCurrentIndex,
aSortRows : aSortRows
};
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_updateModelForSortData
* Updates the model for the sort layout and sets the current properties
* */
_updateModelForSortData : function() {
this.byId("idStepSortLayout").getModel().updateBindings();
this._setSortFieldsFromCurrentDataset();
this.oConfigurationEditor.setIsUnsaved();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_setSortFieldsFromCurrentDataset
* @description handles every change event related to sort layout
* Sets new values on the step object based on the current property model.
* Clears the old values from step object.
* Sets new values by iterating through the current sort data set.
* */
_setSortFieldsFromCurrentDataset : function() {
var oSelf = this;
var aSortProperties = [];
// Loop through current sort model and set orderby properties accordingly.
this.byId("idStepSortLayout").getModel().getData().aSortRows.forEach(function(oSortRow) {
var oSortProperty = {};
oSortProperty.property = oSortRow.property || (oSortRow.aAllProperties.length && oSortRow.aAllProperties[0].property);
oSortProperty.ascending = !oSortRow.ascending || (oSortRow.ascending === oSelf.getText("ascending"));
aSortProperties.push(oSortProperty);
});
this.step.setTopNSortProperties(aSortProperties);
},
/**
* @function
* @name sap.apf.modeler.ui.controller.step#handleChangeForDataReduction
* @description Handler for the data reduction . Changes the visibility of top N fields based on the selected options.
* Also restes the top N values in case , "No Data Reduction" is selected
* */
handleChangeForDataReduction : function(oEvent) {
var bIsTopNVisible; // boolean to check if "Top N" is selected
if (oEvent.getSource().getSelectedButton().getText() === this.getText("noDataReduction")) {
bIsTopNVisible = false;
this._resetTopNFields();
} else {
this._setSortDataForStep();
bIsTopNVisible = true;
}
this._changeVisibilityOfTopN(bIsTopNVisible); //change the visibility of the Top N fields based on the boolean
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_resetTopNFields
* @description resets the Top N fields as well as clears the fields
* */
_resetTopNFields : function() {
this.step.resetTopN();
var oSortModelForStep = new sap.ui.model.json.JSONModel({
aSortRows : []
});
this.byId("idStepSortLayout").setModel(oSortModelForStep);
this.byId("idCustomRecordValue").setValue();
},
/**
* @function
* @name sap.apf.modeler.ui.controller.step#_handleChangeForDataRecordInputValue
* @description Handler for the data records custom input field
* Check if the valid value is given in input field, accordingly sets the state of the data record input field
* */
handleChangeForDataRecordInputValue : function(oEvent) {
var isValidState;
//value for data record should not be negative, float or greater than 10000 - Otherwise the value state for input is invalid
if (oEvent.getSource().getValue().trim().indexOf(".") !== -1 || oEvent.getSource().getValue().trim() <= 0 || oEvent.getSource().getValue().trim() > 10000) {
isValidState = "Error";
} else {
isValidState = "None";
}
oEvent.getSource().setValueState(isValidState);
//read the sort properties from the sort layout and set the sort propetues as well on change of data record input
var aSortProperties = [];
this.byId("idStepSortLayout").getModel().getData().aSortRows.forEach(function(sortRow) {
aSortProperties.push({
property : sortRow.property,
ascending : sortRow.ascending
});
});
if (aSortProperties) {
this.step.setTopNValue(oEvent.getSource().getValue());
this.step.setTopNSortProperties(aSortProperties);
}
this.oConfigurationEditor.setIsUnsaved();
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_changeVisibilityOfTopN
* @param bIsTopNVisible - a boolean which is used to change the visibility of the top N fields
* @description changes the visibility of the the top N fields based on whether top N is set on the step or not
* Also adds/removes the mandatory tag from the input field for Top N
* */
_changeVisibilityOfTopN : function(bIsTopNVisible) {
this.byId("idCustomRecordValue").isMandatory = bIsTopNVisible;
this.byId("idDataRecordsLabel").setVisible(bIsTopNVisible);
this.byId("idDataRecordsLabel").setRequired(bIsTopNVisible);
this.byId("idCustomRecordValue").setVisible(bIsTopNVisible);
this.byId("idStepSortLayout").setVisible(bIsTopNVisible);
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_setMandatoryFields
* @param {Array} fields - Array of form fields
* @description Set mandatory fields on the instance level
* */
_setMandatoryFields : function(fields) {
this.mandatoryFields = this.mandatoryFields || [];
for(var i = 0; i < fields.length; i++) {
fields[i].isMandatory = true;
this.mandatoryFields.push(fields[i]);
}
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_getMandatoryFields
* @param {Object} oEvent - Event instance of the form field
* @description getter for mandatory fields
* */
_getMandatoryFields : function() {
return this.mandatoryFields;
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#_setValidationState
* @param {Object} oEvent - Event instance of the form field
* @description Set validation state of sub view
* */
_setValidationState : function() {
var mandatoryFields = this._getMandatoryFields();
for(var i = 0; i < mandatoryFields.length; i++) {
if (mandatoryFields[i].isMandatory === true) {
if (typeof mandatoryFields[i].getSelectedKeys === "function") {
this.isValidState = (mandatoryFields[i].getSelectedKeys().length >= 1) ? true : false;
} else if (typeof mandatoryFields[i].getValue === "function") {
this.isValidState = (mandatoryFields[i].getValue().trim() !== "") ? true : false;
} else {
this.isValidState = (mandatoryFields[i].getSelectedKey().length >= 1) ? true : false;
}
if (this.isValidState === false) {
break;
}
}
}
},
/**
* @private
* @function
* @name sap.apf.modeler.ui.controller.step#getValidationState
* @description Getter for getting the current validation state of sub view
* */
getValidationState : function() {
this._setValidationState(); //Set the validation state of view
var isValidState = (this.isValidState !== undefined) ? this.isValidState : true;
return isValidState;
}
});<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2014-2016 SAP SE. All rights reserved
*/
sap.ui.define(["jquery.sap.global"],function(q){"use strict";var F=function(){};F.showDialog=function(a,i){};F.closeDialog=function(){};return F;},true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
// Provides control sap.ui.comp.smartfilterbar.SelectOption.
sap.ui.define(['jquery.sap.global', 'sap/ui/comp/library', 'sap/ui/core/Element'],
function(jQuery, library, Element) {
"use strict";
/**
* Constructor for a new smartfilterbar/SelectOption.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* A Select Option can be used to specify default filter values for a control configuration of the SmartFilterBar.
* @extends sap.ui.core.Element
*
* @constructor
* @public
* @alias sap.ui.comp.smartfilterbar.SelectOption
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var SelectOption = Element.extend("sap.ui.comp.smartfilterbar.SelectOption", /** @lends sap.ui.comp.smartfilterbar.SelectOption.prototype */ { metadata : {
library : "sap.ui.comp",
properties : {
/**
* The sign for a Select Option. Possible values are I for include or E for exclude. Constants can be found here: sap.ui.comp.smartfilterbar.SelectOption.SIGN
*/
sign : {type : "string", group : "Misc", defaultValue : 'I'},
/**
* The operator for a select option. The default value is EQ "for equals". Possible values can be found here: sap.ui.comp.smartfilterbar.SelectOption.OPERATOR.
*/
operator : {type : "string", group : "Misc", defaultValue : 'EQ'},
/**
* The low value for a select option.
*/
low : {type : "string", group : "Misc", defaultValue : null},
/**
* The high value for a select option. The high value is only required for a few operators, e.g. BT (between).
*/
high : {type : "string", group : "Misc", defaultValue : null}
}
}});
SelectOption.SIGN = {
I: "I",
include: "I",
E: "E",
exclude: "E"
};
SelectOption.OPERATOR = {
EQ: "EQ",
NE: "NE",
CP: "CP",
GT: "GT",
GE: "GE",
LT: "LT",
LE: "LE",
NP: "NP",
BT: "BT",
NB: "NB"
};
return SelectOption;
}, /* bExport= */ true);
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
/*global jQuery, sap, OData */
jQuery.sap.declare("sap.apf.core.instance");
jQuery.sap.require('sap.apf.utils.utils');
jQuery.sap.require("sap.apf.core.utils.uriGenerator");
jQuery.sap.require("sap.apf.core.metadata");
jQuery.sap.require("sap.apf.core.metadataFacade");
jQuery.sap.require("sap.apf.core.metadataProperty");
jQuery.sap.require("sap.apf.core.ajax");
jQuery.sap.require("sap.apf.core.odataRequest");
jQuery.sap.require("sap.apf.core.messageHandler");
jQuery.sap.require("sap.apf.core.entityTypeMetadata");
jQuery.sap.require("sap.apf.core.metadataFactory");
jQuery.sap.require("sap.apf.core.textResourceHandler");
jQuery.sap.require("sap.apf.core.configurationFactory");
jQuery.sap.require("sap.apf.core.path");
jQuery.sap.require("sap.apf.core.sessionHandler");
jQuery.sap.require("sap.apf.core.resourcePathHandler");
jQuery.sap.require("sap.apf.core.persistence");
jQuery.sap.require("sap.apf.core.readRequest");
jQuery.sap.require("sap.apf.core.readRequestByRequiredFilter");
jQuery.sap.require("sap.apf.core.utils.fileExists");
(function() {
'use strict';
/**
* @class Core Component Instance
* @name sap.apf.core.Instance
* @description Creation of new Core Component Instance
*/
sap.apf.core.Instance = function(oApiInject) {
var that = this;
var oMessageHandler = oApiInject.messageHandler;
var oStartParameter = oApiInject.startParameter;
var sRememberedPath;
var oInject = {
messageHandler : oMessageHandler,
coreApi : that
};
var oResourcePathHandler;
var oMetadataFactory;
var oTextResourceHandler;
var oConfigurationFactory;
var oPath;
var oSessionHandler;
var oPersistence;
var oFileExists;
this.destroy = function() {
oPath.destroy();
};
/**
* @see sap.apf.core.ajax
*/
this.ajax = function(oSettings) {
return sap.apf.core.ajax(oSettings);
};
/**
* @see sap.apf.core.odataRequestWrapper
*/
this.odataRequest = function(oRequest, fnSuccess, fnError, oBatchHandler) {
sap.apf.core.odataRequestWrapper(oMessageHandler, oRequest, fnSuccess, fnError, oBatchHandler);
};
/**
* @see sap.apf.utils.startParameter
*/
this.getStartParameterFacade = function() {
return oStartParameter;
};
this.getMessageHandler = function() {
return oMessageHandler;
};
/**
* @see sap.apf#putMessage for api definition.
* @see sap.apf.core.MessageHandler#putMessage for implementation.
*/
this.putMessage = function(oMessage) {
return oMessageHandler.putMessage(oMessage);
};
/**
* @see sap.apf.core.MessageHandler#check
*/
this.check = function(bExpression, sMessage, sCode) {
return oMessageHandler.check(bExpression, sMessage, sCode);
};
/**
* @see sap.apf#createMessageObject for api definition.
* @see sap.apf.core.MessageHandler#createMessageObject
*/
this.createMessageObject = function(oConfig) {
return oMessageHandler.createMessageObject(oConfig);
};
/**
* @see sap.apf.core.MessageHandler#activateOnErrorHandling
*/
this.activateOnErrorHandling = function(bOnOff) {
oMessageHandler.activateOnErrorHandling(bOnOff);
};
/**
* @see sap.apf.core.MessageHandler#setMessageCallback
*/
this.setCallbackForMessageHandling = function(fnCallback) {
oMessageHandler.setMessageCallback(fnCallback);
};
/**
* @see sap.apf.core.MessageHandler#setApplicationMessageCallback
*/
this.setApplicationCallbackForMessageHandling = function(fnCallback) {
oMessageHandler.setApplicationMessageCallback(fnCallback);
};
/**
* @see sap.apf.core.MessageHandler#getLogMessages
*/
this.getLogMessages = function() {
return oMessageHandler.getLogMessages();
};
/**
* @see sap.apf.core.checkForTimeout
*/
this.checkForTimeout = function(oServerResponse) {
var oMessageObject = sap.apf.core.utils.checkForTimeout(oServerResponse);
// up to now, the error handling was hard coded in checkForTimeout
if (oMessageObject) {
oMessageHandler.putMessage(oMessageObject);
}
return oMessageObject;
};
/**
* @description Returns the instance of the UriGenerator. For internal core using only.
*/
this.getUriGenerator = function() {
return sap.apf.core.utils.uriGenerator;
};
/**
* @see sap.apf.core.MetadataFactory#getMetadata
*/
this.getMetadata = function(sAbsolutePathToServiceDocument) {
return oMetadataFactory.getMetadata(sAbsolutePathToServiceDocument);
};
/**
* @see sap.apf.core.MetadataFactory#getMetadataFacade
*/
this.getMetadataFacade = function() {
return oMetadataFactory.getMetadataFacade();
};
/**
* @see sap.apf.core.MetadataFactory#getEntityTypeMetadata
*/
this.getEntityTypeMetadata = function(sAbsolutePathToServiceDocument, sEntityType) {
return oMetadataFactory.getEntityTypeMetadata(sAbsolutePathToServiceDocument, sEntityType);
};
/**
* @see sap.apf.core.ResourcePathHandler#loadConfigFromFilePath
*/
this.loadApplicationConfig = function(sFilePath) {
oResourcePathHandler.loadConfigFromFilePath(sFilePath);
};
/**
* @see sap.apf.core.TextResourceHandler#loadTextElements
*/
this.loadTextElements = function(textElements) {
oTextResourceHandler.loadTextElements(textElements);
};
/**
* @see sap.apf.core.ResourcePathHandler#getConfigurationProperties
*/
this.getApplicationConfigProperties = function() {
return oResourcePathHandler.getConfigurationProperties();
};
/**
* @see sap.apf.core.ResourcePathHandler#getResourceLocation
*/
this.getResourceLocation = function(sResourceIdentifier) {
return oResourcePathHandler.getResourceLocation(sResourceIdentifier);
};
/**
* @see sap.apf.core.ResourcePathHandler#getPersistenceConfiguration
*/
this.getPersistenceConfiguration = function() {
return oResourcePathHandler.getPersistenceConfiguration();
};
/**
* @see sap.apf.core.ResourcePathHandler#getApplicationConfigurationURL
*/
this.getApplicationConfigurationURL = function() {
return oResourcePathHandler.getApplicationConfigurationURL();
};
// ConfigurationFactory API
/**
* @see sap.apf.core.ConfigurationFactory#getCategories
*/
this.getCategories = function() {
return oConfigurationFactory.getCategories();
};
/**
* @see sap.apf.core.ConfigurationFactory#existsConfiguration
*/
this.existsConfiguration = function(sId) {
return oConfigurationFactory.existsConfiguration(sId);
};
/**
* @see sap.apf.core.ConfigurationFactory#getStepTemplates
*/
this.getStepTemplates = function() {
return oConfigurationFactory.getStepTemplates();
};
/**
* @see sap.apf.core.ConfigurationFactory#getFacetFilterConfigurations
*/
this.getFacetFilterConfigurations = function() {
return oConfigurationFactory.getFacetFilterConfigurations();
};
/**
* @see sap.apf.core.ConfigurationFactory#getNavigationTargets
*/
this.getNavigationTargets = function() {
return oConfigurationFactory.getNavigationTargets();
};
/**
* @description Creates a step object from the configuration object and adds it to the path.
* @param {string} sStepId Step id as defined in the analytical configuration.
* @param {function} fnStepProcessedCallback Callback function for path update.
* @param {string} [sRepresentationId] Parameter, that allows definition of the representation id that shall initially be selected. If omitted the first configured representation will be selected.
* @returns {sap.apf.core.Step} oStep Created step.
*/
this.createStep = function(sStepId, fnStepProcessedCallback, sRepresentationId) {
var oStepInstance;
oMessageHandler.check(sStepId !== undefined && typeof sStepId === "string" && sStepId.length !== 0, "sStepID is unknown or undefined");
oStepInstance = oConfigurationFactory.createStep(sStepId, sRepresentationId);
oPath.addStep(oStepInstance, fnStepProcessedCallback);
return oStepInstance;
};
// Path API
/**
* @see sap.apf.core.Path#getSteps
*/
this.getSteps = function() {
return oPath.getSteps();
};
/**
* @see sap.apf.core.Path#moveStepToPosition
*/
this.moveStepToPosition = function(oStep, nPosition, fnStepProcessedCallback) {
oPath.moveStepToPosition(oStep, nPosition, fnStepProcessedCallback);
};
/**
* @function
* @name sap.apf.core.Instance#updatePath
* @see sap.apf.core.Path#update
*/
this.updatePath = function(fnStepProcessedCallback, bContextChanged) {
oPath.update(fnStepProcessedCallback, bContextChanged);
};
/**
* @see sap.apf.core.Path#removeStep
*/
this.removeStep = function(oStep, fnStepProcessedCallback) {
oPath.removeStep(oStep, fnStepProcessedCallback);
};
/**
* @description Creates a new Path instance
* @param {boolean} [bRememberActualPath] if true, then the path can be restored
*
*/
this.resetPath = function(bRememberActualPath) {
if (bRememberActualPath) {
sRememberedPath = oPath.serialize();
}
if (oPath) {
oPath.destroy();
}
oPath = new sap.apf.core.Path(oInject);
};
/**
* if resetPath has been called with bRememberActualPath, then the old path
* can be restored
*/
this.restoreOriginalPath = function() {
if (sRememberedPath) {
oPath.destroy();
oPath = new sap.apf.core.Path(oInject);
oPath.deserialize(sRememberedPath);
}
};
/**
* @see sap.apf.core.Path#stepIsActive
*/
this.stepIsActive = function(oStep) {
return oPath.stepIsActive(oStep);
};
/**
* @see sap.apf.core.Path#serializePath
*/
this.serializePath = function() {
return oPath.serialize();
};
/**
* @see sap.apf.core.Path#deserializePath
*/
this.deserializePath = function(oSerializedAnalysisPath) {
oPath.deserialize(oSerializedAnalysisPath);
};
// Text Resource Handler API
/**
* @see sap.apf#getTextNotHtmlEncoded
* @see sap.apf.core.TextResourceHandler#getTextNotHtmlEncoded
*/
this.getTextNotHtmlEncoded = function(oLabel, aParameters) {
return oTextResourceHandler.getTextNotHtmlEncoded(oLabel, aParameters);
};
/**
* @see sap.apf#getTextHtmlEncoded
* @see sap.apf.core.TextResourceHandler#getTextHtmlEncoded
*/
this.getTextHtmlEncoded = function(oLabel, aParameters) {
return oTextResourceHandler.getTextHtmlEncoded(oLabel, aParameters);
};
/**
* returns true, if this is the text key for the initial text. Initial text means empty string.
*/
this.isInitialTextKey = function(textKey) {
return (textKey === sap.apf.core.constants.textKeyForInitialText);
};
/**
* @see sap.apf.core.TextResourceHandler#getMessageText
*/
this.getMessageText = function(sCode, aParameters) {
return oTextResourceHandler.getMessageText(sCode, aParameters);
};
/**
* @see sap.apf.core.SessionHandler#getXsrfToken
*/
this.getXsrfToken = function(sServiceRootPath) {
return oSessionHandler.getXsrfToken(sServiceRootPath);
};
/**
* @see sap.apf.core.SessionHandler#setDirtyState
*/
this.setDirtyState = function(state) {
oSessionHandler.setDirtyState(state);
};
/**
* @see sap.apf.core.SessionHandler#isDirty
*/
this.isDirty = function() {
return oSessionHandler.isDirty();
};
/**
* @see sap.apf.core.SessionHandler#setPathName
*/
this.setPathName = function(name) {
oSessionHandler.setPathName(name);
};
/**
* @see sap.apf.core.SessionHandler#getPathName
*/
this.getPathName = function() {
return oSessionHandler.getPathName();
};
/**
* @see sap.apf.core.utils.StartFilterHandler#getCumulativeFilter
*/
this.getCumulativeFilter = function() {
return oApiInject.getCumulativeFilter();
};
/**
* @see sap.apf#createReadRequest
* @description Creates an object for performing an Odata Request get operation.
* @param {String|Object} sRequestConfigurationId - identifies a request configuration, which is contained in the analytical configuration.
* or the request configuration is directly passed as an object oRequestConfiguration.
* @returns {sap.apf.core.ReadRequest}
*/
this.createReadRequest = function(/* sRequestConfigurationId | oRequestConfiguration */requestConfiguration) {
var oRequest = oConfigurationFactory.createRequest(requestConfiguration);
var oRequestConfiguration;
if (typeof requestConfiguration === 'string') {
oRequestConfiguration = oConfigurationFactory.getConfigurationById(requestConfiguration);
} else {
oRequestConfiguration = requestConfiguration;
}
return new sap.apf.core.ReadRequest(oInject, oRequest, oRequestConfiguration.service, oRequestConfiguration.entityType);
};
/**
* @see sap.apf#createReadRequestByRequiredFilter
* @description Creates an object for performing an Odata Request get operation with required filter for parameter entity set key properties & required filters.
* @param {String|Object} sRequestConfigurationId - identifies a request configuration, which is contained in the analytical configuration.
* or the request configuration is directly passed as an object oRequestConfiguration.
* @returns {sap.apf.core.ReadRequestByRequiredFilter}
*/
this.createReadRequestByRequiredFilter = function(/* sRequestConfigurationId | oRequestConfiguration */requestConfiguration) {
var oRequest = oConfigurationFactory.createRequest(requestConfiguration);
var oRequestConfiguration;
if (typeof requestConfiguration === 'string') {
oRequestConfiguration = oConfigurationFactory.getConfigurationById(requestConfiguration);
} else {
oRequestConfiguration = requestConfiguration;
}
return new sap.apf.core.ReadRequestByRequiredFilter(oInject, oRequest, oRequestConfiguration.service, oRequestConfiguration.entityType);
};
/**
* @description Message configurations are loaded.
* @see sap.apf.core.MessageHandler#loadConfig
*/
this.loadMessageConfiguration = function(aMessages, bResetRegistry) {
oMessageHandler.loadConfig(aMessages, bResetRegistry);
};
/**
* @see sap.apf.core.ConfigurationFactory#loadConfig
*/
this.loadAnalyticalConfiguration = function(oConfig) {
oConfigurationFactory.loadConfig(oConfig);
};
/**
* @see sap.apf.core#savePath for api definition.
* @see sap.apf.core.Persistence#createPath
*/
this.savePath = function(arg1, arg2, arg3, arg4) {
var sPathId;
var sName;
var fnCallback;
var oExternalObject;
if (typeof arg1 === 'string' && typeof arg2 === 'string' && typeof arg3 === 'function') {
sPathId = arg1;
sName = arg2;
fnCallback = arg3;
oExternalObject = arg4;
this.setPathName(sName);
oPersistence.modifyPath(sPathId, sName, fnCallback, oExternalObject);
} else if (typeof arg1 === 'string' && typeof arg2 === 'function') {
sName = arg1;
fnCallback = arg2;
oExternalObject = arg3;
this.setPathName(sName);
oPersistence.createPath(sName, fnCallback, oExternalObject);
} else {
oMessageHandler.putMessage(sap.apf.core.createMessageObject({
code : "5027",
aParameters : [ arg1, arg2, arg3 ]
}));
}
};
/**
* @see sap.apf.core.Persistence#readPaths
*/
this.readPaths = function(fnCallback) {
oPersistence.readPaths(fnCallback);
};
/**
* @see sap.apf.core.Persistence#openPath
*/
this.openPath = function(sPathId, fnCallback, nActiveStep) {
function localCallback(oResponse, oEntitiyMetadata, oMessageObject) {
if (!oMessageObject && sRememberedPath) {
sRememberedPath = undefined;
}
if (!oMessageObject) {
that.setPathName(oResponse.path.AnalysisPathName);
}
fnCallback(oResponse, oEntitiyMetadata, oMessageObject);
}
return oPersistence.openPath(sPathId, localCallback, nActiveStep);
};
/**
* @see sap.apf.core.Persistence#deletePath
*/
this.deletePath = function(sPathId, fnCallback) {
oPersistence.deletePath(sPathId, fnCallback);
};
/**
* @see sap.apf#createFilter for api definition
* @see sap.apf.utils.Filter
*/
this.createFilter = function(oSelectionVariant) {
return new sap.apf.utils.Filter(oMessageHandler, oSelectionVariant);
};
/**
* @public
* @function
* @name sap.apf.core#getActiveStep
* @description Returns active step, currently selected step, of analysis path.
* @returns {sap.apf.core.Step}
*/
this.getActiveStep = function() {
return oPath.getActiveSteps()[0];
};
/**
* @public
* @function
* @name sap.apf.core#getCumulativeFilterUpToActiveStep
* @description Returns the cumulative filter up to the active step (included) and the context
* @returns {sap.apf.core.utils.Filter} cumulativeFilter
*/
this.getCumulativeFilterUpToActiveStep = function() {
return oPath.getCumulativeFilterUpToActiveStep();
};
/**
* @public
* @function
* @name sap.apf.core#setActiveStep
* @description Sets handed over step as the active one.
* @param {sap.apf.core.Step} oStep The step to be set as active
* @returns undefined
*/
this.setActiveStep = function(oStep) {
oPath.makeStepActive(oStep);
var aActiveSteps = oPath.getActiveSteps();
var i;
for(i = 0; i < aActiveSteps.length; ++i) {
oPath.makeStepInactive(aActiveSteps[i]);
}
return oPath.makeStepActive(oStep);
};
/**
* @public
* @function
* @name sap.apf.core.Instance#createFirstStep
* @description Method to be used APF internally by the binding class to create instances from representation constructors.
*/
this.createFirstStep = function(sStepId, sRepId, callback) {
var isValidStepId = false;
var stepTemplates;
stepTemplates = that.getStepTemplates();
stepTemplates.forEach(function(item) {
isValidStepId = item.id === sStepId ? true : isValidStepId;
});
if (!isValidStepId) {
oMessageHandler.putMessage(oMessageHandler.createMessageObject({
code : '5036',
aParameters : [ sStepId ]
}));
} else {
that.createStep(sStepId, callback, sRepId);
}
};
/**
* @private
* @function
* @name sap.apf.core.Instance#getFunctionCreateRequest
* @description Returns function createRequest from sap.apf.core.ConfigurationFactory
*/
this.getFunctionCreateRequest = function() {
return oConfigurationFactory.createRequest;
};
// create local singleton instances...
oTextResourceHandler = new sap.apf.core.TextResourceHandler(oInject);
oMessageHandler.setTextResourceHandler(oTextResourceHandler);
if (oApiInject.manifests) {
oInject.manifests = oApiInject.manifests;
}
oFileExists = new sap.apf.core.utils.FileExists();
oConfigurationFactory = new sap.apf.core.ConfigurationFactory(oInject);
var oInjectMetadataFactory = {
entityTypeMetadata : sap.apf.core.EntityTypeMetadata,
hashtable : sap.apf.utils.Hashtable,
metadata : sap.apf.core.Metadata,
metadataFacade : sap.apf.core.MetadataFacade,
metadataProperty : sap.apf.core.MetadataProperty,
messageHandler : oInject.messageHandler,
coreApi : that,
datajs : OData,
configurationFactory : oConfigurationFactory,
fileExists: oFileExists
};
oMetadataFactory = new sap.apf.core.MetadataFactory(oInjectMetadataFactory);
oPath = new sap.apf.core.Path(oInject);
oSessionHandler = new sap.apf.core.SessionHandler(oInject);
oPersistence = new sap.apf.core.Persistence(oInject);
var oInjectRessourcePathHandler = {
coreApi : that,
messageHandler : oInject.messageHandler,
fileExists : oFileExists,
manifests : oApiInject.manifests
};
oResourcePathHandler = new sap.apf.core.ResourcePathHandler(oInjectRessourcePathHandler);
};
}());<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define([
'sap/ui/fl/Utils', 'jquery.sap.global', 'sap/ui/fl/changeHandler/Base'
], function(Utils, jQuery, Base) {
"use strict";
/**
* Change handler for adding a smart form group.
* @constructor
* @alias sap.ui.fl.changeHandler.AddGroup
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.27.0
*/
var AddGroup = function() {
};
AddGroup.prototype = jQuery.sap.newObject(Base.prototype);
/**
* Adds a smart form group.
*
* @param {sap.ui.fl.Change} oChangeWrapper change wrapper object with instructions to be applied on the control map
* @param {sap.ui.comp.smartform.SmartForm} oForm smart form control that matches the change selector for applying the change
* @param {object} oControlMap flat list of ids that point to control instances
* @public
*/
AddGroup.prototype.applyChange = function(oChangeWrapper, oForm) {
var oChange = oChangeWrapper.getDefinition();
if (oChange.texts && oChange.texts.groupLabel && oChange.texts.groupLabel.value && oChange.content && oChange.content.group && oChange.content.group.id) {
jQuery.sap.require("sap.ui.comp.smartform.Group"); //revise in future when concept for accessing controls within change handlers is available
var oGroup = new sap.ui.comp.smartform.Group(oChange.content.group.id);
if (oGroup.setLabel) {
oGroup.setLabel(oChange.texts.groupLabel.value);
}
if (oForm && oForm.insertGroup) {
oForm.insertGroup(oGroup, oChange.content.group.index);
} else {
throw new Error("no parent form provided for adding the group");
}
} else {
Utils.log.error("Change does not contain sufficient information to be applied: [" + oChange.layer + "]" + oChange.namespace + "/" + oChange.fileName + "." + oChange.fileType);
//however subsequent changes should be applied
}
};
/**
* Completes the change by adding change handler specific content
*
* @param {sap.ui.fl.Change} oChangeWrapper change wrapper object to be completed
* @param {object} oSpecificChangeInfo with attributes "groupLabel", the group label to be included in the change and "newControlId", the control ID for the control to be added
* @public
*/
AddGroup.prototype.completeChangeContent = function(oChangeWrapper, oSpecificChangeInfo) {
var oChange = oChangeWrapper.getDefinition();
if (oSpecificChangeInfo.groupLabel) {
this.setTextInChange(oChange, "groupLabel", oSpecificChangeInfo.groupLabel, "XFLD");
} else {
throw new Error("oSpecificChangeInfo.groupLabel attribute required");
}
if (!oChange.content) {
oChange.content = {};
}
if (!oChange.content.group) {
oChange.content.group = {};
}
if ( oSpecificChangeInfo.newControlId ){
oChange.content.group.id = oSpecificChangeInfo.newControlId;
}else {
throw new Error("oSpecificChangeInfo.newControlId attribute required");
}
if (oSpecificChangeInfo.index === undefined) {
throw new Error("oSpecificChangeInfo.index attribute required");
} else {
oChange.content.group.index = oSpecificChangeInfo.index;
}
};
/**
* Gets the id from the group to be added.
*
* @param {object} oChange - addGroup change, which contains the group id within the content
* @returns {string} group id
* @public
*/
AddGroup.prototype.getControlIdFromChangeContent = function(oChange) {
var sControlId;
if (oChange && oChange._oDefinition) {
sControlId = oChange._oDefinition.content.group.id;
}
return sControlId;
};
return AddGroup;
},
/* bExport= */true);
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
/**
* @class facetFilter
* @name facetFilter
* @description Creates the facet filter
* @memberOf sap.apf.ui.reuse.view
*
*/
(function() {
'use strict';
sap.ui.jsview("sap.apf.ui.reuse.view.facetFilter", {
getControllerName : function() {
return "sap.apf.ui.reuse.controller.facetFilter";
},
createContent : function(oController) {
var oFacetFilterList;
var oCoreApi = this.getViewData().oCoreApi;
var aConfiguredFilters = this.getViewData().aConfiguredFilters;
var aFacetFilterListControls = [];
aConfiguredFilters.forEach(function(oConfiguredFilter) {
oFacetFilterList = new sap.m.FacetFilterList({
title : oCoreApi.getTextNotHtmlEncoded(oConfiguredFilter.getLabel()),
multiSelect : oConfiguredFilter.isMultiSelection(),
key : oConfiguredFilter.getPropertyName(),
growing : false,
listClose : oController.onListClose.bind(oController)
});
aFacetFilterListControls.push(oFacetFilterList);
});
aFacetFilterListControls.forEach(function(oFacetFilterListControl) {
oFacetFilterListControl.bindItems("/", new sap.m.FacetFilterItem({
key : '{key}',
text : '{text}',
selected : '{selected}'
}));
var oModel = new sap.ui.model.json.JSONModel([]);
oFacetFilterListControl.setModel(oModel);
});
var oFacetFilter = new sap.m.FacetFilter(oController.createId("idAPFFacetFilter"), {
type : "Simple",
showReset : true,
showPopoverOKButton : true,
lists : aFacetFilterListControls,
reset : oController.onResetPress.bind(oController)
});
if (sap.ui.Device.system.desktop) {
oFacetFilter.addStyleClass("facetfilter");
}
return oFacetFilter;
}
});
}());<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* Constructor for a new AreaMicroChart control.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Chart that displays the history of values and target values as segmented lines and shows thresholds as colored background. This control replaces the deprecated sap.suite.ui.commons.MicroAreaChart.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.12
*
* @public
* @alias sap.suite.ui.microchart.AreaMicroChart
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var AreaMicroChart = Control.extend("sap.suite.ui.microchart.AreaMicroChart", /** @lends sap.suite.ui.microchart.AreaMicroChart.prototype */ {
metadata: {
library: "sap.suite.ui.microchart",
properties: {
/**
* The width of the chart.
*/
width: {type: "sap.ui.core.CSSSize", group : "Misc", defaultValue : null},
/**
* The height of the chart.
*/
height: {type: "sap.ui.core.CSSSize", group : "Misc", defaultValue : null},
/**
* If this property is set it indicates the value X axis ends with.
*/
maxXValue: {type: "float", group : "Misc", defaultValue : null},
/**
* If this property is set it indicates the value X axis ends with.
*/
minXValue: {type : "float", group : "Misc", defaultValue : null},
/**
* If this property is set it indicates the value X axis ends with.
*/
maxYValue: {type: "float", group : "Misc", defaultValue : null},
/**
* If this property is set it indicates the value X axis ends with.
*/
minYValue: {type: "float", group : "Misc", defaultValue : null},
/**
* The view of the chart.
*/
view: {type: "sap.suite.ui.microchart.AreaMicroChartViewType", group : "Appearance", defaultValue : "Normal"},
/**
* The color palette for the chart. If this property is set,
* semantic colors defined in AreaMicroChartItem are ignored.
* Colors from the palette are assigned to each line consequentially.
* When all the palette colors are used, assignment of the colors begins
* from the first palette color.
*/
colorPalette: {type: "string[]", group : "Appearance", defaultValue : [] }
},
events : {
/**
* The event is fired when the user chooses the micro area chart.
*/
press: {}
},
aggregations: {
/**
* The configuration of the actual values line.
* The color property defines the color of the line.
* Points are rendered in the same sequence as in this aggregation.
*/
chart: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The configuration of the max threshold area. The color property defines the color of the area above the max threshold line. Points are rendered in the same sequence as in this aggregation.
*/
maxThreshold: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The configuration of the upper line of the inner threshold area. The color property defines the color of the area between inner thresholds. For rendering of the inner threshold area, both innerMaxThreshold and innerMinThreshold aggregations must be defined. Points are rendered in the same sequence as in this aggregation.
*/
innerMaxThreshold: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The configuration of the bottom line of the inner threshold area. The color property is ignored. For rendering of the inner threshold area, both innerMaxThreshold and innerMinThreshold aggregations must be defined. Points are rendered in the same sequence as in this aggregation.
*/
innerMinThreshold: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The configuration of the min threshold area. The color property defines the color of the area below the min threshold line. Points are rendered in the same sequence as in this aggregation.
*/
minThreshold: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The configuration of the target values line. The color property defines the color of the line. Points are rendered in the same sequence as in this aggregation.
*/
target: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartItem" },
/**
* The label on X axis for the first point of the chart.
*/
firstXLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The label on Y axis for the first point of the chart.
*/
firstYLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The label on X axis for the last point of the chart.
*/
lastXLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The label on Y axis for the last point of the chart.
*/
lastYLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The label for the maximum point of the chart.
*/
maxLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The label for the minimum point of the chart.
*/
minLabel: { multiple: false, type: "sap.suite.ui.microchart.AreaMicroChartLabel" },
/**
* The set of lines.
*/
lines: { multiple: true, type: "sap.suite.ui.microchart.AreaMicroChartItem" }
}
}
});
AreaMicroChart.prototype.init = function(){
this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.suite.ui.microchart");
this.setTooltip("{AltText}");
};
AreaMicroChart.prototype._getCssValues = function() {
this._cssHelper.className = Array.prototype.slice.call(arguments).join(" ");
var oCsses = window.getComputedStyle(this._cssHelper);
if (oCsses.backgroundColor == undefined) {
oCsses.backgroundColor = oCsses["background-color"];
}
if (oCsses.outlineStyle == undefined) {
oCsses.outlineStyle = oCsses["outline-style"];
}
if (oCsses.outlineWidth == undefined) {
oCsses.outlineWidth = oCsses["outline-width"];
}
return oCsses;
};
AreaMicroChart.prototype.__fillThresholdArea = function(c, aPoints1, aPoints2, color) {
c.beginPath();
c.moveTo(aPoints1[0].x, aPoints1[0].y);
for (var i = 1, length = aPoints1.length; i < length; i++) {
c.lineTo(aPoints1[i].x, aPoints1[i].y);
}
for (var j = aPoints2.length - 1; j >= 0 ; j--) {
c.lineTo(aPoints2[j].x, aPoints2[j].y);
}
c.closePath();
c.fillStyle = "white";
c.fill();
c.fillStyle = color;
c.fill();
c.lineWidth = 1;
c.strokeStyle = "white";
c.stroke();
c.strokeStyle = color;
c.stroke();
};
AreaMicroChart.prototype._renderDashedLine = function(c, aPoints, d, aDashes) {
if (c.setLineDash) {
c.setLineDash(aDashes);
this._renderLine(c, aPoints, d);
c.setLineDash([]);
} else {
c.beginPath();
for (var i = 0, length = aPoints.length - 1; i < length; i++) {
c._dashedLine(aPoints[i].x, aPoints[i].y, aPoints[i + 1].x, aPoints[i + 1].y, aDashes);
}
c.stroke();
}
};
AreaMicroChart.prototype._renderLine = function(c, aPoints, d) {
c.beginPath();
c.moveTo(aPoints[0].x, aPoints[0].y);
for (var i = 1, length = aPoints.length; i < length; i++) {
c.lineTo(aPoints[i].x, aPoints[i].y);
}
c.stroke();
};
AreaMicroChart.prototype._renderTarget = function(c, d) {
if (d.target.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcTarget", this.getTarget().getColor());
c.strokeStyle = oCsses.color;
c.lineWidth = parseFloat(oCsses.width);
if (oCsses.outlineStyle == "dotted") {
this._renderDashedLine(c, d.target, d, [parseFloat(oCsses.outlineWidth), 3]);
} else {
this._renderLine(c, d.target, d);
}
} else if (d.target.length == 1) {
jQuery.sap.log.warning("Target is not rendered because only 1 point was given");
}
};
AreaMicroChart.prototype._renderThresholdLine = function(c, aPoints, d) {
if (aPoints && aPoints.length) {
var oCsses = this._getCssValues("sapSuiteAmcThreshold");
c.strokeStyle = oCsses.color;
c.lineWidth = oCsses.width;
this._renderLine(c, aPoints, d);
}
};
AreaMicroChart.prototype._fillMaxThreshold = function(c, d) {
if (d.maxThreshold.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcThreshold", this.getMaxThreshold().getColor());
this.__fillThresholdArea(c, d.maxThreshold, [
{x: d.maxThreshold[0].x, y: d.minY},
{x: d.maxThreshold[d.maxThreshold.length - 1].x, y: d.minY}
], oCsses.backgroundColor);
this._renderThresholdLine(c, d.maxThreshold, d);
} else if (d.maxThreshold.length == 1) {
jQuery.sap.log.warning("Max Threshold is not rendered because only 1 point was given");
}
};
AreaMicroChart.prototype._fillMinThreshold = function(c, d) {
if (d.minThreshold.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcThreshold", this.getMinThreshold().getColor());
this.__fillThresholdArea(c, d.minThreshold, [
{x: d.minThreshold[0].x, y: d.maxY},
{x: d.minThreshold[d.minThreshold.length - 1].x, y: d.maxY}
], oCsses.backgroundColor);
} else if (d.minThreshold.length == 1) {
jQuery.sap.log.warning("Min Threshold is not rendered because only 1 point was given");
}
};
AreaMicroChart.prototype._fillThresholdArea = function(c, d) {
if (d.minThreshold.length > 1 && d.maxThreshold.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcThreshold", "Critical");
this.__fillThresholdArea(c, d.maxThreshold, d.minThreshold, oCsses.backgroundColor);
}
};
AreaMicroChart.prototype._fillInnerThresholdArea = function(c, d) {
if (d.innerMinThreshold.length > 1 && d.innerMaxThreshold.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcThreshold", this.getInnerMaxThreshold().getColor());
this.__fillThresholdArea(c, d.innerMaxThreshold, d.innerMinThreshold, oCsses.backgroundColor);
} else if (d.innerMinThreshold.length || d.innerMaxThreshold.length) {
jQuery.sap.log.warning("Inner threshold area is not rendered because inner min and max threshold were not correctly set");
}
};
AreaMicroChart.prototype._renderChart = function(c, d) {
if (d.chart.length > 1) {
var oCsses = this._getCssValues("sapSuiteAmcChart", this.getChart().getColor());
c.strokeStyle = oCsses.color;
c.lineWidth = parseFloat(oCsses.width);
this._renderLine(c, d.chart, d);
} else if (d.chart.length == 1) {
jQuery.sap.log.warning("Actual values are not rendered because only 1 point was given");
}
};
AreaMicroChart.prototype._renderLines = function(c, d) {
var iCpLength = this.getColorPalette().length;
var iCpIndex = 0;
var that = this;
var fnNextColor = function() {
if (iCpLength) {
if (iCpIndex == iCpLength) {
iCpIndex = 0;
}
return that.getColorPalette()[iCpIndex++];
}
};
var oCsses = this._getCssValues("sapSuiteAmcLine");
c.lineWidth = parseFloat(oCsses.width);
var iLength = d.lines.length;
for (var i = 0; i < iLength; i++) {
if (d.lines[i].length > 1) {
if (iCpLength) {
c.strokeStyle = fnNextColor();
} else {
oCsses = this._getCssValues("sapSuiteAmcLine", this.getLines()[i].getColor());
c.strokeStyle = oCsses.color;
}
this._renderLine(c, d.lines[i], d);
}
}
};
AreaMicroChart.prototype._renderCanvas = function() {
this._cssHelper = document.getElementById(this.getId() + "-css-helper");
var sLabelsWidth = this.$().find(".sapSuiteAmcSideLabels").css("width");
this.$().find(".sapSuiteAmcCanvas, .sapSuiteAmcLabels").css("right", sLabelsWidth).css("left", sLabelsWidth);
var canvas = document.getElementById(this.getId() + "-canvas");
var canvasSettings = window.getComputedStyle(canvas);
var fWidth = parseFloat(canvasSettings.width);
canvas.setAttribute("width", fWidth ? fWidth : 360);
var fHeight = parseFloat(canvasSettings.height);
canvas.setAttribute("height", fHeight ? fHeight : 242);
var c = canvas.getContext("2d");
c.lineJoin = "round";
c._dashedLine = function(x, y, x2, y2, dashArray) {
var dashCount = dashArray.length;
this.moveTo(x, y);
var dx = (x2 - x), dy = (y2 - y);
var slope = dx ? dy / dx : 1e15;
var distRemaining = Math.sqrt(dx * dx + dy * dy);
var dashIndex = 0, draw = true;
while (distRemaining >= 0.1) {
var dashLength = dashArray[dashIndex++ % dashCount];
if (dashLength > distRemaining) {
dashLength = distRemaining;
}
var xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope));
if (dx < 0) {
xStep = -xStep;
}
x += xStep;
y += slope * xStep;
this[draw ? 'lineTo' : 'moveTo'](x, y);
distRemaining -= dashLength;
draw = !draw;
}
};
var d = this._calculateDimensions(canvas.width, canvas.height);
this._fillMaxThreshold(c, d);
this._fillMinThreshold(c, d);
this._fillThresholdArea(c, d);
this._renderThresholdLine(c, d.minThreshold, d);
this._renderThresholdLine(c, d.maxThreshold, d);
this._fillInnerThresholdArea(c, d);
this._renderThresholdLine(c, d.innerMinThreshold, d);
this._renderThresholdLine(c, d.innerMaxThreshold, d);
this._renderTarget(c, d);
this._renderChart(c, d);
this._renderLines(c, d);
};
/**
*
*
* @param fWidth
* @param fHeight
* @returns {object}
*/
AreaMicroChart.prototype._calculateDimensions = function(fWidth, fHeight) {
var maxX, maxY, minX, minY;
maxX = maxY = minX = minY = undefined;
var that = this;
function calculateExtremums() {
if (!that._isMinXValue || !that._isMaxXValue || !that._isMinYValue || !that._isMaxYValue) {
var lines = that.getLines();
if (that.getMaxThreshold()) {
lines.push(that.getMaxThreshold());
}
if (that.getMinThreshold()) {
lines.push(that.getMinThreshold());
}
if (that.getChart()) {
lines.push(that.getChart());
}
if (that.getTarget()) {
lines.push(that.getTarget());
}
if (that.getInnerMaxThreshold()) {
lines.push(that.getInnerMaxThreshold());
}
if (that.getInnerMinThreshold()) {
lines.push(that.getInnerMinThreshold());
}
for (var i = 0, numOfLines = lines.length; i < numOfLines; i++) {
var aPoints = lines[i].getPoints();
for (var counter = 0, a = aPoints.length; counter < a; counter++) {
var tmpVal = aPoints[counter].getXValue();
if (tmpVal > maxX || maxX === undefined) {
maxX = tmpVal;
}
if (tmpVal < minX || minX === undefined) {
minX = tmpVal;
}
tmpVal = aPoints[counter].getYValue();
if (tmpVal > maxY || maxY === undefined) {
maxY = tmpVal;
}
if (tmpVal < minY || minY === undefined) {
minY = tmpVal;
}
}
}
}
if (that._isMinXValue) {
minX = that.getMinXValue();
}
if (that._isMaxXValue) {
maxX = that.getMaxXValue();
}
if (that._isMinYValue) {
minY = that.getMinYValue();
}
if (that._isMaxYValue) {
maxY = that.getMaxYValue();
}
}
calculateExtremums();
var oResult = {
minY: 0,
minX: 0,
maxY: fHeight,
maxX: fWidth,
lines: []
};
var kx;
var fDeltaX = maxX - minX;
if (fDeltaX > 0) {
kx = fWidth / fDeltaX;
} else if (fDeltaX == 0) {
kx = 0;
oResult.maxX /= 2;
} else {
jQuery.sap.log.warning("Min X is more than max X");
}
var ky;
var fDeltaY = maxY - minY;
if (fDeltaY > 0) {
ky = fHeight / (maxY - minY);
} else if (fDeltaY == 0) {
ky = 0;
oResult.maxY /= 2;
} else {
jQuery.sap.log.warning("Min Y is more than max Y");
}
function calculateCoordinates(line) {
var bRtl = sap.ui.getCore().getConfiguration().getRTL();
var fnCalcX = function(fValue) {
var x = kx * (fValue - minX);
if (bRtl) {
x = oResult.maxX - x;
}
return x;
};
var fnCalcY = function(fValue) {
return oResult.maxY - ky * (fValue - minY);
};
var aResult = [];
if (line && kx != undefined && ky != undefined) {
var aPoints = line.getPoints();
var iLength = aPoints.length;
var xi, yi, tmpXValue, tmpYValue;
if (iLength == 1) {
tmpXValue = aPoints[0].getXValue();
tmpYValue = aPoints[0].getYValue();
if (tmpXValue == undefined ^ tmpYValue == undefined) {
var xn, yn;
if (tmpXValue == undefined) {
yn = yi = fnCalcY(tmpYValue);
xi = oResult.minX;
xn = oResult.maxX;
} else {
xn = xi = fnCalcX(tmpXValue);
yi = oResult.minY;
yn = oResult.maxY;
}
aResult.push({x: xi, y: yi}, {x: xn, y: yn});
} else {
jQuery.sap.log.warning("Point with coordinates [" + tmpXValue + " " + tmpYValue + "] ignored");
}
} else {
for (var i = 0; i < iLength; i++) {
tmpXValue = aPoints[i].getXValue();
tmpYValue = aPoints[i].getYValue();
if (tmpXValue != undefined && tmpYValue != undefined) {
xi = fnCalcX(tmpXValue);
yi = fnCalcY(tmpYValue);
aResult.push({x: xi, y: yi});
} else {
jQuery.sap.log.warning("Point with coordinates [" + tmpXValue + " " + tmpYValue + "] ignored");
}
}
}
}
return aResult;
}
oResult.maxThreshold = calculateCoordinates(that.getMaxThreshold());
oResult.minThreshold = calculateCoordinates(that.getMinThreshold());
oResult.chart = calculateCoordinates(that.getChart());
oResult.target = calculateCoordinates(that.getTarget());
oResult.innerMaxThreshold = calculateCoordinates(that.getInnerMaxThreshold());
oResult.innerMinThreshold = calculateCoordinates(that.getInnerMinThreshold());
var iLength = that.getLines().length;
for (var i = 0; i < iLength; i++) {
oResult.lines.push(calculateCoordinates(that.getLines()[i]));
}
return oResult;
};
/**
* Property setter for the Min X value
*
* @param {int} value - new value Min X
* @param {boolean} bSuppressInvalidate - Suppress in validate
* @returns {void}
* @public
*/
AreaMicroChart.prototype.setMinXValue = function(value, bSuppressInvalidate) {
this._isMinXValue = this._isNumber(value);
return this.setProperty("minXValue", this._isMinXValue ? value : NaN, bSuppressInvalidate);
};
/**
* Property setter for the Max X value
*
* @param {int} value - new value Max X
* @param {boolean} bSuppressInvalidate - Suppress in validate
* @returns {void}
* @public
*/
AreaMicroChart.prototype.setMaxXValue = function(value, bSuppressInvalidate) {
this._isMaxXValue = this._isNumber(value);
return this.setProperty("maxXValue", this._isMaxXValue ? value : NaN, bSuppressInvalidate);
};
/**
* Property setter for the Min Y value
*
* @param {value} value - new value Min Y
* @param {boolean} bSuppressInvalidate - Suppress in validate
* @returns {void}
* @public
*/
AreaMicroChart.prototype.setMinYValue = function(value, bSuppressInvalidate) {
this._isMinYValue = this._isNumber(value);
return this.setProperty("minYValue", this._isMinYValue ? value : NaN, bSuppressInvalidate);
};
/**
* Property setter for the Max Y valye
*
* @param {string} value - new value Max Y
* @param {boolean} bSuppressInvalidate - Suppress in validate
* @returns {void}
* @public
*/
AreaMicroChart.prototype.setMaxYValue = function(value, bSuppressInvalidate) {
this._isMaxYValue = this._isNumber(value);
return this.setProperty("maxYValue", this._isMaxYValue ? value : NaN, bSuppressInvalidate);
};
AreaMicroChart.prototype._isNumber = function(n) {
return typeof n === 'number' && !isNaN(n) && isFinite(n);
};
AreaMicroChart.prototype.onAfterRendering = function() {
this._renderCanvas();
};
AreaMicroChart.prototype.ontap = function(oEvent) {
if (sap.ui.Device.browser.internet_explorer) {
this.$().focus();
}
this.firePress();
};
AreaMicroChart.prototype.onkeydown = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.SPACE) {
oEvent.preventDefault();
}
};
AreaMicroChart.prototype.onkeyup = function(oEvent) {
if (oEvent.which == jQuery.sap.KeyCodes.ENTER || oEvent.which == jQuery.sap.KeyCodes.SPACE) {
this.firePress();
oEvent.preventDefault();
}
};
AreaMicroChart.prototype.attachEvent = function(sEventId, oData, fnFunction, oListener) {
sap.ui.core.Control.prototype.attachEvent.call(this, sEventId, oData, fnFunction, oListener);
if (this.hasListeners("press")) {
this.$().attr("tabindex", 0).addClass("sapSuiteUiMicroChartPointer");
}
return this;
};
AreaMicroChart.prototype.detachEvent = function(sEventId, fnFunction, oListener) {
sap.ui.core.Control.prototype.detachEvent.call(this, sEventId, fnFunction, oListener);
if (!this.hasListeners("press")) {
this.$().removeAttr("tabindex").removeClass("sapSuiteUiMicroChartPointer");
}
return this;
};
AreaMicroChart.prototype._getLocalizedColorMeaning = function(sColor) {
return this._oRb.getText(("SEMANTIC_COLOR_" + sColor).toUpperCase());
};
AreaMicroChart.prototype.getAltText = function() {
var sAltText = "";
var oFirstXLabel = this.getFirstXLabel();
var oFirstYLabel = this.getFirstYLabel();
var oLastXLabel = this.getLastXLabel();
var oLastYLabel = this.getLastYLabel();
var oMinLabel = this.getMinLabel();
var oMaxLabel = this.getMaxLabel();
var oActual = this.getChart();
var oTarget = this.getTarget();
var bIsFirst = true;
if (oFirstXLabel && oFirstXLabel.getLabel() || oFirstYLabel && oFirstYLabel.getLabel()) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_START")) + ": " + (oFirstXLabel ? oFirstXLabel.getLabel() : "") + " " + (oFirstYLabel ? oFirstYLabel.getLabel() + " " + this._getLocalizedColorMeaning(oFirstYLabel.getColor()) : "");
bIsFirst = false;
}
if (oLastXLabel && oLastXLabel.getLabel() || oLastYLabel && oLastYLabel.getLabel()) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_END")) + ": " + (oLastXLabel ? oLastXLabel.getLabel() : "") + " " + (oLastYLabel ? oLastYLabel.getLabel() + " " + this._getLocalizedColorMeaning(oLastYLabel.getColor()) : "");
bIsFirst = false;
}
if (oMinLabel && oMinLabel.getLabel()) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_MINIMAL_VALUE")) + ": " + oMinLabel.getLabel() + " " + this._getLocalizedColorMeaning(oMinLabel.getColor());
bIsFirst = false;
}
if (oMaxLabel && oMaxLabel.getLabel()) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_MAXIMAL_VALUE")) + ": " + oMaxLabel.getLabel() + " " + this._getLocalizedColorMeaning(oMaxLabel.getColor());
bIsFirst = false;
}
if (oActual && oActual.getPoints() && oActual.getPoints().length > 0) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_ACTUAL_VALUES")) + ":";
bIsFirst = false;
var aActual = oActual.getPoints();
for (var i = 0; i < aActual.length; i++) {
sAltText += " " + aActual[i].getY();
}
}
if (oTarget && oTarget.getPoints() && oTarget.getPoints().length > 0) {
sAltText += (bIsFirst ? "" : "\n") + this._oRb.getText(("AREAMICROCHART_TARGET_VALUES")) + ":";
var aTarget = oTarget.getPoints();
for (var j = 0; j < aTarget.length; j++) {
sAltText += " " + aTarget[j].getY();
}
}
for (var k = 0; k < this.getLines().length; k++) {
var oLine = this.getLines()[k];
if (oLine.getPoints() && oLine.getPoints().length > 0) {
sAltText += (bIsFirst ? "" : "\n") + oLine.getTitle() + ":";
var aLine = oLine.getPoints();
for (var y = 0; y < aLine.length; y++) {
sAltText += " " + aLine[y].getY();
}
if (this.getColorPalette().length == 0) {
sAltText += " " + this._getLocalizedColorMeaning(oLine.getColor());
}
}
}
return sAltText;
};
AreaMicroChart.prototype.getTooltip_AsString = function() {
var oTooltip = this.getTooltip();
var sTooltip = this.getAltText();
if (typeof oTooltip === "string" || oTooltip instanceof String) {
sTooltip = oTooltip.split("{AltText}").join(sTooltip).split("((AltText))").join(sTooltip);
return sTooltip;
}
return oTooltip ? oTooltip : "";
};
AreaMicroChart.prototype.clone = function(sIdSuffix, aLocalIds, oOptions) {
var oClone = sap.ui.core.Control.prototype.clone.apply(this, arguments);
oClone._isMinXValue = this._isMinXValue;
oClone._isMaxXValue = this._isMaxXValue;
oClone._isMinYValue = this._isMinYValue;
oClone._isMaxYValue = this._isMaxYValue;
return oClone;
};
return AreaMicroChart;
});<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2016 SAP SE. All rights reserved
*/
sap.ui.define([
'jquery.sap.global',
'sap/ui/fl/registry/ChangeRegistry',
'sap/ui/fl/registry/SimpleChanges',
'sap/ui/comp/smartform/flexibility/changes/RemoveField',
'sap/ui/comp/smartform/flexibility/changes/RemoveGroup',
'sap/ui/comp/smartform/flexibility/changes/RenameField',
'sap/ui/comp/smartform/flexibility/changes/RenameGroup',
'sap/ui/comp/smartform/flexibility/changes/AddField',
'sap/ui/comp/smartform/flexibility/changes/AddFields',
'sap/ui/comp/smartform/flexibility/changes/AddGroup',
'sap/ui/comp/smartform/flexibility/changes/MoveGroups',
'sap/ui/comp/smartform/flexibility/changes/MoveFields',
'sap/ui/comp/smartform/flexibility/changes/OrderGroups',
'sap/ui/comp/smartform/flexibility/changes/OrderFields'
], function(jQuery, ChangeRegistry, SimpleChanges, RemoveField, RemoveGroup, RenameField, RenameGroup, AddField, AddFields, AddGroup, MoveGroups, MoveFields, OrderGroups, OrderFields) {
"use strict";
/**
* Change handler for adding a smart form group element (representing a field).
* @name sap.ui.comp.smartform.flexibility.Registration
* @namespace
* @author SAP SE
* @version 1.36.12
* @experimental Since 1.29.0
*/
return {
registerLibrary: function(){
var compChanges = {
orderFields: {
changeType: "orderFields",
changeHandler: OrderFields
},
orderGroups: {
changeType: "orderGroups",
changeHandler: OrderGroups
},
removeField: {
changeType: "removeField",
changeHandler: RemoveField
},
removeGroup: {
changeType: "removeGroup",
changeHandler: RemoveGroup
},
renameField: {
changeType: "renameField",
changeHandler: RenameField
},
renameGroup: {
changeType: "renameGroup",
changeHandler: RenameGroup
},
addField: {
changeType: "addField",
changeHandler: AddField
},
addFields: {
changeType: "addFields",
changeHandler: AddFields
},
addGroup: {
changeType: "addGroup",
changeHandler: AddGroup
},
moveGroups: {
changeType: "moveGroups",
changeHandler: MoveGroups
},
moveFields: {
changeType: "moveFields",
changeHandler: MoveFields
}
};
var oChangeRegistry = ChangeRegistry.getInstance();
oChangeRegistry.registerControlsForChanges({
"sap.ui.comp.smartform.SmartForm": [
compChanges.removeGroup,
compChanges.addGroup,
compChanges.moveGroups,
compChanges.renameField,
SimpleChanges.propertyChange
],
"sap.ui.comp.smartform.Group": [
SimpleChanges.hideControl,
SimpleChanges.unhideControl,
compChanges.renameGroup,
compChanges.addField,
compChanges.addFields,
compChanges.moveFields
],
"sap.ui.comp.smartform.GroupElement": [
SimpleChanges.unhideControl,
SimpleChanges.hideControl,
compChanges.renameField
],
"sap.ui.comp.smarttable.SmartTable": [
SimpleChanges.propertyChange
],
"sap.ui.comp.smartfilterbar.SmartFilterBar": [
SimpleChanges.propertyChange
]
});
}
};
},
/* bExport= */true);
<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2015 SAP SE. All rights reserved
*/
sap.ui.define([
"./LegendBase"
], function (LegendBase) {
"use strict";
var DimensionLegend = LegendBase.extend({
metadata: {
properties: {
shape: {type: "sap.gantt.config.Shape"},
xDimension: {type: "string"},
yDimension: {type: "string"},
xDomain: {type: "array"},
yDomain: {type: "array"}
}
}
});
return DimensionLegend;
}, true);<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2015 SAP SE. All rights reserved
*/
sap.ui.define([
"./LegendBase", "sap/gantt/drawer/ListLegend", "sap/gantt/drawer/CalendarPattern"
], function (LegendBase, ListLegendDrawer, CalendarPattern) {
"use strict";
var ListLegend = LegendBase.extend("sap.gantt.legend.ListLegend", {
metadata: {
properties: {
shapes: {type: "array"}
}
}
});
ListLegend.prototype.init = function () {
LegendBase.prototype.init.apply(this, arguments);
this._oListLegendDrawer = new ListLegendDrawer();
};
ListLegend.prototype.onAfterRendering = function () {
for (var i = 0; i < this._aShapeInstance.length; i++) {
var oShape = this._aShapeInstance[i];
var aSvg = d3.select("#" + this.getId() + "-svg-" + i);
this._oListLegendDrawer._drawPerTag(aSvg, oShape);
}
};
ListLegend.prototype.setShapes = function (aShapes) {
if (aShapes && aShapes.length > 0) {
this._aShapeInstance = this._instantShape(aShapes);
this.setProperty("shapes", aShapes);
}
return this;
};
ListLegend.prototype._instantShape = function (aShapes) {
var aRetVal = [];
// parse shape instances
for (var i = 0; i < aShapes.length; i++) {
if (aShapes[i].getShapeClassName()) {
// create shape instance
var oShapeInst = this._instantiateCustomerClass(aShapes[i].getShapeClassName(), i, aShapes[i]);
if (aShapes[i].getClippathAggregation() && aShapes[i].getClippathAggregation() instanceof Array) {
// create aggregation classes for clip-path
var aPath = this._instantShape(aShapes[i].getClippathAggregation());
aRetVal = aRetVal.concat(aPath);
} else if (aShapes[i].getGroupAggregation() && aShapes[i].getGroupAggregation() instanceof Array) {
// create aggregation classes for group
var aAggregation = this._instantShape(aShapes[i].getGroupAggregation());
for (var k = 0; k < aAggregation.length; k++) {
oShapeInst.addShape(aAggregation[k]);
}
}
if (this._isProperShape(oShapeInst)) {
aRetVal.push(oShapeInst);
}
}
}
return aRetVal;
};
ListLegend.prototype._isProperShape = function (oShapeInst) {
if (oShapeInst instanceof sap.gantt.shape.cal.Calendar) {
jQuery.sap.log.warning("Calendar is not proper shape", "key '" + oShapeInst.mShapeConfig.getKey() + "'", "ListLegend");
return false;
} else if (oShapeInst.getTag() == "clippath") {
return false;
} else {
return true;
}
};
ListLegend.prototype._instantiateCustomerClass = function (sCustomerClassName, sShapeId, oShapeConfig) {
var CustomerClass = jQuery.sap.getObject(sCustomerClassName);
if (!CustomerClass) {
jQuery.sap.require(sCustomerClassName);
CustomerClass = jQuery.sap.getObject(sCustomerClassName);
}
var oCustomerClassInstance = new CustomerClass();
oCustomerClassInstance.mShapeConfig = oShapeConfig;
oCustomerClassInstance.mChartInstance = this;
return oCustomerClassInstance;
};
return ListLegend;
}, true);<file_sep>/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
(c) Copyright 2009-2015 SAP SE. All rights reserved
*/
sap.ui.define([
'jquery.sap.global',
"sap/gantt/GanttChartBase", "sap/ui/core/Core", "sap/ui/table/TreeTable", "sap/ui/table/Row",
"sap/gantt/misc/Utility",
'sap/ui/core/theming/Parameters',
"sap/gantt/shape/SelectedShape", "sap/gantt/shape/ext/rls/SelectedRelationship",
"sap/gantt/drawer/ShapeInRow", "sap/gantt/drawer/ShapeCrossRow", "sap/gantt/drawer/CursorLine", "sap/gantt/drawer/NowLine", "sap/gantt/drawer/VerticalLine","sap/gantt/drawer/CalendarPattern",
"sap/gantt/misc/AxisTime", "sap/gantt/misc/AxisOrdinal", "sap/gantt/misc/Format", "sap/gantt/misc/TreeTableHelper",
// 3rd party lib
"sap/ui/thirdparty/d3"
], function (jQuery, GanttChartBase, Core, TreeTable, Row, Utility, Parameters, SelectedShape, SelectedRelationship,
ShapeInRowDrawer, ShapeCrossRowDrawer, CursorLineDrawer, NowLineDrawer, VerticalLineDrawer, CalendarPattern, AxisTime, AxisOrdinal, Format, TreeTableHelper) {
"use strict";
/**
* Creates and initializes a new Gantt Chart.
*
* @param {string} [sId] ID for the new control, generated automatically if no id is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* Gantt Chart control.
*
* <p>The Gantt chart has a horizontal axis at the top that represents time and a vertical axis that represents rows.
* </p>
*
* @extends sap.gantt.GanttChartBase
*
* @author SAP SE
* @version 1.36.8
*
* @constructor
* @public
* @alias sap.gantt.GanttChart
*/
var GanttChart = GanttChartBase.extend("sap.gantt.GanttChart", /** @lends sap.gantt.GanttChart.prototype */ {
metadata: {
aggregations: {
_treeTable: {type: "sap.ui.table.TreeTable", multiple: false, visibility: "hidden"} // to ensure model pass down
}
}
});
GanttChart.prototype.init = function () {
jQuery.sap.measure.start("GanttChart init","GanttPerf:GanttChart init function");
// create tree table
this._oTT = new TreeTable({
visibleRowCountMode: "Auto",
minAutoRowCount: 1,
selectionBehavior: sap.ui.table.SelectionBehavior.RowOnly,
selectionMode: sap.ui.table.SelectionMode.Multi,
columnHeaderVisible: false
});
this._oTT.addColumn(new sap.ui.table.Column());
this.setAggregation("_treeTable", this._oTT);
// de/attach horizontal scroll bar
this._oTT._oHSb.detachScroll(this._oTT.onhscroll, this._oTT);
this._oTT._oHSb.attachScroll(this._onHSbScroll, this);
// de/attach vertical scroll bar
this._oTT._oVSb.detachScroll(this._oTT.onvscroll, this._oTT);
this._oTT._oVSb.attachScroll(this._onVSbScroll, this);
// sync svg with oTT
this._oTT.attachEvent("_rowsUpdated", this._onTTRowUpdate.bind(this));
this._oTT.addEventDelegate({
onAfterRendering: this._onTTRowUpdate
}, this);
this._oTT.attachEvent("_rowSelectionChange", this._onRowSelectionChange.bind(this));
this._oTT.attachRowSelectionChange(this._onRowSelectionChange, this);
this._oTT.addEventDelegate({
onAfterRendering: this._updateCSSForDummyRow
}, this);
// create drawers
this._oShapeInRowDrawer = new ShapeInRowDrawer();
this._oShapeCrossRowDrawer = new ShapeCrossRowDrawer();
this._oCursorLineDrawer = new CursorLineDrawer();
this._oCalendarPatternDrawer = new CalendarPattern();
// internal private members
this._oAxisTime = undefined;
this._oAxisOrdinal = undefined;
this._aShapeData = undefined; // data to be drawn on svg using registed shape instances
this._aShapeInstance = undefined; // array of shape instances
this._oShapeInstance = undefined; // map of top shape instances
this._oZoom = { // zoom info
base: {}
};
this._oDataNamePerType = {};
this._fLeftOffsetRate = 0.0;
this._oStatusSet = null;
this._nLowerRange = 0;
this._nUpperRange = 0;
this._aSelectedRelationships = undefined;
this._oSelectedShapes = {};
this._aSelectedShapeUids = [];
//add for mouse events to support drag shape over views
this._iMouseDown = 0;
this._bMouseDown = false;
this._bDragging = false;
this._oDraggingData = undefined;
this._lastHoverRowIndex = undefined;
// defualt maps
this._oChartSchemesConfigMap = {};
this._oChartSchemesConfigMap[sap.gantt.config.DEFAULT_CHART_SCHEME_KEY] = sap.gantt.config.DEFAULT_CHART_SCHEME;
this._oObjectTypesConfigMap = {};
this._oObjectTypesConfigMap[sap.gantt.config.DEFAULT_OBJECT_TYPE_KEY] = sap.gantt.config.DEFAULT_OBJECT_TYPE;
this._fExtendFactor = 0.382;
// create default this._oAxisTime
this._calZoomFromTimeAxisConfig(sap.gantt.config.DEFAULT_TIME_AXIS);
this._createAxisTime(sap.gantt.config.DEFAULT_TIME_AXIS);
// performance tuning
this._mDrawDelayMS = 500;
this._mTimeouts = {};
jQuery.sap.measure.end("GanttChart init");
};
GanttChart.prototype.setTimeAxis = function (oTimeAxis) {
this.setProperty("timeAxis", oTimeAxis, true); // no need to trigger rerender
this._calZoomFromTimeAxisConfig(oTimeAxis);
this._createAxisTime(oTimeAxis);
this._oStatusSet = null;
this._draw(true); // only _draw is triggered
return this;
};
GanttChart.prototype.setLocale = function (oLocale) {
this.setProperty("locale", oLocale, true); // no need to trigger rerender
this._oAxisTime.setLocale(oLocale);
this._drawShapes();
this._drawSelectedShapes();
return this;
};
GanttChart.prototype.setChartSchemes = function (aChartSchemes) {
this.setProperty("chartSchemes", aChartSchemes, true); // no need to trigger rerender
// build a map for easy look up
this._oChartSchemesConfigMap = {};
if (aChartSchemes) {
for (var i = 0; i < aChartSchemes.length; i++) {
this._oChartSchemesConfigMap[aChartSchemes[i].getKey()] = aChartSchemes[i];
}
}
this._drawShapes();
this._drawSelectedShapes();
return this;
};
GanttChart.prototype.setObjectTypes = function (aObjectTypes) {
this.setProperty("objectTypes", aObjectTypes, true); // no need to trigger rerender
// build a map for easy look up
this._oObjectTypesConfigMap = {};
if (aObjectTypes) {
for (var i = 0; i < aObjectTypes.length; i++){
this._oObjectTypesConfigMap[aObjectTypes[i].getKey()] = aObjectTypes[i];
}
}
this._drawShapes();
this._drawSelectedShapes();
return this;
};
GanttChart.prototype.setSelectionMode = function (sSelectionMode) {
this.setProperty("selectionMode", sSelectionMode);
if (this._oTT) {
if (sSelectionMode == sap.gantt.SelectionMode.MultiWithKeyboard) {
this._oTT.setSelectionMode(sap.ui.table.SelectionMode.Multi);
}else if (sSelectionMode == sap.gantt.SelectionMode.Multiple){
this._oTT.setSelectionMode(sap.ui.table.SelectionMode.MultiToggle);
}else if (sSelectionMode == sap.gantt.SelectionMode.Single) {
this._oTT.setSelectionMode(sap.ui.table.SelectionMode.Single);
}else {
this._oTT.setSelectionMode(sap.ui.table.SelectionMode.None);
}
}
return this;
};
GanttChart.prototype._calZoomFromTimeAxisConfig = function (oTimeAxis) {
if (!oTimeAxis) {
return;
}
// init an object on this._oZoom
this._oZoom.base.sGranularity = oTimeAxis.getGranularity();
var oGranularity = oTimeAxis.getZoomStrategy()[this._oZoom.base.sGranularity];
this._oZoom.determinedByConfig = {
fRate: 1
};
// get granularity objects
var oFinestGranularity = oTimeAxis.getZoomStrategy()[oTimeAxis.getFinestGranularity()];
var oCoarsestGranularity = oTimeAxis.getZoomStrategy()[oTimeAxis.getCoarsestGranularity()];
var oStart = d3.time.format("%Y%m%d%H%M%S").parse("20000101000000");
// calculate base rate scale
var oBaseDate = jQuery.sap.getObject(oGranularity.innerInterval.unit)
.offset(oStart, oGranularity.innerInterval.span);
this._oZoom.base.fScale = this._calZoomScale(oStart, oBaseDate, oGranularity.innerInterval.range);
// calculate max rate scale
var oMaxDate = jQuery.sap.getObject(oFinestGranularity.innerInterval.unit)
.offset(oStart, oFinestGranularity.innerInterval.span);
var fMaxScale = this._calZoomScale(oStart, oMaxDate, oFinestGranularity.innerInterval.range * 4);
// calculate min rate scale
var oMinDate = jQuery.sap.getObject(oCoarsestGranularity.innerInterval.unit)
.offset(oStart, oCoarsestGranularity.innerInterval.span);
var fMinScale = this._calZoomScale(oStart, oMinDate, oCoarsestGranularity.innerInterval.range);
// calculate zoom rates
this._oZoom.determinedByConfig.fMaxRate = this._oZoom.base.fScale / fMaxScale;
this._oZoom.determinedByConfig.fMinRate = this._oZoom.base.fScale / fMinScale;
};
GanttChart.prototype._calZoomScale = function (oStartDate, oEndDate, iLength) {
return (oEndDate.valueOf() - oStartDate.valueOf()) / iLength;
};
GanttChart.prototype._createAxisTime = function (oConfigTimeAxis) {
var aStrategy = oConfigTimeAxis.getZoomStrategy();
var oHorizonStartTime = d3.time.format("%Y%m%d%H%M%S").parse(
oConfigTimeAxis.getPlanHorizon().getStartTime());
var oHorizonEndTime = d3.time.format("%Y%m%d%H%M%S").parse(
oConfigTimeAxis.getPlanHorizon().getEndTime());
var nHorizonTimeRange = oHorizonEndTime.valueOf() - oHorizonStartTime.valueOf();
var oGranularity = aStrategy[oConfigTimeAxis.getGranularity()];
var nUnitTimeRange = jQuery.sap.getObject(oGranularity.innerInterval.unit)
.offset(oHorizonStartTime, oGranularity.innerInterval.span).valueOf() - oHorizonStartTime.valueOf();
this._oAxisTime = new AxisTime(
[oHorizonStartTime, oHorizonEndTime],
[0, Math.ceil(nHorizonTimeRange * oGranularity.innerInterval.range / nUnitTimeRange)],
oConfigTimeAxis.getRate(), null, null,
this.getLocale(), Core.getConfiguration().getRTL(), oConfigTimeAxis.getZoomStrategy());
this._nLowerRange = this._oAxisTime.getViewRange()[0];
this._nUpperRange = Math.ceil(this._oAxisTime.getViewRange()[1]);
};
GanttChart.prototype.setShapes = function (aShapes) {
this.setProperty("shapes", aShapes, true); // no need to trigger rerender
if (aShapes && aShapes.length > 0) {
this._oShapesConfigMap = {};
for (var i = 0; i < aShapes.length; i++) {
this._oShapesConfigMap[aShapes[i].getKey()] = aShapes[i];
}
this._parseAndSortShape(this._oShapesConfigMap);
this._drawShapes();
this._drawSelectedShapes();
}
return this;
};
GanttChart.prototype._parseAndSortShape = function (oShapeConfig, sTopShapeId) {
var aRetVal = [];
// parse shape instances
var sShapeId, oShapeInst, oSelectedShapeInst, aAggregation, aPath, sSelectedShapeClassName;
for (var i in oShapeConfig) {
sShapeId = sTopShapeId ? sTopShapeId : i;
oShapeInst = {};
if (oShapeConfig[i].getShapeClassName()) {
// create shape instance
oShapeInst = this._instantiateCustomerClass(oShapeConfig[i].getShapeClassName(), i, oShapeConfig[i], sShapeId);
var category = oShapeInst.getCategory(null, this._oAxisTime, this._oAxisOrdinal);
// create selected shape instance for top shape only
if (!sTopShapeId){
sSelectedShapeClassName = oShapeConfig[i].getSelectedClassName();
if (!sSelectedShapeClassName) {
if (category == sap.gantt.shape.ShapeCategory.Relationship) {
sSelectedShapeClassName = "sap.gantt.shape.ext.rls.SelectedRelationship";
oSelectedShapeInst = new SelectedRelationship();
}else {
sSelectedShapeClassName = "sap.gantt.shape.SelectedShape";
}
}
oSelectedShapeInst = this._instantiateCustomerClass(
sSelectedShapeClassName, "selected" + i, oShapeConfig[i], sShapeId);
oShapeInst.setAggregation("selectedShape", oSelectedShapeInst);
}
// create aggregations
if (oShapeConfig[i].getGroupAggregation() && oShapeConfig[i].getGroupAggregation() instanceof Array) {
// create aggregation classes for group
aAggregation = this._parseAndSortShape(oShapeConfig[i].getGroupAggregation(), sShapeId);
for (var k = 0; k < aAggregation.length; k++) {
oShapeInst.addShape(aAggregation[k]);
}
} else if (oShapeConfig[i].getClippathAggregation() && oShapeConfig[i].getClippathAggregation() instanceof Array) {
// create aggregation classes for clip-path
aPath = this._parseAndSortShape(oShapeConfig[i].getClippathAggregation(), sShapeId);
for (var j = 0; j < aPath.length; j++) {
oShapeInst.addPath(aPath[j]);
}
}
}
aRetVal.push(oShapeInst);
}
// sort top shape instances and create map by shape id
if (sTopShapeId){
return aRetVal;
} else {
aRetVal.sort(function (oShape1, oShape2) {
var level1 = jQuery.isNumeric(oShape1.mShapeConfig.getLevel()) ?
oShape1.mShapeConfig.getLevel() : 99;
var level2 = jQuery.isNumeric(oShape2.mShapeConfig.getLevel()) ?
oShape2.mShapeConfig.getLevel() : 99;
return level2 - level1;
});
this._aShapeInstance = aRetVal;
var oShapeMap = {};
jQuery.each(this._aShapeInstance, function (iKey, oValue) {
oShapeMap[oValue.mShapeConfig.getKey()] = oValue;
});
this._oShapeInstance = oShapeMap;
}
};
GanttChart.prototype._instantiateCustomerClass = function (sCustomerClassName, sShapeId, oShapeConfig, sTopShapeId) {
var CustomerClass = jQuery.sap.getObject(sCustomerClassName);
if (!CustomerClass) {
jQuery.sap.require(sCustomerClassName);
CustomerClass = jQuery.sap.getObject(sCustomerClassName);
}
var oCustomerClassInstance = new CustomerClass();
var sTShapeId = sTopShapeId;
if (sTShapeId === undefined) {
sTShapeId = sShapeId;
}
this._storeCustomerClassId(sShapeId, oCustomerClassInstance.getId(), sTopShapeId);
oCustomerClassInstance.mLocaleConfig = this.getLocale();
oCustomerClassInstance.mShapeConfig = oShapeConfig;
oCustomerClassInstance.mChartInstance = this;
return oCustomerClassInstance;
};
/*
* {
* "activity": "__group0", //sId is the Id of shape class instance and it is randomly generated by UI5 framework
* "header": "__group1",
* ...
* }
*/
GanttChart.prototype._storeCustomerClassId = function (sShapeId, sId, sTopShapeId) {
if (!this._customerClassIds){
this._customerClassIds = {};
}
if (this._oShapesConfigMap[sShapeId]){
this._customerClassIds[sShapeId] = {
"classId": sId,
"topShapeId": sTopShapeId
};
}else {
//non-topShape, when no shapeId in the shapeConfig.groupAggregation
var sShape = sTopShapeId + "_" + sShapeId;
this._customerClassIds[sShape] = {
"classId": sId,
"topShapeId": sTopShapeId
};
}
};
GanttChart.prototype._getIdByShapeId = function (sShapeId) {
if (this._customerClassIds && this._customerClassIds[sShapeId]){
return this._customerClassIds[sShapeId].classId;
}
return null;
};
GanttChart.prototype._getShapeIdById = function (sClassId) {
if (this._customerClassIds){
for (var sShapeId in this._customerClassIds) {
var obj = this._customerClassIds[sShapeId];
if (obj.classId === sClassId) {
return {"shapeId": sShapeId, "topShapeId": obj.topShapeId};
}
}
}
return null;
};
GanttChart.prototype._genShapeConfig = function (sShapeId, oProp) {
var obj = {}, oConfig;
if (sShapeId !== null && sShapeId !== undefined) {
obj.shapeId = sShapeId;
}
if (oProp.data) {
obj.data = oProp.data;
}
if (oProp.level) {
obj.level = oProp.level;
}
if (oProp.draw){
oConfig = oProp.draw;
} else {
oConfig = oProp;
}
for (var item in oConfig) {
if (item !== "class") {
obj[item] = oConfig[item];
}
}
return obj;
};
GanttChart.prototype.calculateZoomInfoFromChartWidth = function (iChartWidth) {
var oTimeAxis = this.getTimeAxis();
var oPlanHorizon = oTimeAxis.getPlanHorizon();
var oInitHorizon = oTimeAxis.getInitHorizon();
this._oZoom.determinedByChartWidth = {};
// calculate min zoom rate by time horizon against svg container width
if (oPlanHorizon) {
var fMinScale = this._calZoomScale(
Format.abapTimestampToDate(oPlanHorizon.getStartTime()),
Format.abapTimestampToDate(oPlanHorizon.getEndTime()),
iChartWidth);
this._oZoom.determinedByChartWidth.fMinRate = this._oZoom.base.fScale / fMinScale;
}
// calculate sutible zoom rate by init horizon against svg container width
if (oInitHorizon && oInitHorizon.getStartTime() && oInitHorizon.getEndTime()) {
var fSuitableScale = this._calZoomScale(
Format.abapTimestampToDate(oInitHorizon.getStartTime()),
Format.abapTimestampToDate(oInitHorizon.getEndTime()),
iChartWidth);
this._oZoom.determinedByChartWidth.fSuitableRate = this._oZoom.base.fScale / fSuitableScale;
}
this._oZoom.iChartWidth = iChartWidth;
return this._oZoom;
};
GanttChart.prototype.setTimeZoomRate = function (fTimeZoomRate) {
this.setProperty("timeZoomRate", fTimeZoomRate, true); // no need to trigger rerender
this._oAxisTime.setZoomRate(fTimeZoomRate);
this._oAxisTime.setViewOffset(0);
this._oStatusSet = null;
this._nLowerRange = this._oAxisTime.getViewRange()[0];
this._nUpperRange = Math.ceil(this._oAxisTime.getViewRange()[1]);
this._draw(true); // only _draw is triggered
return this;
};
GanttChart.prototype.getBaseRowHeight = function () {
if (this._oTT.getRows()[0] && this._oTT.getRows()[0].getDomRef()) {
return this._oTT.getRows()[0].getDomRef().scrollHeight;
}
};
/*
* Called by UI5 ManagedObject before and after retrieving data.
*/
GanttChart.prototype.updateRelationships = function (sReason) {
var oBinding = this.getBinding("relationships");
if (oBinding) {
var aContext = oBinding.getContexts(0, 0);
if (aContext && aContext.length > 0) {
this._aRelationshipsContexts = aContext;
}
}
};
/*
* @see JSDoc generated by SAPUI5 control API generator
*/
GanttChart.prototype.addRelationship = function (oRelationship) {
jQuery.sap.log.error("The control manages the relationships aggregation. The method \"addRelationship\" cannot be used programmatically!");
};
/*
* @see JSDoc generated by SAPUI5 control API generator
*/
GanttChart.prototype.insertRelationship = function (iIndex, oRelationship) {
jQuery.sap.log.error("The control manages the relationships aggregation. The method \"insertRelationship\" cannot be used programmatically!");
};
/*
* @see JSDoc generated by SAPUI5 control API generator
*/
GanttChart.prototype.removeRelationship = function (oRelationship) {
jQuery.sap.log.error("The control manages the relationships aggregation. The method \"removeRelationship\" cannot be used programmatically!");
};
/*
* @see JSDoc generated by SAPUI5 control API generator
*/
GanttChart.prototype.getRelationships = function () {
jQuery.sap.log.error("The control manages the relationships aggregation. The method \"getRelationships\" cannot be used programmatically!");
};
/*
* @see JSDoc generated by SAPUI5 control API generator
*/
GanttChart.prototype.destroyRelationships = function () {
jQuery.sap.log.error("The control manages the relationships aggregation. The method \"destroyRelationships\" cannot be used programmatically!");
};
/*
* @see JSDoc generated by SAPUI5 control API generator
*/
GanttChart.prototype.indexOfRelationship = function (oRelationship) {
jQuery.sap.log.error("The control manages the relationships aggregation. The method \"indexOfRelationship\" cannot be used programmatically!");
};
/*
* @see JSDoc generated by SAPUI5 control API generator
*/
GanttChart.prototype.removeAllRelationships = function () {
jQuery.sap.log.error("The control manages the relationships aggregation. The method \"removeAllRelationships\" cannot be used programmatically!");
};
GanttChart.prototype._bindAggregation = function (sName, oBindingInfo) {
if (sName == "rows" && oBindingInfo){
var oModel = this.getModel(oBindingInfo.model);
// resolve the path if view itself is binded
var oBindingContext = this.getBindingContext(oBindingInfo.model);
if (oBindingContext && oModel){
oBindingInfo.path = oModel.resolve(oBindingInfo.path, oBindingContext);
}
this._oTT.bindRows(oBindingInfo);
} else {
return sap.ui.core.Control.prototype._bindAggregation.apply(this, arguments);
}
};
GanttChart.prototype.onBeforeRendering = function () {
this._detachEvents();
this._updateModelForMultiMainRow();
};
GanttChart.prototype._updateModelForMultiMainRow = function() {
var oBinding = this._oTT.getBinding("rows");
if (!oBinding || oBinding.getLength() === 0) {
return;
}
var aRowContext = oBinding.getContexts(0, oBinding.getLength());
var oAllShapeData = {}, iRowSpan = 1, sMainChartScheme,
sType = aRowContext[0].getProperty("type");
if (sType && this._oObjectTypesConfigMap[sType]) {
sMainChartScheme = this._oObjectTypesConfigMap[sType].getProperty("mainChartSchemeKey");
if (sMainChartScheme && this._oChartSchemesConfigMap[sMainChartScheme]) {
iRowSpan = this._oChartSchemesConfigMap[sMainChartScheme].getProperty("rowSpan");
}
}
if (iRowSpan == 1 || iRowSpan == undefined) {
return;
}
for (var i = 0; i < aRowContext.length; i++) {
var oRowData = aRowContext[i].getProperty();
if (TreeTableHelper.isDummyRow(this._oTT, i)) {
continue;
}
if (i < aRowContext.length - 1){
if (TreeTableHelper.isDummyRow(this._oTT, i + 1)) {
continue;
}
}
oRowData.previousNodeNum = 0;
oRowData.afterNodeNum = iRowSpan - 1;
//allShapeData.push(oRowData);
var oDummyData = {"chartScheme" : sMainChartScheme, "mainRowId" : oRowData.id};
var aAddData = [];
for ( var j = 1; j < iRowSpan; j++) {
var oTempData = jQuery.extend(true, {}, oDummyData);
oTempData.previousNodeNum = j;
oTempData.afterNodeNum = iRowSpan - j - 1;
aAddData.push(oTempData);
}
oAllShapeData[i] = aAddData;
}
if (!$.isEmptyObject(oAllShapeData)) {
TreeTableHelper.addDummyData(this._oTT, oAllShapeData, false);
}
};
GanttChart.prototype._detachEvents = function () {
jQuery("#" + this.getId() + "-svg-ctn").unbind("mousemove", this._onSvgCtnMouseMove);
jQuery("#" + this.getId() + "-svg-ctn").unbind("mouseleave", this._onSvgCtnMouseLeave);
jQuery("#" + this.getId() + "-svg-ctn").unbind("mousedown", this._onSvgCtnMouseDown);
jQuery("#" + this.getId() + "-svg-ctn").unbind("mouseenter", this._onSvgCtnMouseEnter);
jQuery("#" + this.getId() + "-svg-ctn").unbind("mouseup", this._onSvgCtnMouseUp);
};
GanttChart.prototype.onAfterRendering = function () {
this._attachEvents();
};
GanttChart.prototype._attachEvents = function () {
var $svgCtn = jQuery("#" + this.getId() + "-svg-ctn");
$svgCtn.bind("mousemove", this._onSvgCtnMouseMove.bind(this));
$svgCtn.bind("mouseleave", this._onSvgCtnMouseLeave.bind(this));
$svgCtn.bind("mousedown", this._onSvgCtnMouseDown.bind(this));
$svgCtn.bind("mouseenter", this._onSvgCtnMouseEnter.bind(this));
$svgCtn.bind("mouseup", this._onSvgCtnMouseUp.bind(this));
};
GanttChart.prototype.expandChartChange = function (isExpand, aExpandChartSchemes, aExpandedIndices) {
if (aExpandChartSchemes.length < 0) {
return;
}
jQuery.sap.measure.start("GanttChart expandChartChange","GanttPerf:GanttChart expandChartChange function");
var aSelectedIndices = (aExpandedIndices && aExpandedIndices.length > 0) ? aExpandedIndices : this._oTT.getSelectedIndices();
var key;
if (isExpand) {
for (key = 0; key < aExpandChartSchemes.length; key++) {
var sScheme = aExpandChartSchemes[key];
var sMode;
if (this._oChartSchemesConfigMap[sScheme] && this._oChartSchemesConfigMap[sScheme].getModeKey()) {
sMode = this._oChartSchemesConfigMap[sScheme].getModeKey();
} else {
sMode = this.getMode();
}
var oAllInsertedData = {};
for (var i = 0; i < aSelectedIndices.length; i++) {
if (TreeTableHelper.isDummyRow(this._oTT, aSelectedIndices[i])) {
continue;
}
var oSelectedData = TreeTableHelper.getContextObject(this._oTT, aSelectedIndices[i]);
var oDummyData = {"__group" : aExpandChartSchemes[key], "parentData" : oSelectedData, "parentRefId" : oSelectedData.id};
//Check whether the current object data has the expanded chart scheme
if (this._oObjectTypesConfigMap[oSelectedData.type] && this._oObjectTypesConfigMap[oSelectedData.type].getExpandedChartSchemeKeys().length > 0) {
var aValidSchems = this._oObjectTypesConfigMap[oSelectedData.type].getExpandedChartSchemeKeys();
if ($.inArray(sScheme, aValidSchems) > -1) {
var aDrawData, iRowSpan = 1;
//If the expandedChartScheme is available in current mode, return all valid data names, which can be drawn by shapes of the expandedChartScheme
var oSchemeInfo = this._collectDataNameForValidChartScheme(sScheme, sMode);
if (oSchemeInfo) {
aDrawData = oSchemeInfo.drawData;
iRowSpan = oSchemeInfo.rowSpan;
//Calculate how many rows need to be inserted into tree table and adapt number of rows according to rowSpan
var aAddedData = this._insertExpandedRowsToTT(aSelectedIndices[i], aDrawData, oDummyData, iRowSpan);
if (aAddedData && aAddedData.length > 0) {
oAllInsertedData[aSelectedIndices[i]] = aAddedData;
}
}
}
}
}
if (!$.isEmptyObject(oAllInsertedData)) {
TreeTableHelper.addDummyData(this._oTT, oAllInsertedData, true);
}
}
} else {
for (key = 0; key < aExpandChartSchemes.length; key++) {
TreeTableHelper.removeDummyDataFromSelectedIndices(this._oTT, aSelectedIndices, aExpandChartSchemes[key]);
}
}
jQuery.sap.measure.end("GanttChart expandChartChange");
};
GanttChart.prototype._collectDataNameForValidChartScheme = function (sScheme, sMode) {
if (this._oChartSchemesConfigMap[sScheme]) {
var aDrawData = [], iRowSpan;
var aShapesForChartScheme = this._oChartSchemesConfigMap[sScheme].getShapeKeys();
iRowSpan = this._oChartSchemesConfigMap[sScheme].getRowSpan();
var that = this;
jQuery.each(aShapesForChartScheme, function (iKey, oVal) {
if (that._oShapesConfigMap[oVal]) {
var aModeKeys = that._oShapesConfigMap[oVal].getModeKeys();
if ((aModeKeys && aModeKeys.length > 0 && $.inArray(sMode, aModeKeys) > -1) || aModeKeys.length == 0 || sMode == sap.gantt.config.DEFAULT_MODE_KEY) {
aDrawData.push(that._oShapesConfigMap[oVal].getShapeDataName());
}
}
});
if (aDrawData.length > 0 && iRowSpan >= 1) {
return {"drawData" : aDrawData, "rowSpan" : iRowSpan};
}
}
};
GanttChart.prototype._insertExpandedRowsToTT = function (iSelectedIndice, aDrawData, oDummyData, iRowSpan) {
var oSelectedData = TreeTableHelper.getContextObject(this._oTT, iSelectedIndice);
if (aDrawData && aDrawData.length > 0) {
var iNumberOfRows = 1, bHasData = false;
$.each(aDrawData, function(ikey, sData) {
if (oSelectedData[sData] && oSelectedData[sData].length > 0) {
bHasData = true;
for (var i = 0; i < oSelectedData[sData].length; i++) {
if (oSelectedData[sData][i].rowIndex !== undefined && oSelectedData[sData][i].rowIndex > iNumberOfRows) {
iNumberOfRows = oSelectedData[sData][i].rowIndex;
}
}
}
});
if (!bHasData) {
return [];
}
var aAddedData = [], k, oTempData;
if (iNumberOfRows > 1 && iRowSpan == 1) {
for (k = 0; k < iNumberOfRows; k++) {
oTempData = jQuery.extend(true, {}, oDummyData);
oTempData.index = k + 1;
aAddedData.push(oTempData);
}
} else {
oDummyData.index = 1;
for (k = 0; k < iRowSpan; k++) {
oTempData = jQuery.extend(true, {}, oDummyData);
aAddedData.push(oTempData);
}
}
return aAddedData;
}
return [];
};
GanttChart.prototype._composeParameterForClickPosition = function (event) {
var aSvg = jQuery("#" + this.getId() + "-svg");
var oSvgPoint = this._getSvgCoodinateByDiv(aSvg[0], event.pageX, event.pageY);
var x = event.pageX - aSvg.offset().left || event.offsetX;
var y = event.pageY - aSvg.offset().top || event.offsetY;
if (!this._oAxisOrdinal) {
return;
}
var oRowInfo, iRowIndex = this._oAxisOrdinal.viewToRowIndex(y, this._oTT.getVisibleRowCount()) + this._oTT.getFirstVisibleRow();
var oLeadingRowInfo, iLeadingRowNum = iRowIndex;
if (TreeTableHelper.isMultipleSpanMainRow(this._oTT, iRowIndex)){
var mainRowGroupIndices = TreeTableHelper.getMultipleSpanMainRowGroupIndices(this._oTT, iRowIndex);
iLeadingRowNum = mainRowGroupIndices[0];
}
if (iLeadingRowNum !== iRowIndex) {
oLeadingRowInfo = TreeTableHelper.getContextObject(this._oTT, iLeadingRowNum);
}
var startTime = this._oAxisTime.viewToTime(x);
oRowInfo = TreeTableHelper.getContextObject(this._oTT, iRowIndex);
var param = {
"startTime": startTime,
"svgPoint": oSvgPoint,
"leadingRowNum": iLeadingRowNum,
"leadingRowInfo": oLeadingRowInfo, //if current row is the main row or current GanttChart is not expand chart and not multi row height, the leadingRowInfo = undefined
"rowIndex": iRowIndex,
"rowInfo": oRowInfo //if current row is a dummy row, rowInfo = undefined
};
return param;
};
/**
* Gets the selected rows, shapes, and relationships
* @return {object} The returned object contains "rows" for all selected rows, "shapes" for all selected shapes, and "relationships" for all selected relationships
*/
GanttChart.prototype.getAllSelections = function () {
var selectedRows = this.getSelectedRows();
var selectedShapes = this.getSelectedShapes();
var selectedRelationships = this.getSelectedRelationships();
var currentSelection = {"rows": selectedRows, "shapes": selectedShapes, "relationships": selectedRelationships};
return currentSelection;
};
/**
* Gets the selected rows
* @return {array} Selected rows
* @public
*/
GanttChart.prototype.getSelectedRows = function () {
var aSelectedRows = [];
var iFirstVisibleRow = this._oTT.getFirstVisibleRow();
var aSelectedIndexs = this._oTT.getSelectedIndices();
for (var i = 0; i < aSelectedIndexs.length; i++) {
var iRowIndex = aSelectedIndexs[i] - iFirstVisibleRow;
if (iRowIndex > -1 && this._aShapeData[iRowIndex] !== undefined) {
aSelectedRows.push(this._aShapeData[iRowIndex]);
}
}
return aSelectedRows;
};
/**
* Gets the selected shapes
* @return {array} selected shapes
* @public
*/
GanttChart.prototype.getSelectedShapes = function () {
var aSelectedShapes = this._oSelectedShapes;
return aSelectedShapes;
};
/**
* Get all the current selected relationships
* @return {array} selected relationships
* @public
*/
GanttChart.prototype.getSelectedRelationships = function () {
return this._aSelectedRelationships;
};
/**
* Selects shapes, and deselects all shapes when aIds is a null list and bIsExclusive is true
* @param {array} [aIds] List of the shapes that you want to select
* @param {boolean} [bIsExclusive] Whether all other selected shapes are deselected
* @return {boolean} True if the selection change is applied
* @public
*/
GanttChart.prototype.selectShapes = function(aIds, bIsExclusive) {
var i, j, aShapeData, oShapeData;
var bSelectionUpdated = false;
if (this._aSelectedShapeUids === undefined) {
this._aSelectedShapeUids = [];
}
if (aIds === undefined || aIds.length < 1) {//deselect all
if (bIsExclusive && this._aSelectedShapeUids.length > 0) {
this._oSelectedShapes = {};
this._aSelectedShapeUids = [];
bSelectionUpdated = true;
}
}else if (bIsExclusive) {
this._oSelectedShapes = {};
this._aSelectedShapeUids = [];
for (i = 0; i < aIds.length; i++) {
aShapeData = this._getShapeDataById(aIds[i], false);
for (j = 0; j < aShapeData.length; j++) {
oShapeData = aShapeData[j];
if (this._judgeEnableSelection(oShapeData)) { // judge whether the uid is existed and whether is enable selection
var bUpdate = this._selectShape(oShapeData);
if (bUpdate) {
bSelectionUpdated = true;
}
}
}
}
}else {
for (i = 0; i < aIds.length; i++) {
aShapeData = this._getShapeDataById(aIds[i], false);
for (j = 0; j < aShapeData.length; j++) {
oShapeData = aShapeData[j];
if (jQuery.inArray(oShapeData.uid, this._aSelectedShapeUids) > -1) {
continue;
}else if (this._judgeEnableSelection(oShapeData) && this._selectShape(oShapeData)) {
bSelectionUpdated = true;
}
}
}
}
if (bSelectionUpdated) {
this._drawSelectedShapes();
}
return bSelectionUpdated;
};
/**
* deselect shapes
* @param {array} [aIds] List of the shapes that you want to deselect
* @return {boolean} True if the selection change is applied
* @public
*/
GanttChart.prototype.deselectShapes = function(aIds) {
var bSelectionUpdated = false;
for (var i = 0; i < aIds.length; i++) {
var aShapeData = this._getShapeDataById(aIds[i]);
var bUpdate;
for (var j = 0; j < aShapeData.length; j++){
bUpdate = this._deselectShape(aShapeData[j]);
if (bUpdate) {
bSelectionUpdated = true;
}
}
}
if (bSelectionUpdated) {
this._drawSelectedShapes();
}
return bSelectionUpdated;
};
/**
* Select rows and all shapes contained in those rows
* @param {array} [aIds] Row uids
* @param {boolean} [bIsExclusive] Wether all other selected rows and shapes are deselected
* @return {boolean} True if the selection change is applied
* @public
*/
GanttChart.prototype.selectRowsAndShapes = function(aIds, bIsExclusive) {
var bSelectionUpdated = false;
var bRowSelectionUpdated = this.selectRows(aIds, bIsExclusive);
if (bIsExclusive) {
this._oSelectedShapes = {};
this._aSelectedShapeUids = [];
}
if (this._aSelectedShapeUids === undefined) {
this._aSelectedShapeUids = [];
}
for (var id in aIds) {
var sId = aIds[id];
var oRowData = this._getRowById(sId);
if (oRowData !== undefined) {
for (var sShapeId in oRowData.data) {
if (oRowData.data[sShapeId] instanceof Array) {
for ( var i = 0; i < oRowData.data[sShapeId].length; i++) {
var oShapeData = oRowData.data[sShapeId][i];
if (jQuery.inArray(oShapeData.uid, this._aSelectedShapeUids) < 0) {
this._selectShape(oShapeData);
bSelectionUpdated = true;
}
}
}
}
}
}
if (bSelectionUpdated) {
this._drawSelectedShapes();
}else if (bRowSelectionUpdated) {
bSelectionUpdated = true;
}
return bSelectionUpdated;
};
/**
* Selects relationships, and deselects all other selected relationships if aIds is a null list and bIsExclusive is true
* @param {array} [aIds] List of the shapes that you want to select
* @param {boolean} [bIsExclusive] Whether all other selected shapes are deselected
* @return {boolean} True if the selection change is applied
* @public
*/
GanttChart.prototype.selectRelationships = function(aIds, bIsExclusive) {
var i, oRelationship;
var bSelectionUpdated = false;
if (this._aSelectedRelationships === undefined) {
this._aSelectedRelationships = [];
}
if (aIds === undefined || aIds.length < 1) {//deselect all
if (bIsExclusive && this._aSelectedRelationships.length > 0) {
this._aSelectedRelationships = [];
bSelectionUpdated = true;
}
}else if (bIsExclusive) {
if (aIds.length == this._aSelectedRelationships.length) {
//check if any new selecting relationship
for (i = 0; i < aIds.length; i++) {
oRelationship = this._getShapeDataById(aIds[i], true)[0];
if (oRelationship !== undefined && jQuery.inArray(oRelationship, this._aSelectedRelationships) >= 0) {
continue;
} else {
bSelectionUpdated = true;
break;
}
}
}
this._aSelectedRelationships = [];
for (i = 0; i < aIds.length; i++) {
oRelationship = this._getShapeDataById(aIds[i], true)[0];
if (oRelationship !== undefined && oRelationship !== null && this._judgeEnableSelection(oRelationship)) {
this._aSelectedRelationships.push(oRelationship);
bSelectionUpdated = true;
}
}
}else {
for (i = 0; i < aIds.length; i++) {
oRelationship = this._getShapeDataById(aIds[i], true)[0];
//if the relationship is unavailable or it is already in selection, ignore
if (oRelationship === undefined || jQuery.inArray(oRelationship, this._aSelectedRelationships) >= 0) {
continue;
} else if (this._judgeEnableSelection(oRelationship)) {
this._aSelectedRelationships.push(oRelationship);
bSelectionUpdated = true;
}
}
}
if (bSelectionUpdated) {
this._drawSelectedShapes();
}
return bSelectionUpdated;
};
/**
* Deselects relationships
* @param {array} [aIds] List of the relationships that you want to deselect
* @return {boolean} True if the selection change is applied
* @public
*/
GanttChart.prototype.deselectRelationships = function(aIds) {
var bSelectionUpdated = false;
var aUids = [];
if (aIds !== undefined) {
for (var i = 0; i < aIds.length; i++) {
var uid = this._getUidById(aIds[i], true)[0];
if (uid !== undefined) {
aUids.push(uid);
}
}
}
for (var j in this._aSelectedRelationships) {
var oSelectedRLS = this._aSelectedRelationships[j];
if (jQuery.inArray(oSelectedRLS.uid, aUids) > -1) {
var iIndex = this._aSelectedRelationships.indexOf(oSelectedRLS);
this._aSelectedRelationships.splice(iIndex, 1);
bSelectionUpdated = true;
}
}
if (bSelectionUpdated) {
this._drawSelectedShapes();
}
return bSelectionUpdated;
};
/**
* Selects rows
* @param {array} [aIds] List of the rows that you want to select
* @param {boolean} [bIsExclusive] Whether all other selected rows are deselected
* @return {boolean} True if the selection change is applied
* @public
*/
GanttChart.prototype.selectRows = function(aIds, bIsExclusive) {
var bSelectionUpdated = false;
var aVisibleRows = this._oTT.getRows();
//var iFirstRow = this._oTT.getFirstVisibleRow();
var aSelectedIndexs = this._oTT.getSelectedIndices();
if (bIsExclusive && aSelectedIndexs.length > 0) {
this._oTT.clearSelection();
bSelectionUpdated = true;
}
for (var i in aVisibleRows) {
var oRow = d3.select("#" + aVisibleRows[i].getId());
//iIndex = iFirstRow + parseInt(oSelectedRow.attr("data-sap-ui-rowindex"), 10);
var iIndex = parseInt(oRow.attr("data-sap-ui-rowindex"), 10);
var oRowData = this._aShapeData[iIndex];
if (oRowData !== undefined && jQuery.inArray(oRowData.data.id, aIds) > -1) {
if (jQuery.inArray(iIndex, aSelectedIndexs) < 0) {
//check if the treetable support multiple selection
var sSelectionMode = this._oTT.getSelectionMode();
if (sSelectionMode === sap.ui.table.SelectionMode.Multi) {
this._oTT.addSelectionInterval(iIndex, iIndex);
}else {
this._oTT.setSelectedIndex(iIndex);
}
bSelectionUpdated = true;
}
}
}
return bSelectionUpdated;
};
/**
* Deselects rows
* @param {array} [aIds] List of the rows that you want to deselect
* @return {boolean} True if the selection change is applied
* @public
*/
GanttChart.prototype.deselectRows = function(aIds) {
var bSelectionUpdated = false;
var aSelectedIndexs = this._oTT.getSelectedIndices();
var aVisibleRows = this._oTT.getRows();
for (var i in aSelectedIndexs) {
var iSelectedIndex = aSelectedIndexs[i];
var oRow = d3.select("#" + aVisibleRows[iSelectedIndex].getId());
var iIndex = parseInt(oRow.attr("data-sap-ui-rowindex"), 10);
var oRowData = this._aShapeData[iIndex];
if (jQuery.inArray(oRowData.data.id, aIds)) {
aSelectedIndexs.splice(iSelectedIndex, 1);
this._oTT.removeSelectionInterval(iSelectedIndex, 1);
bSelectionUpdated = true;
}
}
return bSelectionUpdated;
};
//Private method: check if an element is a relationship by its' sShapeUid
GanttChart.prototype._isRelationship = function (sShapeUid) {
if (this._getShapeDataNameByUid(sShapeUid) === sap.gantt.shape.ShapeCategory.Relationship) {
return true;
}
return false;
};
GanttChart.prototype._onRowSelectionChange = function (oEvent) {
//below is just a workaround, we may need change these in future
var aChangedIndices = oEvent.getParameter("rowIndices"),
aCurrentSelectedIndices = this._oTT.getSelectedIndices(),
aSelectedIndices = [],
aDeselectedIndices = [];
for (var i = 0; i < aChangedIndices.length; i++){
if (aCurrentSelectedIndices.indexOf(aChangedIndices[i]) === -1){
aDeselectedIndices.push(aChangedIndices[i]); //deselected indices by user or delegate
} else {
aSelectedIndices.push(aChangedIndices[i]); //selected indices by user or delegate
}
}
var oTT = this._oTT;
var fnUpdateRowSelection = function(aRowIndices, bSelected){
for (var j = 0; j < aRowIndices.length; j++){
if (TreeTableHelper.isMultipleSpanMainRow(oTT, aRowIndices[j], true)){
//indices is actual index in the table
var aMainRowGroupIndices = TreeTableHelper.getMultipleSpanMainRowGroupIndices(oTT, aRowIndices[j], true);
var iFirstIndex = aMainRowGroupIndices[0],
iLastIndex = aMainRowGroupIndices[aMainRowGroupIndices.length - 1];
for (var m = 0; m < aMainRowGroupIndices.length; m++){
if (bSelected && aCurrentSelectedIndices.indexOf(aMainRowGroupIndices[m]) === -1){
oTT.addSelectionInterval(iFirstIndex,iLastIndex);
} else if (!bSelected && aCurrentSelectedIndices.indexOf(aMainRowGroupIndices[m]) !== -1){
oTT.removeSelectionInterval(iFirstIndex,iLastIndex);
}
}
}
}
};
fnUpdateRowSelection(aSelectedIndices, true);
fnUpdateRowSelection(aDeselectedIndices, false);
this.fireRowSelectionChange({
originEvent: oEvent
});
};
//Private method: ShapeSelectionChange, RelationshipSelectionChange
GanttChart.prototype._selectionChange = function (oShapeData, bCtrl, bShift, origEvent) {
if (this._aSelectedRelationships == undefined){
this._aSelectedRelationships = [];
}
if (this._aSelectedShapeUids == undefined){
this._aSelectedShapeUids = [];
}
/*
* Click on Shapes: Clear any existing selection of all shape and select current shape. Clear all rows selection.
* Click on Shapes + control key: Keep existing selection of all shapes and change selection of current shape. Keep all rows selection. Keep all relationship selection
* above 2 same for the relationships
* Old: Click on Shape + shift key = Click on Shape
*/
var bShapeSelectionChange = false;
var bRelationshipSelectionChange = false;
var targetUid = oShapeData.uid;
var isRelationship = this._isRelationship(targetUid);
if ((bCtrl && this.getSelectionMode() === sap.gantt.SelectionMode.MultiWithKeyboard) || this.getSelectionMode() === sap.gantt.SelectionMode.Multiple){
//when ctrl key is pressed or in Fiori multiple selection mode
if (!isRelationship) {
//if the shape is already in selectedShapes, deselect it, otherwise select it
if (this._aSelectedShapeUids !== undefined && jQuery.inArray(targetUid, this._aSelectedShapeUids) > -1){
if (!this._bDragging) {
bShapeSelectionChange = this._deselectShape(oShapeData);
}
}else {
bShapeSelectionChange = this._selectShape(oShapeData);
}
}else {
if (jQuery.inArray(oShapeData, this._aSelectedRelationships) < 0){
this._aSelectedRelationships.push(oShapeData);
}else {
var index = this._aSelectedRelationships.indexOf(oShapeData);
this._aSelectedRelationships.splice(index,1);
}
bRelationshipSelectionChange = true;
}
}else if (!isRelationship) {
if ((jQuery.inArray(targetUid, this._aSelectedShapeUids) < 0 || this._aSelectedShapeUids.length > 1) && !this._bDragging) {
//clear all the Selected Shapes, add the clicking one
this._oSelectedShapes = {};
this._aSelectedShapeUids = [];
bShapeSelectionChange = true;
}
if (jQuery.inArray(targetUid, this._aSelectedShapeUids) < 0 ) {
var bUpdated = this._selectShape(oShapeData);
if (!bShapeSelectionChange && bUpdated) {
bShapeSelectionChange = true;
}
}
if (this._aSelectedRelationships.length > 0) {
this._aSelectedRelationships = [];
bRelationshipSelectionChange = true;
}
}else {//if the current clicking element is a relationship
if ((jQuery.inArray(oShapeData, this._aSelectedRelationships) < 0) || this._aSelectedRelationships.length > 1){
//clear all the Selected Shapes, add the clicking one
this._aSelectedRelationships = [];
this._aSelectedRelationships.push(oShapeData);
bRelationshipSelectionChange = true;
}
if (this._aSelectedShapeUids !== undefined && this._aSelectedShapeUids.length > 0) {
this._oSelectedShapes = {};
this._aSelectedShapeUids = [];
bShapeSelectionChange = true;
}
}
if (bShapeSelectionChange || bRelationshipSelectionChange) {
this._drawSelectedShapes();
}
return {
shapeSelectionChange: bShapeSelectionChange,
relationshipSelectionChange: bRelationshipSelectionChange
};
};
/*
* update the selected status back to model data
*/
GanttChart.prototype._setSelectedStatusToData = function() {
for (var sRow in this._aShapeData) {
var oRowData = this._aShapeData[sRow];
for (var sShapeDataName in oRowData.data) {
var aShapes = oRowData.data[sShapeDataName];
if (aShapes instanceof Array) {
for ( var iIndex = 0; iIndex < aShapes.length; iIndex++) {
var oShapeData = aShapes[iIndex];
if (jQuery.inArray(oShapeData.uid, this._aSelectedShapeUids) > -1) {
oShapeData.selected = true;
}else {
oShapeData.selected = false;
}
}
}
}
}
for (var i in this._aRelationships) {
this._aRelationships[i].selected = false;
if (this._aSelectedRelationships !== undefined && this._aSelectedRelationships.length > 0){
for (var j in this._aSelectedRelationships) {
if (this._aRelationships[i].uid === this._aSelectedRelationships[j].uid) {
this._aRelationships[i].selected = true;
}
}
}
}
};
/*
* get the selections according to the data from model
*/
GanttChart.prototype._setSelectedStatusFromData = function (aShapeDataNames) {
this._oSelectedShapes = {};
this._aSelectedShapeUids = [];
for (var sRow in this._aShapeData) {
var oRowData = this._aShapeData[sRow];
for (var sShapeDataName in oRowData.data) {
var aShapes = oRowData.data[sShapeDataName];
//only loop the arrays, e.g tasks, activities
if (aShapes instanceof Array && jQuery.inArray(sShapeDataName, aShapeDataNames) > -1) {
for ( var i = 0; i < aShapes.length; i++) {
var oShapeData = aShapes[i];
if (oShapeData.selected) {
if (this._oSelectedShapes[sShapeDataName] === undefined) {
this._oSelectedShapes[sShapeDataName] = [];
}
this._oSelectedShapes[sShapeDataName].push({"shapeUid": oShapeData.uid, "shapeData": oShapeData, "objectInfoRef": oRowData});
this._aSelectedShapeUids.push(oShapeData.uid);
}
}
}
}
}
//loop given relationship data, collect the selected data into the selected relationship collection
this._aSelectedRelationships = [];
for (var j in this._aRelationships) {
if (this._aRelationships[j].selected) {
this._aSelectedRelationships.push(this._aRelationships[j]);
}
}
};
/*
* Synconize the clicks on empty space of chart with selection of rows in the back table
*/
GanttChart.prototype._syncTTSelection = function(event){
jQuery.sap.measure.start("GanttChart syncTTSelection","GanttPerf:GanttChart syncTTSelection function");
var x = event.clientX;
var y = event.clientY;
var bShift = event.shiftKey;
var bCtrl = event.ctrlKey;
var $svg = jQuery("#" + this.getId() + "-svg")[0];
var oClickPoint = this._getSvgCoodinateByDiv($svg, x, y);
var iRowIndex = parseInt(this._oAxisOrdinal.viewToBandIndex(oClickPoint.y), 10);
if (iRowIndex < 0){
return false;
}
var aVisibleRows = this._oTT.getRows();
var iIndex, oSelectedRow = d3.select("#" + aVisibleRows[iRowIndex].getId());
if (iRowIndex < aVisibleRows.length && oSelectedRow && oSelectedRow.attr("data-sap-ui-rowindex")){
iIndex = this._oTT.getFirstVisibleRow() + parseInt(oSelectedRow.attr("data-sap-ui-rowindex"), 10);
}
//disable selection for expaned dummy row
if (TreeTableHelper.isDummyRow(this._oTT, iIndex) && TreeTableHelper.getContextObject(this._oTT, iIndex).__group !== undefined) {
return false;
}
var sSelectionMode = this._oTT.getSelectionMode();
if (iIndex >= 0 && sSelectionMode !== sap.ui.table.SelectionMode.None) {
if (sSelectionMode === sap.ui.table.SelectionMode.Single) {
if (!this._oTT.isIndexSelected(iIndex)) {
this._oTT.setSelectedIndex(iIndex);
} else {
this._oTT.clearSelection();
}
} else {
if (sSelectionMode === sap.ui.table.SelectionMode.Multi && this.getSelectionMode === sap.gantt.SelectionMode.Multiple) {
bCtrl = true;
}
if (bShift) {
// If no row is selected getSelectedIndex returns -1 - then we simply select the clicked row:
/* Click on Empty place + shift key: Keep all shape/relationship selection.
* sync the row selection with original treetable row selection behavior
*/
var iSelectedIndex = this._oTT.getSelectedIndex();
if (iSelectedIndex >= 0) {
if (iSelectedIndex < iIndex) {
this._oTT.addSelectionInterval(iSelectedIndex, iIndex);
}else {
this._oTT.addSelectionInterval(iIndex, iSelectedIndex);
}
}else {
this._oTT.setSelectedIndex(iIndex);
}
}else if (!this._oTT.isIndexSelected(iIndex)) {
if (bCtrl) {
this._oTT.addSelectionInterval(iIndex, iIndex);
} else {
this._oTT.clearSelection();
this._oTT.setSelectedIndex(iIndex);
}
}else if (bCtrl) {
this._oTT.removeSelectionInterval(iIndex, iIndex);
}else if (this._oTT.getSelectedIndices().length > 1) {
this._oTT.clearSelection();
this._oTT.setSelectedIndex(iIndex);
}
}
}
jQuery.sap.measure.end("GanttChart syncTTSelection");
};
//Set global variances for svg events
GanttChart.prototype._setEventStatus = function (sEventName) {
switch (sEventName) {
case "dragEnter":
this._bDragging = true;
break;
case "mouseDown":
this._bMouseDown = true;
this._bDragging = false;
break;
case "shapeDragging":
this._bDragging = true;
break;
case "mouseUp":
this._bMouseDown = false;
break;
case "shapeDragEnd":
this._bDragging = false;
this._oDraggingData = undefined;
break;
case "dragLeave":
this._iMouseDown = 0;
this._bMouseDown = false;
this._bDragging = false;
break;
default:
break;
}
};
GanttChart.prototype._onShapeDragStart = function (oEvent) {
var aSvg = jQuery("#" + this.getId() + "-svg");
//if mouse down on a shape that is dragable
var oSourceShapeData = d3.select(oEvent.target).data()[0];
var sClassId = oEvent.target.getAttribute("class").split(" ")[0];
if (oSourceShapeData !== undefined && jQuery.inArray(oSourceShapeData.uid, this._aSelectedShapeUids) > -1
&& this._judgeEnableDnD(oSourceShapeData, sClassId)) {
var rowInfo = this._getRowByShapeUid(oSourceShapeData.uid);
var x = oEvent.pageX - aSvg.offset().left || oEvent.offsetX;
var y = oEvent.pageY - aSvg.offset().top || oEvent.offsetY;
var shapeX, shapeWidth;
if (oEvent.target.getAttribute("x") && oEvent.target.getAttribute("width")) {
shapeX = parseInt(oEvent.target.getAttribute("x"), 10);
shapeWidth = parseInt(oEvent.target.getAttribute("width"), 10);
}else if (oSourceShapeData.startTime){
var x1 = this._oAxisTime.timeToView(Format.abapTimestampToDate(oSourceShapeData.startTime));
var x2 = this._oAxisTime.timeToView(Format.abapTimestampToDate(oSourceShapeData.endTime));
if (Core.getConfiguration().getRTL()) {
shapeX = x2;
shapeWidth = (x1 - x2) > 0 ? (x1 - x2) : 1;
}else {
shapeX = x1;
shapeWidth = (x2 - x1) > 0 ? (x2 - x1) : 1;
}
}else {
shapeX = x;
shapeWidth = 1;
}
var oDragStartPoint = {"x": x, "y": y, "shapeX": shapeX, "shapeWidth": shapeWidth};
var aSourceShapeData = [];
aSourceShapeData.push({
"shapeData": oSourceShapeData,
"objectInfo": rowInfo
});
for (var sShapeDataName in this._oSelectedShapes) {
var aShapeData = this._oSelectedShapes[sShapeDataName];
if (aShapeData !== undefined) {
for (var i in aShapeData) {
if (aShapeData[i].shapeUid !== oSourceShapeData.uid && this._judgeEnableDnD(aShapeData[i].shapeData)) {
aSourceShapeData.push({
"shapeData": aShapeData[i].shapeData,
"objectInfo": aShapeData[i].objectInfoRef
});
}
}
}
}
this._oDraggingData = {
"sourceShapeData": aSourceShapeData,
"dragStartPoint": oDragStartPoint,
"sourceSvgId": this.getId(),
"targetSvgId": this.getId(),
"domObject": d3.select(oEvent.target)[0][0]
};
this._oDraggingData.fDragHandler = this._onShapeDrag.bind(this);
jQuery(document.body).bind("mousemove", this._oDraggingData.fDragHandler);
this._oDraggingData.fDragEndHandler = this._onShapeDragEnd.bind(this);
jQuery(document.body).bind("mouseup", this._oDraggingData.fDragEndHandler);
}
};
GanttChart.prototype._onShapeDrag = function (oEvent) {
if (oEvent.button !== 0 || oEvent.buttons === 0 || oEvent.ctrlKey) {
return false;
}
var aDragDiv = d3.select("#activtityDragDrop");
var dragDiv = aDragDiv[0];
if (this._oDraggingData === undefined) {
if (!aDragDiv.empty()){
aDragDiv.remove();
}
}else {
var nShapeCount = this._oDraggingData.sourceShapeData.length;
var iShapeX = this._oDraggingData.dragStartPoint.shapeX;
var iStartMouseX = this._oDraggingData.dragStartPoint.x;
if (aDragDiv.empty() || dragDiv === null) {
dragDiv = d3.select("body").append("div").attr("id", "activtityDragDrop")
.style("position", "absolute").style("z-index", "999");
var cloneNode = this._oDraggingData.domObject.cloneNode();
var width = d3.select(cloneNode).attr("width");
var height = d3.select(cloneNode).attr("height");
var fontSize = 12;
var g = dragDiv.append("svg").attr("id", "activtityDragDropSvg").attr("width", width).attr("height", height)
.append("g").attr("id", "activtityDragDropSvgGroup");
var shadow = d3.select(this._oDraggingData.domObject.cloneNode())
.classed("shadow", true)
.attr("fill-opacity", "0.5")
.attr("x", 0)
.attr("y", 0);
g.node().appendChild(shadow.node());
g.append("text")
.attr("x", width / 2 - fontSize / 2)
.attr("y", height - fontSize / 2 + 4)
.attr("fill", "blue")
.attr("font-size", 12)
.text(function () {
return nShapeCount;
});
}
var iCurrentX = iShapeX + (oEvent.pageX - iStartMouseX);
var iCurrentY = oEvent.pageY;//calculate current Y on the align of shape&row
d3.select("#activtityDragDrop").style("left", iCurrentX + 4 + "px");
d3.select("#activtityDragDrop").style("top", iCurrentY + 4 + "px");
jQuery(document.body).addClass("sapGanttDraggingCursor");
this._setEventStatus("shapeDragging");
this._iMouseDown = 0;
}
};
GanttChart.prototype._onShapeDragEnd = function (oEvent) {
//console.log("_onShapeDragEnd",oEvent);
var div = d3.select("#activtityDragDrop");
if (!div.empty()){
div.remove();
}
if (this._bDragging && this._oDraggingData !== undefined) {
var sTargetSvgId = this.getId() + "-svg";
this._collectDraggingShapeData(this._oDraggingData, oEvent);
this.fireShapeDragEnd({
originEvent: oEvent,
sourceSvgId: this._oDraggingData.sourceSvgId,
targetSvgId: sTargetSvgId,
sourceShapeData: this._oDraggingData.sourceShapeData,
targetData: this._oDraggingData.targetData
});
}
if (this._oDraggingData !== undefined) {
jQuery(document.body).unbind("mousemove", this._oDraggingData.fDragHandler);
jQuery(document.body).unbind("mouseup", this._oDraggingData.fDragEndHandler);
}
jQuery(document.body).removeClass("sapGanttDraggingCursor");
this._setEventStatus("shapeDragEnd");
};
GanttChart.prototype._collectDraggingShapeData = function (oDraggingSource, oEvent) {
var aSvg = jQuery("#" + this.getId() + "-svg");
var x = oEvent.pageX - aSvg.offset().left || oEvent.offsetX;
var sStartPointX = oDraggingSource.dragStartPoint.x;
var iDragDistance = parseInt(x, 10) - parseInt(sStartPointX, 10);
var sShapeCurrentStartX = parseInt(oDraggingSource.dragStartPoint.shapeX, 10) + iDragDistance;
var sShapeCurrentEndX = sShapeCurrentStartX + parseInt(oDraggingSource.dragStartPoint.shapeWidth, 10);
var sNewStartTime, sNewEndTime;
if (Core.getConfiguration().getRTL() === true) {
sNewStartTime = Format.dateToAbapTimestamp(this._oAxisTime.viewToTime(sShapeCurrentEndX));
sNewEndTime = Format.dateToAbapTimestamp(this._oAxisTime.viewToTime(sShapeCurrentStartX));
} else {
sNewStartTime = Format.dateToAbapTimestamp(this._oAxisTime.viewToTime(sShapeCurrentStartX));
sNewEndTime = Format.dateToAbapTimestamp(this._oAxisTime.viewToTime(sShapeCurrentEndX));
}
/*
* Only Update the clicking shape data with the row object at the current point
* keep other shape data as the same as they are in sourceshapedata
*/
var param = this._composeParameterForClickPosition(oEvent);
var rowInfo = param.rowInfo;
oDraggingSource.targetData = {
"mouseTimestamp": {startTime: sNewStartTime, endTime: sNewEndTime},
"mode": this.getMode(),
"objectInfo": rowInfo
};
};
/*
* set draggingSource when a drag is from outside of the current chart
*/
GanttChart.prototype.setDraggingData = function (oDraggingSource) {
this._oDraggingData = oDraggingSource;
if (this._oDraggingData !== undefined) {
this._oDraggingData.targetSvgId = this.getId();
jQuery(document.body).unbind("mousemove", this._oDraggingData.fDragHandler);
jQuery(document.body).unbind("mouseup", this._oDraggingData.fDragEndHandler);
this._oDraggingData.fDragHandler = this._onShapeDrag.bind(this);
this._oDraggingData.fDragEndHandler = this._onShapeDragEnd.bind(this);
jQuery(document.body).bind("mousemove", this._oDraggingData.fDragHandler);
jQuery(document.body).bind("mouseup", this._oDraggingData.fDragEndHandler);
this._setEventStatus("dragEnter");
}
};
GanttChart.prototype._onSvgCtnMouseEnter = function (oEvent) {
if (oEvent.currentTarget.id === (this.getId() + '-svg-ctn') && oEvent.button === 0 && oEvent.buttons !== 0) {// check if the mouse left key is down
this.fireChartDragEnter({originEvent: oEvent});
}
};
GanttChart.prototype._onSvgCtnMouseMove = function(oEvent){
var aSvg = jQuery("#" + this.getId() + "-svg");
// calculate svg coordinate for hover
var oSvgPoint = this._getSvgCoodinateByDiv(aSvg[0], oEvent.pageX, oEvent.pageY);
// draw cursorLine. select svgs of all chart instances to impl synchronized cursorLine
if (this.getEnableCursorLine()) {
this._oCursorLineDrawer.drawSvg(
d3.selectAll(".sapGanttChartSvg"),
d3.selectAll(".sapGanttChartHeaderSvg"),
this.getLocale(),
oSvgPoint);
}
//Trigger mouseover event from oSVG to tree table, according to row index
//if current row is the main row or current GanttChart is not expand chart and not multi row height, the leadingRowInfo = undefined, leadingRowNum = rowIndex
//if current row is a dummy row, rowInfo = undefined
var param = this._composeParameterForClickPosition(oEvent);
//only hover the main row when in expand chart
var iRowIndex = param ? param.rowIndex : -1;
var oShapeData = d3.select(oEvent.target).data()[0];
if (iRowIndex > -1 &&
((oShapeData !== undefined && oShapeData.uid !== this._lastHoverShapeUid)
|| (oShapeData === undefined && this._lastHoverShapeUid !== undefined) || iRowIndex !== this._lastHoverRowIndex)) {
this.fireChartMouseOver({
objectInfo: param.rowInfo,
leadingRowInfo: param.leadingRowInfo,
timestamp: param.startTime.getTime(),
svgId: this.getId() + "-svg",
svgCoordinate: param.svgPoint,
effectingMode: this.getMode(),
originEvent: oEvent
});
if (oShapeData !== undefined) {
this._lastHoverShapeUid = oShapeData.uid;
}else {
this._lastHoverShapeUid = undefined;
}
}
if (iRowIndex > -1 && iRowIndex !== this._lastHoverRowIndex) {
var oTT = this._oTT;
var $oTT = jQuery(oTT.getDomRef());
var aHover = $oTT.find(".sapUiTableRowHvr");
var oTargetRow = $oTT.find(".sapUiTableTr")[iRowIndex];
if (this._oTT.getRows()[iRowIndex]) {
var iRowNum = this._oTT.getRows()[iRowIndex].getIndex();
var oRowContent = TreeTableHelper.getContextObject(this._oTT, iRowNum);
if (aHover.length > 0) {
for (var i = 0; i < aHover.length; i++) {
if (jQuery.inArray("sapUiTableTr", aHover[i].classList) > -1) {
jQuery(aHover[i]).mouseleave();
}
}
}
//disable hover for expaned dummy row
if (!TreeTableHelper.isDummyRow(this._oTT, iRowNum) || oRowContent.__group === undefined || oRowContent.__group === null) {
jQuery(oTargetRow).mouseenter();
this._lastHoverRowIndex = iRowIndex;
}
}
}
};
GanttChart.prototype._onSvgCtnMouseLeave = function (oEvent) {
if (oEvent.currentTarget.id === (this.getId() + '-svg-ctn') && this._bDragging && this._oDraggingData !== undefined) {
this._oDraggingData.targetSvgId = undefined;
//if drag a shape out of a chart(view), then fire an event to Gantt
this.fireChartDragLeave({
//eventStatus: this._bDragging, this._mouseup, this.mousedown, or can those status already can be judged by the target(null or not?)
originEvent: oEvent,
draggingSource: this._oDraggingData
});
this._setEventStatus("dragLeave");
}
if (this.getEnableCursorLine()) {
this._oCursorLineDrawer.destroySvg(
d3.selectAll(".sapGanttChartSvg"),
d3.selectAll(".sapGanttChartHeaderSvg"));
}
//Trigger mouseout event from oSVG to tree table
var oTT = this._oTT;
var $oTT = jQuery(oTT.getDomRef());
var aHover = $oTT.find(".sapUiTableRowHvr");
if (aHover.length > 0) {
//to less the times of mouse leave, only trigger the row event
for (var i = 0; i < aHover.length; i++) {
if (jQuery.inArray("sapUiTableTr", aHover[i].classList) > -1) {
jQuery(aHover[i]).mouseleave();
}
}
}
this._lastHoverShapeUid = undefined;
this._lastHoverRowIndex = -1;
};
GanttChart.prototype._onSvgCtnMouseDown = function (oEvent) {
if (oEvent.button == 0 ) {
var oShapeData = d3.select(oEvent.target).data()[0];
var sClassId;
if (oEvent.target.getAttribute("class")){
sClassId = oEvent.target.getAttribute("class").split(" ")[0];
}
//only when the mousedown is happened to a selectable shape, the shape selection change & dragNdrop are available, but the row selection still works
if (sClassId && oShapeData && this._judgeEnableSelection(oShapeData, sClassId)) {
this._oLastSelectedShape = oShapeData;
this._onShapeDragStart(oEvent);
//Needed for disabling default drag and drop behaviour in Firefox. This is not harmful to the behaviour in other browsers.
oEvent.preventDefault();
}
this._iMouseDown++;
this._setEventStatus("mouseDown");
}
};
GanttChart.prototype._onSvgCtnMouseUp = function (event) {
/* check if a dragging is happended, if yes, fireShapeDragEnd
* Otherwise check if a single click or a double click should happend
*/
if (event.button == 2){
var param = this._composeParameterForClickPosition(event);
this.fireChartRightClick({
objectInfo: param.rowInfo,
leadingRowInfo: param.leadingRowInfo,
timestamp: param.startTime.getTime(),
svgId: this.getId() + "-svg",
svgCoordinate: param.svgPoint,
effectingMode: this.getMode(),
originEvent: event
});
}else if (event.button == 0 && !this._bDragging && this._bMouseDown) {
this._onSvgCtnClick(event);
}
};
//event handler for single click on chart
GanttChart.prototype._onSvgCtnClick = function (oEvent) {
var oShapeData = d3.select(oEvent.target).data()[0];
var sClassId;
if (oEvent.target.getAttribute("class")){
sClassId = oEvent.target.getAttribute("class").split(" ")[0];
}
var bSelectionChange = {};
if (oShapeData !== undefined && this._judgeEnableSelection(oShapeData, sClassId) && this._oLastSelectedShape !== undefined && this._oLastSelectedShape.uid === oShapeData.uid) {
bSelectionChange = this._selectionChange(oShapeData, oEvent.ctrlKey, oEvent.shiftKey, oEvent);
}else if (this.getSelectionMode() === sap.gantt.SelectionMode.MultiWithKeyboard) {
this._syncTTSelection(oEvent);
this._oLastSelectedShape = undefined;
}else {
if (this._aSelectedShapeUids !== undefined && this._aSelectedShapeUids.length > 0) {
this._oSelectedShapes = {};
this._aSelectedShapeUids = [];
bSelectionChange.shapeSelectionChange = true;
}
if (this._aSelectedRelationships.length > 0) {
this._aSelectedRelationships = [];
bSelectionChange.relationshipSelectionChange = true;
}
if (bSelectionChange.shapeSelectionChange || bSelectionChange.relationshipSelectionChange) {
this._drawSelectedShapes();
}
}
if (!oEvent.ctrlKey && !oEvent.shiftKey){
var that = this;
setTimeout(function () {
if (that._iMouseDown > 1){
var param = that._composeParameterForClickPosition(oEvent);
that.fireChartDoubleClick({
objectInfo: param.rowInfo,
leadingRowInfo: param.leadingRowInfo,
timestamp: param.startTime.getTime(),
svgId: that.getId() + "-svg",
svgCoordinate: param.svgPoint,
effectingMode: that.getMode(),
originEvent: oEvent
});
}
that._iMouseDown = 0;
that._setEventStatus("mouseUp");
this._oLastSelectedShape = undefined;
}, 300);
}else {
this._iMouseDown = 0;
this._setEventStatus("mouseUp");
this._oLastSelectedShape = undefined;
}
if (bSelectionChange.shapeSelectionChange) {
this.fireShapeSelectionChange({
originEvent: oEvent
});
}
if (bSelectionChange.relationshipSelectionChange) {
this.fireRelationshipSelectionChange({
originEvent: oEvent
});
}
};
GanttChart.prototype._onHSbScroll = function (oEvent) {
var nScrollLeft = this._oTT._oHSb.getScrollPosition();
this.updateLeftOffsetRate(nScrollLeft);
this._draw(false);
this.fireHorizontalScroll({
scrollSteps: nScrollLeft,
leftOffsetRate: this._fLeftOffsetRate
});
};
GanttChart.prototype._onVSbScroll = function (oEvent) {
this.fireVerticalScroll({
scrollSteps: this._oTT._oVSb.getScrollPosition()
});
this._oTT.setFirstVisibleRow(this._oTT._oVSb.getScrollPosition() || 0, true);
};
GanttChart.prototype._hSbScrollLeft = function (nScrollPosition) {
var $chartBodySvgCnt = jQuery("#" + this.getId() + "-svg-ctn");
var $chartHeaderSvgCnt = jQuery("#" + this.getId() + "-header");
var nScrollLeft;
if (Core.getConfiguration().getRTL() === true) {
//Header and Body should have same width. Use header to calculate the scroll position in RTL mode
nScrollLeft = this._oStatusSet.aViewBoundary[1] - $chartHeaderSvgCnt.width() - nScrollPosition;
if ( nScrollLeft < 0 ) {
nScrollLeft = 0;
}
} else {
nScrollLeft = nScrollPosition;
}
//scroll divs
if (Core.getConfiguration().getRTL() === true && sap.ui.Device.browser.name === "ff") {
$chartBodySvgCnt.scrollLeftRTL(nScrollLeft);
$chartHeaderSvgCnt.scrollLeftRTL(nScrollLeft);
} else {
$chartBodySvgCnt.scrollLeft(nScrollLeft);
$chartHeaderSvgCnt.scrollLeft(nScrollLeft);
}
};
GanttChart.prototype.updateLeftOffsetRate = function(nPosition, nContentWidth) {
//In RTL mode, treeTable use ui5 scrollbar control which wrap-ups the jQuery scrollLeft. The functions getScrollPosition() and setScrollPosition()
//act same in 3 browsers: ie, ff, cr. The returned value of getScrollPosition() means the width of hidden DOM element at the right of scroll bar
//Actually 3 browsers have different logic for scroll bar, UI5 scroll bar control wrap-ups the jQuery and make all act as same in ie.
//To calculate the _fLeftOffsetRate, need to convert the returned value of getScrollPosition() to the width of hidden DOM element at the left of scroll bar
var nScrollWidth = nContentWidth ? nContentWidth : parseInt(this._oTT._oHSb.getContentSize(), 0);
var nClientWidth = jQuery("#" + this.getId() + "-svg-ctn").width();
if (nScrollWidth - nClientWidth !== 0) {
if (Core.getConfiguration().getRTL() === true) {
this._fLeftOffsetRate = (nScrollWidth - nPosition - nClientWidth) / (nScrollWidth - nClientWidth);
} else {
this._fLeftOffsetRate = nPosition / (nScrollWidth - nClientWidth);
}
this._fLeftOffsetRate = this._fLeftOffsetRate < 0 ? 0 : this._fLeftOffsetRate;
this._fLeftOffsetRate = this._fLeftOffsetRate > 1 ? 1 : this._fLeftOffsetRate;
}
return this._fLeftOffsetRate;
};
GanttChart.prototype.jumpToPosition = function(value) {
if (!isNaN(value) && !(value instanceof Date)) {
// when input parameter "value" is float value which means left offset rate
this._fLeftOffsetRate = value;
this._draw(false);
return;
}
var oDateToJump, nDatePosition;
var nClientWidth = jQuery("#" + this.getId() + "-svg-ctn").width();
if (!nClientWidth || nClientWidth <= 0) {
return;
}
if (value instanceof Date) {
// when value is Date format
oDateToJump = value;
} else {
// when value is null or undefined
var oTimeAxis = this.getTimeAxis();
var oInitHorizon = oTimeAxis.getInitHorizon();
if (!oInitHorizon || !oInitHorizon.getStartTime() || !oInitHorizon.getEndTime()) {
return;
}
oDateToJump = Format.abapTimestampToDate(oInitHorizon.getStartTime());
// need to adjust zoom rate for jumping to initHorizon
var fSuitableScale = this._calZoomScale(
Format.abapTimestampToDate(oInitHorizon.getStartTime()),
Format.abapTimestampToDate(oInitHorizon.getEndTime()),
nClientWidth);
var fSuitableRate = this._oZoom.base.fScale / fSuitableScale;
this.setTimeZoomRate(fSuitableRate);
}
var nContentWidth = this._nUpperRange - this._nLowerRange;
if (!nContentWidth || nContentWidth <= 0) {
return;
}
if (Core.getConfiguration().getRTL() === true){
//Refer to the comments in updateLeftOffsetRate. Convert the the x value to nScrollLeft
nDatePosition = nContentWidth - this._oAxisTime.timeToView(oDateToJump) - this._oAxisTime.getViewOffset();
nDatePosition = nDatePosition < 0 ? 0 : nDatePosition;
} else {
nDatePosition = this._oAxisTime.timeToView(oDateToJump) + this._oAxisTime.getViewOffset();
}
this.updateLeftOffsetRate(nDatePosition, nContentWidth);
this._draw(false);
};
GanttChart.prototype._onTTRowUpdate = function () {
this._syncSvgHeightWithTT();
this._syncSvgDataWithTT();
this._prepareRelationshipDataFromModel();
this._draw(true);
};
GanttChart.prototype._updateDataString = function () {
var sShapeData = JSON.stringify(this._aShapeData, function(key, value) {
if (key === "bindingObj" || key === "contextObj") {
return undefined;
}
return value;
});
if (this._sShapeData && sShapeData === this._sShapeData) {
this._sShapeData = sShapeData;
return false;
} else {
this._sShapeData = sShapeData;
return true;
}
};
GanttChart.prototype._syncSvgHeightWithTT = function () {
var $svg = this.$().find(".sapGanttChartSvgCtn");
//var nRowNumber = this._oTT.getVisibleRowCount();
$svg.height(this.$().find(".sapUiTableCCnt").height());
};
GanttChart.prototype._syncSvgDataWithTT = function () {
var oBinding = this._oTT.getBinding("rows");
var bJSONTreeBinding = oBinding.getMetadata().getName() === "sap.ui.model.json.JSONTreeBinding";
var iFirstVisibleRow = this._oTT.getFirstVisibleRow();
var iVisibleRowCount = this._oTT.getVisibleRowCount();
// structured data for drawing by D3
this._aShapeData = [];
this._aNonVisibleShapeData = [];
// temporary variables
var _aTopNonVisibleShapeData = [];
var _aBottomNonVisibleShapeData = [];
// default visible range
var aVisibleRange = [iFirstVisibleRow, iFirstVisibleRow + iVisibleRowCount - 1];
if (bJSONTreeBinding) {
aVisibleRange = this._prepareVerticalDrawingRange();
oBinding.getContexts(0, 0);// get all contexts
if (iFirstVisibleRow > 0) {
_aTopNonVisibleShapeData = this._getDrawingData([0, iFirstVisibleRow - 1]);
}
_aBottomNonVisibleShapeData = this._getDrawingData([iFirstVisibleRow + iVisibleRowCount, oBinding.getLength() - 1]);
oBinding.getContexts(aVisibleRange[0], aVisibleRange[1]);// get contexts of visible area
this._aShapeData = this._getDrawingData(aVisibleRange);
} else {
if (this._aRelationshipsContexts && this._aRelationshipsContexts.length > 0){
// oBinding.getContexts(0, 0) returns all contexts so we have to check whether iFirstVisibleRow is larger than 0
if (iFirstVisibleRow > 0) {
_aTopNonVisibleShapeData = this._createShapeDataFromRowContexts(oBinding.getContexts(0, iFirstVisibleRow));
}
_aBottomNonVisibleShapeData = this._createShapeDataFromRowContexts(oBinding.getContexts(iFirstVisibleRow + iVisibleRowCount, oBinding.getLength()));
}
// row contexts of the visible area
// IMPORTANT: this must be called after getting the row contexts of non visible because Table._aRowIndexMap is refreshed every time when getContexts is called.
var aRowContext = oBinding.getContexts(iFirstVisibleRow, iVisibleRowCount);
this._aShapeData = this._createShapeDataFromRowContexts(aRowContext);
}
// merge _aTopNonVisibleShapeData with _aBottomNonVisibleShapeData
this._aNonVisibleShapeData = _aTopNonVisibleShapeData.concat(_aBottomNonVisibleShapeData);
// enhance row data
var aShapeDataNames = this.getShapeDataNames();
if (aShapeDataNames && aShapeDataNames.length > 0) {
Utility.generateRowUid(this._aShapeData,this._oObjectTypesConfigMap, aShapeDataNames); // +uid
Utility.generateRowUid(this._aNonVisibleShapeData, this._oObjectTypesConfigMap, aShapeDataNames); // +uid
this._setSelectedStatusFromData(aShapeDataNames);
} else {
jQuery.sap.log.error("Missing configuration for shapeDataNames.");
}
var iBaseRowHeight = this.getBaseRowHeight();
this._oAxisOrdinal = this._createAxisOrdinal(this._aShapeData, iBaseRowHeight,
(aVisibleRange[0] - iFirstVisibleRow) * iBaseRowHeight);
// this._replaceDataRef(); // replace ref --TODO: move this logic to app
this._cacheObjectPosition(this._aShapeData, this._oAxisOrdinal); // +y, +rowHeight
this._cacheObjectPosition(_aTopNonVisibleShapeData, this._oAxisOrdinal, true); // +y, +rowHeight
this._cacheObjectPosition(_aBottomNonVisibleShapeData, this._oAxisOrdinal, false); // +y, +rowHeight
if (!this._aVisibleRange || this._aVisibleRange[0] !== aVisibleRange[0] || this._aVisibleRange[1] !== aVisibleRange[1]) {
this._aVisibleRange = aVisibleRange;
return true;
}
return false;
};
/*
* Creates shape data array for the given row contexts.
*/
GanttChart.prototype._createShapeDataFromRowContexts = function (aRowContexts) {
var aShapeDataNames = this.getShapeDataNames();
var oBinding = this._oTT.getBinding("rows");
var oModel = oBinding.getModel();
var aShapeData = [];
for (var i = 0; i < aRowContexts.length; i++) {
if (aRowContexts[i] != undefined) {
for (var j = 0; j < aShapeDataNames.length; j++) {
var sShapeName = aShapeDataNames[j];//e.g. 'Header'
var aShapeDataPath = aRowContexts[i].getProperty(sShapeName);//e.g. ["HeaderDetail('0%20')","HeaderDetail('48%20')"]
var oShapeData;
if (aShapeDataPath) {
for (var k = 0; k < aShapeDataPath.length; k++) {
var sShapeDataPath = aShapeDataPath[k];
oShapeData = oModel.getData("/" + sShapeDataPath);
aShapeData.push({
"bindingObj": oBinding,
"contextObj": aRowContexts[i],
"data": aRowContexts[i].getObject(),
"shapeData": [oShapeData],
"id": oShapeData.id,
"shapeName": sShapeName,
"rowIndex": i
});
}
}
}
}
}
return aShapeData;
};
/*
* Calculate [rowHeight] and [y] property for each object based on a given axisY
* @param {object[]} objects Shape data array for whose entity we will add y and rowHeight properties to.
* @param {object} axisY AxisOrdinal object.
* @param {boolean} bAboveOrUnderVisibleArea Optional. Only used for drawing elements in the non visible area.
* if undefined, means the objects are in the visible area
* if true, means the objects are above the visible area, then y are -100
* if false, means the objects are under the visible area, then y are axisY.getViewRange()[1]+100
* @return undefined
*/
GanttChart.prototype._cacheObjectPosition = function (objects, axisY, bAboveVisibleArea) {
if (objects && objects.length > 0) {
if (bAboveVisibleArea === true) {
for (var i = 0; i < objects.length; i++) {
objects[i].y = -100;
objects[i].rowHeight = axisY.getViewBandWidth();
}
} else if (bAboveVisibleArea === false) {
for (var j = 0; j < objects.length; j++) {
objects[j].y = axisY.getViewRange()[1] + 100;
objects[j].rowHeight = axisY.getViewBandWidth();
}
} else {
for (var k = 0; k < objects.length; k++) {
objects[k].y = axisY.elementToView(objects[k].uid);
if (k > 0) {
objects[k - 1].rowHeight = objects[k].y - objects[k - 1].y;
}
}
objects[objects.length - 1].rowHeight = axisY.getViewRange()[1] - objects[objects.length - 1].y;
}
}
};
/*
* Loop this._aRelationshipsContexts and call getObject method on each entity and then push the value into this._aRelationships
*/
GanttChart.prototype._prepareRelationshipDataFromModel = function () {
this._aRelationships = [];
if (this._aRelationshipsContexts) {
for (var i = 0; i < this._aRelationshipsContexts.length; i++) {
var oRelationship = this._aRelationshipsContexts[i].getObject();
if (oRelationship !== undefined) {
this._aRelationships.push(oRelationship);
}
}
}
Utility.generateUidByShapeDataName(this._aRelationships, "relationship"); // +uid for relationships
};
GanttChart.prototype._createAxisOrdinal = function (aShapeData, iBaseRowHeight, fShift) {
var aRowNames = aShapeData.map(function (oRow) {
return oRow.uid;
});
var aRowHeights = aShapeData.map(function (oRow) {
if (oRow.rowSpan) {
return oRow.rowSpan;
} else {
//For blank rows in hierarchy, just return 1, since there is no place to specify its rowSpan now...
return 1;
}
});
return new AxisOrdinal(aRowNames, aRowHeights, iBaseRowHeight, fShift);
};
GanttChart.prototype.getShapeData = function(aRange) {
return this._aShapeData;
};
GanttChart.prototype._getDrawingData = function(aRange) {
var i, j, k, oRow;
var oBinding = this._oTT.getBinding("rows");
var aRowList = [];
for (i = aRange[0]; i <= aRange[1]; i++) {
oRow = TreeTableHelper.getContextObject(this._oTT, i);
if (!oRow) {
continue;
}
if (TreeTableHelper.isDummyRow(this._oTT, i)
&& ((aRowList.length > 0
&& aRowList[aRowList.length - 1].chartScheme
&& aRowList[aRowList.length - 1].chartScheme === oRow.__group
&& aRowList[aRowList.length - 1].index === oRow.index) || oRow.chartScheme)) {
continue;
}
if (oRow.__group) { // expanded row
var sMode;
if (this._oChartSchemesConfigMap[oRow.__group] && this._oChartSchemesConfigMap[oRow.__group].getModeKey() && this._oChartSchemesConfigMap[oRow.__group].getModeKey() !== sap.gantt.config.DEFAULT_MODE_KEY) {
sMode = this._oChartSchemesConfigMap[oRow.__group].getModeKey();
} else {
sMode = this.getMode();
}
var oSchemeInfo = this._collectDataNameForValidChartScheme(oRow.__group, sMode);
var oParent = oRow.parentData ? oRow.parentData : null;
if (oRow.index && oParent && oSchemeInfo && oSchemeInfo.drawData) {
for (j = 0; j < oSchemeInfo.drawData.length; j++) {
if (!oParent[oSchemeInfo.drawData[j]]) {
continue;
}
oRow[oSchemeInfo.drawData[j]] = [];
for (k = 0; k < oParent[oSchemeInfo.drawData[j]].length; k++) {
if (!oParent[oSchemeInfo.drawData[j]][k].rowIndex ||
oRow.index === oParent[oSchemeInfo.drawData[j]][k].rowIndex) {
oRow[oSchemeInfo.drawData[j]].push(oParent[oSchemeInfo.drawData[j]][k]);
}
}
}
}
aRowList.push({
"bindingObj": oBinding,
"data": oRow,
"id": oParent.id,
"rowSpan": oSchemeInfo.rowSpan,
"chartScheme": oRow.__group,
"rowIndex": i,
"index": oRow.index, // > 0
"icon": this._oChartSchemesConfigMap[oRow.__group].getIcon(),
"closeIcon": "./image/closeChart.png",
"name": this._oChartSchemesConfigMap[oRow.__group].getName()
});
} else { // main row
var rowSpan = 1;
var sChartScheme = this._oObjectTypesConfigMap[oRow.type] ?
this._oObjectTypesConfigMap[oRow.type].getMainChartSchemeKey() :
sap.gantt.config.DEFAULT_CHART_SCHEME_KEY;
if (oRow.type) {
var oChartScheme = this._oChartSchemesConfigMap[sChartScheme];
if (oChartScheme) {
rowSpan = oChartScheme.getRowSpan();
}
}
aRowList.push({
"bindingObj": oBinding,
"contextObj": this._oTT.getContextByIndex(i),
"data": oRow,
"id": oRow.id,
"rowSpan": rowSpan,
"chartScheme": sChartScheme,
"rowIndex": i,
"index": 0
});
}
}
return aRowList;
};
GanttChart.prototype._prepareVerticalDrawingRange = function() {
var nLastBindingRow = this._oTT.getBinding("rows").getLength() - 1;
if (nLastBindingRow < 0) {
return [0, -1];
}
var nFirstVisibleRow = this._oTT.getFirstVisibleRow();
var nLastVisibleRow = nFirstVisibleRow + this._oTT.getVisibleRowCount() - 1;
var nFirstDrawingRow = nFirstVisibleRow;
var nLastDrawingRow = nLastVisibleRow < nLastBindingRow ? nLastVisibleRow : nLastBindingRow;
var i, nGroup, nGroupIndex, oRow;
for (i = nFirstVisibleRow; i >= 0; i--) {
if (!TreeTableHelper.isDummyRow(this._oTT, i)) {
break;
}
oRow = TreeTableHelper.getContextObject(this._oTT, i);
if (oRow && oRow.previousNodeNum) {
nFirstDrawingRow = i - oRow.previousNodeNum;
continue;
}
if (!oRow || !oRow.index || oRow.index < 0) {
break;
}
if (!nGroupIndex) {
nGroup = oRow.__group;
nGroupIndex = oRow.index;
} else if (nGroup === oRow.__group && nGroupIndex === oRow.index) {
nFirstDrawingRow = i;
} else {
break;
}
}
nGroupIndex = undefined;
for (i = nLastVisibleRow; i <= nLastBindingRow; i++) {
oRow = TreeTableHelper.getContextObject(this._oTT, i);
if (oRow && oRow.afterNodeNum) {
nLastDrawingRow = i + oRow.afterNodeNum;
continue;
}
if (!TreeTableHelper.isDummyRow(this._oTT, i)) {
break;
}
if (!oRow || !oRow.index || oRow.index < 0) {
break;
}
if (!nGroupIndex) {
nGroup = oRow.__group;
nGroupIndex = oRow.index;
} else if (nGroup === oRow.__group && nGroupIndex === oRow.index) {
nLastDrawingRow = i;
} else {
break;
}
}
return [nFirstDrawingRow, nLastDrawingRow];
};
GanttChart.prototype._prepareHorizontalDrawingRange = function () {
//oStatusSet must keep the value of LTR mode because other functions use it
var nContentWidth = this._nUpperRange - this._nLowerRange;
var nClientWidth = jQuery("#" + this.getId() + "-svg-ctn").width();
if (!this._oStatusSet) {
this._updateScrollWidth();
}
var nScrollLeft = Math.ceil((this._fLeftOffsetRate ? this._fLeftOffsetRate : 0) * (nContentWidth - nClientWidth));
if (this._oStatusSet) {
if ((nClientWidth >= nContentWidth || (this._oStatusSet.aViewBoundary[0] <= nScrollLeft - this._oStatusSet.nOffset &&
this._oStatusSet.aViewBoundary[1] >= nScrollLeft + nClientWidth - this._oStatusSet.nOffset))) {
if (!this._mTimeouts._drawSvg) {
this._scrollSvg();
}
return false;
}
}
var nWidth = nClientWidth * (1 + this._fExtendFactor * 2);
var nOffset = nScrollLeft - nClientWidth * this._fExtendFactor;
if (nOffset < this._nLowerRange) {
nWidth += nOffset;
nOffset = 0;
}
if (nOffset + nWidth > this._nUpperRange) {
nWidth = this._nUpperRange - nOffset;
}
this._oAxisTime.setViewOffset(nOffset);
this._oStatusSet = {
nWidth: nWidth,
nOffset: nOffset,
nScrollLeft: nScrollLeft,
aViewBoundary: [0, nWidth],
aTimeBoundary: [this._oAxisTime.viewToTime(0), this._oAxisTime.viewToTime(nWidth)],
bRTL: Core.getConfiguration().getRTL()
};
return true;
};
GanttChart.prototype._draw = function (bForced) {
if (!this._prepareHorizontalDrawingRange() && !bForced) {
return;
}
var that = this;
this._mTimeouts._drawSvg = this._mTimeouts._drawSvg || window.setTimeout(function() {
that._drawSvg();
that._mDrawDelayMS = 0;
}, this._mDrawDelayMS);
};
GanttChart.prototype._updateScrollWidth = function () {
var nMaxScrollWidth = 100000;
var nContentWidth = this._nUpperRange - this._nLowerRange;
var nScrollWidth = nContentWidth > nMaxScrollWidth ? nMaxScrollWidth : nContentWidth;
if (nScrollWidth + "px" !== this._oTT._oHSb.getContentSize()) {
this._oTT._oHSb.setContentSize(nScrollWidth + "px").bind(this._oTT.getDomRef());
}
};
GanttChart.prototype._updateScrollLeft = function () {
var nScrollWidth = parseInt(this._oTT._oHSb.getContentSize(), 0);
var nClientWidth = jQuery("#" + this.getId() + "-svg-ctn").width();
var nScrollLeft = Math.ceil((this._fLeftOffsetRate ? this._fLeftOffsetRate : 0) * (nScrollWidth - nClientWidth));
if (Core.getConfiguration().getRTL() === true) {
nScrollLeft = nScrollWidth - nScrollLeft - nClientWidth;
}
if (Math.abs(this._oTT._oHSb.getScrollPosition() - nScrollLeft) > 1) {
this._oTT._oHSb.setScrollPosition(nScrollLeft);
}
};
GanttChart.prototype._scrollSvg = function () {
var $svg = jQuery("#" + this.getId() + "-svg");
var $header = jQuery("#" + this.getId() + "-header-svg");
if (this._oStatusSet.nWidth !== $svg.width()) {
$svg.width(this._oStatusSet.nWidth);
}
if (this._oStatusSet.nWidth !== $header.width()) {
$header.width(this._oStatusSet.nWidth);
}
var nContentWidth = this._nUpperRange - this._nLowerRange;
var nClientWidth = jQuery("#" + this.getId() + "-svg-ctn").width();
var nScrollLeft = Math.ceil((this._fLeftOffsetRate ? this._fLeftOffsetRate : 0) * (nContentWidth - nClientWidth));
this._hSbScrollLeft(nScrollLeft - this._oStatusSet.nOffset);
};
GanttChart.prototype._drawSvg = function () {
jQuery.sap.measure.start("GanttChart _drawSvg","GanttPerf:GanttChart _drawSvg function");
// before draw
this._updateScrollLeft();
this._scrollSvg();
this._sUiSizeMode = Utility.findSapUiSizeClass(this);
// draw
this._drawCalendarPattern();
this._drawHeader();
this._drawNowLine();
this._drawVerticalLine();
this._drawShapes();
this._drawSelectedShapes();
// after draw
this.fireEvent("_shapesUpdated", {aSvg: jQuery("#" + this.getId() + "-svg")});
this._updateCSSForDummyRow();
delete this._mTimeouts._drawSvg;
jQuery.sap.measure.end("GanttChart _drawSvg");
};
GanttChart.prototype._drawHeader = function () {
var $headerDom = jQuery(this.getDomRef()).find(".sapGanttChartHeader");
var nSvgHeight = $headerDom.height();
var oHeaderSvg = d3.select(jQuery(this.getDomRef()).find(".sapGanttChartHeaderSvg").get(0));
oHeaderSvg.attr("height", nSvgHeight);
// Split the total SVG height as 5 parts for drawing
// label0 (MM YYYY), label1 (DD) and vertical line (|)
var nfirstRowYOffset = nSvgHeight / 5 * 2;
var nMiddleLineYOffset = nSvgHeight / 5 * 4;
var nSecondRowYOffset = nSvgHeight / 5 * 4;
var aLabelList = this.getAxisTime().getTickTimeIntervalLabel(
this.getAxisTime().getCurrentTickTimeIntervalKey(), null, [0, this._oStatusSet.nWidth]);
// append group
oHeaderSvg.selectAll("g").remove();
var oGroupSvg = oHeaderSvg.append("g");
// append text for labels on first row
oGroupSvg.selectAll("label0")
.data(aLabelList[0])
.enter()
.append("text")
.classed("sapGanttTimeHeaderSvgText0", true)
.text(function (d) {
return d.label;
}).attr("x", function (d) {
return d.value;
}).attr("y", function (d) {
return nfirstRowYOffset;
});
// append text for labels on second row
oGroupSvg.selectAll("label1")
.data(aLabelList[1])
.enter()
.append("text")
.classed("sapGanttTimeHeaderSvgText1", true)
.text(function (d) {
return d.label;
}).attr("x", function (d) {
// 5px spacing for the text
return d.value + (Core.getConfiguration().getRTL() ? -5 : 5);
}).attr("y", function (d) {
return nSecondRowYOffset;
});
// append path for scales on both rows
var sPathData = "";
for (var i = 0; i < aLabelList[1].length; i++) {
var oLabel = aLabelList[1][i];
if (oLabel) {
sPathData +=
" M" +
" " + (oLabel.value - 1 / 2) +
" " + nMiddleLineYOffset +
" L" +
" " + (oLabel.value - 1 / 2 ) +
" " + nSvgHeight;
}
}
oGroupSvg.append("path").classed("sapGanttTimeHeaderSvgPath", true).attr("d", sPathData);
};
GanttChart.prototype._drawCalendarPattern = function () {
var $GanttChartSvg = d3.select("#" + this.getId() + "-svg");
this._oCalendarPatternDrawer.drawSvg($GanttChartSvg, this.getId(), this.getCalendarDef(), this._oStatusSet, this.getBaseRowHeight());
};
GanttChart.prototype._drawNowLine = function () {
this._oNowlineDrawer = new NowLineDrawer(this._oAxisTime);
var $GanttChartHeader = d3.select("#" + this.getId() + "-header-svg"),
$GanttChartSvg = d3.select("#" + this.getId() + "-svg");
if (this.getEnableNowLine()) {
this._oNowlineDrawer.drawSvg($GanttChartSvg, $GanttChartHeader);
} else {
this._oNowlineDrawer.destroySvg($GanttChartSvg, $GanttChartHeader);
}
};
GanttChart.prototype._drawVerticalLine = function() {
this._oVerticalLineDrawer = new VerticalLineDrawer(this.getAxisTime());
var $GanttChartSvg = d3.select("#" + this.getId() + "-svg");
if (this.getEnableVerticalLine()) {
this._oVerticalLineDrawer.drawSvg($GanttChartSvg);
} else {
this._oVerticalLineDrawer.destroySvg($GanttChartSvg);
}
};
GanttChart.prototype._drawShapes = function () {
var aSvg = d3.select("#" + this.getId() + "-svg");
if (!this._oTT || !this._oTT.getRows() || this._oTT.getRows().length <= 0) {
return;
}
// draw shape
if (this._aShapeData && this._aShapeInstance && this._aShapeInstance.length > 0) {
this._collectDataPerShapeId();
var relationshipDataSet = [];
for (var i = 0; i < this._aShapeInstance.length; i++) {
switch (this._aShapeInstance[i].getCategory(null, this._oAxisTime, this._oAxisOrdinal)) {
case sap.gantt.shape.ShapeCategory.InRowShape:
this._oShapeInRowDrawer.drawSvg(aSvg, this._aShapeInstance[i],
this._oAxisTime, this._oAxisOrdinal, this._oStatusSet);
break;
case sap.gantt.shape.ShapeCategory.Relationship:
if (this._judgeDisplayableOfRLS(this._aShapeInstance[i])) {
relationshipDataSet = this._oShapeCrossRowDrawer.generateRelationshipDataSet(aSvg, this._oShapeInstance, this._aNonVisibleShapeData,
this.getShapeDataNames(), this._aRelationships, this._oAxisTime, this._oAxisOrdinal);
}
this._aShapeInstance[i].dataSet = relationshipDataSet;
this._oShapeCrossRowDrawer.drawSvg(aSvg, this._aShapeInstance[i],
this._oAxisTime, this._oAxisOrdinal);
break;
default:
break;
}
}
}
};
//draw all the selected shapes and relationships
GanttChart.prototype._drawSelectedShapes = function () {
if (!this._oTT || !this._oTT.getRows() || this._oTT.getRows().length <= 0) {
return;
}
var aSvg = d3.select("#" + this.getId() + "-svg");
//set selected Status for Shapes and relationships
this._setSelectedStatusToData();
// draw selected shape
this._collectSelectedDataPerShapeId();
for (var sShapeId in this._oShapeInstance) {
var oSelectedClassIns = this._oShapeInstance[sShapeId].getAggregation("selectedShape");
var category = oSelectedClassIns.getCategory(null, this._oAxisTime, this._oAxisOrdinal);
switch (category) {
case sap.gantt.shape.ShapeCategory.InRowShape:
this._oShapeInRowDrawer.drawSvg(aSvg, oSelectedClassIns, this._oAxisTime, this._oAxisrdinal, this._oStatusSet);
break;
case sap.gantt.shape.ShapeCategory.Relationship:
var relationshipDataSet = this._oShapeCrossRowDrawer.generateRelationshipDataSet(aSvg, this._oShapeInstance, this._aNonVisibleShapeData,
this.getShapeDataNames(), this._aSelectedRelationships, this._oAxisTime, this._oAxisOrdinal);
oSelectedClassIns.dataSet = relationshipDataSet;
this._oShapeCrossRowDrawer.drawSvg(aSvg, oSelectedClassIns,
this._oAxisTime, this._oAxisOrdinal);
break;
default:
break;
}
}
};
/*
* This method collect data according to current row's configuration/objectType/shape/chart scheme/mode.
* this._aShapeData contains the data for all different shapes so here we need to pick up by sShapeName
* once is function finished execution, each instance of shape classes will have 'dataset' attribute
* and it is an array of the data picked up from this._aShapeData for drawing that shape.
*/
GanttChart.prototype._collectDataPerShapeId = function () {
var bJSONTreeBinding = (this._oTT.getBinding("rows").getMetadata().getName() === "sap.ui.model.json.JSONTreeBinding");
var oRowData, oShapeData;
//this._oShapeInstance is an object which has properties with format as below:
//property key is the data name for shapes such as 'header'
//property value is the instance of shape classes such as sap.gantt.shape.Rectangle
//so the structure of this._oShapeInstance is like
//{
// 'header': <instance of sap.gantt.shape.ext.Chevron>
// 'task': <sap.gantt.shape.Rectangle>
//}
for (var sShapeId in this._oShapeInstance) {
var sShapeName = this._oShapeInstance[sShapeId].mShapeConfig.getShapeDataName();//e.g. Header
this._oShapeInstance[sShapeId].dataSet = [];
for (var i = 0; i < this._aShapeData.length; i++) {
//this._aShapeData contains the data for all different shapes so here we need to pick up by sShapeName
oRowData = this._aShapeData[i];
if (oRowData.isBlank) {
continue;
}
//if user doesn't configure the shape with 'shapeDataName', add all row data to the shape
if (!sShapeName) {
this._oShapeInstance[sShapeId].dataSet.push({
"objectInfoRef": oRowData,
"shapeData": oRowData.data
});
continue;
}
if (!this._judgeDisplayableByShapeId(oRowData, sShapeId)) {
continue;
}
if (bJSONTreeBinding){
oShapeData = oRowData.data[sShapeName];
}else if (sShapeName == oRowData.shapeName) {
oShapeData = [oRowData.data];
}else {
continue;
}
if (oShapeData){
this._oShapeInstance[sShapeId].dataSet.push({
"objectInfoRef": oRowData,
"shapeData": oShapeData
});
}
}
}
};
GanttChart.prototype._collectSelectedDataPerShapeId = function () {
//group the selected shape data into the dataSet of related selectedClass instance
for (var sShapeId in this._oShapeInstance) {
var sShapeDataName = this._oShapeInstance[sShapeId].mShapeConfig.getShapeDataName();//e.g. Header
var oSelectedClassIns = this._oShapeInstance[sShapeId].getAggregation("selectedShape");
var sCategory = oSelectedClassIns.getCategory(null, this._oAxisTime, this._oAxisOrdinal);
//collect shape data for every selectedClass instance according to current selection
oSelectedClassIns.dataSet = [];
if (sCategory == sap.gantt.shape.ShapeCategory.Relationship) {
var aShapeData = [];
for (var j in this._aSelectedRelationships) {
var oRelationshipData = this._aSelectedRelationships[j];
//only when the relationship is display, it needs to be drew
if (this._getShapeDataById(oRelationshipData.id, true) !== undefined) {
aShapeData.push(oRelationshipData);
}
}
oSelectedClassIns.dataSet.push({
"shapeData": aShapeData
});
}else if (this._oSelectedShapes[sShapeDataName] !== undefined) {
for (var i in this._oSelectedShapes[sShapeDataName]) {
var oShape = this._oSelectedShapes[sShapeDataName][i];
//only when the master shape is displayed, draw the selectedShape
var oRowData = this._getRowByShapeUid(oShape.shapeUid);
if (oRowData !== undefined && oRowData !== null && this._judgeDisplayableByShapeId(oRowData, sShapeId)){
oShape.objectInfoRef = oRowData;
oSelectedClassIns.dataSet.push({
"objectInfoRef": oShape.objectInfoRef,
"shapeData": [oShape.shapeData]
});
}
}
}
}
};
GanttChart.prototype._judgeDisplayableByShapeId = function (oRowData, sShapeId) {
var sChartScheme, oChartScheme, aShapeIdsInChartScheme, sMode;
if (oRowData.data.__group) {
sChartScheme = oRowData.data.__group;
} else {
sChartScheme = this._oObjectTypesConfigMap[oRowData.data.type] ?
this._oObjectTypesConfigMap[oRowData.data.type].getMainChartSchemeKey() :
sap.gantt.config.DEFAULT_CHART_SCHEME_KEY;
}
oChartScheme = this._oChartSchemesConfigMap[sChartScheme];
if (oChartScheme == undefined) {
return false;
}
aShapeIdsInChartScheme = oChartScheme.getShapeKeys();
/*
* determin mode. if mode is coded against chart scheme, it over-write current mode in chart
*/
sMode = oChartScheme.getModeKey() !== sap.gantt.config.DEFAULT_MODE_KEY ?
oChartScheme.getModeKey() :
this.getMode();
//sMode = oChartScheme.getModeKey() ? oChartScheme.getModeKey() : this.getMode();
/*
* check if shape should appear in current chart scheme and mode
*/
if (sChartScheme !== sap.gantt.config.DEFAULT_CHART_SCHEME_KEY &&
aShapeIdsInChartScheme.indexOf(sShapeId) < 0 ||
sMode !== sap.gantt.config.DEFAULT_MODE_KEY &&
this._oShapesConfigMap[sShapeId].getModeKeys() &&
this._oShapesConfigMap[sShapeId].getModeKeys().length > 0 &&
this._oShapesConfigMap[sShapeId].getModeKeys().indexOf(sMode) < 0 ||
!oRowData.data) {
return false;
}
return true;
};
GanttChart.prototype._judgeDisplayableOfRLS = function (oShape) {
var aShapeMode = this._oShapesConfigMap[oShape.mShapeConfig.getKey()] ?
this._oShapesConfigMap[oShape.mShapeConfig.getKey()].getModeKeys() : [];
if (jQuery.inArray(this.getMode(), aShapeMode) < 0 && this.getMode() !== sap.gantt.config.DEFAULT_MODE_KEY) {
return false;
}
return true;
};
//get shapeId by shape uid and related row data uid
GanttChart.prototype._getShapeDataNameByUid = function (sShapeUid) {
//var rowData;
var sShapeDataName;
if (sShapeUid !== undefined) {
var str = "|DATA:";
if (sShapeUid.split(str)[1]) {
sShapeDataName = sShapeUid.split(str)[1].split("[")[0];
}else {
sShapeDataName = sap.gantt.shape.ShapeCategory.Relationship;
}
}
return sShapeDataName;
};
//get Uid by id
GanttChart.prototype._getUidById = function (sId, bRelationship) {
var sUid = [];
if (bRelationship) {
for (var i in this._aRelationships) {
var oRelationship = this._aRelationships[i];
if (oRelationship.id == sId) {
sUid.push(oRelationship.uid);
break;
}
}
}else {
jQuery.each(this._aShapeData, function (k, v) {
var rowInfo = v;
for (var sShape in rowInfo.data) {
if (rowInfo.data[sShape] instanceof Array) {
for (var i in rowInfo.data[sShape]) {
//a shape can appear in different rows, so one id may have several uids
if (rowInfo.data[sShape][i].id == sId) {
sUid.push(rowInfo.data[sShape][i].uid);
}
}
}
}
});
}
return sUid;
};
//get shapeData by uid
GanttChart.prototype._getShapeDataByUid = function (sUid, bRelationship) {
if (bRelationship) {// if it is a relationship
for (var i in this._aRelationships) {
var oRelationship = this._aRelationships[i];
if (oRelationship.uid === sUid) {
return oRelationship;
}
}
}else {
var rowInfo = this._getRowByShapeUid(sUid);
var sShapeDataName = this._getShapeDataNameByUid(sUid);
if (rowInfo !== undefined && rowInfo.data[sShapeDataName] !== undefined) {
for ( var j = 0; j < rowInfo.data[sShapeDataName].length; j++) {
var oShapeData = rowInfo.data[sShapeDataName][j];
if (oShapeData.uid == sUid) {
return oShapeData;
}
}
}
}
return undefined;
};
/*
* get shapeData by id
* @para
* @para
* @return an array as there may be multiple uids for a same id, as the shape can appear more than once
*/
GanttChart.prototype._getShapeDataById = function (sId, bRelationship) {
var aShapeData = [];
var aUids = this._getUidById(sId, bRelationship);
for (var i in aUids) {
var oShapeData = this._getShapeDataByUid(aUids[i], bRelationship);
if (oShapeData !== undefined) {
aShapeData.push(oShapeData);
}
}
return aShapeData;
};
//get row obj by shape uid
//one shape(has an uid as unique key) may appear more then once in different rows, the uid includes row information
GanttChart.prototype._getRowByShapeUid = function (sShapeUid) {
var rowData;
var sShapeDataName = this._getShapeDataNameByUid(sShapeUid);
var bJSONTreeBinding = (this._oTT.getBinding("rows").getMetadata().getName() === "sap.ui.model.json.JSONTreeBinding");
jQuery.each(this._aShapeData, function (k, v) {
var rowInfo = v;
if (bJSONTreeBinding && rowInfo.data[sShapeDataName]) {
for ( var i = 0; i < rowInfo.data[sShapeDataName].length; i++) {
if (rowInfo.data[sShapeDataName][i].uid == sShapeUid) {
rowData = rowInfo;
return false;
}
}
}else if (rowInfo.data.uid === sShapeUid) {
rowData = rowInfo;
return false;
}
});
return rowData;
};
//get row by row id
GanttChart.prototype._getRowById = function (sRowId) {
var rowData;
jQuery.each(this._aShapeData, function (k, v) {
var rowInfo = v;
if (rowInfo.data.id == sRowId) {
rowData = rowInfo;
return false;
}
});
return rowData;
};
GanttChart.prototype._getSvgCoodinateByDiv = function(oNode, x, y){
var oClickPoint = oNode.createSVGPoint();
oClickPoint.x = x;
oClickPoint.y = y;
oClickPoint = oClickPoint.matrixTransform(oNode.getScreenCTM().inverse());
oClickPoint.svgHeight = oNode.height.baseVal.value;
oClickPoint.svgId = this.getId() + "-svg";
return oClickPoint;
};
GanttChart.prototype._getTopShapeInstance = function (oShapeData, sClassId) {
if (sClassId !== undefined) {
var oShapeId = this._getShapeIdById(sClassId);
if (oShapeId !== undefined && oShapeId !== null) {
if (oShapeId.topShapeId !== undefined) {
return this._oShapeInstance[oShapeId.topShapeId];
}else {
return this._oShapeInstance[oShapeId.shapeId];
}
}
}else {
var sShapeDataName = this._getShapeDataNameByUid(oShapeData.uid);
for (var sShapeId in this._oShapeInstance) {
var sShapeName = this._oShapeInstance[sShapeId].mShapeConfig.getShapeDataName();//e.g. Header
if (sShapeDataName === sShapeName){
var sTopShapeId = this._customerClassIds[sShapeId].topShapeId;
if (sTopShapeId !== undefined) {
return this._oShapeInstance[sTopShapeId];
}else {
return this._oShapeInstance[sShapeId];
}
}
}
}
return undefined;
};
//judge if the shape is selectable
GanttChart.prototype._judgeEnableSelection = function (oShapeData, sClassId) {
if (oShapeData === undefined) {
return false;
}
var oTopShapeInstance = this._getTopShapeInstance(oShapeData, sClassId);
if (oTopShapeInstance !== undefined) {
return oTopShapeInstance.getEnableSelection(oShapeData);
}
return false;
};
GanttChart.prototype._judgeEnableDnDByUid = function (sShapeUid) {
if (sShapeUid === undefined || sShapeUid == null) {
return false;
}
var oShapeData;
if (this._isRelationship(sShapeUid)) {
oShapeData = this._getShapeDataByUid(sShapeUid, true);
}else {
oShapeData = this._getShapeDataByUid(sShapeUid, false);
}
return this._judgeEnableDnD(oShapeData);
};
GanttChart.prototype._judgeEnableDnD = function (oShapeData, sClassId) {
if (oShapeData === undefined) {
return false;
}
var oTopShapeInstance = this._getTopShapeInstance(oShapeData, sClassId);
if (oTopShapeInstance !== undefined) {
return oTopShapeInstance.getEnableDnD(oShapeData);
}
return false;
};
/*select shape by adding current selecting shape into the shape selection
* The structure of aSelectedShapes: {"ShapeDataName1": e.g. all selected activities, "ShapeDataName2": e.g. all selected tasks...--- arrays with a struture of {"shapeUid": "shapeData", "objectInfoRef"}
*/
GanttChart.prototype._selectShape = function (oShapeData) {
var oRowInfo = this._getRowByShapeUid(oShapeData.uid);
if (oRowInfo == undefined) {
return false;
}
if (this._aSelectedShapeUids === undefined) {
this._aSelectedShapeUids = [];
}
var sShapeDataName = this._getShapeDataNameByUid(oShapeData.uid);
if (this._oSelectedShapes[sShapeDataName] !== undefined && this._oSelectedShapes[sShapeDataName] !== null ) {
var aShapes = this._oSelectedShapes[sShapeDataName];
if (jQuery.inArray(oShapeData.uid, this._aSelectedShapeUids) > -1) { //if the shape is already in selection
return false;
}else {
this._aSelectedShapeUids.push(oShapeData.uid);
aShapes.push({"shapeUid": oShapeData.uid, "shapeData": oShapeData, "objectInfoRef": oRowInfo});
return true;
}
}else {
this._aSelectedShapeUids.push(oShapeData.uid);
this._oSelectedShapes[sShapeDataName] = [];
this._oSelectedShapes[sShapeDataName].push({"shapeUid": oShapeData.uid, "shapeData": oShapeData, "objectInfoRef": oRowInfo});
return true;
}
};
// deselect current shape by remove it from the collection of selected shapes
GanttChart.prototype._deselectShape = function (oShapeData) {
var sShapeDataName = this._getShapeDataNameByUid(oShapeData.uid);
if (jQuery.inArray(oShapeData.uid, this._aSelectedShapeUids) > -1) {
var iIndex = this._aSelectedShapeUids.indexOf(oShapeData.uid);
this._aSelectedShapeUids.splice(iIndex,1);
var aShapes = this._oSelectedShapes[sShapeDataName];
for (var i in aShapes) {
if (aShapes[i].shapeUid === oShapeData.uid) {
aShapes.splice(i,1);
break;
}
}
return true;
}
return false;
};
GanttChart.prototype._updateCSSForDummyRow = function() {
var aRows = this._oTT.getRows();
var aRowHeaders = this._oTT.$().find(".sapUiTableRowHdrScr").children();
for (var i = 0; i < aRows.length; i++){
var oRow = aRows[i];
var index = oRow.getIndex();
if (index !== -1 && TreeTableHelper.isMultipleSpanMainRow(this._oTT, i)){
var context = TreeTableHelper.getContextObject(this._oTT, index);
if (context.afterNodeNum > 0){
aRows[i].$().addClass("sapGanttTrNoBorder");
$(aRowHeaders[i]).addClass("sapGanttTHeaderNoBorder");
} else {
aRows[i].$().removeClass("sapGanttTrNoBorder");
$(aRowHeaders[i]).removeClass("sapGanttTHeaderNoBorder");
}
} else {
aRows[i].$().removeClass("sapGanttTrNoBorder");
$(aRowHeaders[i]).removeClass("sapGanttTHeaderNoBorder");
}
}
};
GanttChart.prototype.getAxisOrdinal = function () {
return this._oAxisOrdinal;
};
GanttChart.prototype.getAxisTime = function () {
return this._oAxisTime;
};
GanttChart.prototype.ondblclick = function (oEvent) {
return null;
};
GanttChart.prototype.onclick = function (oEvent) {
return null;
};
GanttChart.prototype.getSapUiSizeClass = function () {
return this._sUiSizeMode;
};
GanttChart.prototype.exit = function () {
// TODO: destroy axis time and ordinal after refactor to listener pattern.
// other children are all strong aggregation relations, no need to destroy.
this._detachEvents();
};
return GanttChart;
}, true);
<file_sep>/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
jQuery.sap.declare("sap.apf.core.sessionHandler");
jQuery.sap.require("sap.apf.core.ajax");
jQuery.sap.require("sap.apf.utils.filter");
jQuery.sap.require("sap.apf.core.constants");
(function() {
'use strict';
/**
* @class Handles the session of an APF based application. e.g. the XSRF token handling
*/
/*global setTimeout*/
sap.apf.core.SessionHandler = function(oInject) {
// private vars
var that = this;
var dirtyState = false;
var pathName = '';
var sXsrfToken = "";
var sServiceRootPath = "";
var oHashTableXsrfToken = new sap.apf.utils.Hashtable(oInject.messageHandler);
var nFetchTryCounter = 0;
var oCoreApi = oInject.coreApi;
var oMessageHandler = oInject.messageHandler;
// private functions
var onError = function(oJqXHR, sStatus, sErrorThrown) {
if ((sXsrfToken.length === 0 || sXsrfToken === "unsafe") && nFetchTryCounter < 2) {
setTimeout(that.fetchXcsrfToken, 500 + Math.random() * 1500);
} else {
oMessageHandler.check(false, "No XSRF Token available!", 5101);
}
};
var onFetchXsrfTokenResponse = function(oData, sStatus, oXMLHttpRequest) {
sXsrfToken = oXMLHttpRequest.getResponseHeader("x-csrf-token");
/*
* In case XSRF prevention flag is not set in .xsaccess file for the service, then no "x-csrf-token" field is returned in response header.
* For robustness, XSRF token is set to empty string. Every request triggered by APF contains then a "x-csrf-token" request header field containing an empty string.
*/
if (sXsrfToken === null) {
sXsrfToken = "";
} else if ((sXsrfToken.length === 0 || sXsrfToken === "unsafe") && nFetchTryCounter < 2) {
setTimeout(that.fetchXcsrfToken, 500 + Math.random() * 1500);
}
};
// public vars
/**
* @description Returns the type
* @returns {String}
*/
this.type = "sessionHandler";
// public function
/**
* @see sap.apf.core.ajax
*/
this.ajax = function(oSettings) {
sap.apf.core.ajax(oSettings);
};
/**
* @description Returns the XSRF token as string for a given OData service root path
* @param {String} serviceRootPath OData service root path
* @returns {String}
*/
this.getXsrfToken = function(serviceRootPath) {
sServiceRootPath = serviceRootPath;
if (oHashTableXsrfToken.hasItem(sServiceRootPath)) {
return oHashTableXsrfToken.getItem(sServiceRootPath);
}
that.fetchXcsrfToken();
oHashTableXsrfToken.setItem(sServiceRootPath, sXsrfToken);
return sXsrfToken;
};
/**
* @description fetches XSRF token from XSE
*/
this.fetchXcsrfToken = function() {
that.ajax({
url : oCoreApi.getUriGenerator().getAbsolutePath(sServiceRootPath),
type : "GET",
beforeSend : function(xhr) {
xhr.setRequestHeader("x-csrf-token", "Fetch");
},
success : onFetchXsrfTokenResponse,
error : onError,
async : false
});
nFetchTryCounter = nFetchTryCounter + 1;
};
/**
* @private
* @name sap.apf.core.SessionHandler#setDirtyState
* @function
* @description Stores the current state for dirty information
* @param {boolean} state
*/
this.setDirtyState = function(state) {
dirtyState = state;
};
/**
* @private
* @name sap.apf.core.SessionHandler#isDirty
* @function
* @description Returns the last set state for the dirty information
* @returns {boolean} true: State of current instance is dirty | false: State of current instance is clean
*/
this.isDirty = function() {
return dirtyState;
};
/**
* @private
* @name sap.apf.core.SessionHandler#setPathNamee
* @function
* @description Set name is stored transiently. For persistent storage the methods of persistence object need to be used.
* @param {string} name
*/
this.setPathName = function(name) {
if(typeof name != 'string') {
pathName = '';
return;
}
pathName = name;
};
/**
* @private
* @name sap.apf.core.SessionHandler#getPathNamee
* @function
* @description Returns the last set path name
* @returns {string} path name
*/
this.getPathName = function() {
return pathName;
};
};
}()); | 3fa5d038f5b0cd05a28a6b5f9604b7ab9938b9d5 | [
"JavaScript",
"INI"
] | 89 | JavaScript | johnrochfordhds/sapui5demo | b49a7fd28b03a91c6ec6bc44ef18671a66d661ff | bafee94a6a4914f79cfafceeea7a7f91f27010d8 | |
refs/heads/main | <repo_name>abhishekabhiwan/DemoScripts<file_sep>/AgoraManager.cs
using System;
using System.Collections.Generic;
using agora_gaming_rtc;
using UnityEngine;
public enum AgoraManagerStatus { None, Ready, Joined }
public enum AudioQualityTypeAndCategory { NormalBradcast, MusicMono, MusicStereo, HQMono, HQStereo }
public class AgoraManager : MonoBehaviour
{
public static AgoraManager main;
private IRtcEngine mRtcEngine;
public IRtcEngine IRtcEngine { get { return mRtcEngine; } }
[Header("AgoraManager")]
[SerializeField]
protected string appId;
public AgoraManagerStatus _agoraManagerStatus;
public AgoraManagerStatus Status { get { return _agoraManagerStatus; } set { _agoraManagerStatus = value; AgoraManagerStatusChange(); AgoraManagerStatusChanged(_agoraManagerStatus); } }
public static event Action<AgoraManagerStatus> AgoraManagerStatusChanged = delegate { };
[SerializeField]
protected bool loadOnAwake = true;
[SerializeField]
protected bool loadOnStart = true;
[SerializeField]
protected bool loadOnJoin = true;
[Header("AgoraBehaviours")]
[SerializeField]
protected AgoraBehaviour _actualAgoraBehaviour;
public AgoraBehaviour ActualAgoraBehaviour { get { return _actualAgoraBehaviour; } set { _actualAgoraBehaviour = value; } }
[Header("Join")]
public string channelId;
public string myHexIdToSet;
[SerializeField]
protected uint mId;
public uint MyId { get { return mId; } }
[SerializeField]
protected bool joinNow;
[SerializeField]
protected bool leaveNow;
public bool enableAudioOnJoin = false;
public bool enableVideoOnJoin = true;
public bool enableVideoObserverOnJoin = true;
public static event OnJoinChannelSuccessHandler JoinChannelSuccess = delegate { };
public static event OnUserJoinedHandler UserJoined = delegate { };
public static event OnUserOfflineHandler UserOffline = delegate { };
[Header("ChannelProfile")]
public CHANNEL_PROFILE channelProfile = CHANNEL_PROFILE.CHANNEL_PROFILE_COMMUNICATION;
public CLIENT_ROLE channelBroadcastingRole = CLIENT_ROLE.AUDIENCE;
[Header("Join")]
public AudioQualityTypeAndCategory audioQualityTypeAndCategory = AudioQualityTypeAndCategory.NormalBradcast;
[Header("Stream")]
public bool useStream;
public bool streamReliable;
public bool streamOrdered;
[SerializeField]
protected int streamID;
[SerializeField]
protected bool testUpdateTextStream;
int i = 0;
[SerializeField]
protected bool debugStream;
public static event OnStreamMessageHandler StreamMessage = delegate { };
public static event OnStreamPublishedHandler StreamPublished = delegate { };
public static event OnStreamUnpublishedHandler StreamUnpublished = delegate { };
public static event OnStreamMessageErrorHandler StreamMessageError = delegate { };
[Header("Utils")]
public bool muteOnPause;
[SerializeField]
protected bool _amIMute;
public bool AmIMute { get { return _amIMute; } protected set { _amIMute = value; MuteToggled(_amIMute); } }
public static event Action<bool> MuteToggled = delegate { };
[Space(10)]
public bool muteAllOnPause;
[SerializeField]
protected bool _isAllMute;
public bool IsAllMute { get { return _isAllMute; } protected set { _isAllMute = value; MuteAllToggled(_isAllMute); } }
public static event Action<bool> MuteAllToggled = delegate { };
[Space(10)]
[SerializeField]
protected bool _eco;
public bool Eco { get { return _eco; } protected set { _eco = value; EcoToggled(_eco); } }
public static event Action<bool> EcoToggled = delegate { };
[Header("Fixs")]
public bool useIosFix = true;
[Header("Audio Editor")]
[SerializeField]
protected bool enableAudio;
[SerializeField]
protected bool disableAudio;
[Header("Video Editor")]
[SerializeField]
protected bool enableVideo;
[SerializeField]
protected bool disableVideo;
[Header("Reco Volume")]
public int recoVolume = 100;
[SerializeField]
protected bool _amIRecoMute;
public bool AmIRecoMute { get { return _amIRecoMute; } protected set { _amIRecoMute = value; RecoMuteToggled(_amIMute); } }
public static event Action<bool> RecoMuteToggled = delegate { };
[Header("Stats")]
public bool statsTemp;
public static event OnRemoteAudioStatsHandler RemoteAudioStatsUpdated = delegate { };
[Header("Devices")]
[SerializeField]
protected AgoraAudioDeviceData actualAudioRecordingDevice;
public AgoraAudioDeviceData ActualAudioRecordingDevice { get { return actualAudioRecordingDevice; } }
[SerializeField]
protected bool changeRecordingDevice;
[SerializeField]
protected List<AgoraAudioDeviceData> lastAgoraAudioRecordingDeviceData = new List<AgoraAudioDeviceData>();
[SerializeField]
protected bool updateAgoraAudioRecordingDeviceData;
[Space(10)]
[SerializeField]
protected AgoraAudioDeviceData actualAudioPlaybackDevice;
[SerializeField]
protected bool changePlaybackDevice;
[SerializeField]
protected List<AgoraAudioDeviceData> lastAgoraAudioPlaybackDeviceData = new List<AgoraAudioDeviceData>();
[SerializeField]
protected bool updateAgoraAudioPlaybackDeviceData;
[Space(10)]
[SerializeField]
protected AgoraVideoDeviceData actualVideoDevice;
[SerializeField]
protected bool changeVideoDevice;
[SerializeField]
protected List<AgoraVideoDeviceData> lastAgoraVideoDeviceData = new List<AgoraVideoDeviceData>();
[SerializeField]
protected bool updateAgoraVideoDeviceData;
[Header("Debug")]
public bool simulatePause;
//Editor
private void OnValidate()
{
if (joinNow)
{
Join(channelId, myHexIdToSet);
joinNow = false;
}
if (leaveNow)
{
Leave();
leaveNow = false;
}
if (enableVideo)
{
EnableVideo(true);
enableVideo = false;
}
if (disableVideo)
{
EnableVideo(false);
disableVideo = false;
}
if (enableAudio)
{
EnableAudio(true);
enableAudio = false;
}
if (disableAudio)
{
EnableAudio(false);
disableAudio = false;
}
if (changeRecordingDevice)
{
ChangeRecordingDevice();
changeRecordingDevice = false;
}
if (updateAgoraAudioRecordingDeviceData)
{
GetAudioRecordingDeviceList();
updateAgoraAudioRecordingDeviceData = false;
}
if (changePlaybackDevice)
{
ChangePlaybackDevice();
changePlaybackDevice = false;
}
if (updateAgoraAudioPlaybackDeviceData)
{
GetAudioPlaybackDeviceList();
updateAgoraAudioPlaybackDeviceData = false;
}
if (changeVideoDevice)
{
ChangeVideoDevice();
changeVideoDevice = false;
}
if (updateAgoraVideoDeviceData)
{
GetVideoDeviceList();
updateAgoraVideoDeviceData = false;
}
}
//Mono
private void OnApplicationPause(bool pause)
{
if (pause)
{
if (muteOnPause) MuteLocalAudioStream(true);
}
}
private void OnApplicationFocus(bool focus)
{
if (Application.isEditor)
{
if (simulatePause)
{
OnApplicationPause(!focus);
}
}
}
private void Awake()
{
main = this;
if (loadOnAwake)
{
LoadEngine(appId);
}
}
private void OnDestroy()
{
Leave();
UnloadEngine();
}
private void OnApplicationQuit()
{
Leave();
UnloadEngine();
}
private void Start()
{
//Boh();
if (loadOnStart)
{
if (Status == AgoraManagerStatus.None) LoadEngine(appId);
}
}
private void Update()
{
i++;
if (testUpdateTextStream)
{
SendStreamMessage("TESTTESTOTESTTESTOTESTTESTOTESTTESTO + " + i);
}
}
//Inner
protected void AgoraManagerStatusChange()
{
switch (Status)
{
case AgoraManagerStatus.None:
break;
case AgoraManagerStatus.Ready:
UpdateCurrentRecordingDevice();
break;
case AgoraManagerStatus.Joined:
UpdateCurrentRecordingDevice();
break;
default:
break;
}
}
//Main
public void LoadEngine(string appId = null)
{
if (appId == null) appId = this.appId;
// start sdk
Debug.Log("initializeEngine");
if (mRtcEngine != null)
{
Debug.Log("Engine exists. Please unload it first!");
return;
}
// init engine
mRtcEngine = IRtcEngine.GetEngine(appId);
// enable log
mRtcEngine.SetLogFilter(LOG_FILTER.DEBUG | LOG_FILTER.INFO | LOG_FILTER.WARNING | LOG_FILTER.ERROR | LOG_FILTER.CRITICAL);
// set callbacks (optional)
mRtcEngine.OnJoinChannelSuccess = OnJoinChannelSuccess;
mRtcEngine.OnUserJoined = OnUserJoined;
mRtcEngine.OnUserOffline = OnUserOffline;
mRtcEngine.OnClientRoleChanged = OnClientRoleChanged;
if (useStream)
{
mRtcEngine.OnStreamMessage = OnStreamMessage;
mRtcEngine.OnStreamPublished = OnStreamPublished;
mRtcEngine.OnStreamUnpublished = OnStreamUnpublished;
mRtcEngine.OnStreamMessageError = OnStreamMessageError;
}
//Mute Audio
mRtcEngine.OnUserMutedAudio = OnUserMuteAudio;
mRtcEngine.OnAudioRouteChanged = OnAudioRouteChanged;
//Stats
mRtcEngine.OnRemoteAudioStats = OnRemoteAudioStats;
Status = AgoraManagerStatus.Ready;
}
// unload agora engine
public void UnloadEngine()
{
Debug.Log("calling unloadEngine");
/*
IVideoDeviceManager videoDeviceManager = mRtcEngine.GetVideoDeviceManager();
videoDeviceManager.ReleaseAVideoDeviceManager();
*/
// delete
if (mRtcEngine != null)
{
IRtcEngine.Destroy(); // Place this call in ApplicationQuit
mRtcEngine = null;
}
Status = AgoraManagerStatus.None;
}
public void Join(string channel, string hexId, bool forceRejoin = true) //IN FUTURO DIVIDI QUESTO CRIPT E METTI UN MANAGER PER CHANNEL E PER UTENTI .. e opzioni su cosa faree JOIN
{
Join(channel, forceRejoin, hexId);
}
public void Join(string channel = "", bool forceRejoin = true, string hexId = "") //IN FUTURO DIVIDI QUESTO CRIPT E METTI UN MANAGER PER CHANNEL E PER UTENTI .. e opzioni su cosa faree JOIN
{
Debug.Log("calling join (channel = " + channel + ")");
if (channel == "")
channel = channelId;
if (string.IsNullOrEmpty(hexId))
hexId = myHexIdToSet;
uint uintId = 0;
if (!string.IsNullOrEmpty(hexId))
{
hexId = "";
//Parser non va al momento
/*
byte[] bytes = Encoding.ASCII.GetBytes(hexId);
uintId = BitConverter.ToUInt32(bytes, 0);
//hexId = hexId.Replace("-", "");
//uintId = Convert.ToUInt32(hexId, 16);
Debug.Log(uintId);
byte[] bytes2 = BitConverter.GetBytes(uintId);
string s = System.Text.Encoding.ASCII.GetString(bytes2);
Debug.Log("carlo " + s);
int intValue = 145354545;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
Debug.Log(intValue);
Debug.Log(hexValue);
Debug.Log(intAgain);
hexId = hexId.Replace("-", "").ToUpper();
Debug.Log(hexId);
long intdssdfsdfsdfdf = long.Parse(hexId, System.Globalization.NumberStyles.HexNumber);
// Store integer 182
///uintId = (uint)intAgain;
//int intValue = (int) uintId;
// Convert integer 182 as a hex in a string variable
//string hexValue = intValue.ToString("X");
Debug.Log(intdssdfsdfsdfdf);
*/
}
if (loadOnJoin)
{
if (Status == AgoraManagerStatus.None) LoadEngine(appId);
}
if (Status == AgoraManagerStatus.None)
{
return;
}
else
{
if (Status == AgoraManagerStatus.Joined)
{
if (forceRejoin)
{
Debug.Log("ForceRejoin");
Leave();
}
else
{
Debug.Log("AlreadyJoined");
return;
}
}
if (mRtcEngine == null)
return;
#if UNITY_IOS
if (useIosFix)
{
mRtcEngine.SetParameters("{\"che.audio.keep.audiosession\":true}");
}
#endif
int result = mRtcEngine.SetChannelProfile(channelProfile);
if (result < 0)
{
Debug.LogError("SetChannelProfile ERROR" + result);
return;
}
if (channelProfile == CHANNEL_PROFILE.CHANNEL_PROFILE_LIVE_BROADCASTING)
{
mRtcEngine.SetClientRole(channelBroadcastingRole);
}
// enable video
if (enableVideoOnJoin) EnableVideo(true);
// enable audio
if (enableAudioOnJoin) EnableAudio(true);
// allow camera output callback
if (enableVideoObserverOnJoin) EnableVideoObserver(true);
//Dopo enable audio. per sicurezza
if (channelProfile == CHANNEL_PROFILE.CHANNEL_PROFILE_LIVE_BROADCASTING)
{
switch (audioQualityTypeAndCategory)
{
case AudioQualityTypeAndCategory.NormalBradcast:
mRtcEngine.SetAudioProfile(AUDIO_PROFILE_TYPE.AUDIO_PROFILE_MUSIC_STANDARD, AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_EDUCATION);
break;
case AudioQualityTypeAndCategory.MusicMono:
mRtcEngine.SetAudioProfile(AUDIO_PROFILE_TYPE.AUDIO_PROFILE_MUSIC_STANDARD, AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_GAME_STREAMING);
break;
case AudioQualityTypeAndCategory.MusicStereo:
mRtcEngine.SetAudioProfile(AUDIO_PROFILE_TYPE.AUDIO_PROFILE_MUSIC_STANDARD_STEREO, AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_GAME_STREAMING);
break;
case AudioQualityTypeAndCategory.HQMono:
mRtcEngine.SetAudioProfile(AUDIO_PROFILE_TYPE.AUDIO_PROFILE_MUSIC_HIGH_QUALITY, AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_GAME_STREAMING);
break;
case AudioQualityTypeAndCategory.HQStereo:
mRtcEngine.SetAudioProfile(AUDIO_PROFILE_TYPE.AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO, AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_GAME_STREAMING);
break;
}
}
// join channel
result = mRtcEngine.JoinChannel(channel, null, uintId);
if (result < 0)
{
Debug.LogError("Join ERROR " + result);
return;
}
channelId = channel;
myHexIdToSet = hexId;
if (useStream) //TO DO ///|CARL FINISCI
{
// Optional: if a data stream is required, here is a good place to create it
streamID = mRtcEngine.CreateDataStream(streamReliable, streamOrdered);
Debug.Log("initializeEngine done, data stream id = " + streamID);
if (streamID < 0)
{
Debug.LogError("CreateDataStream ERROR " + streamID);
}
}
}
}
public void Leave()
{
Debug.Log("calling leave");
if (mRtcEngine == null)
return;
//EnableAudio(false);
//EnableVideo(false);
// leave channel
int result = mRtcEngine.LeaveChannel();
if (result < 0)
{
Debug.LogError("LeaveChannel ERROR" + result);
}
// deregister video frame observers in native-c code
EnableVideoObserver(false);
Status = AgoraManagerStatus.Ready;
}
//Callbacks Generic
private void OnJoinChannelSuccess(string channelName, uint uid, int elapsed)
{
Debug.Log("JoinChannelSuccessHandler: uid = " + uid);
mId = uid;
JoinChannelSuccess(channelName, uid, elapsed);
Status = AgoraManagerStatus.Joined;
//Debug.Log(" mRtcEngine.GetCallId();: uid = " + mRtcEngine.GetCallId());
/*
GameObject textVersionGameObject = GameObject.Find("VersionText");
textVersionGameObject.GetComponent<Text>().text = "SDK Version : " + getSdkVersion();
*/
}
// When a remote user joined, this delegate will be called. Typically
// create a GameObject to render video on it
private void OnUserJoined(uint uid, int elapsed)
{
Debug.Log("onUserJoined: uid = " + uid + " elapsed = " + elapsed);
// this is called in main thread
UserJoined(uid, elapsed);
//////////////////////////////////////////////////////////////////////////////////////// FAI <NAME> <NAME>
/*
// find a game object to render video stream from 'uid'
GameObject go = GameObject.Find(uid.ToString());
if (!ReferenceEquals(go, null))
{
return; // reuse
}
// create a GameObject and assign to this new user
VideoSurface videoSurface = makeImageSurface(uid.ToString());
if (!ReferenceEquals(videoSurface, null))
{
// configure videoSurface
videoSurface.SetForUser(uid);
videoSurface.SetEnable(true);
videoSurface.SetVideoSurfaceType(AgoraVideoSurfaceType.RawImage);
videoSurface.SetGameFps(30);
}*/
}
// When remote user is offline, this delegate will be called. Typically
// delete the GameObject for this user
private void OnUserOffline(uint uid, USER_OFFLINE_REASON reason)
{
// remove video stream
Debug.Log("onUserOffline: uid = " + uid + " reason = " + reason);
UserOffline(uid, reason);
/*// this is called in main thread
GameObject go = GameObject.Find(uid.ToString());
if (!ReferenceEquals(go, null))
{
Object.Destroy(go);
}*/
}
//ChannelProfile
public void ChannelRole(CLIENT_ROLE clientRole)
{
mRtcEngine.SetClientRole(clientRole);
channelBroadcastingRole = clientRole;
}
protected void OnClientRoleChanged(CLIENT_ROLE_TYPE oldRole, CLIENT_ROLE_TYPE newRole)
{
//In the Live Broadcast profile, when a user switches user roles after joining a channel, a successful setClientRole method call triggers the following callbacks
//The local client: OnClientRoleChangedHandler
//The remote client: OnUserJoinedHandler or OnUserOfflineHandler(BECOME_AUDIENCE)
Debug.Log("oldRole " + oldRole + " newRole " + newRole);
}
//Callbacks Stream
protected void OnStreamMessageError(uint userId, int streamId, int code, int missed, int cached) // CREARE UNA SEZIONE DI GESTIONE DEi messaggi ????
{
if (debugStream) Debug.LogError("OnStreamMessageError userId " + userId + " streamId " + streamId + " code " + code + " missed " + missed + " cached " + cached);
StreamMessageError(userId, streamId, code, missed, cached);
}
protected void OnStreamMessage(uint userId, int streamId, string data, int length) // CREARE UNA SEZIONE DI GESTIONE DEi messaggi ????
{
//* @param userId The user ID of the remote user sending the message.
//* @param streamId The stream ID.
//* @param data The data received by the local user.
//* @param length The length of the data in bytes.
if (debugStream) Debug.Log("OnStreamMessage userId " + userId + " streamId " + streamId + " data " + data + " length " + length);
StreamMessage(userId, streamId, data, length);
}
protected void OnStreamPublished(string url, int error) // CREARE UNA SEZIONE DI GESTIONE DEi messaggi ????
{
if (debugStream) Debug.Log("OnStreamPublished url " + url + " error " + error);
StreamPublished(url, error);
}
protected void OnStreamUnpublished(string url) // CREARE UNA SEZIONE DI GESTIONE DEi messaggi ????
{
if (debugStream) Debug.Log("OnStreamUnpublished url " + url);
StreamUnpublished(url);
}
//Audio
public void AdjustRecordingSignalVolume(int volume)
{
if (!AmIRecoMute)
{
if (mRtcEngine != null)
{
int result = mRtcEngine.AdjustRecordingSignalVolume(volume);
if (result < 0)
{
Debug.LogError("AdjustRecordingSignalVolume ERROR" + result);
}
}
}
else
{
if (mRtcEngine != null)
{
int result = mRtcEngine.AdjustRecordingSignalVolume(0); //Risettto sempre a zero pe rsicurezza
if (result < 0)
{
Debug.LogError("AdjustRecordingSignalVolume ERROR" + result);
}
}
}
if (volume != 0)
{
recoVolume = volume;
}
}
public void MuteReco(bool mute) //Per differenziare in mixing
{
if (mute)
{
AdjustRecordingSignalVolume(0);
AmIRecoMute = mute;
}
else
{
AmIRecoMute = mute;
AdjustRecordingSignalVolume(recoVolume);
}
}
public void AdjustPlaybackSignalVolume(int volume)
{
int result = mRtcEngine.AdjustPlaybackSignalVolume(volume);
if (result < 0)
{
Debug.LogError("AdjustPlaybackSignalVolume ERROR" + result);
}
}
public void AdjustUserPlaybackSignalVolume(int volume)
{
Debug.LogError("AdjustUserPlaybackSignalVolume ERROR");
//mRtcEngine.AdjustPlaybackSignalVolume();
}
public void MuteVideo(bool mute)
{
int result = mRtcEngine.MuteAllRemoteVideoStreams(mute);
if (result < 0)
{
Debug.LogError("Mute ERROR" + result);
}
}
public void MuteAudio(bool mute)
{
int result = mRtcEngine.MuteAllRemoteAudioStreams(mute);
if (result < 0)
{
Debug.LogError("Mute ERROR" + result);
}
}
public void MuteLocalAudioStream(bool mute)
{
if (mRtcEngine != null)
{
int result = mRtcEngine.MuteLocalAudioStream(mute);
if (result < 0)
{
Debug.LogError("Mute ERROR" + result);
IsAllMute = false;
}
}
IsAllMute = mute;
}
public void MuteAllRemoteAudioStreams(bool mute)
{
int result = mRtcEngine.MuteAllRemoteAudioStreams(mute);
if (result < 0)
{
Debug.LogError("Mute ERROR" + result);
}
}
public void MuteAll(bool mute)
{
MuteAudio(mute);
MuteVideo(mute);
}
public int EnableAudio(bool enable)
{
int result = -1;
if (mRtcEngine != null)
{
if (enable)
{
result = mRtcEngine.EnableAudio();
if (result < 0)
{
Debug.LogError("EnableAudio ERROR" + result);
}
}
else
{
result = mRtcEngine.DisableAudio();
if (result < 0)
{
Debug.LogError("DisableAudio ERROR" + result);
}
}
}
return result;
}
public int SetExternalAudio(bool enabled, int sampleRate, int channels = 1)//@param sampleRate Sets the sample rate(Hz) of the external audio source, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz.
{
return mRtcEngine.SetExternalAudioSource(enabled, sampleRate, channels);
}
public int PushAudioFrame(AudioFrame audioFrame)
{
return mRtcEngine.PushAudioFrame(audioFrame);
}
//Eco
AudioRecordingDeviceManager audioRecordingDeviceManagerEco = null;
public int StartEchoTest()
{
int result = -1;
if (mRtcEngine != null)
{
if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
{
//https://docs.agora.io/en/Voice/test_switch_device_unity?platform=Unity
//ONLO FOR IOS and ANDROID????
result = mRtcEngine.StartEchoTest(3);
if (result < 0)
{
Eco = false;
Debug.LogError("StartEchoTest ERROR" + result);
}
else
{
Eco = true;
}
}
else
{
audioRecordingDeviceManagerEco = (AudioRecordingDeviceManager)mRtcEngine.GetAudioRecordingDeviceManager();
mRtcEngine.OnVolumeIndication = OnVolumeIndicationHandler;
audioRecordingDeviceManagerEco.CreateAAudioRecordingDeviceManager();
mRtcEngine.EnableAudioVolumeIndication(300, 3, true);
result = audioRecordingDeviceManagerEco.StartAudioRecordingDeviceTest(300);
if (result < 0)
{
Eco = false;
Debug.LogError("StartEchoTest ERROR" + result);
}
else
{
Eco = true;
}
//audioRecordingDeviceManager.ReleaseAAudioRecordingDeviceManager();
/*
// Initializes the IRtcEngine.
mRtcEngine = IRtcEngine.GetEngine(appId);
mRtcEngine.OnVolumeIndication = OnVolumeIndicationHandler;
// Retrieves the AudioRecordingDeviceManager object.
AudioRecordingDeviceManager audioRecordingDeviceManager = (AudioRecordingDeviceManager)mRtcEngine.GetAudioRecordingDeviceManager();
// Creates an AudioRecordingDeviceManager instance.
audioRecordingDeviceManager.CreateAAudioRecordingDeviceManager();
// Retrieves the total number of the indexed audio recording devices in the system.
int count = audioRecordingDeviceManager.GetAudioRecordingDeviceCount();
// Retrieves the device ID of the target audio recording device. The value of index should not more than the number retrieved from GetAudioRecordingDeviceCount.
audioRecordingDeviceManager.GetAudioRecordingDevice(0, ref deviceNameA, ref deviceIdA);
// Sets the audio recording device using the device ID.
audioRecordingDeviceManager.SetAudioRecordingDevice(deviceIdA);
// Enables the audio volume callback.
mRtcEngine.EnableAudioVolumeIndication(300, 3, true);
// Starts the audio recording device test.
audioRecordingDeviceManager.StartAudioRecordingDeviceTest(300);
// Stops the audio recording device test.
audioRecordingDeviceManager.StopAudioRecordingDeviceTest();
// Releases AudioRecordingDeviceManager instance.
audioRecordingDeviceManager.ReleaseAAudioRecordingDeviceManager();
*/
}
}
else
{
Eco = false;
}
return result;
}
public int StopEchoTest()
{
int result = -1;
if (mRtcEngine != null)
{
if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
{
result = mRtcEngine.StopEchoTest();
if (result < 0)
{
Debug.LogError("StopEchoTest ERROR" + result);
}
}
else
{
audioRecordingDeviceManagerEco = (AudioRecordingDeviceManager)mRtcEngine.GetAudioRecordingDeviceManager();
mRtcEngine.OnVolumeIndication = OnVolumeIndicationHandler;
audioRecordingDeviceManagerEco.CreateAAudioRecordingDeviceManager();
result = audioRecordingDeviceManagerEco.StopAudioRecordingDeviceTest();
if (result < 0)
{
Debug.LogError("StopEchoTest ERROR" + result);
}
audioRecordingDeviceManagerEco.ReleaseAAudioRecordingDeviceManager();
}
}
Eco = false;
return result;
}
//InVolumeInicator
public static Action<AudioVolumeInfo[], int, int> OnVolumeIndicationUpdate = delegate { };
protected void OnVolumeIndicationHandler(AudioVolumeInfo[] speakers, int speakerNumber, int totalVolume)
{
//Debug.Log("speakerNumber " + speakerNumber + " totalVolume " + totalVolume);
OnVolumeIndicationUpdate(speakers, speakerNumber, totalVolume);
}
//Velume
public void StartGetMicVolumeIndication()
{
// Initializes the IRtcEngine.
if (mRtcEngine != null)
{
mRtcEngine.OnVolumeIndication = OnVolumeIndicationHandler;
mRtcEngine.EnableAudioVolumeIndication(50, 3, true);
}
}
public void StopMicVolumeIndication()
{
if (mRtcEngine != null)
{
mRtcEngine.EnableAudioVolumeIndication(-1, 3, true);
}
}
//Audio Device
public List<AgoraAudioDeviceData> GetAudioRecordingDeviceList()
{
Debug.Log("CARLO 1");
lastAgoraAudioRecordingDeviceData = new List<AgoraAudioDeviceData>();
if (mRtcEngine != null)
{
Debug.Log("CARLO 2");
AudioRecordingDeviceManager audioDeviceManager = AudioRecordingDeviceManager.GetInstance(mRtcEngine);
if (audioDeviceManager.CreateAAudioRecordingDeviceManager())
{
Debug.Log("CARLO 3");
Debug.Log("audioDeviceManager.GetAudioDeviceCount() 2" + audioDeviceManager.GetAudioRecordingDeviceCount());
for (int i = 0; i < audioDeviceManager.GetAudioRecordingDeviceCount(); i++)
{
string deviceId = "";
string deviceName = "";
audioDeviceManager.GetAudioRecordingDevice(i, ref deviceName, ref deviceId);
lastAgoraAudioRecordingDeviceData.Add(new AgoraAudioDeviceData(deviceId, deviceName));
}
//Release
int result = audioDeviceManager.ReleaseAAudioRecordingDeviceManager();
if (result < 0)
{
Debug.LogError("ReleaseAAudioRecordingDeviceManager ERROR" + result);
}
}
}
return lastAgoraAudioRecordingDeviceData;
}
public void UpdateCurrentRecordingDevice()
{
if (mRtcEngine != null)
{
AudioRecordingDeviceManager audioDeviceManager = AudioRecordingDeviceManager.GetInstance(mRtcEngine);
if (audioDeviceManager.CreateAAudioRecordingDeviceManager())
{
string deviceId = "";
string deviceName = "";
audioDeviceManager.GetCurrentRecordingDeviceInfo(ref deviceName, ref deviceId);
AgoraAudioDeviceData agoraAudioDeviceData = new AgoraAudioDeviceData();
agoraAudioDeviceData.deviceId = deviceId;
agoraAudioDeviceData.deviceName = deviceName;
actualAudioRecordingDevice = agoraAudioDeviceData;
//Release
int result = audioDeviceManager.ReleaseAAudioRecordingDeviceManager();
if (result < 0)
{
Debug.LogError("ReleaseAAudioRecordingDeviceManager ERROR" + result);
}
}
}
}
public void SetAudioRecordingDevice(AgoraAudioDeviceData agoraAudioDeviceData)
{
if (mRtcEngine != null)
{
AudioRecordingDeviceManager audioDeviceManager = AudioRecordingDeviceManager.GetInstance(mRtcEngine);
Debug.Log("SetAudioDevice audioDeviceManager + " + audioDeviceManager);
if (audioDeviceManager.CreateAAudioRecordingDeviceManager())
{
Debug.Log("SetAudioDevice audioDeviceManager 2 + " + audioDeviceManager);
audioDeviceManager.SetAudioRecordingDevice(agoraAudioDeviceData.deviceId);
//Release
int result = audioDeviceManager.ReleaseAAudioRecordingDeviceManager();
if (result < 0)
{
Debug.LogError("ReleaseAAudioRecordingDeviceManager ERROR" + result);
}
actualAudioRecordingDevice = agoraAudioDeviceData;
}
}
}
public void ChangeRecordingDevice()
{
List<AgoraAudioDeviceData> agoraAudioRecordingDeviceData = GetAudioRecordingDeviceList();
if (agoraAudioRecordingDeviceData.Count > 0)
{
bool done = false;
int i = 0;
foreach (AgoraAudioDeviceData agoraAudioDeviceData in agoraAudioRecordingDeviceData)
{
if (agoraAudioDeviceData.deviceId == actualAudioRecordingDevice.deviceId)
{
done = true;
break;
}
i++;
}
if (!done)
{
i = 0;
}
else
{
i++;
i %= agoraAudioRecordingDeviceData.Count;
}
SetAudioRecordingDevice(agoraAudioRecordingDeviceData[i]);
}
}
public List<AgoraAudioDeviceData> GetAudioPlaybackDeviceList()
{
Debug.Log("CARLO 1");
lastAgoraAudioPlaybackDeviceData = new List<AgoraAudioDeviceData>();
if (mRtcEngine != null)
{
Debug.Log("CARLO 2");
AudioPlaybackDeviceManager audioDeviceManager = AudioPlaybackDeviceManager.GetInstance(mRtcEngine);
if (audioDeviceManager.CreateAAudioPlaybackDeviceManager())
{
Debug.Log("CARLO 3");
Debug.Log("audioDeviceManager.GetAudioDeviceCount() 2" + audioDeviceManager.GetAudioPlaybackDeviceCount());
for (int i = 0; i < audioDeviceManager.GetAudioPlaybackDeviceCount(); i++)
{
string deviceId = "";
string deviceName = "";
audioDeviceManager.GetAudioPlaybackDevice(i, ref deviceName, ref deviceId);
lastAgoraAudioPlaybackDeviceData.Add(new AgoraAudioDeviceData(deviceId, deviceName));
}
//Release
int result = audioDeviceManager.ReleaseAAudioPlaybackDeviceManager();
if (result < 0)
{
Debug.LogError("ReleaseAAudioPlaybackDeviceManager ERROR" + result);
}
}
}
return lastAgoraAudioPlaybackDeviceData;
}
public void SetAudioPlaybackDevice(AgoraAudioDeviceData agoraAudioDeviceData)
{
if (mRtcEngine != null)
{
AudioPlaybackDeviceManager audioDeviceManager = AudioPlaybackDeviceManager.GetInstance(mRtcEngine);
Debug.Log("SetAudioDevice audioDeviceManager + " + audioDeviceManager);
if (audioDeviceManager.CreateAAudioPlaybackDeviceManager())
{
Debug.Log("SetAudioDevice audioDeviceManager 2 + " + audioDeviceManager);
audioDeviceManager.SetAudioPlaybackDevice(agoraAudioDeviceData.deviceId);
//Release
int result = audioDeviceManager.ReleaseAAudioPlaybackDeviceManager();
if (result < 0)
{
Debug.LogError("ReleaseAAudioPlaybackDeviceManager ERROR" + result);
}
}
}
}
public void ChangePlaybackDevice()
{
}
//Audio Callbacks
protected void OnUserMuteAudio(uint uid, bool muted)
{
if (uid == mId)
{
AmIMute = muted;
}
}
protected void OnAudioRouteChanged(AUDIO_ROUTE aUDIO_ROUTE)
{
Debug.Log("AUDIO ROOT " + aUDIO_ROUTE);
}
//Video
public int EnableVideo(bool enable)
{
int result = -1;
if (mRtcEngine != null)
{
if (enable)
{
result = mRtcEngine.EnableVideo();
if (result < 0)
{
Debug.LogError("EnableVideo ERROR" + result);
}
}
else
{
result = mRtcEngine.DisableVideo();
if (result < 0)
{
Debug.LogError("DisableVideo ERROR" + result);
}
}
}
return result;
}
public int EnableLocalVideo(bool enable)
{
int result = -1;
if (mRtcEngine != null)
{
result = mRtcEngine.EnableLocalVideo(enable);
if (result < 0)
{
Debug.LogError("EnableLocalVideo ERROR" + result);
}
}
return result;
}
public int SetExternalVideo(bool value)
{
return mRtcEngine.SetExternalVideoSource(value, false);
}
public int PushVideoFrame(ExternalVideoFrame externalVideoFrame)
{
return mRtcEngine.PushVideoFrame(externalVideoFrame);
}
public int SetVideoEncoderConfiguration(VideoEncoderConfiguration videoEncoderConfiguration)
{
return mRtcEngine.SetVideoEncoderConfiguration(videoEncoderConfiguration);
}
public List<AgoraVideoDeviceData> GetVideoDeviceList()
{
Debug.Log("CARLO 1");
lastAgoraVideoDeviceData = new List<AgoraVideoDeviceData>();
if (mRtcEngine != null)
{
Debug.Log("CARLO 2");
VideoDeviceManager videoDeviceManager = VideoDeviceManager.GetInstance(mRtcEngine);
if (videoDeviceManager.CreateAVideoDeviceManager())
{
Debug.Log("CARLO 3");
Debug.Log("videoDeviceManager.GetVideoDeviceCount() 2" + videoDeviceManager.GetVideoDeviceCount());
for (int i = 0; i < videoDeviceManager.GetVideoDeviceCount(); i++)
{
string deviceId = "";
string deviceName = "";
videoDeviceManager.GetVideoDevice(i, ref deviceName, ref deviceId);
lastAgoraVideoDeviceData.Add(new AgoraVideoDeviceData(deviceId, deviceName));
}
//Release
int result = videoDeviceManager.ReleaseAVideoDeviceManager();
if (result < 0)
{
Debug.LogError("ReleaseAVideoDeviceManager ERROR" + result);
}
}
}
return lastAgoraVideoDeviceData;
}
public void SetVideoDevice(AgoraVideoDeviceData agoraVideoDeviceData)
{
if (mRtcEngine != null)
{
VideoDeviceManager videoDeviceManager = VideoDeviceManager.GetInstance(mRtcEngine);
Debug.Log("SetVideoDevice videoDeviceManager + " + videoDeviceManager);
if (videoDeviceManager.CreateAVideoDeviceManager())
{
Debug.Log("SetVideoDevice videoDeviceManager 2 + " + videoDeviceManager);
videoDeviceManager.SetVideoDevice(agoraVideoDeviceData.deviceId);
//Release
int result = videoDeviceManager.ReleaseAVideoDeviceManager();
if (result < 0)
{
Debug.LogError("ReleaseAVideoDeviceManager ERROR" + result);
}
}
}
}
public void ChangeVideoDevice()
{
}
//Video Observer
public int EnableVideoObserver(bool enable)
{
int result = -1;
if (mRtcEngine != null)
{
if (enable)
{
result = mRtcEngine.EnableVideoObserver();
if (result < 0)
{
Debug.LogError("EnableVideoObserver ERROR" + result);
}
}
else
{
result = mRtcEngine.DisableVideoObserver();
if (result < 0)
{
Debug.LogWarning("DisableVideoObserver ERROR" + result);
}
}
}
return result;
}
//Stream
public void SendStreamMessage(string message)
{
int result = mRtcEngine.SendStreamMessage(streamID, message);
if (result < 0)
{
if (debugStream) Debug.LogError("SendStreamMessage ERROR" + result); ;
}
else
{
if (debugStream) Debug.Log("SendStreamMessage " + message);
}
}
//Stats
protected void OnRemoteAudioStats(RemoteAudioStats remoteAudioStats)
{
if (mRtcEngine != null)
{
RemoteAudioStatsUpdated(remoteAudioStats);
}
}
//Utils
public string GetSdkVersion()
{
string ver = IRtcEngine.GetSdkVersion();
if (ver == "2.9.1.45")
{
ver = "2.9.2"; // A conversion for the current internal version#
}
return ver;
}
}
[Serializable]
public struct AgoraVideoDeviceData
{
public string deviceId;
public string deviceName;
public AgoraVideoDeviceData(string deviceId, string deviceName)
{
this.deviceId = deviceId;
this.deviceName = deviceName;
}
}
[Serializable]
public struct AgoraAudioDeviceData
{
public string deviceId;
public string deviceName;
public AgoraAudioDeviceData(string deviceId, string deviceName)
{
this.deviceId = deviceId;
this.deviceName = deviceName;
}
}
/*
// accessing GameObject in Scnene1
// set video transform delegate for statically created GameObject
public void Boh()
{
// Attach the SDK Script VideoSurface for video rendering
GameObject quad = GameObject.Find("Quad");
if (ReferenceEquals(quad, null))
{
Debug.Log("BBBB: failed to find Quad");
return;
}
else
{
quad.AddComponent<VideoSurface>();
}
GameObject cube = GameObject.Find("Cube");
if (ReferenceEquals(cube, null))
{
Debug.Log("BBBB: failed to find Cube");
return;
}
else
{
cube.AddComponent<VideoSurface>();
}
}
public VideoSurface makePlaneSurface(string goName)
{
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Plane);
if (go == null)
{
return null;
}
go.name = goName;
// set up transform
go.transform.Rotate(-90.0f, 0.0f, 0.0f);
float yPos = Random.Range(3.0f, 5.0f);
float xPos = Random.Range(-2.0f, 2.0f);
go.transform.position = new Vector3(xPos, yPos, 0f);
go.transform.localScale = new Vector3(0.25f, 0.5f, .5f);
// configure videoSurface
VideoSurface videoSurface = go.AddComponent<VideoSurface>();
return videoSurface;
}
private const float Offset = 100;
public VideoSurface makeImageSurface(string goName)
{
GameObject go = new GameObject();
if (go == null)
{
return null;
}
go.name = goName;
// to be renderered onto
go.AddComponent<RawImage>();
// make the object draggable
go.AddComponent<UIElementDragger>();
GameObject canvas = GameObject.Find("Canvas");
if (canvas != null)
{
go.transform.parent = canvas.transform;
}
// set up transform
go.transform.Rotate(0f, 0.0f, 180.0f);
float xPos = Random.Range(Offset - Screen.width / 2f, Screen.width / 2f - Offset);
float yPos = Random.Range(Offset, Screen.height / 2f - Offset);
go.transform.localPosition = new Vector3(xPos, yPos, 0f);
go.transform.localScale = new Vector3(3f, 4f, 1f);
// configure videoSurface
VideoSurface videoSurface = go.AddComponent<VideoSurface>();
return videoSurface;
}
*/
//Stats https://docs.agora.io/en/Voice/in-call_quality_unity?platform=Unity
/*
networkTransportDelay The network delay from the sender to the receiver. Stages 2 + 3 + 4 in the figure above
jitterBufferDelay The network delay from the receiver to the network jitter buffer. Stage 5 in the figure above
audioLossRate The frame loss rate of the received remote audio streams in the reported interval.
Stages 2 + 3 + 4 + 5 in the figure above
In a reported interval, audio freeze occurs when the audio frame loss rate reaches 4%.
receivedSampleRate The sample rate of the received remote audio streams in the reported interval.
receivedBitrate The average bitrate of the received remote audio streams in the reported interval.
totalFrozenTime The total freeze time (ms) of the remote audio streams after the remote user joins the channel.
Agora defines totalFrozenTime = The number of times the audio freezes × 2 × 1000 (ms).
The total time is the cumulative duration after the remote user joins the channel.
frozenRate The total audio freeze time as a percentage of the total time when the audio is available. When the remote user/host neither stops sending the audio stream nordisables the audio module after joining the channel, the audio is available.
*/<file_sep>/PubNubChatManager.cs
using System;
using PubNubAPI;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public enum FirebaseState { Testing, Build };
#region Serialize Class
[Serializable]
public class ChatJsonData
{
public string uuid;
public string username;
public string text;
public string chatID;
public long personalTimeToken;
public List<MessageActions> messageActions;
}
[Serializable]
public class MessageActions
{
public string actionType;
public MessageActionsTypeValue messageActionsTypeValues;
}
[Serializable]
public class MessageActionsTypeValue
{
public string actionValue;
public List<MessageActionAttributes> attributes;
}
[Serializable]
public class MessageActionAttributes
{
public string id;
public long actionTimetoken;
}
#endregion
public class PubNubChatManager : MonoBehaviour
{
public static PubNubChatManager instance;
public PubNub pubnub;
public FirebaseState firebaseState = FirebaseState.Testing;
public PubNubStatus pubnubStatus = PubNubStatus.None;
#region Delegate
public static event Action<bool, ChatPrefabData_OvrCommunity> SubscribeToHybrid_Type1 = delegate { }; //success, user data
public static event Action<bool, OVRCommunityFriendsPrefabData> SubscribeToHybrid_Type2 = delegate { }; //success, user data
public static event Action<bool, string> UnsubscribeToHybrid = delegate { }; //success, result
public static event Action<string, string, bool, ushort> FetchMsgDelegate = delegate { }; //myUUID, otherUUID,isActionIncluded, history message count
public static event Action<string, string, ushort> GetHistoryDelegate = delegate { }; //myUUID, otherUUID, history message count
public static event Action<string, string, Dictionary<string, object>> SendMessageDelegate = delegate { }; //myUUID, otherUUID, message payload
public static event Action<bool, bool, ChatJsonData, long, bool> MessageRecieve = delegate { }; //success, isSent, message payload, isHistory
public static event Action<string, string> SignalDelegate = delegate { }; //otherUUID, typing state
public static event Action<bool, object> SignalRecieved = delegate { }; //success, channel name, signal
public static event Action<string, string, string, string, long> SendActionDelegate = delegate { }; //actionType, actionValue, myUUID, otherUUID, message time token
public static event Action<bool, string, string, string, long> ActionRecieved = delegate { }; //success, sender UUID, action type, action value, message time token
public static event Action<string, string, long> SetMembership = delegate { }; //myUUID, otherUUID, message time token
public static event Action<string> GetMembership = delegate { }; //myUUID
public static event Action<string, string> RemoveMembership = delegate { }; //myUUID, message time token
public static event Action<bool, ChatJsonData> LocalNotificationTrigger = delegate { };
#endregion
private void Awake()
{
pubnubStatus = PubNubStatus.None;
if (instance == null)
{
instance = this;
transform.SetParent(null);
DontDestroyOnLoad(this);
}
else
{
Destroy(gameObject);
}
}
private void OnEnable()
{
#if UNITY_ANDROID
if (firebaseState == FirebaseState.Build)
Firebase.Messaging.FirebaseMessaging.TokenReceived += OnTokenReceived;
#endif
UserManager.UserManagerStatusChanged += UserManager_UserManagerStatusChanged;
UserManager.UserDataUpdated += OnUserDataUpdated;
}
private void OnDisable()
{
#if UNITY_ANDROID
if (firebaseState == FirebaseState.Build)
Firebase.Messaging.FirebaseMessaging.TokenReceived -= OnTokenReceived;
#endif
UserManager.UserManagerStatusChanged -= UserManager_UserManagerStatusChanged;
UserManager.UserDataUpdated -= OnUserDataUpdated;
OVRCommunityRemoveFriend.instance.LastDataRecivedChanged -= DeleteChat;
OVRCommunityDeclineRequest.instance.LastDataRecivedChanged -= DeleteChat;
}
private void Start()
{
if (pubnubStatus == PubNubStatus.None)
UserManager_UserManagerStatusChanged(UserManager.main.Status);
}
private void UserManager_UserManagerStatusChanged(UserManagerStatus obj)
{
switch (obj)
{
case UserManagerStatus.LoggedIn:
PubNubConfig();
break;
case UserManagerStatus.LogedOut:
pubnubStatus = PubNubStatus.None;
if (StaticDataManager_OvrCommunity.deviceToken != null)
RemovePushFromChannels(StaticDataManager_OvrCommunity.deviceToken);
break;
}
}
void OnUserDataUpdated()
{
UserData data = UserManager.main.UserData;
if (data.ovrId != null)
{
//Debug.Log("name : " + UserManager.main.UserData.name);
StaticDataManager_OvrCommunity.myName = data.DisplayName;
}
}
public void PubNubConfig()
{
Debug.Log("PubNub Config");
OVRCommunityRemoveFriend.instance.LastDataRecivedChanged += DeleteChat;
OVRCommunityDeclineRequest.instance.LastDataRecivedChanged += DeleteChat;
pubnubStatus = PubNubStatus.Connecting;
StaticDataManager_OvrCommunity.myUUID = UserManager.main.UserData.ovrId;
StaticDataManager_OvrCommunity.myName = UserManager.main.UserData.DisplayName;
PNConfiguration pnConfiguration = new PNConfiguration
{
PublishKey = StaticDataManager_OvrCommunity.pubNubPublishKey,
SubscribeKey = StaticDataManager_OvrCommunity.pubNubSubscribeKey,
SecretKey = StaticDataManager_OvrCommunity.pubNubSecretKey,
LogVerbosity = PNLogVerbosity.BODY,
UUID = StaticDataManager_OvrCommunity.myUUID
};
pubnub = new PubNub(pnConfiguration, this.gameObject);
if (pubnub == null)
PubNubStateChangeCallback(false);
else
PubNubStateChangeCallback(true);
SubscribingToMyself(UserManager.main.UserData.ovrId);
pubnub.SubscribeCallback += SubscribeCallbackHandler;
}
private void PubNubStateChangeCallback(bool state)
{
if (!state)
{
OvrCanvasManager.main.ChangeCanvasStatus(OvrCanvasStatus.Home);
Debug.LogError("Failed to configure PubNub...");
StaticDataManager_OvrCommunity.leftBtnAction = () =>
{
PubNubConfig();
};
pubnubStatus = PubNubStatus.None;
string communityServiceError = LocalizedStringsManager.main.GetString(OvrCommunityStringKeyData.GetOne(instance, OvrCommunityStringKey.CommunityServiceError));
CanvasManagerBridge.SceneMainCanvas.OpenSimpleDoubleDialogPopUp(
communityServiceError,
StaticDataManager_OvrCommunity.ErrorRightBtnText,
null,
StaticDataManager_OvrCommunity.ErrorLeftBtnText,
StaticDataManager_OvrCommunity.leftBtnAction);
}
else
{
pubnubStatus = PubNubStatus.Joined;
}
}
void SubscribeCallbackHandler(object sender, EventArgs e)
{
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;
if (mea.Status != null)
{
switch (mea.Status.Category)
{
case PNStatusCategory.PNUnexpectedDisconnectCategory:
case PNStatusCategory.PNTimeoutCategory:
// handle publish
break;
}
}
if (mea.MessageResult != null)
{
ChatJsonData finalPayload = PayloadConverter.instance.PayloadChecker(mea.MessageResult.Payload);
finalPayload.messageActions.Clear();
//StartCoroutine(NewMessageRecieved(finalPayload, mea));
if (ChatUiManager_OvrCommunity.instance != null)
{
//Debug.LogError("In here 0");
if (ChatUiManager_OvrCommunity.instance.OtherUserCommunityInfo == null || ChatUiManager_OvrCommunity.instance.OtherUserCommunityInfo.public_name == null || ChatUiManager_OvrCommunity.instance.OtherUUID == null)
{
//Debug.LogError("In here 1");
StartCoroutine(GetMessageCount(StaticDataManager_OvrCommunity.myUUID));
MessageRecieve(true, false, finalPayload, mea.MessageResult.Timetoken, false);
LocalNotificationTrigger(true, finalPayload);
}
else
{
//Debug.LogError("In here 2");
if (mea.MessageResult.Channel == GetHybridChannelName(StaticDataManager_OvrCommunity.myUUID, ChatUiManager_OvrCommunity.instance.OtherUUID))
{
//Debug.LogError("In here 3");
SetMembershipData(
StaticDataManager_OvrCommunity.myUUID,
ChatUiManager_OvrCommunity.instance.OtherUserCommunityInfo.uuID,
mea.MessageResult.Timetoken);
if (finalPayload.uuid == ChatUiManager_OvrCommunity.instance.OtherUUID)
MessageRecieve(true, false, finalPayload, mea.MessageResult.Timetoken, false);
}
else
{
//Debug.LogError("In here 4");
if (finalPayload.uuid != ChatUiManager_OvrCommunity.instance.OtherUUID)
{
//Debug.LogError("In here 4b");
LocalNotificationTrigger(true, finalPayload);
}
}
}
}
else
{
//Debug.LogError("In here 5");
StartCoroutine(GetMessageCount(StaticDataManager_OvrCommunity.myUUID));
LocalNotificationTrigger(true, finalPayload);
}
}
if (mea.SignalEventResult != null)
{
SignalRecieved(true, mea.SignalEventResult.Payload);
}
if (mea.MessageActionsEventResult != null)
{
//Debug.Log("Action channel : " + mea.MessageActionsEventResult.Channel);
if (mea.MessageActionsEventResult.Data != null)
{
if (ChatUiManager_OvrCommunity.instance.OtherUUID != null)
{
if (mea.MessageActionsEventResult.Channel == GetHybridChannelName(StaticDataManager_OvrCommunity.myUUID, ChatUiManager_OvrCommunity.instance.OtherUUID))
{
PNMessageActionsResult data = mea.MessageActionsEventResult.Data;
ActionRecieved(true, data.UUID, data.ActionType, data.ActionValue, data.MessageTimetoken);
}
}
}
}
/*if (mea.PresenceEventResult != null)
{
Debug.Log("SubscribeCallback in presence" +
mea.PresenceEventResult.Channel +
mea.PresenceEventResult.Occupancy +
mea.PresenceEventResult.Event);
}*/
}
void SubscribingToMyself(string UUID)
{
pubnub.Subscribe()
.Channels(new List<string> { GetChannelName(UUID) })
.WithPresence()
.Execute();
if (firebaseState == FirebaseState.Testing)
StaticDataManager_OvrCommunity.deviceToken = "<PASSWORD>FAxfz:APA91bEJLJHziSXGN0t_Z5EO3VSM2pAco3XCy0XHsU2VWy0Yukw70UPpLuqAumEYxMNSI0rTTWHKox_Ss7Fchik41_WyKi5mDh8QRJXejaXV-lVUd45cjl5ypjWYCYxPJLi7zmWxG3R0";
StartCoroutine(ConfigPush());
GetMembership(UUID);
}
#region Create Push Notification
#if UNITY_ANDROID
public void OnTokenReceived(object sender, Firebase.Messaging.TokenReceivedEventArgs token)
{
Debug.Log("Firebase Token Recieved : " + token.Token);
StaticDataManager_OvrCommunity.deviceToken = token.Token;
}
#endif
private IEnumerator ConfigPush()
{
Debug.Log("Token Recieved : " + StaticDataManager_OvrCommunity.deviceToken);
while (StaticDataManager_OvrCommunity.deviceToken == "" || StaticDataManager_OvrCommunity.deviceToken == null)
yield return new WaitForEndOfFrame();
AddPushToChannels(StaticDataManager_OvrCommunity.myUUID, StaticDataManager_OvrCommunity.deviceToken);
}
private void AddPushToChannels(string UUID, string deviceID)
{
Debug.LogError("Setting up Push Notification");
pubnub.AddPushNotificationsOnChannels()
#if UNITY_ANDROID
.PushType(PNPushType.GCM)
#elif UNITY_IOS
.PushType(PNPushType.APNS2)
.Topic(OVRCommunityStaticDataManager.iosPushPayloadTopic)
.Environment(PNPushEnvironment.production)
#endif
.Channels(new List<string> { GetChannelName(UUID) })
.DeviceID(deviceID)
.Async((result, status) =>
{
if (status.Error)
{
Debug.LogError(string.Format("AddPush Error: {0}, {1}, {2}",
status.StatusCode,
status.ErrorData.Info,
status.Category
));
}
#if UNITY_ANDROID
Debug.Log("Notification Configured for Android.");
#elif UNITY_IOS
Debug.Log("Notification Configured for IOS.");
#endif
});
}
private void RemovePushFromChannels(string deviceID)
{
Debug.Log("Removing Push Notification");
if (pubnub != null)
{
pubnub.RemoveAllPushNotifications()
#if UNITY_ANDROID
.PushType(PNPushType.GCM)
#elif UNITY_IOS
.PushType(PNPushType.APNS2)
.Topic(OVRCommunityStaticDataManager.iosPushPayloadTopic)
.Environment(PNPushEnvironment.production)
#endif
.DeviceID(deviceID)
.Async((result, status) =>
{
if (status.Error)
{
Debug.LogError(string.Format("RemovePush Error: {0}, {1}, {2}",
status.StatusCode,
status.ErrorData.Info,
status.Category
));
}
else
{
#if UNITY_ANDROID
Debug.Log("Notifications Removed from android.");
#elif UNITY_IOS
Debug.Log("Notifications Removed from iOS.");
#endif
CleanPubNubData();
}
});
}
}
private void CleanPubNubData()
{
if (pubnub != null)
{
pubnub.CleanUp();
pubnub.SubscribeCallback -= SubscribeCallbackHandler;
pubnub = null;
}
StaticDataManager_OvrCommunity.myName = null;
StaticDataManager_OvrCommunity.myUUID = null;
}
#endregion
#region Subscribe To Hybrid Channel
public void SubscribeToHybridChannel(string UUID_1, string UUID_2, ChatPrefabData_OvrCommunity data)
{
pubnub.Subscribe()
.Channels(new List<string> { GetHybridChannelName(UUID_1, UUID_2) })
.Execute();
SubscribeToHybrid_Type1(true, data);
}
public void SubscribeToHybridChannel(string UUID_1, string UUID_2, OVRCommunityFriendsPrefabData data)
{
pubnub.Subscribe()
.Channels(new List<string> { GetHybridChannelName(UUID_1, UUID_2) })
.Execute();
SubscribeToHybrid_Type2(true, data);
}
#endregion
#region Unsubscribe To Hybrid Channel
public void UnsubscribeToHybridChannel(string UUID_1, string UUID_2)
{
if (pubnub != null)
{
pubnub.Unsubscribe()
.Channels(new List<string> { GetHybridChannelName(UUID_1, UUID_2) })
.Async((resut, status) =>
{
if (status.Error)
{
Debug.LogError(string.Format("Error in Unsubcribing : {0}, {1}, {2}",
status.StatusCode,
status.ErrorData.Info,
status.Category
));
UnsubscribeToHybrid(false, "");
}
else
{
//Debug.Log("Unsubscribe Successfull.." + resut.Message);
UnsubscribeToHybrid(true, resut.Message);
}
});
}
}
#endregion
#region Generate Channel Names
public string GetChannelName(string uuid)
{
return "channel_" + uuid;
}
public string GetHybridChannelName(string id1, string id2)
{
string hybridChnl = "";
int i = 0;
while (true)
{
if (id1.ToUpper()[i] != id2.ToUpper()[i])
{
if (id1.ToUpper()[i] < id2.ToUpper()[i])
hybridChnl = "channel_" + id1 + "_" + id2;
else
hybridChnl = "channel_" + id2 + "_" + id1;
break;
}
i++;
}
return hybridChnl;
}
#endregion
public void FetchAllMsg(string UUID_1, string UUID_2, bool isActionIncluded, ushort numberOfMesseges)
{
FetchMsgDelegate(UUID_1, UUID_2, isActionIncluded, numberOfMesseges);
}
public void SendPushMessage(string UUID_1, string UUID_2, Dictionary<string, object> payload)
{
SendMessageDelegate(UUID_1, UUID_2, payload);
}
public void GetHistory(string UUID_1, string UUID_2, ushort historyMsgCount)
{
GetHistoryDelegate(UUID_1, UUID_2, historyMsgCount);
}
public void SetMembershipData(string UUID_1, string UUID_2, long timeToken)
{
SetMembership(UUID_1, UUID_2, timeToken);
}
public void GetUpdatedMessageCount(string UUID)
{
GetMembership(UUID);
}
private IEnumerator GetMessageCount(string UUID)
{
yield return new WaitForSeconds(1f);
GetMembership(UUID);
}
public void SendSignal(string UUID, string state)
{
SignalDelegate(UUID, state);
}
public void AddMessageAction(string actionType, string actionValue, string UUID_1, string UUID_2, long timeToken)
{
SendActionDelegate(actionType, actionValue, UUID_1, UUID_2, timeToken);
}
#region Delete Message
public void DeleteChat(bool state, string UUID)
{
if (state)
{
RemoveMembership(StaticDataManager_OvrCommunity.myUUID, UUID);
pubnub.DeleteMessages()
.Channel(GetHybridChannelName(StaticDataManager_OvrCommunity.myUUID, UUID))
.Async((result, status) =>
{
if (!status.Error)
Debug.Log("Chat Deleted.");
else
{
Debug.Log(status.Error);
Debug.Log(status.StatusCode);
Debug.Log(status.ErrorData.Info);
}
});
}
}
#endregion
/*public bool deleteMessageFromAllChannels = false;
private void Update()
{
if (deleteMessageFromAllChannels)
DeleteAllChat();
}
private void DeleteAllChat()
{
if (deleteMessageFromAllChannels)
{
deleteMessageFromAllChannels = false;
for (int i = 0; i < OVRCommunityStaticDataManager.subscriebedChannelsList.Count; i++)
{
pubnub.DeleteMessages()
.Channel(OVRCommunityStaticDataManager.subscriebedChannelsList[i])
.Async((result, status) =>
{
if (!status.Error)
Debug.Log("Chat Deleted.");
else
{
Debug.Log(status.Error);
Debug.Log(status.StatusCode);
Debug.Log(status.ErrorData.Info);
}
});
}
}
}*/
}<file_sep>/PubNubSendMessage.cs
using System;
using UnityEngine;
using System.Collections.Generic;
public class PubNubSendMessage : MonoBehaviour
{
public static event Action<bool, bool, ChatJsonData, long, bool> MessageSent = delegate { }; //success, isSent, chat payload, isHistory
private void OnEnable()
{
PubNubChatManager.SendMessageDelegate += SendMessage;
}
private void OnDisable()
{
PubNubChatManager.SendMessageDelegate -= SendMessage;
}
private void SendMessage(string UUID_1, string UUID_2, Dictionary<string, object> payload)
{
Debug.Log("Sending message with Push Notification.");
PubNubChatManager.instance.pubnub.Publish()
.Channel(PubNubChatManager.instance.GetChannelName(UUID_2))
.Message(payload)
.Async((result, status) =>
{
if (status.Error)
{
Debug.LogError(string.Format("Publish Error: {0}, {1}, {2}",
status.StatusCode,
status.ErrorData.Info,
status.Category));
MessageSent(false, false, null, 0, false);
}
else
{
//Debug.Log("Message Time token 1 : " + result.Timetoken);
((ChatJsonData)payload["payload"]).personalTimeToken = result.Timetoken;
PublishToHybrid(UUID_1, UUID_2, payload);
}
});
}
private void PublishToHybrid(string UUID_1, string UUID_2, Dictionary<string, object> payload)
{
PubNubChatManager.instance.pubnub.Publish()
.Channel(PubNubChatManager.instance.GetHybridChannelName(UUID_1, UUID_2))
.Message(payload)
.Async((result, status) =>
{
if (status.Error)
{
Debug.LogError(string.Format("Publish Hybrid Error: {0}, {1}, {2}",
status.StatusCode,
status.ErrorData.Info,
status.Category));
}
else
{
/*AddMessageAction(
MessageActionTypeEnum.reaction.ToString() + "_" + StaticDataManager.myUUID,
"none",
StaticDataManager.myUUID,
StaticDataManager.currentUserUUID,
result.Timetoken);*/
//Debug.Log("Message Time token 2 : " + result.Timetoken);
ChatJsonData data = (ChatJsonData)payload["payload"];
MessageSent(true, true, data, result.Timetoken, false);
}
});
ChatUiManager_OvrCommunity.instance.chatInputField.text = "";
}
} | c536d0f0ebfb2b5c97a370bd81f001056bc9e9fd | [
"C#"
] | 3 | C# | abhishekabhiwan/DemoScripts | c68ec7524d6af0f32e8e8c9fe72173bc4ab7c830 | 85302b1147ad19e55d983dc83a690bd3af025747 | |
refs/heads/master | <repo_name>RVA-ALT-Lab/altlab-more-private<file_sep>/index.php
<?php
/*
Plugin Name: ALT Lab More Private Posts Options
Plugin URI: https://github.com/
Description: Choose your privacy levels with greater precision
Version: 1.0
Author: <NAME>
Author URI: http://altlab.vcu.edu
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Domain Path: /languages
Text Domain: my-toolset
*/
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
add_action( 'wp_enqueue_scripts', 'acf_security_load_scripts', 10, 2 );
function acf_security_load_scripts() {
wp_enqueue_style( 'acf-security-addon', plugin_dir_url( __FILE__) . 'css/acf-security.css');
}
//filter content
function super_privacy_content_filter($content) {
global $post;
$post_id = $post->ID;
$source_url = get_permalink($post_id);
$warning_flag = '';
$user = wp_get_current_user();
if (get_acf_privacy_level($post_id)){
$allowed_roles = array_map('strtolower', get_acf_privacy_level($post_id));
$ability = implode(", ", $allowed_roles);
//if it has public just show it
if (array_intersect($allowed_roles, ['public'] ) || array_intersect($allowed_roles, $user->roles )) {
return $content;
}
//not public do the following checks
if (array_intersect($allowed_roles, $user->roles ) && is_user_logged_in() && current_user_can( 'edit', $post_id ) || is_super_admin(get_current_user_id())){
if (current_user_can('editor')){
$warning_flag = '<div id="access-flag">The content below is restricted to the following roles: '. $ability .'. <br>This message only appears for those who can edit this content. </div>';
}
return $warning_flag . $content;
}
else if (!array_intersect($allowed_roles, $user->roles ) && is_user_logged_in()) {
return 'Your access to this content is restricted. You need to be one of the following roles to see this content.<p class="ok-roles"><strong>Roles:</strong> ' . $ability . '</p>' ;
} else if (!is_user_logged_in() && !array_intersect($allowed_roles, ['public'] )){
return 'Please <a href="' . wp_login_url() . '?origin=' . $source_url .'" title="Login">login</a> to see if you have access to this content.';
}
} else if (array_intersect($allowed_roles, $user->roles ) && is_user_logged_in())
{
return $content;
}
}
add_filter( 'the_content', 'super_privacy_content_filter' );
function get_acf_privacy_level($post_id){
$privacy_setting = get_field( "privacy_settings", $post_id );
return $privacy_setting;
}
//clean RSS feed
function cleanse_feed_content($content) {
global $post;
$post_id = $post->ID;
if(count(get_acf_privacy_level($post_id))>0) {
return 'Content is restricted. You need to go to the site and login.';
} else {
return $content;
}
}
add_filter( 'the_content_feed', 'cleanse_feed_content');
add_filter( 'the_excerpt_rss', 'cleanse_feed_content');
//CLEAN JSON
function cleanse_json_content($response, $post, $request) {
global $post;
$post_id = $post->ID;
$restricted = 'Content is restricted. You need to go to the site and login.';
if (count(get_acf_privacy_level($post_id))>0) {
$response->data['content']['rendered'] = $restricted;
$response->data['excerpt']['rendered'] = $restricted;
}
return $response;
}
add_filter('rest_prepare_post', 'cleanse_json_content', 10, 3);
//LOGIN REDIRECT TO ORIGIN PAGE WHERE YOU COULDN'T SEE STUFF
function acf_security_login_redirect( $redirect_to, $request, $user ) {
$source_url = $_GET["origin"];
if ($source_url != false) {
$redirect_to = $source_url;
return $redirect_to;
} else {
return $redirect_to;
}
}
add_filter( 'login_redirect', 'acf_security_login_redirect', 10, 3 );
//ACF STUFF
//save json data
add_filter('acf/settings/save_json', 'save_acf_files_here');
function save_acf_files_here( $path ) {
// update path
$path = plugin_dir_path( __FILE__ ) . '/acf-json';
// return
return $path;
}
add_filter('acf/settings/load_json', 'my_acf_json_load_point');
function my_acf_json_load_point( $paths ) {
// remove original path (optional)
unset($paths[0]);
// append path
$paths[] = plugin_dir_path( __FILE__ ) . '/acf-json';
// return
return $paths;
}
add_filter('acf/load_field/name=privacy_settings', 'populate_user_levels');
//ADD ALL AVAILABLE USER ROLES AUTOMATICALLY
function populate_user_levels( $field )
{
// reset choices
$field['privacy_settings'] = array();
global $wp_roles;
//print("<pre>".print_r($wp_roles,true)."</pre>");
$roles = $wp_roles->get_names();
array_push($roles, 'Public');
foreach ($roles as $role) {
$field['choices'][ $role ] = $role;
}
return $field;
} | 081fab0d7291d91a5c17d82a30167f210ebc8abe | [
"PHP"
] | 1 | PHP | RVA-ALT-Lab/altlab-more-private | 778ba9639cff74b0ba02f77699dbfc7bb2b309a1 | 6922bc9cbc2fa92f91d7bcb4decd47b86969c7f5 | |
refs/heads/master | <repo_name>smartcyberhacker/opscript<file_sep>/gui/code.go
package gui
import (
"fmt"
"regexp"
"strings"
)
type codeLines []codeLine
type codeLine struct {
isSeparator bool
lineIdx int
text string
}
func (cls codeLines) first() codeLine {
if len(cls) == 0 {
return codeLine{}
}
for _, l := range cls {
if !l.isSeparator {
return l
}
}
return cls[0]
}
func (cls codeLines) last() codeLine {
l := len(cls)
if l == 0 {
return codeLine{}
}
for i := range cls {
l := cls[l-i-1]
if !l.isSeparator {
return l
}
}
return cls[l-1]
}
func (cls codeLines) next(curLine int) codeLine {
if len(cls) == 0 {
return codeLine{}
}
for _, l := range cls {
if !l.isSeparator && l.lineIdx > curLine {
return l
}
}
return cls[len(cls)-1]
}
func (cls codeLines) previous(curLine int) codeLine {
l := len(cls)
if l == 0 {
return codeLine{}
}
for i := range cls {
l := cls[l-i-1]
if !l.isSeparator && l.lineIdx < curLine {
return l
}
}
return cls[0]
}
func formatDisasm(line string, indentation *int, indentationStep int) string {
opData := regexp.MustCompile(`OP_DATA_\d+ `)
line = opData.ReplaceAllString(line, "")
parts := strings.SplitN(line, ":", 3)
if len(parts) != 3 {
return line
}
code := strings.TrimSpace(parts[2])
// Decrease indentation for OP_ELSE and OP_ENDIF statements
if strings.HasPrefix(code, "OP_ELSE") ||
strings.HasPrefix(code, "OP_ENDIF") {
*indentation -= indentationStep
}
line = fmt.Sprintf(" %s%s", strings.Repeat(" ", *indentation), code)
// Increase indentation for all line inside OP_IF and OP_ELSE
if strings.HasPrefix(code, "OP_IF") ||
strings.HasPrefix(code, "OP_NOTIF") ||
strings.HasPrefix(code, "OP_ELSE") {
*indentation += indentationStep
}
return line
}
func isPubkeyScript(line string) bool {
return strings.HasPrefix(line, "01:")
}
func isSignatureScript(line string) bool {
return strings.HasPrefix(line, "00:")
}
func isWitnessScript(line string) bool {
return strings.HasPrefix(line, "02:")
}
func isFirstScriptLine(line string) bool {
return strings.Contains(line, ":0000: ")
}
<file_sep>/gui/gui.go
package gui
import (
"fmt"
"regexp"
"strings"
"github.com/Jeiwan/opscript/debugger"
"github.com/Jeiwan/opscript/spec"
"github.com/jroimartin/gocui"
)
const (
keyTilde = '~'
keyQ = 'q'
viewDebug = "debug"
viewScript = "script"
viewSpec = "spec"
viewStack = "stack"
)
// GUI ...
type GUI struct {
codeLines codeLines
cui *gocui.Gui
debugger *debugger.Debugger
spec spec.Script
}
// New returns a new GUI.
func New(debugger *debugger.Debugger, spec spec.Script) (*GUI, error) {
c, err := gocui.NewGui(gocui.OutputNormal)
if err != nil {
return nil, err
}
g := &GUI{
codeLines: []codeLine{},
cui: c,
debugger: debugger,
spec: spec,
}
g.populateCodeLines()
c.SetManagerFunc(g.layout)
g.setKeybindings(c)
return g, nil
}
// Stop ...
func (g GUI) Stop() {
g.cui.Close()
}
// Start ...
func (g GUI) Start() error {
if err := g.cui.MainLoop(); err != nil && err != gocui.ErrQuit {
return err
}
return nil
}
func (g *GUI) layout(c *gocui.Gui) error {
maxX, maxY := c.Size()
if v, err := c.SetView(viewScript, 0, 0, int(0.5*float64(maxX))-1, maxY-1); err != nil {
if err != gocui.ErrUnknownView {
return fmt.Errorf("setView 'script': %+v", err)
}
v.Title = "Script"
v.Highlight = true
v.SelBgColor = gocui.ColorGreen
v.SelFgColor = gocui.ColorBlack
g.renderCodeLines(v)
cx, _ := v.Cursor()
v.SetCursor(cx, g.codeLines.first().lineIdx)
c.SetCurrentView(viewScript)
}
if v, err := c.SetView(viewStack, int(0.5*float64(maxX)), 0, maxX-1, int(0.7*float64(maxY))-1); err != nil {
if err != gocui.ErrUnknownView {
return err
}
v.Title = "Stack"
if err := g.updateStack(); err != nil {
return err
}
}
if v, err := c.SetView(viewSpec, int(0.5*float64(maxX)), int(0.7*float64(maxY)), maxX-1, maxY-1); err != nil {
if err != gocui.ErrUnknownView {
return err
}
v.Title = "Spec"
v.Wrap = true
if err := g.updateSpec(); err != nil {
return err
}
}
if v, err := c.SetView(viewDebug, int(0.7*float64(maxX)), int(0.4*float64(maxY)), maxX-1, int(0.6*float64(maxY))); err != nil {
if err != gocui.ErrUnknownView {
return err
}
v.Title = "Debug"
if _, err := g.cui.SetViewOnBottom(viewDebug); err != nil {
return err
}
}
return nil
}
func (g *GUI) populateCodeLines() {
g.codeLines = nil
curLine := 0
var hasSigScript bool
var hasPkScript bool
indentation := 0
indentationStep := 4
for _, s := range g.debugger.Steps {
if isFirstScriptLine(s.Disasm) {
var line codeLine
line.isSeparator = true
line.lineIdx = curLine
if isSignatureScript(s.Disasm) {
hasSigScript = true
line.text = " Signature Script\n"
curLine++
} else if isPubkeyScript(s.Disasm) {
hasPkScript = true
line.text = "\n Pubkey Script\n"
curLine++
if hasSigScript {
curLine++
}
} else if isWitnessScript(s.Disasm) {
line.text = "\n Witness Script\n"
curLine++
if hasPkScript || hasSigScript {
curLine++
}
}
g.codeLines = append(g.codeLines, line)
}
var line codeLine
line.lineIdx = curLine
line.text = fmt.Sprintln(formatDisasm(s.Disasm, &indentation, indentationStep))
g.codeLines = append(g.codeLines, line)
curLine++
}
}
func (g *GUI) renderCodeLines(v *gocui.View) {
for _, cl := range g.codeLines {
fmt.Fprint(v, cl.text)
}
}
func (g GUI) setKeybindings(c *gocui.Gui) error {
if err := c.SetKeybinding(viewScript, gocui.KeyArrowUp, gocui.ModNone, g.cursorUp); err != nil {
return err
}
if err := c.SetKeybinding(viewScript, gocui.KeyArrowDown, gocui.ModNone, g.cursorDown); err != nil {
return err
}
if err := c.SetKeybinding("", keyQ, gocui.ModNone, quit); err != nil {
return err
}
if err := c.SetKeybinding("", keyTilde, gocui.ModNone, g.showDebugView); err != nil {
return err
}
return nil
}
func (g GUI) updateDebug(line string) error {
v, err := g.cui.View(viewDebug)
if err != nil {
return err
}
v.Autoscroll = true
fmt.Fprint(v, line)
return nil
}
func (g GUI) updateSpec() error {
v, err := g.cui.View(viewSpec)
if err != nil {
return err
}
v.Clear()
step := g.debugger.CurrentStep()
opcodeRegex := regexp.MustCompile(`OP_[\w_]+`)
opcode := opcodeRegex.FindString(step.Disasm)
if opcode == "" || strings.HasPrefix(opcode, "OP_DATA") {
return nil
}
spec := g.spec[opcode]
if spec.Word == "" {
fmt.Fprintf(v, " Missing spec for %s.", opcode)
return nil
}
fmt.Fprintf(v, " %s (%s)\n\n", spec.Word, spec.Opcode)
fmt.Fprintf(v, " Input: %s\n", spec.Input)
fmt.Fprintf(v, " Output: %s\n", spec.Output)
fmt.Fprintf(v, " \n %s", spec.Short)
return nil
}
func (g GUI) updateStack() error {
v, err := g.cui.View(viewStack)
if err != nil {
return err
}
v.Clear()
step := g.debugger.CurrentStep()
for i := range step.Stack {
fmt.Fprintf(v, " %x\n", step.Stack[len(step.Stack)-i-1])
}
return nil
}
func quit(g *gocui.Gui, v *gocui.View) error {
return gocui.ErrQuit
}
<file_sep>/gui/code_test.go
package gui
import "testing"
func TestFormatDisasm(t *testing.T) {
tests := []struct {
name string
input string
indentation int
expected string
}{
{name: "data",
input: "00:0000: OP_DATA_3 deadbeef",
indentation: 0,
expected: " deadbeef"},
{name: "op",
input: "00:0000: OP_1",
indentation: 0,
expected: " OP_1"},
{name: "with indentation",
input: "00:0000: OP_1",
indentation: 4,
expected: " OP_1"},
}
for _, test := range tests {
actual := formatDisasm(test.input, &test.indentation, 2)
if actual != test.expected {
t.Errorf("expected: %s, actual: %s", test.expected, actual)
}
}
}
<file_sep>/blockchain/node/node.go
package node
import (
"fmt"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/wire"
"github.com/sirupsen/logrus"
)
// Node is a Bitcoin node.
type Node struct {
host string
rpcUser string
rpcPass string
}
// New returns a new Node.
func New(host, rpcUser, rpcPass string) *Node {
return &Node{
host: host,
rpcUser: rpcUser,
rpcPass: rpcPass,
}
}
// GetTransaction returns a transaction by its hash.
func (n Node) GetTransaction(txHash string) (*wire.MsgTx, error) {
btcclient, err := rpcclient.New(&rpcclient.ConnConfig{
HTTPPostMode: true,
DisableTLS: true,
Host: n.host,
User: n.rpcUser,
Pass: n.rpc<PASSWORD>,
}, nil)
if err != nil {
logrus.Fatal(fmt.Errorf("new Bitcoin client: %+v", err))
}
defer btcclient.Shutdown()
hash, err := chainhash.NewHashFromStr(txHash)
if err != nil {
return nil, fmt.Errorf("parse txid: %+v", err)
}
txResp, err := btcclient.GetRawTransaction(hash)
if err != nil {
return nil, fmt.Errorf("get raw transaction: %+v", err)
}
return txResp.MsgTx(), nil
}
<file_sep>/README.md
## OP_SCRIPT
A viewer and debugger of Bitcoin scripts. **Early development.**
![Screenshot](./screenshot.png)
## Features
1. Can fetch transactions from:
1. A Bitcoin node (requires a full node with `txindex=1`). Default.
1. [Blockstream.info](https://blockstream.info) JSON API. Use `--blockstream` flag.
1. Automatically finds related output.
1. Allows to navigate forward and backward.
1. Shows stack per line of code.
1. Shows opcodes information (hex code, input, output, and description).
1. Supports witness data (SegWit).
1. Uses [`btcd/txscript`](https://github.com/btcsuite/btcd/tree/master/txscript) under the hood.
## Usage
1. `go get github.com/Jeiwan/opscript`
1. `opscript help`
```shell
Usage:
opscript [flags] transactionHash:inputIndex
opscript [command]
Available Commands:
buildspec
help Help about any command
Flags:
--blockstream Use blockstream.info API to get transactions.
-h, --help help for opscript
--node Use Bitcoin node to get transactions (requires 'txindex=1'). (default true)
--node-addr string Bitcoin node address. (default "127.0.0.1:8332")
--rpc-pass string Bitcoin JSON-RPC password.
--rpc-user string Bitcoin JSON-RPC username.
Use "opscript [command] --help" for more information about a command.
```
## Key bindings
* `q` – quit
* `↑`/`↓` – navigate between lines of code
## Examples
* Using Blockstream.info API:
```shell
opscript --blockstream 70fde4687efab8dae09737f87e30042030288fec42fd9e12f34c435cdeb7812c
```
* Specifying input index:
```shell
opscript --blockstream 70fde4687efab8dae09737f<PASSWORD>:0
```
* Using a Bitcoin node:
```shell
opscript --rpc-user=woot --rpc-pass=woot <PASSWORD>
```
<file_sep>/cmd/buildspec.go
package cmd
import (
"encoding/json"
"io/ioutil"
"github.com/Jeiwan/opscript/spec"
"github.com/spf13/cobra"
)
func newBuildSpecCmd() *cobra.Command {
const outFile = "spec.json"
cmd := &cobra.Command{
Use: "buildspec",
RunE: func(cmd *cobra.Command, args []string) error {
spec, err := spec.NewFromBitcoinWiki()
if err != nil {
return err
}
specJSON, err := json.MarshalIndent(spec, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(outFile, specJSON, 0644)
},
}
return cmd
}
<file_sep>/go.mod
module github.com/Jeiwan/opscript
go 1.12
require (
github.com/PuerkitoBio/goquery v1.5.0
github.com/btcsuite/btcd v0.20.1-beta
github.com/jroimartin/gocui v0.4.0
github.com/mattn/go-runewidth v0.0.6 // indirect
github.com/nsf/termbox-go v0.0.0-20190817171036-93860e161317 // indirect
github.com/sirupsen/logrus v1.4.2
github.com/spf13/cobra v0.0.5
github.com/stretchr/testify v1.3.0 // indirect
golang.org/x/net v0.0.0-20190603091049-60506f45cf65
)
<file_sep>/debugger/step.go
package debugger
// Step ...
type Step struct {
Disasm string
Stack [][]byte
}
<file_sep>/gui/keys.go
package gui
import (
"github.com/jroimartin/gocui"
)
func (g *GUI) cursorDown(c *gocui.Gui, v *gocui.View) error {
if v != nil {
if len(g.codeLines) == 0 {
return nil
}
ox, oy := v.Origin()
_, maxY := v.Size()
cx, cy := v.Cursor()
nextLine := g.codeLines.next(cy + oy)
maxY-- // one-line padding at the bottom
if nextLine.lineIdx == cy+oy {
return nil
}
if nextLine.lineIdx > maxY && cy == maxY {
oy++
if err := v.SetOrigin(ox, oy); err != nil {
return err
}
}
if err := v.SetCursor(cx, nextLine.lineIdx-oy); err != nil {
if err := v.SetOrigin(ox, maxY); err != nil {
return err
}
}
g.debugger.Next()
if err := g.updateStack(); err != nil {
return err
}
if err := g.updateSpec(); err != nil {
return err
}
}
return nil
}
func (g *GUI) cursorUp(c *gocui.Gui, v *gocui.View) error {
if v != nil {
if len(g.codeLines) == 0 {
return nil
}
ox, oy := v.Origin()
cx, cy := v.Cursor()
prevLine := g.codeLines.previous(oy + cy)
firstLine := g.codeLines.first()
if prevLine.lineIdx == 0 {
if err := v.SetOrigin(cx, 0); err != nil {
return err
}
if err := v.SetCursor(cx, firstLine.lineIdx); err != nil {
return err
}
return nil
}
if prevLine.lineIdx < oy {
if err := v.SetOrigin(cx, oy-(oy-prevLine.lineIdx)); err != nil {
return err
}
prevLine.lineIdx = oy
}
if err := v.SetCursor(cx, prevLine.lineIdx-oy); err != nil {
if err := v.SetOrigin(ox, firstLine.lineIdx); err != nil {
return err
}
}
g.debugger.Previous()
if err := g.updateStack(); err != nil {
return err
}
if err := g.updateSpec(); err != nil {
return err
}
}
return nil
}
func (g *GUI) showDebugView(c *gocui.Gui, v *gocui.View) error {
if _, err := g.cui.SetViewOnTop(viewDebug); err != nil {
return err
}
return nil
}
<file_sep>/cmd/opscript.go
package cmd
import (
"encoding/hex"
"errors"
"fmt"
"strconv"
"strings"
"github.com/Jeiwan/opscript/blockchain/blockstream"
"github.com/Jeiwan/opscript/blockchain/node"
"github.com/Jeiwan/opscript/debugger"
"github.com/Jeiwan/opscript/gui"
"github.com/Jeiwan/opscript/spec"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
// Blockchain ...
type Blockchain interface {
GetTransaction(txHash string) (*wire.MsgTx, error)
}
// New ...
func New(spec spec.Script) *cobra.Command {
rootCmd := newRootCmd(spec)
buildSpecCmd := newBuildSpecCmd()
rootCmd.AddCommand(buildSpecCmd)
return rootCmd
}
func newRootCmd(spec spec.Script) *cobra.Command {
var useNode, useBlockstream bool
var nodeAddr, rpcUser, rpcPass string
cmd := &cobra.Command{
Use: "opscript [flags] transactionHash:inputIndex",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
var bchain Blockchain
switch {
case useBlockstream:
bchain = blockstream.New()
case useNode:
bchain = node.New(nodeAddr, rpcUser, rpcPass)
}
txHash, txInput, err := parseArgs(args)
if err != nil {
return err
}
tx, err := bchain.GetTransaction(txHash)
if err != nil {
return err
}
prevOut := tx.TxIn[txInput].PreviousOutPoint
prevTx, err := bchain.GetTransaction(prevOut.Hash.String())
if err != nil {
logrus.Fatal(fmt.Errorf("get prev transaction: %+v", err))
}
en, err := newEngine(tx, prevTx.TxOut[prevOut.Index].PkScript, txInput)
if err != nil {
logrus.Fatal(fmt.Errorf("new engine: %+v", err))
}
d, err := debugger.New(en)
if err != nil {
logrus.Fatalln(err)
}
gui, err := gui.New(d, spec)
if err != nil {
logrus.Fatalln(err)
}
defer gui.Stop()
if err := gui.Start(); err != nil {
logrus.Fatalln(err)
}
return nil
},
}
cmd.Flags().BoolVar(&useNode, "node", true, "Use Bitcoin node to get transactions (requires 'txindex=1').")
cmd.Flags().BoolVar(&useBlockstream, "blockstream", false, "Use blockstream.info API to get transactions.")
cmd.Flags().StringVar(&nodeAddr, "node-addr", "127.0.0.1:8332", "Bitcoin node address.")
cmd.Flags().StringVar(&rpcUser, "rpc-user", "", "Bitcoin JSON-RPC username.")
cmd.Flags().StringVar(&rpcPass, "rpc-pass", "", "Bitcoin JSON-RPC password.")
return cmd
}
func newEngine(tx *wire.MsgTx, output []byte, inputIdx int) (*txscript.Engine, error) {
e, err := txscript.NewEngine(
output,
tx,
inputIdx,
txscript.ScriptVerifyWitness+txscript.ScriptBip16+txscript.ScriptVerifyCleanStack+txscript.ScriptVerifyMinimalData,
nil,
nil,
-1,
)
if err != nil {
return nil, err
}
return e, nil
}
func parseArgs(args []string) (txHash string, input int, err error) {
if len(args) != 1 {
return "", -1, errors.New("wrong number of arguments")
}
parts := strings.Split(args[0], ":")
if len(parts) == 2 {
input, err = strconv.Atoi(parts[1])
if err != nil {
return "", -1, err
}
}
if hashBytes, err := hex.DecodeString(parts[0]); err != nil || len(hashBytes) != 32 {
return "", -1, errors.New("wrong transaction hash")
}
txHash = parts[0]
return
}
<file_sep>/Makefile
default:
cat Makefile
spec:
go run *.go buildspec
go-bindata -pkg internal -o internal/bindata.go spec.json
test:
go test -v ./...<file_sep>/blockchain/blockstream/transaction.go
package blockstream
type transaction struct {
Txid string `json:"txid"`
Version int32 `json:"version"`
Locktime int `json:"locktime"`
Size int `json:"size"`
Weight int `json:"weight"`
Fee int `json:"fee"`
Vin []vin `json:"vin"`
Vout []vout `json:"vout"`
Status status `json:"status"`
}
type vin struct {
Txid string `json:"txid"`
Vout uint32 `json:"vout"`
IsCoinbase bool `json:"is_coinbase"`
Scriptsig string `json:"scriptsig"`
ScriptsigAsm string `json:"scriptsig_asm"`
InnerRedeemscriptAsm string `json:"inner_redeemscript_asm"`
InnerWitnessscriptAsm string `json:"inner_witnessscript_asm"`
Sequence int `json:"sequence"`
Witness []string `json:"witness"`
Prevout vout `json:"prevout"`
}
type vout struct {
Scriptpubkey string `json:"scriptpubkey"`
ScriptpubkeyAsm string `json:"scriptpubkey_asm"`
ScriptpubkeyType string `json:"scriptpubkey_type"`
ScriptpubkeyAddress string `json:"scriptpubkey_address"`
Value int64 `json:"value"`
}
type status struct {
Confirmed bool `json:"confirmed"`
BlockHeight int `json:"block_height"`
BlockHash string `json:"block_hash"`
BlockTime int `json:"block_time"`
}
<file_sep>/spec/spec.go
package spec
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/sirupsen/logrus"
)
// Opcode ...
type Opcode struct {
Word string `json:"word"`
WordAlt string `json:"word_alt"`
Opcode string `json:"opcode"`
Input string `json:"input"`
Output string `json:"output"`
Short string `json:"short"`
}
// Script ...
type Script map[string]Opcode
// NewFromBitcoinWiki parses https://en.bitcoin.it/wiki/Script and extract Script specification.
func NewFromBitcoinWiki() (*Script, error) {
const specURL = "https://en.bitcoin.it/wiki/Script"
const totalTables = 10
spec := make(Script)
resp, err := http.Get(specURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("spec page is not available: %d, %s", resp.StatusCode, b)
}
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return nil, err
}
var scrapedTables uint8
doc.Find("table.wikitable").Each(func(i int, s *goquery.Selection) {
if scrapedTables >= totalTables {
return
}
s.Find("tr").Each(func(j int, s *goquery.Selection) {
cells := s.Find("td").Map(func(k int, s *goquery.Selection) string {
return s.Text()
})
if len(cells) == 0 {
return
}
ops := cellsToOps(cells)
for _, op := range ops {
spec[op.Word] = op
}
})
scrapedTables++
})
return &spec, nil
}
func cellsToOps(cells []string) []Opcode {
if len(cells) == 0 {
return nil
}
for i := range cells {
cells[i] = strings.TrimSpace(cells[i])
}
var input, output string
word := cells[0]
opcodeDec := cells[1]
opcode := cells[2]
if len(cells) == 6 {
input = cells[3]
output = cells[4]
}
short := cells[len(cells)-1]
if !strings.HasPrefix(word, "OP_") {
logrus.Infof("skipping %s\n", word)
return nil
}
var ops []Opcode
alts := strings.Split(word, ", ")
rnge := strings.Split(word, "-")
if len(alts) == 2 && len(rnge) == 2 {
rnge = strings.Split(alts[1], "-")
alts = []string{alts[0]}
opcodeDec = strings.Split(opcodeDec, ", ")[1]
}
cleanWord := regexp.MustCompile(`OP_[\w_-]+`)
if len(alts) == 1 {
ops = append(ops, Opcode{
Word: cleanWord.FindString(alts[0]),
Opcode: opcode,
Input: input,
Output: output,
Short: short,
})
}
if len(alts) == 2 {
ops = append(ops, []Opcode{
{
Word: cleanWord.FindString(alts[0]),
WordAlt: cleanWord.FindString(alts[1]),
Opcode: opcode,
Input: input,
Output: output,
Short: short,
},
{
Word: cleanWord.FindString(alts[1]),
WordAlt: cleanWord.FindString(alts[0]),
Opcode: opcode,
Input: input,
Output: output,
Short: short,
},
}...)
}
if len(rnge) == 2 {
leftOp := rnge[0]
rightOp := rnge[1]
opNumber := regexp.MustCompile(`(OP_[A-Z]*)(\d+)`)
leftMatches := opNumber.FindStringSubmatch(leftOp)
rightMatches := opNumber.FindStringSubmatch(rightOp)
if len(leftMatches) != 3 || len(rightMatches) != 3 {
logrus.Errorf("skipping %s: invalid opcodes range %q, %q\n", word, leftMatches, rightMatches)
return ops
}
leftN, err := strconv.Atoi(leftMatches[2])
if err != nil {
logrus.Errorf("skipping %s: %+v\n", word, err)
return ops
}
rightN, err := strconv.Atoi(rightMatches[2])
if err != nil {
logrus.Errorf("skipping %s: %+v\n", word, err)
return ops
}
opcodes := strings.Split(opcodeDec, "-")
if len(opcodes) != 2 {
logrus.Errorf("skipping %s: invalid opcode %+v\n", word, opcodeDec)
return ops
}
opcodeLeft, err := strconv.Atoi(opcodes[0])
if err != nil {
logrus.Errorf("skipping %s: %+v\n", word, err)
return ops
}
var outputLeft int
isEmptyOutput := len(output) == 0
if !isEmptyOutput {
outputs := strings.Split(output, "-")
if len(outputs) != 2 {
logrus.Errorf("skipping %s: invalid output %+v\n", word, output)
return ops
}
outputLeft, err = strconv.Atoi(outputs[0])
if err != nil {
logrus.Errorf("skipping %s: %+v\n", word, err)
return ops
}
}
for i := leftN; i <= rightN; i++ {
op := Opcode{
Word: fmt.Sprintf("%s%d", leftMatches[1], i),
Opcode: fmt.Sprintf("0x%x", opcodeLeft+i-leftN),
Input: input,
Short: short,
}
if !isEmptyOutput {
op.Output = strconv.Itoa(outputLeft + i - leftN)
}
ops = append(ops, op)
}
}
return ops
}
<file_sep>/blockchain/blockstream/blockstream.go
package blockstream
import (
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
)
const baseURL = "https://blockstream.info/api/"
// Blockstream is a client for https://blockstream.info
type Blockstream struct {
}
// New returns a new Blockstream client.
func New() *Blockstream {
return &Blockstream{}
}
// GetTransaction returns a transaction by its hash.
func (b Blockstream) GetTransaction(txHash string) (*wire.MsgTx, error) {
url := fmt.Sprintf("%s/tx/%s", baseURL, txHash)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("failed to get a transaction: %s", b)
}
var tx transaction
if err := json.NewDecoder(resp.Body).Decode(&tx); err != nil {
return nil, err
}
msgTx := wire.NewMsgTx(tx.Version)
msgTx.LockTime = uint32(tx.Locktime)
for _, vin := range tx.Vin {
voutHash, err := chainhash.NewHashFromStr(vin.Txid)
if err != nil {
return nil, err
}
sigScript, err := hex.DecodeString(vin.Scriptsig)
if err != nil {
return nil, err
}
var witness [][]byte
for _, w := range vin.Witness {
ws, err := hex.DecodeString(w)
if err != nil {
return nil, err
}
witness = append(witness, ws)
}
newInput := wire.NewTxIn(
wire.NewOutPoint(voutHash, vin.Vout),
sigScript,
witness,
)
newInput.Sequence = uint32(vin.Sequence)
msgTx.AddTxIn(newInput)
}
for _, vout := range tx.Vout {
pkScript, err := hex.DecodeString(vout.Scriptpubkey)
if err != nil {
return nil, err
}
msgTx.AddTxOut(
wire.NewTxOut(
vout.Value,
pkScript,
),
)
}
if msgTx.TxHash().String() != tx.Txid {
return nil, fmt.Errorf("transaction hash doesn't match")
}
return msgTx, nil
}
<file_sep>/debugger/debugger.go
package debugger
import (
"github.com/btcsuite/btcd/txscript"
"github.com/sirupsen/logrus"
)
// Debugger ...
type Debugger struct {
CurrentPos uint16
Engine *txscript.Engine
Steps []Step
}
// New ...
func New(en *txscript.Engine) (*Debugger, error) {
var steps []Step
Loop:
for {
var step Step
d, err := en.DisasmPC()
if err != nil {
return nil, err
}
logrus.Debugf("EXECUTING: %s", d)
done, err := en.Step()
if err != nil {
return nil, err
}
step.Disasm = d
step.Stack = en.GetStack()
steps = append(steps, step)
if done {
logrus.Debugf("FINISHED")
break Loop
}
}
return &Debugger{
CurrentPos: 0,
Engine: en,
Steps: steps,
}, nil
}
// Next ...
func (d *Debugger) Next() bool {
if int(d.CurrentPos+1) >= len(d.Steps) {
return false
}
d.CurrentPos++
return true
}
// Previous ...
func (d *Debugger) Previous() bool {
if int(d.CurrentPos-1) < 0 {
return false
}
d.CurrentPos--
return true
}
// CurrentStep ...
func (d *Debugger) CurrentStep() *Step {
return &d.Steps[d.CurrentPos]
}
<file_sep>/main.go
package main
import (
"encoding/json"
"os"
"github.com/Jeiwan/opscript/cmd"
"github.com/Jeiwan/opscript/internal"
"github.com/Jeiwan/opscript/spec"
"github.com/sirupsen/logrus"
)
func main() {
if os.Getenv("DEBUG") != "" {
logrus.SetLevel(logrus.DebugLevel)
}
specData, err := internal.Asset("spec.json")
if err != nil {
logrus.Fatalln(err)
}
scriptSpec := make(spec.Script)
if err := json.Unmarshal(specData, &scriptSpec); err != nil {
logrus.Fatalln(err)
}
if err := cmd.New(scriptSpec).Execute(); err != nil {
os.Exit(1)
}
}
| e472481262b14267594a625c533c853747baf168 | [
"Markdown",
"Go Module",
"Go",
"Makefile"
] | 16 | Go | smartcyberhacker/opscript | fd19fada5511f879d73243bdef5a94e93ff6b37b | fa987472e09c0c0e32df11ed1a57206c6a725215 | |
refs/heads/master | <file_sep>#ifndef ASDA_H
#define ASDA_H
class asda
{
public:
asda();
};
#endif // ASDA_H
<file_sep>#include "basetest.h"
#include "sefa.h"
#include <QDataStream>
#include <QDebug>
#include <QFile>
#include <QDateTime>
#include <QVariant>
#include <iostream>
#include <cstring>
using namespace std;
/*
* camel casing, +
* Serialization: +
* - versioning, signature +
* - endianness(little-endian,big-endian)
* Event loop
* QHash ve QMap arasındakı fark? +
*
* github:
* - URL
* - git remote
* - git push|pull
* - ssh-keygen
*/
void enterNameSurname(QString &oprtr,QString &site)
{
QTextStream qtin(stdin);
QString name,surname;
cout<<"Please enter name and surname: ";
qtin>>name>>surname;
name.append(" ");
name.append(surname);
oprtr=name;
cout<<"\nPlease enter your site: ";
qtin>>site;
}
int chooseTest(void)
{
cout<<"Please choose the test which you want : \n";
cout<<"(1)-Functionality Test \n";
cout<<"(2)-Stress Test \n";
cout<<"(3)-Performance Test : ";
int choose;
cin>>choose;
return choose;
}
void afterChooseTest(Sefa t,QDataStream &stream)
{
int num;
t.starttime(QDateTime :: currentDateTime());
qDebug()<<QDateTime :: currentDateTime();
num=t.getState();
qDebug() << "test with state" << t.getState();
stream << QString("test with state")<< num; //Stream
t.start();
num=t.getState();
qDebug() << "test with state" << t.getState();
stream << QString("test with state")<< num; //Stream
/* wait test to start */
while (t.getState() == BaseTest::STATE_STARTING)
{
t.afterstart();
}
qDebug("test is started");
/* now the test is running, wait it for to be completed */
num=t.getState();
qDebug() << "test with state" << t.getState();
stream << QString("test with state")<< num; //Stream
while (t.getState() == BaseTest::STATE_RUNNING)
t.run();
num=t.getState();
stream << QString("test with state")<< num; //Stream
t.stop();
num=t.getState();
qDebug() << "test finished with state" << t.getState();
stream << QString("test finished with state")<< num; //Stream
/* save test results to the disk */
t.finishtime(QDateTime :: currentDateTime());
qDebug()<<QDateTime :: currentDateTime();
}
void afterWritingFile(void)
{
qDebug("\n\nAfter Writing File:\n\n");
QFile file2("setting.dat");
file2.open(QIODevice::ReadOnly);
//while(file2.isOpen() == 0);
QDataStream stream2(&file2);
QString str,str2;
int num2;
stream2>>num2;
if(num2!=0x11223344)
{
qDebug("This folder is wrong");
return ;
}
stream2>>str;
qDebug()<<str;
stream2>>str>>str2;
qDebug() << str<<str2;
stream2 >> str;
qDebug() << str;
stream2 >> str>>num2;
qDebug() << str<<num2;
stream2 >> str>>num2;
qDebug() << str<<num2;
stream2 >> str>>num2;
qDebug() << str<<num2;
stream2 >> str>>num2;
qDebug() << str<<num2;
stream2 >> str>>num2;
qDebug() << str<<num2;
}
int main(int argc, char *argv[])
{
(void)argc; //make compiler happy
(void)argv;
QFile file("setting.dat");
file.open(QIODevice::WriteOnly);
QDataStream stream(&file);
int sign=0x11223344;
stream<<sign; //Stream
QString version("Version 0");
stream<<version;
QString oprtr,site;
enterNameSurname(oprtr,site);
qDebug()<<oprtr<<site<<endl;
stream<<oprtr<<site; //Stream
Sefa t;
//---------------------------------------------------------------------------------------
t.testSiteANDtestOperator(oprtr,site);
int num;
num=chooseTest();
if(num==1)
{
stream<<QString("Selected test is Functionality Test "); //Stream
} //go to Functionality Test
else if(num==2)
{
stream<<QString("Selected test is Stress Test "); //Stream
} //go to Stress Test
else if(num==3)
{
stream<<QString("Selected test is Performance Test "); //Stream
} //go to Performance Test
else
{
qDebug("Wrong input");
return 0;
}
//-----------------------------------------------------------------------------------------
afterChooseTest(t,stream);
file.close();
afterWritingFile();
return 0;
}
<file_sep># TestDemo2
just another demo
<file_sep>#include "basetest.h"
#include <QDateTime>
BaseTest::BaseTest()
{
state = STATE_IDLE;
}
BaseTest::TestState BaseTest::getState()
{
return state;
}
void BaseTest::setState(BaseTest::TestState s)
{
state = s;
}
void BaseTest::testSiteANDtestOperator(QString site,QString oprtr)
{
testSite=site;
testOperator=oprtr;
}
void BaseTest :: starttime(QDateTime dt)
{
startTime=dt;
}
void BaseTest :: finishtime(QDateTime dt)
{
finishTime=dt;
}
<file_sep>#ifndef STRESSTEST_H
#define STRESSTEST_H
#include "basetest.h"
class Sefa : public BaseTest
{
public:
Sefa();
int start();
int stop();
int run();
int afterstart();
const QList<QString> getTestResults();
int testResult();
};
#endif // STRESSTEST_H
<file_sep>#ifndef BASETEST_H
#define BASETEST_H
#include <QHash>
#include <QList>
#include <QString>
#include <QStringList>
#include <QDateTime>
#include <QVariant>
class BaseTest
{
public:
BaseTest();
enum TestState {
STATE_IDLE,
STATE_STARTING,
STATE_RUNNING,
STATE_STOPPING,
};
virtual int start() = 0;
virtual int stop() = 0;
virtual int run() = 0;
virtual const QList<QString> getTestResults() = 0;
TestState getState();
void starttime(QDateTime dt);
void finishtime(QDateTime dt);
void testSiteANDtestOperator(QString site,QString oprtr);
virtual int testResult() = 0;
protected:
void setState(TestState s);
QStringList log; /* will be filled by sub-classes */ //Burada neler tutulacaktı?
QHash<QString, QVariant> testParameters; /* will be set by sub-class users */ //Burada neler tutulacaktı?
private:
TestState state; //yapıldı
QDateTime startTime; //yapıldı
QDateTime finishTime; //yapıldı
QString testSite; //yapıldı
QString testOperator; //yapıldı
/* run time */
};
#endif // BASETEST_H
| 2904173240d7891b4d0214c403985892cbc4ed32 | [
"Markdown",
"C++"
] | 6 | C++ | sefamert/TestDemo2 | fec70768d566cfff7636cc53bbd17bb4324d2ce1 | 318facc51a0a5ed5017f3e70f628735e520d42e5 | |
refs/heads/master | <repo_name>AlexanderMg12/expenses-table<file_sep>/config.py
HOST = "test"
USER = "test"
PASSWORD = "<PASSWORD>"
DATABASE = "test"
TABLE_NAME = "expenses"
ERROR_PAGE = "Error_page.html"
REDIRECT_PAGE = "index"
<file_sep>/expenses.py
from typing import Union
from flask_bootstrap import Bootstrap
from flask import Flask, request, redirect, url_for, render_template
from mysql.connector import Error
from werkzeug.wrappers.response import Response
from config import ERROR_PAGE, REDIRECT_PAGE
from sql_handler import (
get_all_data,
get_data_to_id,
add_line,
delete_line_to_id,
delete_all_lines,
update_line,
)
from logger import logger_expenses
from utils import get_dollar_value, get_line_to_id
app = Flask(__name__)
Bootstrap(app)
@app.route("/", methods=["GET"])
def index() -> str:
"""Основной route приложения.
Returns:
str: html страницы.
"""
try:
all_data = get_all_data()
return render_template("index.html", data=all_data)
except Error as e:
logger_expenses.error(f"Ошибка: {e}", exc_info=True)
return render_template(ERROR_PAGE)
@app.route("/add_data", methods=["POST"])
def add_data() -> Union[Response, str]:
"""Добавление строки с данными в таблицу.
Returns:
Union[Response, str]: редирект на основную html или html-страница.
"""
form = request.form
rubles = float(form["rub"])
waste_or_income = form["w/i"]
description = form["desc"]
dollars = round(rubles / get_dollar_value(), 2)
try:
add_line(rubles, dollars, waste_or_income, description)
logger_expenses.debug(
"Добавлена строка с данными: "
f"rubles = {rubles}, dollars = {dollars}, "
f"w/i = {waste_or_income}, description = {description}"
)
return redirect(url_for(REDIRECT_PAGE))
except Error as e:
logger_expenses.error(f"Ошибка: {e}", exc_info=True)
return render_template(ERROR_PAGE)
@app.route("/delete_data", methods=["POST"])
def delete_data() -> Union[Response, str]:
"""Удаление строки с данными в таблице.
Returns:
Union[Response, str]: редирект на основную html или html-страница.
"""
line_id = int(request.form["id"])
delete_line = get_data_to_id(line_id)[0]
logger_expenses.debug(
f"Запрос на удаление строки с id {line_id}, данные строки: "
f"rubles = {delete_line[1]}, dollars = {delete_line[2]}, date = {delete_line[3]}, "
f"w/i = {delete_line[4]}, description = {delete_line[5]}"
)
try:
delete_line_to_id(line_id)
logger_expenses.debug(f"Удалена строка с id {line_id}")
return redirect(url_for(REDIRECT_PAGE))
except Error as e:
logger_expenses.error(f"Ошибка: {e}", exc_info=True)
return render_template(ERROR_PAGE)
@app.route("/delete_all_data", methods=["POST"])
def delete_all_data() -> Union[Response, str]:
"""Удаление всех строк в таблице.
Returns:
Union[Response, str]: редирект на основную html или html-страница.
"""
try:
delete_all_lines()
logger_expenses.debug("Все данные удалены")
return redirect(url_for(REDIRECT_PAGE))
except Error as e:
logger_expenses.error(f"Ошибка: {e}", exc_info=True)
return render_template(ERROR_PAGE)
@app.route("/update_data", methods=["POST"])
def update_data() -> Union[Response, str]:
"""Route для изменения строки с данными в таблицу.
Returns:
Union[Response, str]: редирект на основную html или html-страница.
"""
line_id = int(request.form["id"])
line_to_id = get_line_to_id(line_id)
logger_expenses.debug(
f"Запрос на изменение данных в строке с id {line_id}: "
f"rubles = {line_to_id[1]}, dollars = {line_to_id[2]}, date = {line_to_id[3]}, "
f"w/i = {line_to_id[4]}, description = {line_to_id[5]}"
)
form = request.form
rubles = float(form["rub"]) if form["rub"] else line_to_id[1]
waste_or_income = form["w/i"] if form["w/i"] else line_to_id[4]
description = form["desc"] if form["desc"] else line_to_id[5]
dollars = round(rubles / get_dollar_value(), 2)
try:
update_line(rubles, waste_or_income, description, dollars, line_id)
line_to_id = get_line_to_id(line_id)
logger_expenses.debug(
"Данные изменены на: "
f"rubles = {line_to_id[1]}, dollars = {line_to_id[2]}, date = {line_to_id[3]}, "
f"w/i = {line_to_id[4]}, description = {line_to_id[5]}"
)
return redirect(url_for(REDIRECT_PAGE))
except Error as e:
logger_expenses.error(f"Ошибка: {e}", exc_info=True)
return render_template(ERROR_PAGE)
if __name__ == "__main__":
app.run()
<file_sep>/requirements.txt
Flask==1.1.2
redis==5.0.7
requests==2.22.0
flask_bootstrap==3.3.7.1
mysql_connector_repackaged==0.3.1
<file_sep>/logger.py
import logging
logging.basicConfig(level=logging.DEBUG)
logger_expenses = logging.getLogger("expenses")
my_handler = logging.FileHandler("log_table.log")
my_format = logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %(message)s")
my_handler.setFormatter(my_format)
logger_expenses.addHandler(my_handler)
logger_expenses.setLevel(logging.DEBUG)
<file_sep>/redis_handler.py
import redis
from typing import Union
redis_conn = redis.Redis()
def recording_dollar_value(dollar_value: str) -> None:
"""Запись значения доллара
Args:
dollar_value: значение доллара
"""
redis_conn.setex("dollar", 3600, dollar_value)
def check_dollar_value() -> Union[bytes, None]:
"""Проверка наличия значения доллара в кэш
Return:
Union[bytes, None]: значение доллара или ничего
"""
return redis_conn.get("dollar")
<file_sep>/create_table.py
import mysql.connector
from mysql.connector import Error
conn = mysql.connector.connect(
host="localhost", user="alexandr", password="1", database="mysqltest"
)
cursor = conn.cursor()
create_table_data = """
CREATE TABLE IF NOT EXISTS expenses (
id INT AUTO_INCREMENT,
rubles FLOAT NOT NULL,
dollars FLOAT NOT NULL,
date_time DATETIME NOT NULL,
waste_or_income TEXT NOT NULL,
description TEXT NOT NULL,
PRIMARY KEY (id)
)
"""
try:
cursor.execute(create_table_data)
conn.commit()
print("Таблица создана")
except Error as e:
print(e)
<file_sep>/sql_handler.py
import mysql.connector
from typing import List
from config import HOST, USER, PASSWORD, DATABASE, TABLE_NAME
mysql_conn = mysql.connector.connect(
host=HOST, user=USER, password=<PASSWORD>, database=DATABASE
)
mysql_cursor = mysql_conn.cursor()
def get_all_data() -> List[tuple]:
"""Получение всех данных из таблицы.
Return:
List[tuple]: Все данные таблицы.
"""
query = f"SELECT * FROM {TABLE_NAME}"
mysql_cursor.execute(query)
return mysql_cursor.fetchall()
def get_data_to_id(line_id: int) -> List[tuple]:
"""Получение значений из таблицы по заданному id.
Args:
line_id: id строки в таблице.
Return:
List[tuple]: Данные строки из таблицы по заданному id.
"""
query = f"SELECT * FROM {TABLE_NAME} WHERE id = {line_id}"
mysql_cursor.execute(query)
return mysql_cursor.fetchall()
def add_line(
rubles: float, dollars: float, waste_or_income: str, description: str
) -> None:
"""Добавление новой строки в таблицу.
Args:
rubles: значение суммы в рублях.
dollars: значение суммы в долларах.
waste_or_income: вид транзакции (расход/доход).
description: описание транзакции.
"""
query = """INSERT INTO expenses
( rubles, dollars, date_time, waste_or_income, description )
VALUES ( %s, %s, NOW(), %s, %s)"""
mysql_cursor.execute(query, (rubles, dollars, waste_or_income, description))
mysql_conn.commit()
def delete_line_to_id(line_id: int) -> None:
"""Удаление строки в таблице по заданному id.
Args:
line_id: id строки в таблице.
"""
query = f"DELETE FROM {TABLE_NAME} WHERE id = {line_id}"
mysql_cursor.execute(query)
mysql_conn.commit()
def delete_all_lines() -> None:
"""Удаление всех данных таблицы."""
query = f"DELETE FROM {TABLE_NAME}"
mysql_cursor.execute(query)
mysql_conn.commit()
def update_line(
rubles: float, waste_or_income: str, description: str, dollars: float, line_id: int
) -> None:
"""Обновление данных строки в таблице.
Args:
rubles: рубли.
waste_or_income: расход или доход.
description: описание.
dollars: доллары.
line_id: id строки в таблице.
"""
query = """UPDATE expenses SET
rubles = %s,
waste_or_income = %s,
description = %s,
dollars = %s,
date_time = NOW()
WHERE id = %s"""
mysql_cursor.execute(
query, (rubles, waste_or_income, description, dollars, line_id)
)
mysql_conn.commit()
<file_sep>/utils.py
import re
from typing import Union
import requests
from flask import render_template
from mysql.connector import Error
from werkzeug.wrappers.response import Response
from redis_handler import recording_dollar_value, check_dollar_value
from sql_handler import get_data_to_id
from logger import logger_expenses
from config import ERROR_PAGE
def get_dollar_value() -> float:
"""Получаем значения доллара из redis, если значения нет, парсим сайт,
для получения значения и записываем его в redis.
Return:
float: значение доллара.
"""
dollar_value_cache = check_dollar_value()
if dollar_value_cache is None:
dollar_html = requests.get("https://www.banki.ru/products/currency/usd/")
dollar_value = re.search(
r'<div class="currency-table__large-text">(\d+.\d+)', dollar_html.text
).group(1)
dollar_value = dollar_value.replace(",", ".")
recording_dollar_value(dollar_value)
else:
dollar_value = dollar_value_cache.decode("utf-8", "replace")
return float(dollar_value)
def get_line_to_id(line_id: int) -> Union[tuple, Response]:
"""Получение кортежа с данными строки из таблицы базы данных.
Args:
line_id: id строки в таблице.
Return:
Union[tuple, Response]: кортеж с данными строки из таблицы или страницу с ошибкой
"""
try:
return get_data_to_id(line_id)[0]
except Error as err:
logger_expenses.error(f"Ошибка: {err}", exc_info=True)
return render_template(ERROR_PAGE)
| b96868da444b93a8df2c39211922aff15828fba3 | [
"Python",
"Text"
] | 8 | Python | AlexanderMg12/expenses-table | 607844abb0852a46e424e43e90bd0cc9e8533348 | c5d533451db96035e76bcb01e196e1cbacf68338 | |
refs/heads/master | <file_sep>from setuptools import setup
setup(
name="TimeSeriesD3MWrappers",
version="1.2.0",
description="Two forecasting primitives: Vector Autoregression and Deep Autoregressive forecasting. Two classification primiives: KNN and LSTM FCN with attention",
packages=["TimeSeriesD3MWrappers"],
install_requires=[
"numpy>=1.15.4,<=1.17.3",
"scipy>=1.2.1,<=1.3.1",
"scikit-learn[alldeps]>=0.20.3,<=0.21.3",
"pandas>=0.23.4,<=0.25.2",
"tensorflow-gpu == 2.0.0",
"tslearn == 0.2.5",
"statsmodels==0.10.2",
"pmdarima==1.0.0",
"deepar @ git+https://github.com/NewKnowledge/deepar@d06db4f6324ab8006c9b4703408ce3b6ae955cf4#egg=deepar-0.0.2",
],
entry_points={
"d3m.primitives": [
"time_series_classification.k_neighbors.Kanine = TimeSeriesD3MWrappers.primitives.classification_knn:Kanine",
"time_series_forecasting.vector_autoregression.VAR = TimeSeriesD3MWrappers.primitives.forecasting_var:VAR",
"time_series_classification.convolutional_neural_net.LSTM_FCN = TimeSeriesD3MWrappers.primitives.classification_lstm:LSTM_FCN",
"time_series_forecasting.lstm.DeepAR = TimeSeriesD3MWrappers.primitives.forecasting_deepar:DeepAR",
],
},
)
<file_sep>#!/bin/bash -e
Paths=('d3m.primitives.time_series_classification.k_neighbors.Kanine' 'd3m.primitives.time_series_forecasting.vector_autoregression.VAR' 'd3m.primitives.time_series_forecasting.lstm.DeepAR' 'd3m.primitives.time_series_classification.convolutional_neural_net.LSTM_FCN')
for i in "${Paths[@]}"; do
cd /primitives/v2019.11.10/Distil
cd $i
echo $i
cd *
python3 -m d3m index describe -i 4 $i > primitive.json
done
<file_sep># Repository of D3M wrappers for time series classification and forecasting
**TimeSeriesD3MWrappers/primitives**:
D3M primitives
1. **classification_knn.py**: wrapper for tslearn's KNeighborsTimeSeriesClassifier algorithm
2. **classification_lstm.py**: wrapper for LSTM Fully Convolutional Networks for Time Series Classification paper, original repo (https://github.com/titu1994/MLSTM-FCN), paper (https://arxiv.org/abs/1801.04503)
3. **forecasting_deepar.py**: wrapper for DeepAR recurrent, autoregressive Time Series Forecasting algorithm (https://arxiv.org/abs/1704.04110). Custom implementation repo (https://github.com/NewKnowledge/deepar)
4. **forecasting_var.py**: wrapper for **statsmodels**' implementation of vector autoregression for multivariate time series
**TimeSeriesD3MWrappers/pipelines**:
Example pipelines for primitives. Latest are:
1. **forecasting_pipeline_imputer.py**: pipeline for DeepAR primitive on all forecasting datasets
2. **forecasting_pipeline_var.py**: pipeline for VAR primitive on all forecasting datasets (except terra datasets)
3. **Kanine_pipeline.py**: pipeline for Kanine primitive on all classification datasets
4. **LSTM_FCN_pipeline.py**: pipeline for LSTM_FCN primitive on all classification datasets
Model utils
1. **layer_utils.py**: implementation of AttentionLSTM in tensorflow (compatible with 2), originally from https://github.com/houshd/LSTM-FCN
2. **lstm_model_utils.py**: functions to generate LSTM_FCN model architecture and data generators
3. **var_model_utils.py**: wrapper of the **auto_arima** method from **pmdarima.arima** with some specific parameters fixed
| d7e4d9d5b89bb5d1eee8be5529583e6d4a770e5a | [
"Markdown",
"Python",
"Shell"
] | 3 | Python | mindis/TimeSeries-D3M-Wrappers | f1029c43849fd9caee071ee93352e4b6609b5b25 | 33d443710d2eb45bea646aee28546aac91fb7291 | |
refs/heads/main | <file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pstrait <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/03 17:58:18 by pstrait #+# #+# */
/* Updated: 2020/12/24 19:05:01 by pstrait ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_strchr(const char *s, int c)
{
char *str;
str = (char *)s;
while (*str != c)
{
if (*str == '\0')
{
return (NULL);
}
str++;
}
return (str);
}
int check_pref_buff(char **prev_buff, char **line)
{
char *pos;
char *p_prev_buff;
if (*prev_buff)
{
free(*line);
if ((pos = ft_strchr(*prev_buff, '\n')))
{
*pos = '\0';
*line = ft_strdup(*prev_buff);
p_prev_buff = *prev_buff;
pos++;
if (ft_strlen(pos))
{
*prev_buff = ft_strdup(pos);
free(p_prev_buff);
}
else
*prev_buff = NULL;
return (1);
}
*line = ft_strdup(*prev_buff);
free(*prev_buff);
*prev_buff = NULL;
}
return (0);
}
int read_file(int fd, char *buff, char **line, char **prev_buff)
{
char *pos;
int ret;
char *tmp_buff;
while ((ret = read(fd, buff, BUFFER_SIZE)) > 0)
{
buff[ret] = '\0';
if ((pos = ft_strchr(buff, '\n')))
{
*pos = '\0';
tmp_buff = *line;
*line = ft_strjoin(*line, buff);
if (++pos < &buff[ret])
*prev_buff = ft_strdup(pos);
free(tmp_buff);
free(buff);
return (1);
}
tmp_buff = *line;
*line = ft_strjoin(*line, buff);
free(tmp_buff);
}
free(buff);
return (ret < 0 ? -1 : 0);
}
int get_next_line(int fd, char **line)
{
static char *prev_buff = NULL;
char *buff;
int ret_code;
if (fd < 0 || !line || BUFFER_SIZE < 1)
return (-1);
*line = malloc(1);
**line = '\0';
if (check_pref_buff(&prev_buff, line) == 1)
return (1);
buff = malloc(sizeof(char*) * (BUFFER_SIZE) + 1);
if (!buff)
{
free(*line);
*line = NULL;
return (-1);
}
ret_code = read_file(fd, buff, line, &prev_buff);
return (ret_code);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pstrait <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/09 18:37:22 by pstrait #+# #+# */
/* Updated: 2020/12/24 19:05:07 by pstrait ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
size_t ft_strlen(const char *s)
{
size_t count;
count = 0;
while (*s != '\0')
{
s++;
count++;
}
return (count);
}
size_t ft_strlcat(char *dst, const char *src, size_t dstsize)
{
size_t dst_size;
size_t src_size;
size_t total_string_size;
size_t size;
dst_size = ft_strlen(dst);
src_size = ft_strlen(src);
total_string_size = dstsize;
if (!dst || !src)
return ((size_t)NULL);
if (total_string_size <= dst_size)
return (total_string_size + src_size);
dst += dst_size;
size = total_string_size - dst_size - 1;
while (size-- && *src)
{
*dst = *src;
src++;
dst++;
}
*dst = '\0';
return (dst_size + src_size);
}
size_t ft_strlcpy(char *restrict dst, const char *restrict src,
size_t dstsize)
{
size_t i;
unsigned char *psrc;
unsigned char *pdst;
i = 0;
psrc = (unsigned char *)src;
pdst = (unsigned char *)dst;
if (dstsize < 1)
return (ft_strlen(src));
if (!dst || !src)
return ((size_t)NULL);
while (dstsize - 1 && psrc[i])
{
pdst[i] = psrc[i];
dstsize--;
i++;
}
pdst[i] = '\0';
return (ft_strlen(src));
}
char *ft_strjoin(char const *s1, char const *s2)
{
size_t size_st;
char *str;
if (!s1 || !s2)
return (NULL);
size_st = ft_strlen(s1) + ft_strlen(s2) + 1;
str = malloc(size_st);
if (str == NULL)
return (NULL);
ft_strlcpy(str, s1, size_st);
ft_strlcat(str, s2, size_st);
return (str);
}
char *ft_strdup(const char *s1)
{
char *str;
str = malloc(ft_strlen(s1) + 1);
if (str == NULL)
return (0);
ft_strlcpy(str, s1, ft_strlen(s1) + 1);
return (str);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pstrait <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/03 17:53:13 by pstrait #+# #+# */
/* Updated: 2020/12/24 19:04:14 by pstrait ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef GET_NEXT_LINE_H
# define GET_NEXT_LINE_H
# ifndef BUFFER_SIZE
# define BUFFER_SIZE 5
# endif
# include <unistd.h>
# include <fcntl.h>
# include <stdlib.h>
# include <stdio.h> //delete
int get_next_line(int fd, char **line);
size_t ft_strlen(const char *s);
size_t ft_strlcat(char *dst, const char *src, size_t dstsize);
size_t ft_strlcpy(char *restrict dst, const char *restrict src,
size_t dstsize);
char *ft_strjoin(char const *s1, char const *s2);
char *ft_strdup(const char *s1);
#endif
| db18b28a04509e34d430a1e819a1a8aa11d78dd9 | [
"C"
] | 3 | C | 0x64696d61/c_t | d427b740a25b2fac9263ee3886714de5c5298b79 | f67628c2b6a0d7fc7c8b75dbf1032fd200c8de21 | |
refs/heads/master | <file_sep>package dbtLab3;
import java.sql.*;
import java.util.*;
/**
* Database is a class that specifies the interface to the movie database. Uses
* JDBC.
*/
public class Database {
/**
* The database connection.
*/
private Connection conn;
/**
* Create the database interface object. Connection to the database is
* performed later.
*/
public Database() {
conn = null;
}
/**
* Open a connection to the database, using the specified user name and
* password.
*/
public boolean openConnection(String filename) {
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + filename);
} catch (SQLException e) {
e.printStackTrace();
return false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Close the connection to the database.
*/
public void closeConnection() {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Check if the connection to the database has been established
*
* @return true if the connection has been established
*/
public boolean isConnected() {
return conn != null;
}
public boolean userExists(String userId) {
try {
String sql = "SELECT * FROM users WHERE username = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userId);
ResultSet rs = ps.executeQuery();
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public ArrayList<Movie> getMovies() {
ArrayList<Movie> movies = new ArrayList<Movie>();
try {
String sql = "SELECT * FROM movies";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
movies.add(new Movie(rs));
}
return movies;
} catch (SQLException e) {
e.printStackTrace();
}
return movies;
}
public ArrayList<String> getDates(String movieName) {
ArrayList<String> dates = new ArrayList<String>();
try {
String sql = "SELECT date FROM performances WHERE name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, movieName);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
dates.add(rs.getString("date"));
}
return dates;
} catch (SQLException e) {
e.printStackTrace();
}
return dates;
}
public Performance getPerformance(String movieName, String date) {
try {
String sql = "SELECT * FROM performances WHERE name = ? AND date = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, movieName);
ps.setString(2, date);
ResultSet rs = ps.executeQuery();
return new Performance(rs);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public boolean makeReservation(String movieName, String date) {
try {
conn.setAutoCommit(false);
String sql = "SELECT available_seats FROM performances WHERE name = ? AND date = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, movieName);
ps.setString(2, date);
ResultSet rs = ps.executeQuery();
int seats = rs.getInt("available_seats");
if (seats > 0) {
sql = "UPDATE performances SET available_seats = ? WHERE name = ? AND date = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, seats - 1);
ps.setString(2, movieName);
ps.setString(3, date);
ps.executeUpdate();
sql = "INSERT INTO reservations (username, movie_name, date) VALUES (?, ?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, CurrentUser.instance().getCurrentUserId());
ps.setString(2, movieName);
ps.setString(3, date);
ps.executeUpdate();
conn.commit();
return true;
} else {
conn.rollback();
}
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
<file_sep># EDA216 - Database Technology
The labs for the course EDA216 - Database Technology
<file_sep>-- Delete the tables if they exist.
-- Disable foreign key checks, so the tables can
-- be dropped in arbitrary order.
PRAGMA foreign_keys=OFF;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS reservations;
DROP TABLE IF EXISTS performances;
DROP TABLE IF EXISTS movies;
DROP TABLE IF EXISTS theaters;
PRAGMA foreign_keys=ON;
-- Create the tables.
CREATE TABLE users (
username VARCHAR(15),
name TEXT NOT NULL,
address TEXT,
phone_number CHAR(10) NOT NULL,
primary key (username)
);
CREATE TABLE performances (
name TEXT,
date DATE,
theater_name TEXT,
available_seats INTEGER check (available_seats >= 0),
primary key (name, date),
foreign key (name) references movies(name),
foreign key (theater_name) references theaters(name)
);
CREATE TABLE reservations (
reservation_number INTEGER PRIMARY KEY,
username VARCHAR(15),
movie_name TEXT,
date DATE,
foreign key (movie_name, date) references performances(name, date),
foreign key (username) references users(username)
);
CREATE TABLE movies (
name TEXT,
primary key (name)
);
CREATE TABLE theaters (
name TEXT,
seats INTEGER NOT NULL CHECK (seats > 0),
primary key (name)
);
-- Insert data into the tables.
INSERT INTO users (username, name, address, phone_number) VALUES
('andy', 'AndyTruong', 'LTH', 0789456321),
('andy2', 'Andy2', NULL, 0123456789),
('andy3123', 'Andy3', 'dawdaw', 0258695847);
INSERT INTO theaters (name, seats) VALUES
('Royal', 498),
('Filmstaden Entré', 60),
('Filmstaden Storgatan', 63);
INSERT INTO movies (name) VALUES
('<NAME>'),
('Allied'),
('American Pastoral'),
('Arrival'),
('Assassin''s Creed'),
('Bamse och häxans dotter'),
('Cosi fan tutte - opera från Parisoperan'),
('Elle'),
('En alldeles särskild dag - Klassiker'),
('En man som heter Ove'),
('En midommarnattsdröm - balett från Parisoperan'),
('Fifty shades darker'),
('Filmen om Badrock'),
('Fyren mellan haven'),
('Hundraettåringen som smet från notan och försvann'),
('Jackie'),
('Jag, <NAME>'),
('Jätten'),
('La La Land'),
('Lion'),
('Live by night'),
('Manchester by the sea'),
('Marcus & Martinus - Tillsammans mot drömmen'),
('<NAME>appa <NAME>'),
('<NAME>'),
('Passengers'),
('Pettson & Findus - Juligheter'),
('Resident Evil - The Final Chapter'),
('Rings'),
('Rogue One: A Star Wars Story'),
('Sing'),
('Skönheten i allt'),
('Split'),
('The Bye Bye Man'),
('The Handmaiden'),
('The Lego Batman Movie'),
('Trolls'),
('Trubaduren - opera från Royal Opera House'),
('Törnrosa - balett från Royal Opera House'),
('Vaiana'),
('V<NAME>'),
('xXx: The Return of Xander Cage');
INSERT INTO performances (name, date, theater_name, available_seats) VALUES
('La La Land', '2017-02-01', 'Royal', 496),
('La La Land', '2017-02-02', 'Filmstaden Storgatan', 63),
('Jätten', '2017-02-02', 'Filmstaden Storgatan', 63);
INSERT INTO reservations (username, movie_name, date) VALUES
('andy', 'La La Land', '2017-02-01'),
('andy2', 'La La Land', '2017-02-01');
-- And re-enable foreign key checks.
PRAGMA foreign_key = on;
<file_sep>package dbtLab3;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Performance {
public String movie;
public String date;
public String theater;
public int available_seats;
public Performance(ResultSet rs) throws SQLException {
this.movie = rs.getString("name");
this.date = rs.getString("date");
this.theater = rs.getString("theater_name");
this.available_seats = rs.getInt("available_seats");
}
}
| ceef48c6dce662cbc46ea2917c8a85a79ee34979 | [
"Markdown",
"Java",
"SQL"
] | 4 | Java | AndyT94/EDA216-Database_Technology | c717afca4a67b42a366b526e03185e6567cf51f5 | 3057c1b5a41a6fd48eda6b3cbcbf21e13d168141 | |
refs/heads/master | <file_sep># ClippyGen
makes clippy
![Example 1](ClippyExample1.gif?raw=true "Clippy example")
<file_sep>(function ($) {
$.fn.makeClippy = function (settings) {
// add the required html elements
$(this).append('<div id="clippy-container"><div id="clippy-itself"><img src="images/clippy.png" alt="clippy" /></div><div id="clippy-bubble"><div id="clippy-bubble-triangle-border"></div><div id="clippy-bubble-triangle"></div><span id="clippy-text"></span><div id="clippy-options"></div></div></div>');
// use jqueryui to make clippy movable
$("#clippy-container").draggable();
// create a new clippymodel and put it in a variable that is accessible to every man and his dog
clippy = new clippyModel();
return this;
};
}(jQuery));
// a model to persist the status of clippy
var clippyModel = function () {
var self = this;
self.showClippy = false; // the visibility status of your friend and mine, clippy
self.currentText = null; // the text in the speech bubble
self.options = []; // the collection of options (actions/questions) displayed in the speech bubble
self.clickAction = null; // the action, if any, to take when clippy is clicked
self.haveBoundEvents = false; // arg, keep track of whether we've bound the events to our html
self.isDragging = false; // track if we're dragging so we can avoid raising a click event on drags
// allow user to set what happens when clippy is clicked
self.onClick = function (action) {
self.clickAction = action;
};
// allows the user to get clippy to output some text in his speechbubble
self.say = function (contents, options) {
self.currentText = contents;
$("#clippy-text").html(self.currentText);
self.updateOptions(options);
self.showHideSpeechBubble();
if (!self.showClippy) {
self.show();
}
};
// used to updated the options (actions/questions) in the speech bubble
self.updateOptions = function (options) {
if (options) {
self.options = options;
} else {
self.options = [];
}
self.renderOptions();
};
// generates the html for the options
self.renderOptions = function () {
$("#clippy-options").html(null);
for (var i = 0; i < self.options.length; i++) {
var option = self.options[i];
var newOption = '<div id="clippy-option-'+i+'" data-index="'+i+'" class="clippy-option">' + option.text+'</div>';
$("#clippy-options").append(newOption);
$("#clippy-option-" + i).bind("click", function () {
var optionIndex = $(this).data("index");
var action = self.options[optionIndex].action;
action();
});
}
};
// allows the user to close the speech bubble
self.closeBubble = function () {
self.currentText = null;
$("#clippy-text").html(null);
self.showHideSpeechBubble();
};
// shows or hides the speech bubble html based on the status of the model
self.showHideSpeechBubble = function () {
if (self.currentText === null) {
$("#clippy-bubble").hide();
} else {
$("#clippy-bubble").css('display', 'inline-block');
}
};
// shows clippy on the screen
self.show = function (settings) {
settings = settings || {};
var top = settings.top || '100px';
var left = settings.left || '600px';
$("#clippy-container").css({ top: top });
$("#clippy-container").css({ left: left });
self.showClippy = true;
self.updateClippyVisibility();
if (!self.haveBoundEvents) {
self.haveBoundEvents = true;
$("#clippy-itself").bind("mouseup", function (e) {
var actionFunction = function () {
var wasDragging = self.isDragging;
self.isDragging = false;
if (!wasDragging) {
if (self.clickAction) {
self.clickAction();
}
}
}();
$('#clippy-container').css('cursor', 'grab');
});
$("#clippy-itself").bind("mousedown", function (e) {
$('#clippy-container').css('cursor', 'grabbing');
self.isDragging = false;
});
$("#clippy-itself").bind("mousemove", function (e) {
self.isDragging = true;
});
}
};
// allows the user to remove clippy
self.hide = function () {
self.showClippy = false;
self.updateClippyVisibility();
};
// shows or hides the clippy html dependant on the model
self.updateClippyVisibility = function () {
if (self.showClippy) {
$("#clippy-container").css('display', 'inline-block');
} else {
$("#clippy-container").hide();
}
};
};
var clippy = null; | 70704612f08f87f7ef9d3c770a3a0084aa1bed5f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | kelvinperrie/ClippyGen | 210247837b4ee86eeaa697a76da142c4a80504e3 | 6a401988551296c5af8de6bc401b256c51f3315d | |
refs/heads/master | <repo_name>KodeBlockr/Archi2016_Project1<file_sep>/103062143_01/simulator/simulator.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *writeSnapshot;
FILE *writeError;
void add();
void addu();
void sub();
void and();
void or();
void xor();
void nor();
void nand();
void slt();
void sll();
void srl();
void sra();
void jr();
void addi();
void addiu();
void lw();
void lh();
void lhu();
void lb();
void lbu();
void sw();
void sh();
void sb();
void lui();
void andi();
void ori();
void nori();
void slti();
void beq();
void bne();
void bgtz();
void j();
void jal();
void printRegister();
int BigEndian(unsigned int);
unsigned int imemory[5000];
unsigned int carryAddress;
unsigned int temp;
int reg[100], dmemory[5000], num;
int i = 0;
int l, k, halt = 0, tmp, tmpSigned, a, b, c, d, pc, sp, iNum, dNum, opcode;
int funct, rs, rt, rd, iCycle = 0, dCycle = 0, cycle = 0, Cshamt, CimmediateUnsigned;
short Cimmediate;
int main()
{
//Initial
memset(imemory,0,5000);
memset(dmemory,0,5000);
memset(reg,0,100);
FILE *iimage;
FILE *dimage;
//Read File
iimage=fopen("iimage.bin","rb");
dimage=fopen("dimage.bin","rb");
writeSnapshot=fopen("snapshot,rpt","w");
writeError=fopen("error_dump.rpt","w");
fread(&pc,sizeof(int),1,iimage);
pc=BigEndian(pc);
fread(&iNum,sizeof(int),1,iimage);
iNum=BigEndian(iNum);
iCycle=pc;
i=pc;
num=0;
while(num!=iNum){
fread(&imemory[iCycle],sizeof(int),1,iimage);
iCycle=iCycle+4;
num++;
}
fread(®[29],sizeof(int),1,dimage);
reg[29]=BigEndian(reg[29]);
sp=reg[29];
fread(&dNum,sizeof(int),1,dimage);
dNum=BigEndian(dNum);
while(dCycle!=dNum){
fread(&dmemory[dCycle],sizeof(int),1,dimage);
dCycle++;
}
fclose(iimage);
fclose(dimage);
//Print Register
printRegister();
for(i=pc;i<iCycle;i+=4){
imemory[i]=BigEndian(imemory[i]);
}
for(i=0;i<dCycle;i++){
dmemory[i]=BigEndian(dmemory[i]);
}
for(i=pc;i<iCycle;){
cycle++;
opcode=imemory[i]>>26;
funct=(imemory[i]<<26)>>26;
rs=(imemory[i]<<6)>>27;
rt=(imemory[i]<<11)>>27;
rd=(imemory[i]<<16)>>27;
Cshamt=(imemory[i]<<21)>>27;
Cimmediate=((imemory[i]<<16)>>16);
CimmediateUnsigned=Cimmediate&0x0000FFFF;
carryAddress=(imemory[i]<<6)>>6;
i = i+4;
if(opcode==0x00){
if(funct==0x20)add();
else if(funct==0x21)addu();
else if(funct==0x22)sub();
else if(funct==0x24)and();
else if(funct==0x25)or();
else if(funct==0x26)xor();
else if(funct==0x27)nor();
else if(funct==0x28)nand();
else if(funct==0x2A)slt();
else if(funct==0x00)sll();
else if(funct==0x02)srl();
else if(funct==0x03)sra();
else if(funct==0x08)jr();
}
else if(opcode==0x08)addi();
else if(opcode==0x09)addiu();
else if(opcode==0x23)lw();
else if(opcode==0x21)lh();
else if(opcode==0x25)lhu();
else if(opcode==0x20)lb();
else if(opcode==0x24)lbu();
else if(opcode==0x2B)sw();
else if(opcode==0x29)sh();
else if(opcode==0x28)sb();
else if(opcode==0x0F)lui();
else if(opcode==0x0C)andi();
else if(opcode==0x0D)ori();
else if(opcode==0x0E)nori();
else if(opcode==0x0A)slti();
else if(opcode==0x04)beq();
else if(opcode==0x05)bne();
else if(opcode==0x07)bgtz();
else if(opcode==0x02)j();
else if(opcode==0x03)jal();
else if(opcode==0x3F)break;
if(halt==1)break;
//Print Register
printRegister();
}
fclose(writeSnapshot);
fclose(writeError);
}
int BigEndian(unsigned int k){
a=k>>24;
b=((k<<8)>>24)<<8;
c=((k>>8)<<24)>>8;
d=k<<24;
k=a+b+c+d;
return k;
}
void add()
{
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
int regTmp=reg[rs]+reg[rt];
int regTmp_tmp=regTmp>>31;
int rsTmp=reg[rs]>>31;
int rtTmp=reg[rt]>>31;
if((rsTmp==rtTmp)&&(regTmp_tmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
reg[rd]=regTmp;
if(rd==0){
reg[rd]=0;
return;
}
}
void addu(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
int regTemp = reg[rs]+reg[rt];
reg[rd] = regTemp;
if(rd==0){
reg[rd]=0;
return;
}
}
void sub(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
int regTemp=reg[rs]-reg[rt];
int regTemp_Temp=regTemp>>31;
int rsTemp=reg[rs]>>31;
int rtTemp=(0-reg[rt])>>31;
if((rsTemp==rtTemp)&&(regTemp_Temp!=rsTemp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
reg[rd]=regTemp;
if(rd==0){
reg[rd]=0;
return;
}
}
void and(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
reg[rd]=reg[rs]®[rt];
}
void or(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=reg[rs]|reg[rt];
}
void xor(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=reg[rs]^reg[rt];
}
void nor(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=~(reg[rs]|reg[rt]);
}
void nand(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=~(reg[rs]®[rt]);
}
void slt(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=(reg[rs]<reg[rt]);
}
void sll(){
if(rd==0){
if(!(rt==0&&Cshamt==0)){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
}
reg[rd]=reg[rt]<<Cshamt;
}
void srl(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=reg[rt];
for(l=0;l<Cshamt;l++){
reg[rd]=(reg[rd]>>1)&0x7FFFFFFF;
}
}
void sra(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=reg[rt]>>Cshamt;
}
void jr(){
i=reg[rs];
}
void addi(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
int regTemp=reg[rs]+Cimmediate;
int regTemp_Temp=regTemp>>31;
int rsTemp=reg[rs]>>31;
int CTemp=Cimmediate>>15;
if((rsTemp==CTemp)&&(regTemp_Temp!=rsTemp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
reg[rt]=regTemp;
if(rt==0){
reg[rt]=0;
return;
}
}
void addiu(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
int regTemp=reg[rs]+Cimmediate;
int regTemp_Temp=regTemp>>31;
int rsTemp=reg[rs]>>31;
int cTemp=Cimmediate>15;
reg[rt]=regTemp;
if(rt==0){
reg[rt]=0;
return;
}
}
void lw(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
tmp=reg[rs]+Cimmediate;
if((reg[rs]>0&&Cimmediate>0&&tmp<0)||(reg[rs]<0&&Cimmediate<0&&tmp>0)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||(tmp+3<0)||(tmp>1023)||(tmp+3)>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(tmp%4!=0){
fprintf(writeError, "In cycle %d: Misalignment Error\n", cycle);
halt=1;
}
if(halt==1)return;
reg[rt]=dmemory[tmp/4];
if(rt==0){
reg[rt]=0;
return;
}
}
void lh(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
tmp=reg[rs]+Cimmediate;
int tmpTemp=tmp>>31;
int rsTemp=reg[rs]>>31;
int cTemp=Cimmediate>>15;
if((rsTemp==cTemp)&&(tmpTemp!=rsTemp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||(tmp+1<0)||(tmp>1023)||(tmp+1)>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt = 1;
}
if(tmp%2!=0){
fprintf(writeError, "In cycle %d: Misalignment Error\n", cycle);
halt = 1;
}
if(halt==1) return;
if(rt==0){
reg[rt]=0;
return;
}
if(tmp%4==0)tmpSigned=dmemory[tmp/4]>>16;
else if(tmp%4==2)tmpSigned=(dmemory[tmp/4]<<16)>>16;
if(tmpSigned>>15==1)reg[rt]=tmpSigned|0xFFFF0000;
else reg[rt]=tmpSigned;
}
void lhu(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||(tmp+1<0)||(tmp>1023)||(tmp+1)>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(tmp%2!=0){
fprintf(writeError, "In cycle %d: Misalignment Error\n", cycle);
halt=1;
}
if(halt==1)return;
if(rt==0){
reg[rt]=0;
return;
}
temp=dmemory[tmp/4];
if(tmp%4==0)temp=temp>>16;
else if(tmp%4==2)temp=(temp<<16)>>16;
reg[rt]=temp;
}
void lb(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||tmp>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(halt==1)return;
if(rt==0){
reg[rt]=0;
return;
}
if(tmp%4==0)tmpSigned=dmemory[tmp/4]>>24;
else if(tmp%4==1)tmpSigned=(dmemory[tmp/4]<<8)>>24;
else if(tmp%4==2)tmpSigned=(dmemory[tmp/4]<<16)>>24;
else if(tmp%4==3)tmpSigned=(dmemory[tmp/4]<<24)>>24;
if(tmpSigned>>7==1)reg[rt]=tmpSigned|0xFFFFFF00;
else reg[rt]=tmpSigned;
}
void lbu(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||tmp>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(halt==1)return;
if(rt==0){
reg[rt]=0;
return;
}
temp=dmemory[tmp/4];
if(tmp%4==0)temp=temp>>24;
else if(tmp%4==1)temp=(temp<<8)>>24;
else if(tmp%4==2)temp=(temp<<16)>>24;
else if(tmp%4==3)temp=(temp<<24)>>24;
reg[rt]=temp;
}
void sw(){
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||(tmp+3<0)||(tmp>1023)||(tmp+3)>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(tmp%4!=0){
fprintf(writeError, "In cycle %d: Misalignment Error\n", cycle);
halt=1;
}
if(halt==1)return;
dmemory[tmp/4]=reg[rt];
}
void sh(){
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||(tmp+1<0)||(tmp>1023)||(tmp+1)>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(tmp%2!=0){
fprintf(writeError, "In cycle %d: Misalignment Error\n", cycle);
halt=1;
}
if(halt==1)return;
tmpSigned=reg[rt]&0x0000FFFF;
if(tmp%4==0)dmemory[tmp/4]=(dmemory[tmp/4]&0x0000FFFF)+(tmpSigned<<16);
else if(tmp%4==2)dmemory[tmp/4]=(dmemory[tmp/4]&0xFFFF0000)+tmpSigned;
}
void sb(){
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||tmp>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(halt==1)return;
tmpSigned=reg[rt]&0x000000FF;
if(tmp%4==0)dmemory[tmp/4]=(dmemory[tmp/4]&0x00FFFFFF)+(tmpSigned<<24);
else if(tmp%4==1)dmemory[tmp/4]=(dmemory[tmp/4]&0xFF00FFFF)+(tmpSigned<<16);
else if(tmp%4==2)dmemory[tmp/4]=(dmemory[tmp/4]&0xFFFF00FF)+(tmpSigned<<8);
else if(tmp%4==3)dmemory[tmp/4]=(dmemory[tmp/4]&0xFFFFFF00)+tmpSigned;
}
void lui(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
else reg[rt]=(int)(CimmediateUnsigned<<16);
}
void andi(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
else reg[rt]=reg[rs]&CimmediateUnsigned;
}
void ori(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
else reg[rt]=reg[rs]|CimmediateUnsigned;
}
void nori(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
else reg[rt]=~(reg[rs]|CimmediateUnsigned);
}
void slti(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
else reg[rt]=(reg[rs]<Cimmediate);
}
void beq(){
int Cimmediate4=Cimmediate*4;
int pcTmp=i+Cimmediate4;
if((Cimmediate>0&&Cimmediate4<=0)||(Cimmediate<0&&Cimmediate4>=0)||(i>0&&Cimmediate4>0&&pcTmp<0)||(i<0&&Cimmediate4<0&&pcTmp>0)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(reg[rs]==reg[rt])i=pcTmp;
}
void bne(){
int Cimmediate4=Cimmediate*4;
int pcTmp=i+Cimmediate4;
if((Cimmediate>0&&Cimmediate4<=0)||(Cimmediate<0&&Cimmediate4>=0)||(i>0&&Cimmediate4>0&&pcTmp<0)||(i<0&&Cimmediate4<0&&pcTmp>0)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(reg[rs]!=reg[rt])i=pcTmp;
}
void bgtz(){
int Cimmediate4=Cimmediate*4;
int pcTmp=i+Cimmediate4;
if((Cimmediate>0&&Cimmediate4<=0)||(Cimmediate<0&&Cimmediate4>=0)||(i>0&&Cimmediate4>0&&pcTmp<0)||(i<0&&Cimmediate4<0&&pcTmp>0)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(reg[rs]>0)i=pcTmp;
}
void j(){
i=((i>>28)<<28)+carryAddress*4;
}
void jal(){
reg[31]=i;
i=((i>>28)<<28)+carryAddress*4;
}
void printRegister(){
fprintf(writeSnapshot, "cycle %d\n", cycle);
for(k=0;k<32;k++){
fprintf(writeSnapshot, "$%02d: 0x%08X\n",k,reg[k]);
}
fprintf(writeSnapshot, "PC: 0x%08X\n\n\n", i);
}
<file_sep>/103062143_01/simulator/Makefile
CC = gcc -Wall
SRCS = ./*.c
OBS = ./*.o
single_cycle: SRC
$(CC) -o $@ $(OBS)
SRC: $(SRCS)
$(CC) -c $(SRCS)
clean: $(OBS)
rm $(OBS) single_cycle
<file_sep>/103062143_01/simulator/processor.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *writeSnapshot;
FILE *writeError;
void add();
void addu();
void sub();
void and();
void or();
void xor();
void nor();
void nand();
void slt();
void sll();
void srl();
void sra();
void jr();
void addi();
void addiu();
void lw();
void lh();
void lhu();
void lb();
void lbu();
void sw();
void sh();
void sb();
void lui();
void andi();
void ori();
void nori();
void slti();
void beq();
void bne();
void bgtz(); // <--------------------------------------
void j();
void jal();
void printRegister();
int toBigEndian(unsigned int);
unsigned int iMemory[5000],Caddress,tmpp;
int reg[100],dMemory[5000],num;
int i=0,l,k,halt=0,tmp,tmpSigned,a,b,c,d,pc,sp,iNum,dNum,opcode,funct,rs,rt,rd,iCycle=0,dCycle=0,cycle=0,Cshamt,CimmediateUnsigned;
short Cimmediate;
int main()
{
memset(iMemory,0,5000);
memset(dMemory,0,5000);
memset(reg,0,100);
FILE *iimage;
FILE *dimage;
iimage=fopen( "iimage.bin","rb");
dimage=fopen( "dimage.bin","rb");
writeSnapshot=fopen("snapshot.rpt","w");
writeError=fopen("error_dump.rpt","w");
fread(&pc,sizeof(int),1,iimage);
pc=toBigEndian(pc);
fread(&iNum,sizeof(int),1,iimage);
iNum=toBigEndian(iNum);
iCycle=pc;
i=pc;
num=0;
while(num!=iNum){
fread(&iMemory[iCycle],sizeof(int),1,iimage);
iCycle+=4;
num++;
}
fread(®[29],sizeof(int),1,dimage);
reg[29]=toBigEndian(reg[29]);
sp=reg[29];
fread(&dNum,sizeof(int),1,dimage);
dNum=toBigEndian(dNum);
while(dCycle!=dNum){
fread(&dMemory[dCycle],sizeof(int),1,dimage);
dCycle++;
}
fclose(iimage);
fclose(dimage);
//Little-Endian to Big-Endian
printRegister();
for(i=pc;i<iCycle;i+=4){
iMemory[i]=toBigEndian(iMemory[i]);
}
for(i=0;i<dCycle;i++){
dMemory[i]=toBigEndian(dMemory[i]);
}
for(i=pc;i<iCycle;){
cycle++;
opcode=iMemory[i]>>26;
funct=(iMemory[i]<<26)>>26;
rs=(iMemory[i]<<6)>>27;
rt=(iMemory[i]<<11)>>27;
rd=(iMemory[i]<<16)>>27;
Cshamt=(iMemory[i]<<21)>>27;
Cimmediate=((iMemory[i]<<16)>>16);
CimmediateUnsigned=Cimmediate&0x0000FFFF;
Caddress=(iMemory[i]<<6)>>6;
i+=4;
if(opcode==0x00){
if(funct==0x20)add();
else if(funct==0x21)addu(); // <-------------------
else if(funct==0x22)sub();
else if(funct==0x24)and();
else if(funct==0x25)or();
else if(funct==0x26)xor();
else if(funct==0x27)nor();
else if(funct==0x28)nand();
else if(funct==0x2A)slt();
else if(funct==0x00)sll();
else if(funct==0x02)srl();
else if(funct==0x03)sra();
else if(funct==0x08)jr();
}
else if(opcode==0x08)addi();
else if(opcode==0x09)addiu(); // <-----------------
else if(opcode==0x23)lw();
else if(opcode==0x21)lh();
else if(opcode==0x25)lhu();
else if(opcode==0x20)lb();
else if(opcode==0x24)lbu();
else if(opcode==0x2B)sw();
else if(opcode==0x29)sh();
else if(opcode==0x28)sb();
else if(opcode==0x0F)lui();
else if(opcode==0x0C)andi();
else if(opcode==0x0D)ori();
else if(opcode==0x0E)nori();
else if(opcode==0x0A)slti();
else if(opcode==0x04)beq();
else if(opcode==0x05)bne();
else if(opcode==0x07)bgtz(); // <-----------
else if(opcode==0x02)j();
else if(opcode==0x03)jal();
else if(opcode==0x3F)break;
if(halt==1)break;
printRegister();
}
fclose(writeSnapshot);
fclose(writeError);
}
void add(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
int regTmp=reg[rs]+reg[rt];
int regTmpTmp=regTmp>>31;
int rsTmp=reg[rs]>>31;
int rtTmp=reg[rt]>>31;
if((rsTmp==rtTmp)&&(regTmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
reg[rd]=regTmp;
if(rd==0){
reg[rd]=0;
return;
}
}
void addu(){ // <----------------------
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
int regTmp=reg[rs]+reg[rt];
reg[rd]=regTmp;
if(rd==0){
reg[rd] = 0;
return;
}
}
void sub(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
int regTmp=reg[rs]-reg[rt];
int regTmpTmp=regTmp>>31;
int rsTmp=reg[rs]>>31;
int rtTmp=(0-reg[rt])>>31;
if((rsTmp==rtTmp)&&(regTmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
reg[rd]=regTmp;
if(rd==0){
reg[rd]=0;
return;
}
}
void and(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=reg[rs]®[rt];
}
void or(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=reg[rs]|reg[rt];
}
void xor(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=reg[rs]^reg[rt];
}
void nor(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=~(reg[rs]|reg[rt]);
}
void nand(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=~(reg[rs]®[rt]);
}
void slt(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=(reg[rs]<reg[rt]);
}
void sll(){
if(rd==0){
if(!(rt==0&&Cshamt==0)){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
}
reg[rd]=reg[rt]<<Cshamt;
}
void srl(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=reg[rt];
for(l=0;l<Cshamt;l++){
reg[rd]=(reg[rd]>>1)&0x7FFFFFFF;
}
}
void sra(){
if(rd==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
return;
}
reg[rd]=reg[rt]>>Cshamt;
}
void jr(){
i=reg[rs];
}
void addi(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
int regTmp=reg[rs]+Cimmediate;
int regTmpTmp=regTmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(regTmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
reg[rt]=regTmp;
if(rt==0){
reg[rt]=0;
return;
}
}
void addiu(){ // <------------
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
int regTmp=reg[rs]+Cimmediate;
int regTmpTmp=regTmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
/*if((rsTmp==cTmp)&&(regTmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}*/
reg[rt]=regTmp;
if(rt==0){
reg[rt]=0;
return;
}
}
void lw(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
tmp=reg[rs]+Cimmediate;
if((reg[rs]>0&&Cimmediate>0&&tmp<0)||(reg[rs]<0&&Cimmediate<0&&tmp>0)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||(tmp+3<0)||(tmp>1023)||(tmp+3)>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(tmp%4!=0){
fprintf(writeError, "In cycle %d: Misalignment Error\n", cycle);
halt=1;
}
if(halt==1)return;
reg[rt]=dMemory[tmp/4];
if(rt==0){
reg[rt]=0;
return;
}
}
void lh(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||(tmp+1<0)||(tmp>1023)||(tmp+1)>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(tmp%2!=0){
fprintf(writeError, "In cycle %d: Misalignment Error\n", cycle);
halt=1;
}
if(halt==1)return;
if(rt==0){
reg[rt]=0;
return;
}
if(tmp%4==0)tmpSigned=dMemory[tmp/4]>>16;
else if(tmp%4==2)tmpSigned=(dMemory[tmp/4]<<16)>>16;
if(tmpSigned>>15==1)reg[rt]=tmpSigned|0xFFFF0000;
else reg[rt]=tmpSigned;
}
void lhu(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||(tmp+1<0)||(tmp>1023)||(tmp+1)>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(tmp%2!=0){
fprintf(writeError, "In cycle %d: Misalignment Error\n", cycle);
halt=1;
}
if(halt==1)return;
if(rt==0){
reg[rt]=0;
return;
}
tmpp=dMemory[tmp/4];
if(tmp%4==0)tmpp=tmpp>>16;
else if(tmp%4==2)tmpp=(tmpp<<16)>>16;
reg[rt]=tmpp;
}
void lb(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||tmp>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(halt==1)return;
if(rt==0){
reg[rt]=0;
return;
}
if(tmp%4==0)tmpSigned=dMemory[tmp/4]>>24;
else if(tmp%4==1)tmpSigned=(dMemory[tmp/4]<<8)>>24;
else if(tmp%4==2)tmpSigned=(dMemory[tmp/4]<<16)>>24;
else if(tmp%4==3)tmpSigned=(dMemory[tmp/4]<<24)>>24;
if(tmpSigned>>7==1)reg[rt]=tmpSigned|0xFFFFFF00;
else reg[rt]=tmpSigned;
}
void lbu(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||tmp>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(halt==1)return;
if(rt==0){
reg[rt]=0;
return;
}
tmpp=dMemory[tmp/4];
if(tmp%4==0)tmpp=tmpp>>24;
else if(tmp%4==1)tmpp=(tmpp<<8)>>24;
else if(tmp%4==2)tmpp=(tmpp<<16)>>24;
else if(tmp%4==3)tmpp=(tmpp<<24)>>24;
reg[rt]=tmpp;
}
void sw(){
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||(tmp+3<0)||(tmp>1023)||(tmp+3)>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(tmp%4!=0){
fprintf(writeError, "In cycle %d: Misalignment Error\n", cycle);
halt=1;
}
if(halt==1)return;
dMemory[tmp/4]=reg[rt];
}
void sh(){
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||(tmp+1<0)||(tmp>1023)||(tmp+1)>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(tmp%2!=0){
fprintf(writeError, "In cycle %d: Misalignment Error\n", cycle);
halt=1;
}
if(halt==1)return;
tmpSigned=reg[rt]&0x0000FFFF;
if(tmp%4==0)dMemory[tmp/4]=(dMemory[tmp/4]&0x0000FFFF)+(tmpSigned<<16);
else if(tmp%4==2)dMemory[tmp/4]=(dMemory[tmp/4]&0xFFFF0000)+tmpSigned;
}
void sb(){
tmp=reg[rs]+Cimmediate;
int tmpTmp=tmp>>31;
int rsTmp=reg[rs]>>31;
int cTmp=Cimmediate>>15;
if((rsTmp==cTmp)&&(tmpTmp!=rsTmp)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(tmp<0||tmp>1023){
fprintf(writeError, "In cycle %d: Address Overflow\n", cycle);
halt=1;
}
if(halt==1)return;
tmpSigned=reg[rt]&0x000000FF;
if(tmp%4==0)dMemory[tmp/4]=(dMemory[tmp/4]&0x00FFFFFF)+(tmpSigned<<24);
else if(tmp%4==1)dMemory[tmp/4]=(dMemory[tmp/4]&0xFF00FFFF)+(tmpSigned<<16);
else if(tmp%4==2)dMemory[tmp/4]=(dMemory[tmp/4]&0xFFFF00FF)+(tmpSigned<<8);
else if(tmp%4==3)dMemory[tmp/4]=(dMemory[tmp/4]&0xFFFFFF00)+tmpSigned;
}
void lui(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
else reg[rt]=(int)(CimmediateUnsigned<<16);
}
void andi(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
else reg[rt]=reg[rs]&CimmediateUnsigned;
}
void ori(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
else reg[rt]=reg[rs]|CimmediateUnsigned;
}
void nori(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
else reg[rt]=~(reg[rs]|CimmediateUnsigned);
}
void slti(){
if(rt==0){
fprintf(writeError, "In cycle %d: Write $0 Error\n", cycle);
}
else reg[rt]=(reg[rs]<Cimmediate);
}
void beq(){
int Cimmediate4=Cimmediate*4;
int pcTmp=i+Cimmediate4;
if((Cimmediate>0&&Cimmediate4<=0)||(Cimmediate<0&&Cimmediate4>=0)||(i>0&&Cimmediate4>0&&pcTmp<0)||(i<0&&Cimmediate4<0&&pcTmp>0)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(reg[rs]==reg[rt])i=pcTmp;
}
void bne(){
int Cimmediate4=Cimmediate*4;
int pcTmp=i+Cimmediate4;
if((Cimmediate>0&&Cimmediate4<=0)||(Cimmediate<0&&Cimmediate4>=0)||(i>0&&Cimmediate4>0&&pcTmp<0)||(i<0&&Cimmediate4<0&&pcTmp>0)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(reg[rs]!=reg[rt])i=pcTmp;
}
void bgtz(){
int Cimmediate4=Cimmediate*4;
int pcTmp=i+Cimmediate4;
if((Cimmediate>0&&Cimmediate4<=0)||(Cimmediate<0&&Cimmediate4>=0)||(i>0&&Cimmediate4>0&&pcTmp<0)||(i<0&&Cimmediate4<0&&pcTmp>0)){
fprintf(writeError, "In cycle %d: Number Overflow\n", cycle);
}
if(reg[rs]>0)i=pcTmp;
}
void j(){
i=((i>>28)<<28)+Caddress*4;
}
void jal(){
reg[31]=i;
i=((i>>28)<<28)+Caddress*4;
}
void printRegister(){
fprintf(writeSnapshot, "cycle %d\n", cycle);
for(k=0;k<32;k++){
fprintf(writeSnapshot, "$%02d: 0x%08X\n",k,reg[k]);
}
fprintf(writeSnapshot, "PC: 0x%08X\n\n\n", i);
}
int toBigEndian(unsigned int k){
a=k>>24;
b=((k<<8)>>24)<<8;
c=((k>>8)<<24)>>8;
d=k<<24;
k=a+b+c+d;
return k;
}
| 0d50c7643a82091a0cccd3e0731a75d5a03193da | [
"C",
"Makefile"
] | 3 | C | KodeBlockr/Archi2016_Project1 | cfb370f95edc02567ddb1b435c1e52d77cb04815 | edc9b1046dc5921bba8331083f38fb1aa234bb4c | |
refs/heads/master | <file_sep>import {Component, OnInit} from '@angular/core';
import {concat, interval, merge, of} from 'rxjs';
import {map} from 'rxjs/operators';
import {createHttpObservable} from '../common/util';
@Component({
selector: 'about',
templateUrl: './about.component.html',
styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {
ngOnInit() {
const source1$ = of(1, 2, 3);
const source2$ = of(4, 5, 6);
const source3$ = of(7, 8, 9);
const result$ = concat(source1$, source2$, source3$);
result$.subscribe(console.log);
const interval1 = interval(1000);
const interval2 = interval1.pipe(map(val => val * 10));
const merge$ = merge(interval1, interval2);
const sub = merge$.subscribe(console.log);
setTimeout(() => sub.unsubscribe(), 3000);
const http$ = createHttpObservable('/api/courses');
const sub2 = http$.subscribe(console.log);
setTimeout(() => sub2.unsubscribe());
}
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {Course} from '../model/course';
import {Observable, throwError, timer} from 'rxjs';
import {catchError, delayWhen, finalize, map, retryWhen, shareReplay} from 'rxjs/operators';
import {createHttpObservable} from '../common/util';
import {Store} from '../common/store.service';
@Component({
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
beginnerCourses$: Observable<Course[]>;
advancedCourses$: Observable<Course[]>;
constructor(private store: Store) {
}
ngOnInit() {
const http$ = createHttpObservable('/api/courses');
const courses$ = http$.pipe(
// catchError(err => {
// console.log('error happened', err);
// return throwError(err);
// }),
// finalize get executed when the observable completes or errors out
// finalize(() => {
// console.log('finalized ...');
// }),
map(response => response['payload']),
shareReplay(),
retryWhen(errors => {
return errors.pipe(
delayWhen(() => timer(2000))
);
})
// 1.catch and replace: catchError(err => of([])) // catch error and return empty list of courses
// 2. catch and rethrow and finalize
);
this.beginnerCourses$ = courses$.pipe(
map((courses: Course[]) =>
courses.filter(course => course.category === 'BEGINNER')
));
this.advancedCourses$ = courses$.pipe(
map((courses: Course[]) =>
courses.filter(course => course.category === 'ADVANCED'))
);
}
}
| ac3fe7d9d4fb367fef95c982762fdcafe998de0e | [
"TypeScript"
] | 2 | TypeScript | andiausrust/rxjs-ang-univ | 641ed3ed5131ad35c74fe95dcf5ea317840e7fe8 | 4e2e64cab2519a2a2d5c1c68706c516406531c70 | |
refs/heads/master | <file_sep>using CardWorkbench.Models;
using DevExpress.Mvvm;
using DevExpress.Mvvm.UI;
using DevExpress.Xpf.Core.Native;
using DevExpress.Xpf.Editors;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.LayoutControl;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
namespace CardWorkbench.ViewModels.CommonTools
{
public class FrameDumpViewModel : ViewModelBase
{
//Button名称
public readonly string BUTTON_PLAY_FRAMEDATA_NAME = "startFrameData_btn";
public readonly string BUTTON_RECORD_FRAMEDATA_NAME = "recordFrameData_btn";
//Button Image控件名称
public readonly string IMAGE_PLAY_FRAMEDATA_NAME = "playFrameDataImg";
public readonly string IMAGE_RECORD_FRAMEDATA_NAME = "recordFrameDataImg";
//Image资源路径
public readonly string PATH_IMAGE_PLAY_PAUSE = "/Images/play/pause.png";
public readonly string PATH_IMAGE_PLAY_PLAY = "/Images/play/play.png";
public readonly string PATH_IMAGE_PLAY_RECORD = "/Images/play/record.png";
public readonly string PATH_IMAGE_PLAY_RECORDING = "/Images/play/recording.png";
//按钮提示文本
public readonly string TOOLTIP_BUTTON_PLAY_FRAMEDATA = "开始";
public readonly string TOOLTIP_BUTTON_PAUSE_FRAMEDATA = "暂停";
public readonly string TOOLTIP_BUTTON_RECORD_FRAMEDATA = "记录";
public readonly string TOOLTIP_BUTTON_STOP_RECORD_FRAMEDATA = "停止记录";
//FRAMEData的Grid名称
public readonly string GRID_FRAMEDATA_NAME = "frameGrid";
//显示"当前时间"的textbox名称
public readonly string TEXTBOX_CURRENTTIME_NAME = "currentTimeTextbox";
//模式切换下拉框名称
public readonly string COMBOBOX_CHANGEMODEL_NAME = "modeChangeComboBox";
//模式切换下拉选项名称
public readonly string COMBOBOX_CHANGEMODEL_REALTIME = "实时";
public readonly string COMBOBOX_CHANGEMODEL_PLAYBACK = "回放";
//回放设置组名称
public readonly string LAYOUTGROUP_PLAYBACK_NAME = "playBack_setting_group";
//回放时间显示panel名称
public readonly string PANEL_RECORDTIME_NAME = "recordTimePanel";
//回放时间显示image名称
public readonly string IMAGE_RECORDTIME_NAME = "recordTimeImage";
//回放时间显示文本名称
public readonly string TEXTBLOCK_RECORDTIME_NAME = "recordTimeText";
private DispatcherTimer record_timer = null; //记录数据时的timer
private DateTime startTime; //记录数据时的起始时间
private TimeSpan timePassed, timeSinceLastStop; //记录间隔时间,自上次记录停止的间隔时间(暂时没用到)
private TextBlock recordTimeText; //记录时间显示文本
private DispatcherTimer timer = new DispatcherTimer(); //模拟grid数据刷新的timer
GridControl frameDataGrid = null;
int frameNum = 9; //临时子帧号
int fullFrameCount = 0; //已接收的全帧个数
int updateRowCount = 0; //更新的行
int filterTempRow = 0; //筛选后的更新行
bool isTimerPause = false; //刷新计时器是否暂停
string filterFrameID = "ALL"; //筛选子帧ID的临时变量
bool isReset = false; //是否重置接收数据
//获得文件选择对话框服务
public IOpenFileDialogService OpenFileDialogService { get { return GetService<IOpenFileDialogService>(); } }
//获得保存文件对话框服务
public ISaveFileDialogService SaveFileDialogService { get { return GetService<ISaveFileDialogService>(); } }
/// <summary>
/// 原始帧显示模块打开加载后执行命令
/// </summary>
public ICommand frameDumpLoadedCommand {
get { return new DelegateCommand<RoutedEventArgs>(onframeDumpLoaded, x => { return true; }); }
}
private void onframeDumpLoaded(RoutedEventArgs e)
{
FrameworkElement root = LayoutHelper.GetTopLevelVisual(e.Source as DependencyObject);
StackPanel recordTimeTextPanel = LayoutHelper.FindElementByName(root, PANEL_RECORDTIME_NAME) as StackPanel;
TextBox currentTimeTextbox = recordTimeTextPanel.FindName(TEXTBOX_CURRENTTIME_NAME) as TextBox;
DispatcherTimer _timer = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 1), DispatcherPriority.Normal, delegate
{
currentTimeTextbox.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
}, currentTimeTextbox.Dispatcher);
}
/// <summary>
/// 点击“开始”接收或播放数据命令
/// </summary>
public ICommand startFrameDataCommand
{
get { return new DelegateCommand<RoutedEventArgs>(onStartFrameDataClick, x => { return true; }); }
}
private void onStartFrameDataClick(RoutedEventArgs e)
{
//获得必要的界面对象
ToggleButton startFrameData_btn = e.Source as ToggleButton;
FrameworkElement root = LayoutHelper.GetTopLevelVisual(startFrameData_btn as DependencyObject);
ToggleButton recordFrameDataButton = LayoutHelper.FindElementByName(root, BUTTON_RECORD_FRAMEDATA_NAME) as ToggleButton;
Image playFrameDataImg = startFrameData_btn.FindName(IMAGE_PLAY_FRAMEDATA_NAME) as Image;
Image recordFrameDataImg = recordFrameDataButton.FindName(IMAGE_RECORD_FRAMEDATA_NAME) as Image;
Image recordFlashImage = LayoutHelper.FindElementByName(root, IMAGE_RECORDTIME_NAME) as Image;
StackPanel recordTimeTextPanel = LayoutHelper.FindElementByName(root, PANEL_RECORDTIME_NAME) as StackPanel;
ComboBoxEdit comboBox = LayoutHelper.FindElementByName(root, COMBOBOX_CHANGEMODEL_NAME) as ComboBoxEdit;
string modeComboBoxValue = comboBox.EditValue as string;
frameDataGrid = (GridControl)LayoutHelper.FindElementByName(root, GRID_FRAMEDATA_NAME);
if (startFrameData_btn.IsChecked == true) //开始播放
{
//更改按钮外观
playFrameDataImg.Source = new BitmapImage(new Uri(PATH_IMAGE_PLAY_PAUSE, UriKind.Relative));
startFrameData_btn.ToolTip = TOOLTIP_BUTTON_PAUSE_FRAMEDATA;
//当前模式是实时时记录按钮可点击
if (COMBOBOX_CHANGEMODEL_REALTIME.Equals(modeComboBoxValue))
{
recordFrameDataButton.IsEnabled = true;
}
//新建一个线程去更新datagrid
//List<FrameModel> row_lst = frameDataGrid.ItemsSource as List<FrameModel>;
//foreach (FrameModel rowModel in row_lst)
//{
// UpdateFrameGridWorker thread_worker = new UpdateFrameGridWorker(rowModel);
// Thread workerThread = new Thread(thread_worker.DoWork);
// workerThread.Start();
// thread_worker.DoWork();
//}
timer.Interval = TimeSpan.FromMilliseconds(500);
if (!isTimerPause)
{
timer.Tick += new EventHandler(doWork);
}
timer.Start();
}
else //暂停播放
{
//还原按钮外观
playFrameDataImg.Source = new BitmapImage(new Uri(PATH_IMAGE_PLAY_PLAY, UriKind.Relative));
startFrameData_btn.ToolTip = TOOLTIP_BUTTON_PLAY_FRAMEDATA;
//如果正在记录则需停止记录
if (recordFrameDataButton.IsChecked == true)
{
stopRecordFrameData(recordFrameDataButton, recordFrameDataImg, recordFlashImage, recordTimeTextPanel);
}
recordFrameDataButton.IsEnabled = false; //记录按钮不可用
//控制刷新计时器
timer.Stop();
isTimerPause = true; //暂停刷新
}
}
/// <summary>
/// "记录"数据按钮命令
/// </summary>
public ICommand recordFrameDataCommand
{
get { return new DelegateCommand<RoutedEventArgs>(onRecordFrameDataClick, x => { return true; }); }
}
private void onRecordFrameDataClick(RoutedEventArgs e)
{
ToggleButton recordFrameData_btn = e.Source as ToggleButton;
Image recordFrameDataImg = recordFrameData_btn.FindName(IMAGE_RECORD_FRAMEDATA_NAME) as Image;
FrameworkElement root = LayoutHelper.GetTopLevelVisual(recordFrameData_btn as DependencyObject);
StackPanel recordTimeTextPanel = LayoutHelper.FindElementByName(root, PANEL_RECORDTIME_NAME) as StackPanel;
Image recordFlashImage = recordTimeTextPanel.FindName(IMAGE_RECORDTIME_NAME) as Image;
recordTimeText = recordTimeTextPanel.FindName(TEXTBLOCK_RECORDTIME_NAME) as TextBlock;
if (recordFrameData_btn.IsChecked == true) //开始记录
{
//TODO 需要判断 1.当前是否有支持记录的设备 2.当前是否开始已开始运行实时数据
//更改按钮外观
recordFrameDataImg.Source = new BitmapImage(new Uri(PATH_IMAGE_PLAY_RECORDING, UriKind.Relative));
recordFrameData_btn.ToolTip = TOOLTIP_BUTTON_STOP_RECORD_FRAMEDATA;
//显示记录时间,开始动画
recordTimeTextPanel.Visibility = Visibility.Visible;
DoubleAnimation da = new DoubleAnimation();
da.From = 1;
da.To = 0.2;
da.RepeatBehavior = RepeatBehavior.Forever;
da.AutoReverse = true;
da.Duration = TimeSpan.FromMilliseconds(500);
recordFlashImage.BeginAnimation(TextBlock.OpacityProperty, da);
//开始记录,启动记录时间文本的定时器
record_timer = new DispatcherTimer();
record_timer.Tick += record_timer_tick;
record_timer.Interval = new TimeSpan(0, 0, 0, 0, 1);
startTime = DateTime.Now;
record_timer.Start();
}
else
{
//停止记录
stopRecordFrameData(recordFrameData_btn, recordFrameDataImg, recordFlashImage, recordTimeTextPanel);
//恢复记录按钮状态
recordFrameData_btn.IsEnabled = true;
}
}
/// <summary>
/// 设置时间文本的handle函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void record_timer_tick(object sender, object e) {
timePassed = DateTime.Now - startTime;
recordTimeText.Text = convertNumberString((timeSinceLastStop + timePassed).Hours) + ":"
+ convertNumberString((timeSinceLastStop + timePassed).Minutes) + ":"
+ convertNumberString((timeSinceLastStop + timePassed).Seconds) + "."
+ convertNumberString((timeSinceLastStop + timePassed).Milliseconds);
}
/// <summary>
/// 时间值(时分秒)文本转换,转换数字为两位数文本
/// </summary>
/// <param name="number">时分秒数值</param>
/// <returns>时分秒文本</returns>
private string convertNumberString(int number) {
string result;
if (number < 10)
{
result = "0" + number;
return result;
}
result = number.ToString();
return result;
}
/// <summary>
/// 停止记录数据
/// </summary>
/// <param name="recordFrameDataButton">记录数据按钮对象</param>
/// <param name="recordFrameDataImg">记录数据按钮图标</param>
/// <param name="recordFlashImage">记录数据时显示的图片</param>
/// <param name="recordTimeTextPanel">记录数据时显示的panel</param>
private void stopRecordFrameData(ToggleButton recordFrameDataButton, Image recordFrameDataImg, Image recordFlashImage, StackPanel recordTimeTextPanel)
{
//停止记录计时
if (record_timer != null)
{
record_timer.Stop();
record_timer = null;
}
else
{
return; //当前没有记录数据则退出
}
//重置记录按钮状态
recordFrameDataButton.IsChecked = false;
//还原按钮外观
recordFrameDataImg.Source = new BitmapImage(new Uri(PATH_IMAGE_PLAY_RECORD, UriKind.Relative));
recordFrameDataButton.ToolTip = TOOLTIP_BUTTON_RECORD_FRAMEDATA;
//弹出记录文件“另存为...”对话框
SaveFileDialogService.Filter = "数据文件|*.dat"; ;
SaveFileDialogService.FilterIndex = 1;
bool saveResult = SaveFileDialogService.ShowDialog();
if (saveResult)
{
//TODO 写入数据文件
MessageBox.Show("保存成功");
}
//结束动画,隐藏记录时间
recordFlashImage.BeginAnimation(TextBlock.OpacityProperty, null);
recordTimeTextPanel.Visibility = Visibility.Hidden;
}
private void doWork(object sender, EventArgs e)
{
List<FrameModel> row_lst = frameDataGrid.ItemsSource as List<FrameModel>;
//开始更新datagrid
// foreach (FrameModel rowModel in row_lst.OrderBy(rowModel => rowModel.FrameID))
frameDataGrid.Dispatcher.BeginInvoke(new Action(() =>
{
if (frameNum % row_lst.Count == 1 ) //翻页
{
updateRowCount = 0; //还原成更新第一行
isReset = false; //还原重置标记
fullFrameCount += 1; //接收到全帧数递增1
}
if (isReset)
{
updateRowCount = 0; //还原成更新第一行
isReset = false; //还原重置标记
}
if ("ALL".Equals(this.filterFrameID))
{
int ID = updateRowCount+1;
row_lst[updateRowCount] = new FrameModel() { FrameID = frameNum, SyncWord = "EB101", Word1 = "FF"+frameNum, Word2 = "FFF", Word3 = "FF"+frameNum, ID = ID + "", Word5 = "FFFF", Word6 = "FFFF", Word7 = "FFFF", Word8 = "FFFF", Word9 = "FFFF", Word10 = "FFFF", Word11 = "FFFF", Word12 = "FFFF" };
frameDataGrid.RefreshRow(updateRowCount);
}
else
{
int result = int.Parse(this.filterFrameID);
//Console.WriteLine("result:" + result);
//Console.WriteLine("frameNum:" + frameNum);
//Console.WriteLine("fullFrameCount:" + fullFrameCount);
if (frameNum == result || frameNum == result + row_lst.Count * fullFrameCount) //所有是过滤值的才更新
{
if (filterTempRow % row_lst.Count == 0)
{
filterTempRow = 0;
}
//Console.WriteLine("update row:"+updateRowCount);
row_lst[filterTempRow] = new FrameModel() { FrameID = frameNum, SyncWord = "EB101", Word1 = "FF" + frameNum, Word2 = "FFF", Word3 = "FF" + frameNum, ID = result + "", Word5 = "FFFF", Word6 = "FFFF", Word7 = "FFFF", Word8 = "FFFF", Word9 = "FFFF", Word10 = "FFFF", Word11 = "FFFF", Word12 = "FFFF" };
frameDataGrid.RefreshRow(filterTempRow);
filterTempRow++;
}
}
updateRowCount++;
frameNum++;
}));
}
/// <summary>
/// 过滤子帧号命令
/// </summary>
public ICommand filterFrameIDCommand {
get { return new DelegateCommand<RoutedEventArgs>(onfilterFrameIDChanged, x => { return true; }); }
}
private void onfilterFrameIDChanged(RoutedEventArgs e) {
ComboBoxEdit comboBox = e.Source as ComboBoxEdit;
string filterId = comboBox.EditValue as string;
filterFrameID = filterId;
isReset = true;
}
/// <summary>
/// 设置当前模式命令
/// </summary>
public ICommand changeModelCommand
{
get { return new DelegateCommand<RoutedEventArgs>(onChangeModel, x => { return true; }); }
}
private void onChangeModel(RoutedEventArgs e)
{
//TODO 1. 如有数据,则先停止暂停当前的数据播放
//2.切换模式
ComboBoxEdit comboBox = e.Source as ComboBoxEdit;
string model = comboBox.EditValue as string;
FrameworkElement root = LayoutHelper.GetTopLevelVisual(comboBox as DependencyObject);
LayoutGroup playBackSettingGroup = LayoutHelper.FindElementByName(root, LAYOUTGROUP_PLAYBACK_NAME) as LayoutGroup;
ToggleButton recordFrameDataBtn = LayoutHelper.FindElementByName(root, BUTTON_RECORD_FRAMEDATA_NAME) as ToggleButton;
ToggleButton startFrameData_btn = LayoutHelper.FindElementByName(root, BUTTON_PLAY_FRAMEDATA_NAME) as ToggleButton;
Image playFrameDataImg = startFrameData_btn.FindName(IMAGE_PLAY_FRAMEDATA_NAME) as Image;
Image recordFrameDataImg = recordFrameDataBtn.FindName(IMAGE_RECORD_FRAMEDATA_NAME) as Image;
Image recordFlashImage = LayoutHelper.FindElementByName(root, IMAGE_RECORDTIME_NAME) as Image;
StackPanel recordTimeTextPanel = LayoutHelper.FindElementByName(root, PANEL_RECORDTIME_NAME) as StackPanel;
if (COMBOBOX_CHANGEMODEL_REALTIME.Equals(model)) //实时模式
{
//回放设置不可见
playBackSettingGroup.IsEnabled = false;
playBackSettingGroup.IsCollapsed = true;
}
else if (COMBOBOX_CHANGEMODEL_PLAYBACK.Equals(model)) //回放模式
{
//回放设置可见
playBackSettingGroup.IsEnabled = true;
playBackSettingGroup.IsCollapsed = false;
}
//暂停接收数据,如当前正在记录则弹出保存对话框
pauseReceiveFrameData(startFrameData_btn, recordFrameDataBtn, playFrameDataImg, recordFrameDataImg,recordFlashImage, recordTimeTextPanel);
//还原“播放”按钮状态
startFrameData_btn.IsChecked = false;
}
/// <summary>
/// 暂停接收数据,更改按钮状态。如当前正在记录则弹出保存对话框
/// </summary>
/// <param name="startFrameData_btn">播放数据按钮对象</param>
/// <param name="recordFrameDataButton">记录数据按钮对象</param>
/// <param name="playFrameDataImg">播放数据按钮图标</param>
/// <param name="recordFrameDataImg">记录数据按钮图标</param>
/// <param name="recordFlashImage">记录时间文本图标</param>
/// <param name="recordTimeTextPanel">记录时间panel</param>
private void pauseReceiveFrameData(ToggleButton startFrameData_btn, ToggleButton recordFrameDataButton, Image playFrameDataImg, Image recordFrameDataImg, Image recordFlashImage, StackPanel recordTimeTextPanel)
{
//如果正在接收数据,还原“播放”按钮状态和外观
if (startFrameData_btn.IsChecked == true)
{
//还原“播放”按钮状态和外观
playFrameDataImg.Source = new BitmapImage(new Uri(PATH_IMAGE_PLAY_PLAY, UriKind.Relative));
startFrameData_btn.ToolTip = TOOLTIP_BUTTON_PLAY_FRAMEDATA;
//TODO 暂停播放数据
//----临时停止刷新计时器----
timer.Stop();
isTimerPause = true; //暂停刷新
//-----
}
//如果正在记录数据,提示另存为,隐藏记录时间文本
if (recordFrameDataButton.IsChecked == true)
{
stopRecordFrameData(recordFrameDataButton, recordFrameDataImg, recordFlashImage, recordTimeTextPanel);
}
recordFrameDataButton.IsEnabled = false; //重置记录按钮状态
}
/// <summary>
/// 选择回放文件按钮命令
/// </summary>
public ICommand selectPlayBackDatafileCommand
{
get { return new DelegateCommand<RoutedEventArgs>(onSelectPlayBackDatafile, x => { return true; }); }
}
private void onSelectPlayBackDatafile(RoutedEventArgs e)
{
Button buttonInfo = e.Source as Button;
ButtonEdit be = LayoutHelper.FindLayoutOrVisualParentObject<ButtonEdit>(buttonInfo as DependencyObject);
if (be == null)
return;
//System.Windows.Forms.FileDialog dialog = new System.Windows.Forms.OpenFileDialog();
//if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
//{
// be.EditValue = dialog.FileName;
//}
OpenFileDialogService.Filter = "数据文件|*.dat";
OpenFileDialogService.FilterIndex = 1;
bool DialogResult = OpenFileDialogService.ShowDialog();
if (DialogResult)
{
IFileInfo file = OpenFileDialogService.Files.First();
be.EditValue = file.Name;
}
}
}
//子线程刷新
//public class UpdateFrameGridWorker
//{
// List<FrameModel> row_lst;
// GridControl frameDataGrid;
// public UpdateFrameGridWorker(List<FrameModel> row_lst, GridControl frameDataGrid)
// {
// this.row_lst = row_lst;
// this.frameDataGrid = frameDataGrid;
// }
// public void DoWork()
// {
// //开始更新datagrid
// // foreach (FrameModel rowModel in row_lst.OrderBy(rowModel => rowModel.FrameID))
// frameDataGrid.Dispatcher.BeginInvoke(new Action(() =>
// {
// for (int i = 0; i < row_lst.Count; i++)
// {
// row_lst[i] = new FrameModel() { FrameID = 9, SyncWord = "EB101", Word1 = "FFFF", Word2 = "FFF", Word3 = "FFFF", ID = 9 + "", Word5 = "FFFF", Word6 = "FFFF", Word7 = "FFFF", Word8 = "FFFF", Word9 = "FFFF", Word10 = "FFFF", Word11 = "FFFF", Word12 = "FFFF" };
// frameDataGrid.RefreshRow(i);
// }
// }));
// //row.ItemArray = new object[] { 9, "EB101", "FFFF", "FFFF", "FFFF", 9 + "", "FFFF", "FFFF", "FFFF", "FFFF", "FFFF", "FFFF", "FFFF", "FFFF" };
// }
// public void RequestStop()
// {
// _shouldStop = true;
// }
// // Volatile is used as hint to the compiler that this data
// // member will be accessed by multiple threads.
// private volatile bool _shouldStop;
//}
//事件发生前转换类
//public class StartFrameDataBtnClickEventArgsConverter : EventArgsConverterBase<RoutedEventArgs>
//{
// //按钮文本常量
// public readonly string BUTTON_CONTENT_START = "开始";
// public readonly string BUTTON_CONTENT_STOP = "停止";
// protected override object Convert(RoutedEventArgs args)
// {
// GridControl frameDataGrid = null;
// ToggleButton startFrameData_btn = args.Source as ToggleButton;
// FrameworkElement root = LayoutHelper.GetTopLevelVisual(startFrameData_btn as DependencyObject);
// frameDataGrid = (GridControl)LayoutHelper.FindElementByName(root, "frameGrid");
// if (startFrameData_btn.IsChecked == true)
// {
// startFrameData_btn.Content = BUTTON_CONTENT_STOP;
// //frameDataGrid.ItemsSource = FrameTestCase.generateData();
// }
// else {
// startFrameData_btn.Content = BUTTON_CONTENT_START;
// }
// return frameDataGrid;
// }
//}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CardWorkbench.Views.CommonTools;
using CardWorkbench.Views.CommonControls;
using CardWorkbench.Views.MenuControls;
using DevExpress.Xpf.NavBar;
using DevExpress.Xpf.Ribbon;
using CardWorkbench.Utils;
namespace CardWorkbench
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : DXRibbonWindow
{
public MainWindow()
{
InitializeComponent();
new NavBarDragDropHelper(toolBoxNavBar); //注册右侧导航工具栏可拖动
}
}
}
<file_sep>using DevExpress.Xpf.Core.Native;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace CardWorkbench.Utils
{
/// <summary>
/// 界面UI控件工具类
/// </summary>
public class UIControlHelper
{
/// <summary>
/// 使点击的控件在容器中置顶
/// </summary>
/// <param name="e">鼠标点击event参数</param>
/// <param name="containerName">容器名称</param>
public static void setClickedUserControl2TopIndex(MouseButtonEventArgs e,string containerName)
{
UserControl parentControl = LayoutHelper.FindParentObject<UserControl>(e.Source as DependencyObject);
FrameworkElement root = LayoutHelper.GetTopLevelVisual(e.Source as DependencyObject);
Canvas workCanvas = (Canvas)LayoutHelper.FindElementByName(root, containerName);
BringToFront(workCanvas as FrameworkElement, parentControl);
}
/// <summary>
/// 获得容器中顶层控件的zindex值
/// </summary>
/// <param name="element">容器</param>
/// <returns></returns>
public static int getMaxZIndexOfContainer(FrameworkElement element)
{
if (element == null) return -1;
Canvas canvas = element as Canvas;
if (canvas == null) return -1;
if (canvas.Children == null || canvas.Children.Count == 0)
{
return 0;
}
var maxZ = canvas.Children.OfType<UIElement>()
//.Where(x => x != pane)
.Select(x => Canvas.GetZIndex(x))
.Max();
return maxZ;
}
/// <summary>
/// 在容器中置顶指定控件
/// </summary>
/// <param name="element">容器</param>
/// <param name="pane">需要置顶的控件</param>
public static void BringToFront(FrameworkElement element, Control pane)
{
int maxZ = getMaxZIndexOfContainer(element);
if (maxZ == -1)
{
return;
}
Canvas.SetZIndex(pane, maxZ + 1);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace CardWorkbench.Models
{
public class FrameModel
{
public int FrameID { get; set; }
public string SyncWord { get; set; }
public string Word1 { get; set; }
public string Word2 { get; set; }
public string Word3 { get; set; }
public string ID { get; set; }
public string Word5 { get; set; }
public string Word6 { get; set; }
public string Word7 { get; set; }
public string Word8 { get; set; }
public string Word9 { get; set; }
public string Word10 { get; set; }
public string Word11 { get; set; }
public string Word12 { get; set; }
}
public static class FrameTestCase
{
public static IList<FrameModel> generateData()
{
List<FrameModel> frameModelList = new List<FrameModel>();
for (int i = 1; i < 9; i++)
{
frameModelList.Add(new FrameModel() { FrameID = i, SyncWord = "EB101", Word1 = "CODE", Word2 = "CODE", Word3 = "CODE", ID = i + "", Word5 = "CODE", Word6 = "CODE", Word7 = "CODE", Word8 = "CODE", Word9 = "CODE", Word10 = "CODE", Word11 = "CODE", Word12 = "CODE" });
}
return frameModelList;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CardWorkbench.Views.MenuControls
{
/// <summary>
/// ReceiverUC.xaml 的交互逻辑
/// </summary>
public partial class ReceiverUC : UserControl
{
//Grid增加border边线
public void AddGridBorder()
{
int rows = MainGrid.RowDefinitions.Count;
int columns = MainGrid.ColumnDefinitions.Count;
//TagButton btnTag = new TagButton();
for (int i = 0; i < rows; i++)
{
if (i != rows - 1)
{
#region
for (int j = 0; j < columns; j++)
{
Border border = null;
if (j == columns - 1)
{
border = new Border()
{
BorderBrush = new SolidColorBrush(Colors.Gray),
BorderThickness = new Thickness(1, 1, 1, 0)
};
}
else
{
border = new Border()
{
BorderBrush = new SolidColorBrush(Colors.Gray),
BorderThickness = new Thickness(1, 1, 0, 0)
};
}
Grid.SetRow(border, i);
Grid.SetColumn(border, j);
MainGrid.Children.Add(border);
}
#endregion
}
else
{
for (int j = 0; j < columns; j++)
{
Border border = null;
if (j + 1 != columns)
{
border = new Border
{
BorderBrush = new SolidColorBrush(Colors.Gray),
BorderThickness = new Thickness(1, 1, 0, 1)
};
}
else
{
border = new Border
{
BorderBrush = new SolidColorBrush(Colors.Gray),
BorderThickness = new Thickness(1, 1, 1, 1)
};
}
Grid.SetRow(border, i);
Grid.SetColumn(border, j);
MainGrid.Children.Add(border);
}
}
}
}
public ReceiverUC()
{
InitializeComponent();
AddGridBorder();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CardWorkbench.Models
{
/// <summary>
/// 参数分类实体
/// </summary>
public class ParamSortType
{
public int paramSortTypeId { get; set; }
public string paramSortTypeName { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CardWorkbench.ViewModels.MenuControls
{
public class FrameSyncUCViewModel : MenuControlsViewModel
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CardWorkbench.Models
{
/// <summary>
/// 校准类型实体类
/// </summary>
public class CalibrateType
{
public int calibrateTypeId { get; set; }
public string calibrateTypeName { get; set; }
}
}
<file_sep>using DevExpress.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CardWorkbench.ViewModels.CommonControls
{
/// <summary>
/// 自定义控件时间ViewModel类
/// </summary>
public class TimeControlViewModel : CommonControlViewModel
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DevExpress.Xpf.Grid.Core;
using CardWorkbench.Models;
using System.Windows.Controls;
namespace CardWorkbench.Views.CommonTools
{
/// <summary>
/// FrameDump.xaml 的交互逻辑
/// </summary>
public partial class FrameDump : UserControl
{
public static List<FrameModel> frames = new List<FrameModel>();
public FrameDump()
{
InitializeComponent();
insertRows();
}
public void insertRows()
{
frameGrid.ItemsSource = FrameTestCase.generateData();
}
}
}
<file_sep>using CardWorkbench.Utils;
using DevExpress.Mvvm;
using DevExpress.Xpf.Charts;
using DevExpress.Xpf.Core.Native;
using DevExpress.Xpf.Gauges;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace CardWorkbench.ViewModels.CommonControls
{
/// <summary>
/// 自定义控件圆形仪表ViewModel类
/// </summary>
public class CirleControlViewModel : CommonControlViewModel
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DevExpress.Xpf.Docking;
namespace CardWorkbench.Views.CommonTools
{
/// <summary>
/// BitSyncControlPanel.xaml 的交互逻辑
/// </summary>
public partial class BitSyncControlPanel : UserControl
{
public BitSyncControlPanel()
{
InitializeComponent();
this.LayoutPanel.Caption = "位同步控件";
}
}
}
<file_sep>using DevExpress.Xpf.Core.Native;
using DevExpress.Xpf.Editors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CardWorkbench.Views.MenuControls
{
/// <summary>
/// PlayBack.xaml 的交互逻辑
/// </summary>
public partial class PlayBack : UserControl
{
public PlayBack()
{
InitializeComponent();
}
private void ButtonInfo_Click(object sender, RoutedEventArgs e)
{
ButtonEdit be = LayoutHelper.FindLayoutOrVisualParentObject<ButtonEdit>(sender as DependencyObject, true);
if (be == null)
return;
System.Windows.Forms.FileDialog dialog = new System.Windows.Forms.OpenFileDialog();
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
be.EditValue = dialog.FileName;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CardWorkbench.Models
{
public class HardwareModel
{
//板卡ID
public int cardID { get; set; }
//板卡型号
public string cardModel { get; set; }
//板卡功能描述
public string cardDescription { get; set; }
//todo: 板卡组成对象
}
public static class HardwareModelTestCase
{
public static IList<HardwareModel> generateData()
{
List<HardwareModel> hardwareList = new List<HardwareModel>();
for (int i = 1; i < 6; i++)
{
hardwareList.Add(new HardwareModel() { cardID = i, cardModel = "GDP4425", cardDescription = "接收机,未同步,帧同步,模拟" });
}
return hardwareList;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace CardWorkbench.Models
{
/// <summary>
/// 参数实体类
/// </summary>
public class Param
{
public int paramId { get; set; }
[DisplayName("CalibrateType")]
public int calibrateTypeId { get; set; }
[DisplayName("ParamSortType")]
public int paramSortTypeId { get; set; }
public string paramName { get; set; }
public string paramChineseName { get; set; }
public virtual CalibrateType calibrateType { get; set; }
public virtual ParamSortType paramSortType { get; set; }
}
/// <summary>
/// 测试数据
/// </summary>
public static class SampleData
{
public static List<Param> paramList { get; set; }
public static List<CalibrateType> calibrateTypeList { get; set; }
public static List<ParamSortType> paramSortTypeList { get; set; }
public static void initData() //初始化数据
{
if (paramList != null)
{
return;
}
calibrateTypeList = new List<CalibrateType>
{
new CalibrateType { calibrateTypeName = "点对校准" },
new CalibrateType { calibrateTypeName = "多项式校准" }
};
int i = 0;
calibrateTypeList.ForEach(x => x.calibrateTypeId = ++i);
paramSortTypeList = new List<ParamSortType>
{
new ParamSortType { paramSortTypeName = "飞控" },
new ParamSortType { paramSortTypeName = "航电" },
new ParamSortType { paramSortTypeName = "USDC" },
new ParamSortType { paramSortTypeName = "IDMP" },
new ParamSortType { paramSortTypeName = "其它" }
};
i = 0;
paramSortTypeList.ForEach(x => x.paramSortTypeId = ++i);
paramList = new List<Param>
{
new Param { paramName = "Rock" , paramChineseName = "名称1",
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Jazz" , paramChineseName = "名称2" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "航电") },
new Param { paramName = "Metal" , paramChineseName = "名称3" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "多项式校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "IDMP") },
new Param { paramName = "Alternative" , paramChineseName = "名称4" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Disco" , paramChineseName = "名称5" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "IDMP") },
new Param { paramName = "Blues" , paramChineseName = "名称6" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "多项式校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "航电") },
new Param { paramName = "Latin" , paramChineseName = "名称7" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "USDC") },
new Param { paramName = "Reggae" , paramChineseName = "名称8" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Pop" , paramChineseName = "名称9",
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "多项式校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Classical" , paramChineseName = "名称10",
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "USDC") },
new Param { paramName = "Rock" , paramChineseName = "名称1",
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "ID" , paramChineseName = "ID参数" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "其它") },
new Param { paramName = "Metal" , paramChineseName = "名称3" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "多项式校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "IDMP") },
new Param { paramName = "Alternative" , paramChineseName = "名称4" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Disco" , paramChineseName = "名称5" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "IDMP") },
new Param { paramName = "Blues" , paramChineseName = "名称6" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "多项式校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "航电") },
new Param { paramName = "Latin" , paramChineseName = "名称7" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "USDC") },
new Param { paramName = "Reggae" , paramChineseName = "名称8" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Pop" , paramChineseName = "名称9",
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "多项式校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Classical" , paramChineseName = "名称10",
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "USDC") },
new Param { paramName = "Rock" , paramChineseName = "名称1",
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Jazz" , paramChineseName = "名称2" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "航电") },
new Param { paramName = "Metal" , paramChineseName = "名称3" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "多项式校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "IDMP") },
new Param { paramName = "Alternative" , paramChineseName = "名称4" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Disco" , paramChineseName = "名称5" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "IDMP") },
new Param { paramName = "Blues" , paramChineseName = "名称6" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "多项式校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "航电") },
new Param { paramName = "Latin" , paramChineseName = "名称7" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "USDC") },
new Param { paramName = "Reggae" , paramChineseName = "名称8" ,
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Pop" , paramChineseName = "名称9",
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "多项式校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "飞控") },
new Param { paramName = "Classical" , paramChineseName = "名称10",
calibrateType = calibrateTypeList.Single(a => a.calibrateTypeName == "点对校准"),
paramSortType = paramSortTypeList.Single(a => a.paramSortTypeName == "USDC") }
};
}
}
}
<file_sep>using CardWorkbench.Views.CommonControls;
using CardWorkbench.Views.CommonTools;
using CardWorkbench.Utils;
using DevExpress.Mvvm;
using DevExpress.Xpf.Core.Native;
using DevExpress.Xpf.Docking;
using DevExpress.Xpf.NavBar;
using DevExpress.Xpf.Ribbon;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CardWorkbench.Models;
using DevExpress.Xpf.Editors;
using System.Windows.Threading;
using System.Windows.Media;
using DevExpress.Data;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Bars;
using CardWorkbench.Views.MenuControls;
using CardWorkbench.Views.CardStateGroup;
using System.Threading;
using DevExpress.Xpf.Core;
namespace CardWorkbench.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
//控件名称
public static readonly string TOOLBOX_TEXTCONTROL_NAME = "toolbox_textCtrl"; //文本
public static readonly string TOOLBOX_LINECONTROL_NAME = "toolbox_lineCtrl"; //二维曲线
public static readonly string TOOLBOX_METERCONTROL_NAME = "toolbox_meterCtrl"; //仪表
public static readonly string TOOLBOX_LIGHTCONTROL_NAME = "toolbox_lightCtrl"; //工作灯
public static readonly string TOOLBOX_TIMECONTROL_NAME = "toolbox_timeCtrl"; //时间
//工作区document group 名称
public static readonly string DOCUMENTGROUP_NAME = "documentContainer";
//工作区自定义控件Canvas名称
public static readonly string CANVAS_CUSTOM_CONTROL_NAME = "workCanvas";
//Ribbon标签栏及其组件名称
public static readonly string RIBBONCONTROL_NAME = "ribbonControl";
public static readonly string RIBBONPAGE_TOOLS_NAME = "toolsRibbonPage";
//工具panel名称、标题
public static readonly string PANEL_FRAMEDUMP_NAME = "frameDumpPanel";
public static readonly string PANEL_FRAMEDUMP_CAPTION = "原始帧显示";
public static readonly string PANEL_RECEIVERCHART_NAME = "receiverChartPanel";
public static readonly string PANEL_RECEIVERCHART_CAPTION = "接收机波形显示";
public static readonly string PANEL_BITSYNCCHART_NAME = "bitSyncChartPanel";
public static readonly string PANEL_BITSYNCCHART_CAPTION = "位同步波形显示";
public static readonly string PANEL_DECOMOUTPUT_NAME = "decomOutputPanel";
public static readonly string PANEL_DECOMOUTPUT_CAPTION = "解码输出";
public static readonly string PANEL_CUSTOMCONTROL_NAME = "mainControl"; //自定义控件
public static readonly string DOCUMENTPANEL_WORKSTATE_NAME = "document1"; //工作区硬件工作状态panel名称
//硬件设置菜单栏对话框名称
public static readonly string DIALOG_HARDWAR_RECOGNITION_NAME = "hardwareRecognitionDialog";
public static readonly string DIALOG_RECEIVER_SETTING_NAME = "receiverSettingDialog"; //接收机设置
public static readonly string DIALOG_BITSYNC_SETTING_NAME = "bitSyncSettingDialog"; //位同步设置
public static readonly string DIALOG_FRAMESYNC_SETTING_NAME = "frameSyncSettingDialog"; //帧同步设置
public static readonly string DIALOG_TIME_SETTING_NAME = "timeSettingDialog"; //时间设置
public static readonly string DIALOG_PLAYBACK_SETTING_NAME = "playBackSettingDialog"; //回放设置
//注册服务声明
public IDialogService hardwareRecognitionDialogService { get { return GetService<IDialogService>(DIALOG_HARDWAR_RECOGNITION_NAME); } } //获得硬件识别对话框服务
public IDialogService receiverSettingDialogService { get { return GetService<IDialogService>(DIALOG_RECEIVER_SETTING_NAME); } } //获得接收机设置对话框服务
public IDialogService bitSyncSettingDialogService { get { return GetService<IDialogService>(DIALOG_BITSYNC_SETTING_NAME); } } //获得位同步设置对话框服务
public IDialogService frameSyncSettingDialogService { get { return GetService<IDialogService>(DIALOG_FRAMESYNC_SETTING_NAME); } } //获得帧同步设置对话框服务
public IDialogService timeSettingDialogService { get { return GetService<IDialogService>(DIALOG_TIME_SETTING_NAME); } } //获得时间同步设置对话框服务
public IDialogService playBackSettingDialogService { get { return GetService<IDialogService>(DIALOG_PLAYBACK_SETTING_NAME); } } //获得模拟回放设置对话框服务
public IOpenFileDialogService OpenFileDialogService { get { return GetService<IOpenFileDialogService>() ; } } //获得文件选择对话框服务
public ISplashScreenService SplashScreenService { get { return GetService<ISplashScreenService>(); } } //LOADING splash screen服务
//参数实体类列表
public List<Param> paramList { get; set; }
public List<CalibrateType> calibrateTypeList { get; set; }
public List<ParamSortType> paramSortTypeList { get; set; }
//参数grid某行是否拖拽开始
bool _dragStarted = false;
//参数grid面板table view的名称
public static readonly string PARAM_GRID_TABLEVIEW_NAME = "paramGridTabelView";
public MainWindowViewModel() {
//初始化参数数据
SampleData.initData();
paramList = SampleData.paramList;
calibrateTypeList = SampleData.calibrateTypeList;
paramSortTypeList = SampleData.paramSortTypeList;
//
}
#region 顶部功能菜单命令绑定
/// <summary>
/// 硬件识别对话框命令
/// </summary>
public ICommand hardwareRecognitionCommand
{
get { return new DelegateCommand<LayoutPanel>(onHardwareRecognitionClick, x => { return true; }); }
}
private void onHardwareRecognitionClick(LayoutPanel cardMenuPanel)
{
UICommand okCommand = new UICommand()
{
Caption = "确定",
IsCancel = false,
IsDefault = true,
Command = new DelegateCommand<CancelEventArgs>(
x => { },
true
),
};
UICommand cancelCommand = new UICommand()
{
Id = MessageBoxResult.Cancel,
Caption = "取消",
IsCancel = true,
IsDefault = false,
};
UICommand result = hardwareRecognitionDialogService.ShowDialog(
dialogCommands: new List<UICommand>() { okCommand, cancelCommand },
title: "硬件识别",
viewModel: null
);
if (result == okCommand)
{
//cardMenuConfigPanel
onSelectHardwareLoad(cardMenuPanel);
}
}
/// <summary>
/// 加载选中板卡显示配置菜单命令
/// </summary>
private void onSelectHardwareLoad(LayoutPanel cardMenuPanel)
{
cardMenuPanel.Content = new CardMenuConfig();
FrameworkElement root = LayoutHelper.GetRoot(cardMenuPanel);
//TEST 显示主页硬件状态////////////////////////////////////////////////
GroupBox receiverGrpBox = (GroupBox)root.FindName("groupBox_recState");
GroupBox bitSyncGrpBox = (GroupBox)root.FindName("groupBox_bitSyncState");
GroupBox frameSyncGrpBox = (GroupBox)root.FindName("groupBox_frameSyncState");
receiverGrpBox.Content = new ReceiverStateGroupBox();
bitSyncGrpBox.Content = new BitSyncStateGroupBox();
frameSyncGrpBox.Content = new FrameSyncStateGroupBox();
////////////////////////////////////////////////////
//开启ribbon工具标签页
RibbonControl ribbonControl = (RibbonControl)LayoutHelper.FindElementByName(root, RIBBONCONTROL_NAME);
RibbonPage ribbonPage = ribbonControl.Manager.FindName(RIBBONPAGE_TOOLS_NAME) as RibbonPage;
ribbonPage.IsEnabled = true;
}
/// <summary>
/// 打开读取本地硬件配置文件对话框
/// </summary>
public ICommand openHardwareConfigCommand {
get { return new DelegateCommand<LayoutPanel>(onOpenHardwareConfigClick, x => { return true; }); }
}
private void onOpenHardwareConfigClick(LayoutPanel cardMenuPanel)
{
//System.Windows.Forms.FileDialog dialog = new System.Windows.Forms.OpenFileDialog();
//if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
//{
// onSelectHardwareLoad(cardMenuPanel);
//}
OpenFileDialogService.Filter = "配置文件|*.xml";
OpenFileDialogService.FilterIndex = 1;
bool DialogResult = OpenFileDialogService.ShowDialog();
if (!DialogResult)
{
//ResultFileName = string.Empty;
}
else
{
onSelectHardwareLoad(cardMenuPanel);
//IFileInfo file = OpenFileDialogService.Files.First();
//ResultFileName = file.Name;
//using (var stream = file.OpenText())
//{
// FileBody = stream.ReadToEnd();
//}
}
}
/// <summary>
/// ”原始帧显示“ 按钮Command
/// </summary>
public ICommand frameDumpCommand {
get { return new DelegateCommand<DockLayoutManager>(onFrameDumpClick, x => { return true; }); }
}
private void onFrameDumpClick(DockLayoutManager dockManager)
{
createWorkDocumentPanel(dockManager, DOCUMENTGROUP_NAME, PANEL_FRAMEDUMP_NAME, PANEL_FRAMEDUMP_CAPTION, new FrameDump());
}
/// <summary>
/// "接收机波形显示" 按钮command
/// </summary>
public ICommand receiverChartCommand
{
get { return new DelegateCommand<DockLayoutManager>(onReceiverChartClick, x => { return true; }); }
}
private void onReceiverChartClick(DockLayoutManager dockManager)
{
createWorkDocumentPanel(dockManager, DOCUMENTGROUP_NAME, PANEL_RECEIVERCHART_NAME, PANEL_RECEIVERCHART_CAPTION, new ReceiverChartControl());
}
/// <summary>
/// "位同步波形显示" 按钮Command
/// </summary>
public ICommand bitSyncChartCommand
{
get { return new DelegateCommand<DockLayoutManager>(onBitSyncChartClick, x => { return true; }); }
}
private void onBitSyncChartClick(DockLayoutManager dockManager)
{
createWorkDocumentPanel(dockManager, DOCUMENTGROUP_NAME, PANEL_BITSYNCCHART_NAME, PANEL_BITSYNCCHART_CAPTION, new BitSyncChart());
}
/// <summary>
/// ”解码输出“ 按钮Command
/// </summary>
public ICommand decomOutputCommand
{
get { return new DelegateCommand<DockLayoutManager>(onDecomOutputClick, x => { return true; }); }
}
private void onDecomOutputClick(DockLayoutManager dockManager)
{
createWorkDocumentPanel(dockManager, DOCUMENTGROUP_NAME, PANEL_DECOMOUTPUT_NAME, PANEL_DECOMOUTPUT_CAPTION, new DecomOutputPanel());
}
/// <summary>
/// "自定义控件" 按钮Command
/// </summary>
public ICommand customControlCommand {
get { return new DelegateCommand<DockLayoutManager>(onCustomControlClick, x => { return true; }); }
}
private void onCustomControlClick(DockLayoutManager dockManager)
{
DocumentGroup documentGroup = dockManager.GetItem(DOCUMENTGROUP_NAME) as DocumentGroup;
DocumentPanel docPanel = dockManager.GetItem(PANEL_CUSTOMCONTROL_NAME) as DocumentPanel;
if (docPanel != null && docPanel.IsClosed)
{
dockManager.DockController.Restore(docPanel);
}
dockManager.DockController.Activate(docPanel);
}
/// <summary>
/// 在工作区document group创建新的document Panel
/// </summary>
/// <param name="dockManager">dock布局管理器</param>
/// <param name="documentGroupName">documentGroup名称</param>
/// <param name="addDocPanelName">新增Document panel名称</param>
/// <param name="addDocPanelCaption">新增Document Panel显示标题</param>
/// <param name="panelContent">新增Document Panel的内容元素</param>
private void createWorkDocumentPanel(DockLayoutManager dockManager, string documentGroupName, string addDocPanelName, string addDocPanelCaption, object panelContent)
{
DocumentGroup documentGroup = dockManager.GetItem(documentGroupName) as DocumentGroup;
DocumentPanel docPanel = dockManager.GetItem(addDocPanelName) as DocumentPanel;
if (docPanel == null)
{
docPanel = dockManager.DockController.AddDocumentPanel(documentGroup);
docPanel.Caption = addDocPanelCaption;
docPanel.Content = panelContent;
docPanel.Name = addDocPanelName;
}
else if (docPanel.IsClosed)
{
dockManager.DockController.Restore(docPanel);
}
dockManager.DockController.Activate(docPanel);
}
#endregion
#region 硬件设置对话框命令绑定
/// <summary>
/// 接收机设置对话框命令
/// </summary>
public ICommand receiverSettingCommand
{
get { return new DelegateCommand<object>(onReceiverSettingClick, x => { return true; }); }
}
private void onReceiverSettingClick(object context)
{
DXSplashScreen.Show<SplashScreenView>(); //显示loading框
UICommand okCommand = new UICommand()
{
Caption = "确定",
IsCancel = false,
IsDefault = true,
Command = new DelegateCommand<CancelEventArgs>(
x => { },
true
),
};
UICommand cancelCommand = new UICommand()
{
Id = MessageBoxResult.Cancel,
Caption = "取消",
IsCancel = true,
IsDefault = false,
};
//DXSplashScreen.Show<SplashScreenView>();
UICommand result = receiverSettingDialogService.ShowDialog(
dialogCommands: new List<UICommand>() { okCommand, cancelCommand },
title: "接收机设置",
viewModel: null
);
if (result == okCommand)
{
MessageBox.Show("successfull!!");
}
}
/// <summary>
/// 位同步设置对话框命令
/// </summary>
public ICommand bitSyncSettingCommand
{
get { return new DelegateCommand<object>(onBitSyncSettingClick, x => { return true; }); }
}
private void onBitSyncSettingClick(object context)
{
DXSplashScreen.Show<SplashScreenView>(); //显示loading框
UICommand okCommand = new UICommand()
{
Caption = "确定",
IsCancel = false,
IsDefault = true,
Command = new DelegateCommand<CancelEventArgs>(
x => { },
true
),
};
UICommand cancelCommand = new UICommand()
{
Id = MessageBoxResult.Cancel,
Caption = "取消",
IsCancel = true,
IsDefault = false,
};
UICommand result = bitSyncSettingDialogService.ShowDialog(
dialogCommands: new List<UICommand>() { okCommand, cancelCommand },
title: "位同步设置",
viewModel: null
);
if (result == okCommand)
{
MessageBox.Show("successfull!!");
}
}
/// <summary>
/// 帧同步设置对话框命令
/// </summary>
public ICommand frameSyncSettingCommand
{
get { return new DelegateCommand<object>(onFrameSyncSettingClick, x => { return true; }); }
}
private void onFrameSyncSettingClick(object context)
{
DXSplashScreen.Show<SplashScreenView>(); //显示loading框
UICommand okCommand = new UICommand()
{
Caption = "确定",
IsCancel = false,
IsDefault = true,
Command = new DelegateCommand<CancelEventArgs>(
x => { },
true
),
};
UICommand cancelCommand = new UICommand()
{
Id = MessageBoxResult.Cancel,
Caption = "取消",
IsCancel = true,
IsDefault = false,
};
UICommand result = frameSyncSettingDialogService.ShowDialog(
dialogCommands: new List<UICommand>() { okCommand, cancelCommand },
title: "帧同步设置",
viewModel: null
);
if (result == okCommand)
{
MessageBox.Show("successfull!!");
}
}
/// <summary>
/// 时间同步设置对话框命令
/// </summary>
public ICommand timeSettingCommand
{
get { return new DelegateCommand<object>(ontimeSyncSettingClick, x => { return true; }); }
}
private void ontimeSyncSettingClick(object context)
{
DXSplashScreen.Show<SplashScreenView>(); //显示loading框
UICommand okCommand = new UICommand()
{
Caption = "确定",
IsCancel = false,
IsDefault = true,
Command = new DelegateCommand<CancelEventArgs>(
x => { },
true
),
};
UICommand cancelCommand = new UICommand()
{
Id = MessageBoxResult.Cancel,
Caption = "取消",
IsCancel = true,
IsDefault = false,
};
UICommand result = timeSettingDialogService.ShowDialog(
dialogCommands: new List<UICommand>() { okCommand, cancelCommand },
title: "时间同步设置",
viewModel: null
);
if (result == okCommand)
{
MessageBox.Show("successfull!!");
}
}
/// <summary>
/// 模拟回放设置对话框命令
/// </summary>
public ICommand playBackSettingCommand
{
get { return new DelegateCommand<object>(onPlayBackSettingClick, x => { return true; }); }
}
private void onPlayBackSettingClick(object context)
{
DXSplashScreen.Show<SplashScreenView>(); //显示loading框
UICommand okCommand = new UICommand()
{
Caption = "确定",
IsCancel = false,
IsDefault = true,
Command = new DelegateCommand<CancelEventArgs>(
x => { },
true
),
};
UICommand cancelCommand = new UICommand()
{
Id = MessageBoxResult.Cancel,
Caption = "取消",
IsCancel = true,
IsDefault = false,
};
UICommand result = playBackSettingDialogService.ShowDialog(
dialogCommands: new List<UICommand>() { okCommand, cancelCommand },
title: "模拟回放设置",
viewModel: null
);
if (result == okCommand)
{
MessageBox.Show("successfull!!");
}
}
#endregion
#region 控件栏拖拽命令绑定
public ICommand dropToolBoxCommand
{
get { return new DelegateCommand<DragEventArgs>(onDropToolBoxNavItem, x => { return true; }); }
}
//拖拽事件
private void onDropToolBoxNavItem(DragEventArgs e)
{
object originalSource = e.OriginalSource;
NavBarItemControl item = LayoutHelper.FindParentObject<NavBarItemControl>(originalSource as DependencyObject);
NavBarGroupHeader header = LayoutHelper.FindParentObject<NavBarGroupHeader>(originalSource as DependencyObject);
NavBarItem data = e.Data.GetData(NavBarDragDropHelper.FormatName) as NavBarItem;
if (data != null && data.Name != null)
{
string navItemName = data.Name;
FrameworkElement root = LayoutHelper.GetTopLevelVisual(originalSource as DependencyObject);
Canvas workCanvas = (Canvas)LayoutHelper.FindElementByName(root, CANVAS_CUSTOM_CONTROL_NAME);
UserControl commonControl = null;
int maxZindex = UIControlHelper.getMaxZIndexOfContainer(workCanvas);
if (TOOLBOX_TEXTCONTROL_NAME.Equals(navItemName)) //文本控件
{
commonControl = new TextControl();
}
else if (TOOLBOX_LINECONTROL_NAME.Equals(navItemName)) //曲线控件
{
commonControl = new ChartControl();
}
else if (TOOLBOX_LIGHTCONTROL_NAME.Equals(navItemName)) //工作灯控件
{
commonControl = new LampControl();
}
else if (TOOLBOX_METERCONTROL_NAME.Equals(navItemName)) //仪表控件
{
commonControl = new CirleControl();
}
else if (TOOLBOX_TIMECONTROL_NAME.Equals(navItemName)) //时间控件
{
commonControl = new TimeControl();
}
if (commonControl != null)
{
Canvas.SetZIndex(commonControl, maxZindex + 1);
workCanvas.Children.Add(commonControl);
}
}
}
#endregion
#region 参数Grid面板命令绑定
public ICommand ParamGridMouseDownCommand
{
get { return new DelegateCommand<MouseButtonEventArgs>(onParamGridMouseDown, x => { return true; }); }
}
private void onParamGridMouseDown(MouseButtonEventArgs e)
{
FrameworkElement root = LayoutHelper.GetTopLevelVisual(e.Source as DependencyObject);
TableView paramTableView = (TableView)LayoutHelper.FindElementByName(root, PARAM_GRID_TABLEVIEW_NAME);
int rowHandle = paramTableView.GetRowHandleByMouseEventArgs(e);
if (rowHandle != GridDataController.InvalidRow)
_dragStarted = true;
}
public ICommand ParamGridMouseMoveCommand
{
get { return new DelegateCommand<MouseEventArgs>(onParamGridMouseMove, x => { return true; }); }
}
private void onParamGridMouseMove(MouseEventArgs e)
{
FrameworkElement root = LayoutHelper.GetTopLevelVisual(e.Source as DependencyObject);
TableView paramTableView = (TableView)LayoutHelper.FindElementByName(root, PARAM_GRID_TABLEVIEW_NAME);
//int rowHandle = paramTableView.GetRowHandleByMouseEventArgs(e);
//RowControl rowControl = paramTableView.GetRowElementByRowHandle(rowHandle) as RowControl;
//此处必须新建控件的dipatcher线程做处理,否则在拖动参数时会出现界面假死的情况
paramTableView.Dispatcher.BeginInvoke(new Action(() =>
{
if (_dragStarted)
{
//Console.WriteLine("start..............");
FrameworkElement element = paramTableView.GetRowElementByMouseEventArgs(e);
RowData rowData = null;
if (element != null)
{
rowData = element.DataContext as RowData;
if (rowData == null)
{
return;
}
DataObject data = CreateDataObject(rowData);
DragDrop.DoDragDrop(element, data, DragDropEffects.Move | DragDropEffects.Copy);
}
_dragStarted = false;
//Console.WriteLine("end..............");
}
}));
}
private DataObject CreateDataObject(RowData rowData)
{
DataObject data = new DataObject();
//data.SetData(typeof(int), rowHandle);
data.SetData(typeof(RowData), rowData);
return data;
}
#endregion
#region 自定义控件Panel按钮命令绑定
public ICommand resetCommonControlsPanelCommand
{
get { return new DelegateCommand<Canvas>(onResetCommonControlsBtnClick, x => { return true; }); }
}
private void onResetCommonControlsBtnClick(Canvas commonControlsCanvas)
{
if (commonControlsCanvas != null)
{
commonControlsCanvas.Children.Clear();
}
}
/// <summary>
/// 控件键盘按键响应事件命令
/// </summary>
public ICommand CanvasDeleteKeyDownCommand
{
get { return new DelegateCommand<KeyEventArgs>(onCanvasDeleteKeyDown, x => { return true; }); }
}
private void onCanvasDeleteKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Delete) //删除按键
{
//UserControl control = LayoutHelper.FindParentObject<UserControl>(e.Source as DependencyObject);
// FrameworkElement root = LayoutHelper.GetTopLevelVisual(e.Source as DependencyObject);
Canvas workCanvas = e.Source as Canvas;
if (workCanvas == null)
{
FrameworkElement root = LayoutHelper.GetTopLevelVisual(e.Source as DependencyObject);
workCanvas = (Canvas)LayoutHelper.FindElementByName(root, CANVAS_CUSTOM_CONTROL_NAME);
}
var maxZ = UIControlHelper.getMaxZIndexOfContainer(workCanvas); //当前最顶层的控件
if (workCanvas.Children.Count != 0)
{
foreach (FrameworkElement childElement in workCanvas.Children)
{
if (Canvas.GetZIndex(childElement) == maxZ)
{
workCanvas.Children.Remove(childElement); //删除
break;
}
}
}
}
}
#endregion
}
}
<file_sep>using DevExpress.Xpf.Core.Native;
using DevExpress.Xpf.NavBar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
namespace CardWorkbench.Utils
{
/// <summary>
/// 导航栏拖放工具类
/// </summary>
class NavBarDragDropHelper
{
private System.Windows.Point _MouseDownLocation;
private readonly NavBarControl _NavBar;
public const string FormatName = "NavBarDragFormat"; //定义一个drag动作临时DataObject名称
public NavBarDragDropHelper(NavBarControl navBar)
{
_NavBar = navBar;
_NavBar.PreviewMouseLeftButtonDown += _NavBar_PreviewMouseLeftButtonDown; //左键按下方法
_NavBar.PreviewMouseMove += _NavBar_PreviewMouseMove; //鼠标移动方法
_NavBar.AllowDrop = false; //工具导航条本身不允许放置
//_NavBar.DragOver += _NavBar_DragOver;
//_NavBar.Drop += _NavBar_Drop;
}
void _NavBar_DragOver(object sender, DragEventArgs e)
{
//e.Effects = DragDropEffects.Copy;
if (!e.Data.GetDataPresent(FormatName))
{
e.Effects = DragDropEffects.None;
}
}
void _NavBar_Drop(object sender, DragEventArgs e)
{
object originalSource = e.OriginalSource;
NavBarItemControl item = LayoutHelper.FindParentObject<NavBarItemControl>(originalSource as DependencyObject);
NavBarGroupHeader header = LayoutHelper.FindParentObject<NavBarGroupHeader>(originalSource as DependencyObject);
NavBarItem data = e.Data.GetData(FormatName) as NavBarItem;
if (data != null)
{
NavBarItem navItem = item == null ? null : item.DataContext as NavBarItem;
NavBarGroup group = navItem == null ? header.DataContext as NavBarGroup : navItem.Group;
Console.WriteLine(navItem);
OnDragDrop(navItem, group, data);
}
}
void _NavBar_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
_MouseDownLocation = e.GetPosition(null);
}
void _NavBar_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed && CheckDiff(_MouseDownLocation - e.GetPosition(null)))
{
NavBarItemControl item = e.OriginalSource as NavBarItemControl;
if (item == null)
{
return;
}
NavBarItem navBarItem = item.DataContext as NavBarItem;
DataObject dragData = new DataObject(FormatName, navBarItem);
DragDrop.DoDragDrop(_NavBar, dragData, DragDropEffects.Copy);
}
}
private static bool CheckDiff(Vector diff)
{
return (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance);
}
private void OnDragDrop(NavBarItem targetItem, NavBarGroup targetGroup, NavBarItem data)
{
DataRowView dataRowView = data.DataContext as DataRowView;
DataTable sourceTable = dataRowView.DataView.Table;
DataTable targetTable = (targetGroup.NavBar.ItemsSource as DataView).Table;
DataRowView targetDataRow = targetItem == null ? null : targetItem.DataContext as DataRowView;
int targetIndex = targetItem == null ? targetTable.Rows.Count : targetTable.Rows.IndexOf(targetDataRow.Row);
DataRow newRow = targetTable.NewRow();
newRow["Group"] = targetGroup.DataContext.ToString();
newRow["Item"] = dataRowView["Item"];
targetTable.Rows.InsertAt(newRow, targetIndex);
sourceTable.Rows.Remove(dataRowView.Row);
dataRowView.Delete();
sourceTable.AcceptChanges();
}
}
}
<file_sep>using DevExpress.Xpf.Charts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace CardWorkbench.Views.CommonTools
{
/// <summary>
/// EyeChart.xaml 的交互逻辑
/// </summary>
public partial class EyeChart : UserControl
{
private DispatcherTimer timer = new DispatcherTimer();
private int number = 50;
private int value = 1;
private int interval = 1;
public EyeChart()
{
InitializeComponent();
timer.Interval = TimeSpan.FromMilliseconds(100);
timer.Tick += new EventHandler(RefreshPlot);
timer.IsEnabled = true;
}
private void RefreshPlot(object sender,EventArgs e)
{
if(value>number)
{
value = 1;
}else
{
value+=2;
}
SeriesPoint p = new SeriesPoint(interval, value);
series.Points.Add(p);
interval++;
if(series.Points.Count>number)
{
series.Points.RemoveAt(0);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DevExpress.Xpf.NavBar;
using DevExpress.Xpf.Docking;
namespace CardWorkbench.Views.CommonTools
{
/// <summary>
/// WareTreeControl.xaml 的交互逻辑
/// </summary>
public partial class WareTreeControl : UserControl
{
public AutoHideGroup TargetGroup { get; set; }
//public ReceiverControlPanel ReceiverPanel{get;set;}
public BitSyncControlPanel BitPanel { get; set; }
public WareTreeControl(AutoHideGroup targetGroup)
{
InitializeComponent();
this.TargetGroup = targetGroup;
//this.ReceiverPanel = new ReceiverControlPanel();
this.BitPanel = new BitSyncControlPanel();
}
private void NavBarGroup_MouseDown(object sender, MouseButtonEventArgs e)
{
NavBarGroup selectGroup = (NavBarGroup)this.navcontrol.View.GetNavBarGroup(e);
NavBarItem item = (NavBarItem)this.navcontrol.View.GetNavBarItem(e);
if(item==null||item.Content==null)
{
return;
}
string value = (string)item.Content;
if ("接收机".Equals(value))
{
if(this.TargetGroup.Items.Count>0)
{
LayoutPanel panel = (LayoutPanel)this.TargetGroup.Items[0];
panel.Visibility = System.Windows.Visibility.Hidden;
}
this.TargetGroup.Items.Clear();
//this.TargetGroup.Items.Add(this.ReceiverPanel.LayoutPanel);
//this.ReceiverPanel.LayoutPanel.Visibility = System.Windows.Visibility.Visible;
}else if("位同步".Equals(value))
{
if (this.TargetGroup.Items.Count > 0)
{
LayoutPanel panel = (LayoutPanel)this.TargetGroup.Items[0];
panel.Visibility = System.Windows.Visibility.Hidden;
}
this.TargetGroup.Items.Clear();
this.TargetGroup.Items.Add(this.BitPanel.LayoutPanel);
this.BitPanel.LayoutPanel.Visibility = System.Windows.Visibility.Visible;
}
}
}
}
<file_sep>using CardWorkbench.Utils;
using DevExpress.Mvvm;
using DevExpress.Xpf.Core.Native;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace CardWorkbench.ViewModels.CommonControls
{
/// <summary>
/// 自定义控件通用ViewModel类
/// </summary>
public abstract class CommonControlViewModel : ViewModelBase
{
/// <summary>
/// 控件点击事件命令
/// </summary>
public ICommand CommonControlClickCommand
{
get { return new DelegateCommand<MouseButtonEventArgs>(onCommonControlClick, x => { return true; }); }
}
private void onCommonControlClick(MouseButtonEventArgs e)
{
UIControlHelper.setClickedUserControl2TopIndex(e, MainWindowViewModel.CANVAS_CUSTOM_CONTROL_NAME);
}
}
}
<file_sep>using DevExpress.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CardWorkbench.ViewModels.CommonControls
{
/// <summary>
/// 自定义控件指示灯ViewModel类
/// </summary>
public class LampControlViewModel : CommonControlViewModel
{
}
}
<file_sep>using CardWorkbench.Models;
using CardWorkbench.Utils;
using DevExpress.Mvvm;
using DevExpress.Xpf.Charts;
using DevExpress.Xpf.Core.Native;
using DevExpress.Xpf.Grid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
namespace CardWorkbench.ViewModels.CommonControls
{
/// <summary>
/// 自定义控件曲线ViewModel类
/// </summary>
public class ChartControlViewModel : CommonControlViewModel
{
private DispatcherTimer timer = new DispatcherTimer();
private int number = 50;
private int value = 1;
private int interval = 1;
private LineSeries2D series2D = null;
public ICommand ChartControlDragEnterCommand
{
get { return new DelegateCommand<DragEventArgs>(onChartControlDragEnter, x => { return true; }); }
}
private void onChartControlDragEnter(DragEventArgs e)
{
e.Effects = DragDropEffects.Copy;
e.Handled = true;
}
public ICommand ChartControlDropCommand
{
get { return new DelegateCommand<DragEventArgs>(onChartControlDrop, x => { return true; }); }
}
private void onChartControlDrop(DragEventArgs e)
{
//int rowHandle = (int)e.Data.GetData(typeof(int));
//MyObject myObject = (MyObject)grid1.GetRow(rowHandle);
//MessageBox.Show("Hello"+rowHandle);
RowData rowData = (RowData)e.Data.GetData(typeof(RowData));
if (rowData != null)
{
//FrameworkElement root = LayoutHelper.GetTopLevelVisual(e.Source as DependencyObject);
Pane chartPane = e.Source as Pane;
XYDiagram2D xyDiagram2D = LayoutHelper.FindParentObject<XYDiagram2D>(chartPane as DependencyObject);
ChartControl parentChartControl = LayoutHelper.FindParentObject<ChartControl>(chartPane as DependencyObject);
if (parentChartControl != null)
{
Title lineChartTile = parentChartControl.Titles[0] as Title ;
Param rowParam = rowData.Row as Param;
string titleContent = lineChartTile.Content as string;
if (titleContent == null || "".Equals(titleContent))
{
lineChartTile.Content = rowParam.paramChineseName + "曲线";
}
}
if (series2D == null && xyDiagram2D != null)
{
series2D = xyDiagram2D.Series[0] as LineSeries2D;
timer.Interval = TimeSpan.FromMilliseconds(50);
timer.Tick += new EventHandler(RefreshPlot);
timer.IsEnabled = true;
}
}
//MessageBox.Show(((Param)rowData.Row).paramName);
}
private void RefreshPlot(object sender, EventArgs e)
{
if (value > number)
{
value = 1;
}
else
{
value += 2;
}
SeriesPoint p = new SeriesPoint(interval, value);
if (series2D != null)
{
series2D.Points.Add(p);
interval++;
if (series2D.Points.Count > number)
{
series2D.Points.RemoveAt(0);
}
}
}
}
}
<file_sep>using DevExpress.Mvvm;
using DevExpress.Xpf.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace CardWorkbench.ViewModels.MenuControls
{
public abstract class MenuControlsViewModel : ViewModelBase
{
public ICommand stopLoadingSplashCommand
{
get { return new DelegateCommand<object>(onstopLoadingSplashLoaded, x => { return true; }); }
}
private void onstopLoadingSplashLoaded(object context)
{
DXSplashScreen.Close();
}
}
}
<file_sep>
using DevExpress.Mvvm;
using DevExpress.Xpf.Gauges;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
namespace CardWorkbench.ViewModels.CustomControls
{
public class RFLevelMasterGaugeViewModel : ViewModelBase
{
//临时引入一个信号强度计时器
private DispatcherTimer timer = new DispatcherTimer();
//信号强度刻度条
LinearScale linearScale;
//信号强度进度条命令
public ICommand masterMcLevelProgressBarCommand
{
get { return new DelegateCommand<RoutedEventArgs>(onMasterMcLevelProgressBarLoaded, x => { return true; }); }
}
private void onMasterMcLevelProgressBarLoaded(RoutedEventArgs e)
{
linearScale = e.Source as LinearScale;
timer.Interval = TimeSpan.FromMilliseconds(200);
timer.Tick += new EventHandler(masterLevelRandomChange);
timer.Start();
}
private void masterLevelRandomChange(object sender, EventArgs e)
{
Random rnd = new Random();
double val = rnd.Next(-110, -9); // creates a number between 1 and 12
linearScale.Ranges[0].EndValue = new RangeValue(val);
}
}
}
| 381d7d770bb5c7a46314422b4afc32e5335fb422 | [
"C#"
] | 24 | C# | avicitcd/CardGroupRepository | 6c9441e1cd8304c7b7753a528497f414e9267278 | f84e30146719d677d1ba39026c0e574218d3c6d3 | |
refs/heads/master | <repo_name>TeacHKal/PHP---Scripts-for-Android-Chat-app<file_sep>/chat_app/index.php
<?php
echo "tannaan";<file_sep>/chat_app/chat.php
<?php
echo "lalal";<file_sep>/chat_app/upload.php
<?php
include 'credencials.php';
$db_driver = Credencials::db_driver;
$servername = Credencials::servername;
$dbname = Credencials::dbname;
$port = Credencials::port;
$username = Credencials::username;
$password = Credencials::password;
// $json = file_get_contents ( $_POST['data1'] );
$obj = json_decode ( $_POST ['json'] );
$nickname = $obj->{'nickname'};
$message = $obj->{'message'};
try {
$conn = new PDO ( "mysql:host=$servername;dbname=$dbname", $username, $password );
// set the PDO error mode to exception
$conn->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// prepare sql and bind parameters
$stmt = $conn->prepare ( "INSERT INTO chat_app (nickname, message)
VALUES (:nickname, :message)" );
$stmt->bindParam ( ':nickname', $nickname );
$stmt->bindParam ( ':message', $message );
// insert a row
// $nickname = "Bot1";
// $message = "This is a bot message";
$stmt->execute ();
echo "New records created successfully";
} catch ( PDOException $e ) {
echo "Error: " . $e->getMessage ();
}
$conn = null;
<file_sep>/chat_app/.credencials.php
<?php
// Example of Credencials
class Credencials {
const db_driver = "mysql";
const servername = "";
const dbname = "";
const port = "";
const username = "";
const password = "";
}
<file_sep>/chat_app/download.php
<?php
include 'credencials.php';
$db_driver = Credencials::db_driver;
$servername = Credencials::servername;
$dbname = Credencials::dbname;
$port = Credencials::port;
$username = Credencials::username;
$password = Credencials::password;
try {
$conn = new PDO ( "mysql:host=$servername;dbname=$dbname", $username, $password );
// set the PDO error mode to exception
$conn->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->prepare ( "SELECT * FROM chat_app ORDER BY timestamp DESC LIMIT 30" );
$stmt->execute ();
$expression = $stmt->fetchAll ( \PDO::FETCH_ASSOC );
$result = json_encode ( $expression );
echo $result;
} catch ( PDOException $e ) {
echo "Error: " . $e->getMessage ();
}
$conn = null; | 5495d3b0a637c88595a29368ded4748c3716407a | [
"PHP"
] | 5 | PHP | TeacHKal/PHP---Scripts-for-Android-Chat-app | bde0ec5f107998ffee633266a27483634c4ffed6 | e4eff6fde359e5138f112ee9b73a38d72353debe | |
refs/heads/main | <file_sep>module.exports = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(err => {
next(err === undefined ? 'Unknown error occurred' : err);
});
};<file_sep>const express = require('express');
const router = express.Router();
const db = require('../models');
const asyncWrap = require('../middleware/asyncWrap');
router.post('/add-visit', asyncWrap(async (req, res) => {
const currentCount = await db.config.findOne({ where: {
id: 1,
}
});
try {
const incrementResult = await currentCount.increment('visit_count', { by: 1 })
res.status(201).send({ success: true, result: incrementResult });
} catch (e) {
console.log(e);
res.status(400).send(e);
}
}));
router.get('/get-statistics', asyncWrap(async (req, res, next) => {
const usersCount = await db.users.findAll();
const visits = await db.config.findAll();
const visitCount = visits[0]?.dataValues?.visit_count;
const lessonsCount = await db.lessons.findAll();
if (!usersCount || !visitCount || !lessonsCount) {
return res.status(404).json({ success: false, message: 'Some of statistics are missing' });
}
else {
res.status(200).send({ success: true, statistics: {
users: usersCount.length,
visits: visitCount,
lessons: lessonsCount.length,
}
});
}
}));
module.exports = router;<file_sep>const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors')
const indexRouter = require('./routes/index');
const globalRouter = require('./routes/global');
const authRouter = require('./routes/auth')
const usersRouter = require('./routes/users');
const lessonRouter = require('./routes/lessons');
const chapterRouter = require('./routes/chapters');
const sectionRouter = require('./routes/sections');
const testRouter = require('./routes/test');
const commentsRouter = require('./routes/comments')
const app = express();
const Options = {
origin: ["http://localhost:3000"],
allowedHeaders: [
"Content-Type",
"Authorization",
"Access-Allow-Origin-Control",
"Access-Control-Request-Headers",
],
credentials: true,
enablePreflight: true,
}
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors(Options));
// app.use('/auth', require('./auth'));
// app.use(require('./middleware/auth'));
app.use('/', indexRouter);
app.use('/global', globalRouter);
app.use('/auth', authRouter);
app.use('/users', usersRouter);
app.use('/lessons', lessonRouter);
app.use('/chapters', chapterRouter);
app.use('/sections', sectionRouter);
app.use('/test', testRouter);
app.use('/comment', commentsRouter)
module.exports = app;
<file_sep>const express = require('express');
const router = express.Router();
const db = require('../models');
const asyncWrap = require('../middleware/asyncWrap');
const bcrypt = require('bcryptjs');
router.post('/sign-up', asyncWrap(async (req, res) => {
const { first_name, last_name, email, password } = req.body;
const hashedPass = bcrypt.hashSync(password, 13);
if (!req.body.email || !req.body.password) {
res.status(400).send({
status: false,
message: 'Fields are required!'
});
} else {
await db.users.create({
email,
password: <PASSWORD>,
first_name,
last_name,
type: 'user',
}).then(() => {
res.status(201).send({ success: true });
}).catch((error) => {
res.status(400).send(error);
});
}
}))
module.exports = router;
<file_sep>const express = require('express');
const router = express.Router();
const db = require('../models');
const asyncWrap = require('../middleware/asyncWrap');
router.get('/get-sections', asyncWrap(async (req, res, next) => {
const { chapter_id } = req.query;
const sections = await db.sections.findAll({
where: {
chapterId: chapter_id,
}
});
if (!sections)
return res.status(404).json({ success: false, message: 'No Section found' });
else {
const sectionsResponse = sections?.map((section) => {
return {
id: section.id,
title: section.title,
};
})
res.status(200).send({ success: true, sections: sectionsResponse });
}
}));
router.post('/create-section', asyncWrap(async (req, res) => {
const { section, id } = req.body;
if (!section) {
res.status(400).send({
status: false,
message: 'Field is required!'
});
} else {
let result;
try {
result = await db.sections.create({
title: section,
chapterId: id,
})
res.status(201).send({success: true});
} catch (e) {
console.log(e);
res.status(400).send(e);
}
}
}));
module.exports = router;<file_sep>const express = require('express');
const router = express.Router();
const db = require('../models');
const asyncWrap = require('../middleware/asyncWrap');
router.get('/get-chapters', asyncWrap(async (req, res, next) => {
const chapters = await db.chapters.findAll();
if (!chapters)
return res.status(404).json({ success: false, message: 'No lesson found' });
else {
const chaptersResponse = chapters?.map((chapter) => {
return {
id: chapter.id,
title: chapter.title,
};
})
res.status(200).send({success: true, chapters: chaptersResponse });
}
}));
router.post('/create-chapter', asyncWrap(async (req, res) => {
const { chapter } = req.body;
if (!chapter) {
res.status(400).send({
status: false,
message: 'Field is required!'
});
} else {
let result;
try {
result = await db.chapters.create({
title: chapter,
})
res.status(201).send({ success: true });
} catch (e) {
console.log(e);
res.status(400).send(e);
}
}
}));
module.exports = router;<file_sep>const express = require('express');
const router = express.Router();
const db = require('../models');
const asyncWrap = require('../middleware/asyncWrap');
router.get('/get-tests', asyncWrap(async (req, res) => {
const { sectionId } = req.query;
const tests = await db.tests.findAll({
where: {
sectionId: +sectionId,
},
attributes: [
'id',
],
include: [
{
model: db.questions,
attributes: [
'id',
'testId',
'question',
],
include: [
{
model: db.answers,
attributes: [
'id',
'questionId',
'option',
]
}
]
}
]
});
if (!tests)
return res.status(404).json({ success: false, message: 'No Test found' });
else {
res.status(200).send({ success: true, tests });
}
}))
router.post('/create-test', asyncWrap(async (req, res) => {
const { data, sectionId, questionsCount } = req.body;
if (!data || !sectionId) {
res.status(400).send({
status: false,
message: 'Fields are required!'
});
} else {
let testResult
let result;
try {
for(let i = 0; i < questionsCount; i++) {
testResult = await db.tests.create({
sectionId,
})
result = await db.questions.create({
testId: testResult.dataValues.id,
question: data[`question_${i}`],
})
await [1,2,3,4].forEach((_, index) => (
db.answers.create({
questionId: result.dataValues.id,
option: data[`answer_${i}_${index}`],
isCorrect: data[`correct_${i}_${index}`],
})
))
}
res.status(201).send({ success: true });
} catch (e) {
console.log(e);
res.status(400).send(e);
}
}
}));
router.post('/submit-test', asyncWrap(async (req, res) => {
const { answers, sectionId } = req.body;
const tests = await db.tests.findAll({
where: {
sectionId: +sectionId,
},
attributes: [
'id',
],
include: [
{
model: db.questions,
attributes: [
'id',
'testId',
'question',
],
include: [
{
model: db.answers,
attributes: [
'id',
'questionId',
'option',
'isCorrect',
]
}
]
}
]
});
const correctAnswers = tests.map(val => val.questions[0].answers.map(answer => answer.dataValues));
const correctOptions = correctAnswers.map (item => item.find(option => option.isCorrect));
const rightAnswerIds = Object.values(answers);
const matchingOptions = correctOptions.map(option => rightAnswerIds.includes(option.id.toString()));
let correctAnswersCount = matchingOptions.filter(value => !!value).length;
res.status(200).send({ success: true, data: { correctOptions, correctAnswersCount }});
}));
module.exports = router;<file_sep>const jwt = require('jsonwebtoken');
const User = require('../models/users');
const asyncWrap = require('./asyncWrap');
module.exports = asyncWrap(async (req, res, next) => {
const token = req.headers['x-access-token'];
if (!token)
return res
.status(401)
.send({ success: false, message: 'No token provided.' });
jwt.verify(token, '<PASSWORD>', async (err, decoded) => {
if (err)
return res
.status(500)
.send({ success: false, message: 'Failed to authenticate token.' });
const user = await User.findById(decoded.id, { password: 0 });
if (!user) {
return res.status(404).send('No user found.');
}
req.user = user;
next();
});
}); | 6ab54eb8a33b88fa796ec098bb0c7ae3ba459d08 | [
"JavaScript"
] | 8 | JavaScript | NatNatali/discrete-server | f50149e0bc215e25edf17cec0c59145d2f1c3ca2 | f171504b2c9e2cb8d38d7936aa31565a52639607 | |
refs/heads/master | <file_sep>package son.nt.en.feed.adapter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.List;
import son.nt.en.R;
import son.nt.en.elite.BusElite;
import son.nt.en.elite.EliteDto;
import son.nt.en.otto.OttoBus;
/**
* Created by Sonnt on 7/7/15.
*/
public class AdapterFeedElite extends RecyclerView.Adapter<AdapterFeedElite.ViewHolder> {
private static final String TAG = AdapterFeedElite.class.getSimpleName();
public List<EliteDto> mValues;
Context context;
private final WeakReference<Context> contextWeakReference;
private int previous = 0;
public AdapterFeedElite(Context cx) {
this.context = cx;
this.contextWeakReference = new WeakReference<>(cx);
}
public void setData(List<EliteDto> mValues) {
this.mValues = mValues;
notifyDataSetChanged();
}
public EliteDto getItem(int position) {
return mValues.get(position);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_feed_elite_daily, viewGroup, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
EliteDto EliteDto = mValues.get(position);
final EliteDto dto = EliteDto;
String no = String.valueOf(position).trim();
if (no.length() == 1) {
no = no + " ";
} else if (no.length() == 2) {
no = no + " ";
}
viewHolder.createdTimeTextView.setText(no);
viewHolder.messageTextView.setText(dto.title);
viewHolder.messengerTextView.setText(dto.des);
Glide.with(context) //
.load(dto.image)//
.centerCrop()//
.diskCacheStrategy(DiskCacheStrategy.ALL)//
.into(viewHolder.imgBackground);
}
@Override
public int getItemCount() {
return mValues == null ? 0 : mValues.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView messageTextView;
public TextView messengerTextView;
public TextView createdTimeTextView;
public ImageView imgBackground;
public ViewHolder(View v) {
super(v);
messageTextView = (TextView) itemView.findViewById(R.id.messageTextView);
messengerTextView = (TextView) itemView.findViewById(R.id.messengerTextView);
createdTimeTextView = (TextView) itemView.findViewById(R.id.createdTimeTextView);
imgBackground = (ImageView) itemView.findViewById(R.id.imageView);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OttoBus.post(new BusElite(getAdapterPosition()));
}
});
}
}
}
<file_sep>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
classpath 'com.google.gms:google-services:3.0.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
classpath 'me.tatarka:gradle-retrolambda:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
// Sdk and tools
minSdkVersion = 16
targetSdkVersion = 23
compileSdkVersion = 23
buildToolsVersion = '23.0.3'
// App dependencies
supportLibraryVersion = '24.0.0'
butterKnifeVersion = '7.0.1'
frescoVersion = '0.10.0'
dagger2Version = '2.2'
pacerlVersion= '1.1.5'
rxAndroidVersion = '1.2.0'
gsonVersion = '2.6.2'
rxJavaVersion = '1.1.5'
retrofitVersion = '2.0.2'
loggingInterceptorVersion = '2.7.5'
okhttp3Version ='3.3.1'
//Testing
robolectricVersion = '3.1-rc1'
jUnitVersion = '4.12'
assertJVersion = '1.7.1'
mockitoVersion = '2.0.2-beta'
powerMockitoVersion = '1.6.5'
hamcrestVersion = '1.3'
dexmakerVersion = '1.0'
espressoVersion = '2.2.2'
runnerVersion = '0.5'
rulesVersion = '0.5'
testingSupportLibVersion = '0.1'
supportLibraryDependencies = [
appcompatV7: "com.android.support:appcompat-v7:${supportLibraryVersion}",
supportV4: "com.android.support:support-v4:${supportLibraryVersion}",
design: "com.android.support:design:${supportLibraryVersion}",
recyclerview: "com.android.support:recyclerview-v7:${supportLibraryVersion}",
cardview: "com.android.support:cardview-v7:${supportLibraryVersion}",
annotations:"com.android.support:support-annotations:${supportLibraryVersion}",
]
domainDependencies = [
daggerApt: "com.google.dagger:dagger-compiler:${dagger2Version}",
dagger: "com.google.dagger:dagger:${dagger2Version}",
parcelerApt:"org.parceler:parceler:${pacerlVersion}",
parceler:"org.parceler:parceler-api:${pacerlVersion}",
rxJava: "io.reactivex:rxjava:${rxJavaVersion}",
rxAndroid: "io.reactivex:rxandroid:${rxAndroidVersion}",
fresco:"com.facebook.fresco:fresco:${frescoVersion}",
butterknife:"com.jakewharton:butterknife:${butterKnifeVersion}",
gson:"com.google.code.gson:gson:${gsonVersion}",
retrofit:"com.squareup.retrofit2:retrofit:${retrofitVersion}",
retrofitAdapter: "com.squareup.retrofit2:adapter-rxjava:${retrofitVersion}",
retrofitConverter: "com.squareup.retrofit2:converter-gson:${retrofitVersion}",
]
domainTestDependencies = [
junit: "junit:junit:${jUnitVersion}",
mockito: "org.mockito:mockito-all:${mockitoVersion}",
robolectric: "org.robolectric:robolectric:${robolectricVersion}",
]
}
<file_sep>package son.nt.en.di;
import android.app.Application;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* Created by sonnt on 8/15/16.
*/
@Module
public class AppModule
{
Application mApplication;
public AppModule(Application mApplication)
{
this.mApplication = mApplication;
}
@Provides
@Singleton
Application provideMyApplication()
{
return mApplication;
}
@Provides
@Singleton
DatabaseReference provideDatabaseReference()
{
return FirebaseDatabase.getInstance().getReference();
}
}
<file_sep>package son.nt.en.login;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import son.nt.en.HomeActivity;
import son.nt.en.R;
import son.nt.en.base.BaseActivity;
import son.nt.en.google_client_api.DaggerGoogleApiComponent;
import son.nt.en.google_client_api.GoogleApiClientModule;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends BaseActivity
implements OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_READ_CONTACTS = 0;
private static final String REQUEST_START = "REQUEST_START";
private static final String TAG = LoginActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 9001;
@BindView(R.id.sign_in_button)
SignInButton mSignInButton;
@BindView(R.id.login_welcome)
TextView mTxtWelcome;
@BindView(R.id.login_skip)
TextView mTxtSkip;
@Inject
FirebaseAuth mFirebaseAuth;
@Inject
FirebaseUser mFirebaseUser;
@Inject
GoogleApiClient mGoogleApiClient;
private boolean isNotStart = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
isNotStart = getIntent().getBooleanExtra("REQUEST_START", false);
//inject
GoogleApiClientModule googleApiClientModule = new GoogleApiClientModule(this, getString(R.string.default_web_client_id), this);
DaggerGoogleApiComponent.builder().googleApiClientModule(googleApiClientModule).build().inject(this);
// Set up the login form.
mTxtWelcome.setText(getString(R.string.welcome_to, getString(R.string.app_name)));
mSignInButton.setOnClickListener(this);
mTxtSkip.setOnClickListener(this);
if (mFirebaseUser != null) {
moveToHome();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button: {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
break;
}
case R.id.login_skip: {
moveToHome();
break;
}
}
}
private void moveToHome() {
Toast.makeText(this, "Hello " + mFirebaseUser.getDisplayName(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed
Log.e(TAG, "Google Sign In failed.");
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mFirebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
} else {
if (isNotStart) {
setResult(RESULT_OK);
finish();
} else {
moveToHome();
finish();
}
}
}
});
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
//Do nothing
}
}
<file_sep>package son.nt.en.hellochao;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.bumptech.glide.Glide;
import com.squareup.otto.Subscribe;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import son.nt.en.FireBaseConstant;
import son.nt.en.R;
import son.nt.en.base.BaseFragment;
import son.nt.en.otto.OttoBus;
import son.nt.en.service.GoPlayer;
import son.nt.en.service.MusicService;
import son.nt.en.utils.Logger;
/**
* Created by sonnt on 7/11/16.
*/
public class HelloChaoFragment extends BaseFragment implements HelloChaoContract.View, View.OnClickListener, TextWatcher {
public static final String TAG = HelloChaoFragment.class.getSimpleName();
private RecyclerView mMessageRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ProgressBar mProgressBar;
@BindView(R.id.CoordinatorLayoutChat)
CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.txt_search)
EditText txtSearch;
@BindView(R.id.btn_clear)
View btnClear;
@BindView(R.id.player_play)
ImageView mImgPlay;
@BindView(R.id.img_track)
ImageView mImgTrack;
@BindView(R.id.txt_title)
TextView mTxtTitle;
@BindView(R.id.txt_des)
TextView mTxtDes;
DatabaseReference mFirebaseDatabaseReference;
private AdapterHelloChao mAdapter;
boolean isBind = false;
MusicService mPlayService;
SearchHandler mSearchHandler;
HelloChaoContract.Presenter mPresenter;
public static HelloChaoFragment newInstace() {
HelloChaoFragment f = new HelloChaoFragment();
return f;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OttoBus.register(this);
MusicService.bindToMe(getContext(), serviceConnectionPlayer);
mPresenter = new HelloChaoPresenter(this, FirebaseDatabase.getInstance().getReference());
}
@Override
public void onDestroy() {
OttoBus.unRegister(this);
getActivity().unbindService(serviceConnectionPlayer);
if (mSearchHandler != null) {
mSearchHandler.removeMessage();
mSearchHandler = null;
}
super.onDestroy();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hello_chao, container, false);
ButterKnife.bind(this, view);
// Initialize ProgressBar and RecyclerView.
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mMessageRecyclerView = (RecyclerView) view.findViewById(R.id.messageRecyclerView);
//search
btnClear.setOnClickListener(this);
txtSearch.addTextChangedListener(this);
mLinearLayoutManager = new LinearLayoutManager(getActivity());
mLinearLayoutManager.setStackFromEnd(true);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
mAdapter = new AdapterHelloChao(getActivity());
// New child entries
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
mFirebaseDatabaseReference.child(FireBaseConstant.TABLE_HELLO_CHAO).orderByChild("text")
.addValueEventListener(valueEventListener);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
mMessageRecyclerView.setAdapter(mAdapter);
//onclick
mImgPlay.setOnClickListener(this);
return view;
}
ServiceConnection serviceConnectionPlayer = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.LocalBinder localBinder = (MusicService.LocalBinder) service;
mPlayService = localBinder.getService();
isBind = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
isBind = false;
mPlayService = null;
}
};
@Subscribe
public void getSelection(BusSentence busSentence) {
if (mPlayService != null) {
mPlayService.setDataToService(mAdapter.mValues);
mPlayService.playAtPos(busSentence.pos);
}
}
/**
* called from {@link MusicService#play()}
*/
@Subscribe
public void getFromService(GoPlayer goPlayer) {
mTxtTitle.setText(goPlayer.title);
mTxtDes.setText(goPlayer.des);
mImgPlay.setImageResource(goPlayer.command == GoPlayer.DO_PLAY ? R.drawable.icon_paused : R.drawable.icon_played);
if (goPlayer.image != null) {
Glide.with(this).load(goPlayer.image).fitCenter().into(mImgTrack);
}
}
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Logger.debug(TAG, ">>>" + " valueEventListener onDataChange");
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
List<HelloChaoSentences> list = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
HelloChaoSentences post = postSnapshot.getValue(HelloChaoSentences.class);
list.add(post);
}
mAdapter.setData(list);
mPresenter.setData(list);
mMessageRecyclerView.scrollToPosition(0);
if (mPlayService != null) {
mPlayService.setDataToService(list);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
}
};
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_clear: {
txtSearch.setText("");
break;
}
case R.id.player_play: {
if (mPlayService != null) {
mPlayService.play();
}
break;
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() > 0) {
btnClear.setVisibility(View.VISIBLE);
} else {
btnClear.setVisibility(View.GONE);
}
if (mSearchHandler == null) {
mSearchHandler = new SearchHandler(this);
}
mSearchHandler.removeMessage();
mSearchHandler.doSearch();
}
private void doSearch() {
String keyword = txtSearch.getText().toString();
Logger.debug(TAG, ">>>" + "doSearch:" + keyword);
mPresenter.doSearch(keyword);
}
@Override
public void resultSearch(List<HelloChaoSentences> list) {
mAdapter.setData(list);
}
private static class SearchHandler extends Handler {
public static final int WHAT_SEARCH = 1;
WeakReference<HelloChaoFragment> helloChaoFragmentWeakReference = new WeakReference<HelloChaoFragment>(null);
public SearchHandler(HelloChaoFragment helloChaoFragment) {
helloChaoFragmentWeakReference = new WeakReference<HelloChaoFragment>(helloChaoFragment);
}
@Override
public void handleMessage(Message message) {
switch (message.what) {
case WHAT_SEARCH: {
HelloChaoFragment f = helloChaoFragmentWeakReference.get();
if (f != null) {
f.doSearch();
}
break;
}
}
}
public void removeMessage() {
removeMessages(WHAT_SEARCH);
}
public void doSearch() {
sendEmptyMessageDelayed(WHAT_SEARCH, 750);
}
}
}
<file_sep>package son.nt.en.feed;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import rx.Single;
import rx.SingleSubscriber;
import son.nt.en.FireBaseConstant;
import son.nt.en.MsConst;
import son.nt.en.elite.EliteDto;
import son.nt.en.esl.EslDailyDto;
import son.nt.en.hellochao.HelloChaoSentences;
import son.nt.en.utils.Logger;
/**
* Created by sonnt on 8/22/16.
*/
public class FeedRepository implements FeedContract.IRepository {
public static final String TAG = FeedRepository.class.getSimpleName();
SingleSubscriber<List<EliteDto>> subscriberElite;
SingleSubscriber<List<EslDailyDto>> subscriberEsl;
DatabaseReference mDatabaseReference;
@Inject
public FeedRepository(DatabaseReference databaseReference) {
mDatabaseReference = databaseReference;
}
@Override
public void getElite(SingleSubscriber<List<EliteDto>> getElites) {
this.subscriberElite = getElites;
Query query = mDatabaseReference.child(FireBaseConstant.TABLE_ELITE_DAILY).limitToFirst(5);
query.addListenerForSingleValueEvent(mEliteValueEventListener);
}
@Override
public void getESL(SingleSubscriber<List<EslDailyDto>> subscriberEsl) {
this.subscriberEsl = subscriberEsl;
Query query = mDatabaseReference.child(FireBaseConstant.TABLE_ESL_DAILY).limitToFirst(5);
query.addListenerForSingleValueEvent(mESlValueEventListener);
}
@Override
public Single<List<HelloChaoSentences>> getDailyHelloChao() {
return Single.create(new Single.OnSubscribe<List<HelloChaoSentences>>() {
@Override
public void call(SingleSubscriber<? super List<HelloChaoSentences>> singleSubscriber) {
try {
Document document = Jsoup.connect(MsConst.HELLO_CHAO_THU_THACH_TRONG_NGAY).get();
Elements items = document.getElementsByAttributeValue("class", "box shadow light callout");
Elements data = items.get(0).getElementsByClass("raw-menu");
List<HelloChaoSentences> helloChaoSentences = new ArrayList<>();
HelloChaoSentences helloChaoSentence;
for (Element e : data.get(0).getAllElements()) {
if (e.nodeName().equals("li")) {
String link = e.getElementsByAttribute("href").attr("href");
String textEng = e.getAllElements().get(1).text();
String textVi = e.getAllElements().get(0).text().replace(textEng, "");
Logger.debug(TAG, ">>>" + "link:" + link + " ;textVi:" + textVi + ";textEng:" + textEng);
helloChaoSentence = new HelloChaoSentences(textEng, link, textVi);
helloChaoSentences.add(helloChaoSentence);
}
}
singleSubscriber.onSuccess(helloChaoSentences);
} catch (Exception e) {
singleSubscriber.onError(e);
}
}
});
}
ValueEventListener mESlValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<EslDailyDto> list = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
EslDailyDto post = postSnapshot.getValue(EslDailyDto.class);
list.add(post);
}
subscriberEsl.onSuccess(list);
}
@Override
public void onCancelled(DatabaseError databaseError) {
subscriberEsl.onError(new Throwable(databaseError.getMessage()));
}
};
ValueEventListener mEliteValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<EliteDto> list = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
EliteDto post = postSnapshot.getValue(EliteDto.class);
list.add(post);
}
subscriberElite.onSuccess(list);
}
@Override
public void onCancelled(DatabaseError databaseError) {
subscriberElite.onError(new Exception((databaseError.toException())));
}
};
}
<file_sep>package son.nt.en;
import android.app.Application;
import android.content.Intent;
import son.nt.en.di.AppComponent;
import son.nt.en.di.AppModule;
import son.nt.en.di.DaggerAppComponent;
import son.nt.en.service.MusicService;
/**
* Created by sonnt on 7/15/16.
*/
public class MyApplication extends Application
{
AppComponent mAppComponent;
@Override
public void onCreate()
{
super.onCreate();
dagger2();
startService(new Intent(getApplicationContext(), MusicService.class));
}
@Override
public void onTerminate()
{
super.onTerminate();
stopService(new Intent(getApplicationContext(), MusicService.class));
}
private void dagger2()
{
mAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
}
public AppComponent getAppComponent()
{
return mAppComponent;
}
}
<file_sep>package son.nt.en.hellochao;
/**
* Created by sonnt on 7/14/16.
*/
public class BusSentence {
public BusSentence(int pos) {
this.pos = pos;
}
public int pos;
}
<file_sep>package son.nt.en.elite;
import son.nt.en.base.IBasePresenter;
/**
* Created by sonnt on 7/14/16.
*/
public interface ContractDailyElite {
interface View {
}
interface Presenter extends IBasePresenter
{
}
interface Repository {
void getData();
}
}
<file_sep>package son.nt.en.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
/**
* Created by sonnt on 8/15/16.
*/
public abstract class BaseInjectActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
injectPresenter();
}
abstract public void injectPresenter ();
}
<file_sep>package son.nt.en.feed.di;
import com.google.firebase.database.DatabaseReference;
import dagger.Module;
import dagger.Provides;
import son.nt.en.di.scoped.ActivityScoped;
import son.nt.en.feed.FeedContract;
import son.nt.en.feed.FeedPresenter;
import son.nt.en.feed.FeedRepository;
import son.nt.en.utils.CompositeSubs;
/**
* Created by sonnt on 8/15/16.
* This module is used to create {@link son.nt.en.feed.FeedPresenter}
*/
@Module
public class FeedPresenterModule
{
private FeedContract.View mView;
public FeedPresenterModule(FeedContract.View mView)
{
this.mView = mView;
}
@Provides
@ActivityScoped
FeedContract.View provideView ()
{
return mView;
}
@Provides
@ActivityScoped
FeedContract.IRepository provideRepository (DatabaseReference databaseReference)
{
return new FeedRepository(databaseReference);
}
@Provides
@ActivityScoped
CompositeSubs provideCompositeSubs ()
{
return new CompositeSubs();
}
@Provides
@ActivityScoped
FeedContract.Presenter providePresenter (FeedContract.IRepository repository, FeedContract.View view, CompositeSubs compositeSubs) {
return new FeedPresenter(repository, view, compositeSubs);
}
}
<file_sep>package son.nt.en.esl;
import android.text.TextUtils;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import rx.Observer;
import son.nt.en.FireBaseConstant;
import son.nt.en.utils.Logger;
/**
* Created by sonnt on 7/29/16.
*/
public class FireBaseRepository implements EslDailyContract.IRepository
{
public static final String TAG = FireBaseRepository.class.getSimpleName();
DatabaseReference mDatabaseReference;
List<EslDailyDto> mList = new ArrayList<>();
Observer<List<EslDailyDto>> observer;
public FireBaseRepository(DatabaseReference mDatabaseReference)
{
this.mDatabaseReference = mDatabaseReference;
}
@Override
public void getData(Observer<List<EslDailyDto>> callback)
{
mDatabaseReference.child(FireBaseConstant.TABLE_ESL_DAILY).addValueEventListener(valueEventListener);
this.observer = callback;
}
ValueEventListener valueEventListener = new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
mList.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
EslDailyDto post = postSnapshot.getValue(EslDailyDto.class);
mList.add(post);
}
/**
* get result at {@link EslDailyPresenter#observer}
*/
observer.onNext(mList);
}
@Override
public void onCancelled(DatabaseError databaseError)
{
observer.onError(new Throwable(databaseError.toException()));
}
};
@Override
public void doSearch4(String keyword, Observer<List<EslDailyDto>> callback)
{
Logger.debug(TAG, ">>>" + "doSearch4:" + keyword + ";mList:" + mList.size());
if (TextUtils.isEmpty(keyword))
{
callback.onNext(mList);
return;
}
//search
List<EslDailyDto> list = new ArrayList<>();
for (EslDailyDto d : mList)
{
if (d.getHomeTitle().toLowerCase().contains(keyword.toLowerCase())
|| d.getHomeDescription().toLowerCase().contains(keyword.toLowerCase()))
{
list.add(d);
}
}
callback.onNext(list);
}
@Override
public List<EslDailyDto> doSearch3(String keyword) {
if (TextUtils.isEmpty(keyword))
{
return mList;
}
//search
List<EslDailyDto> list = new ArrayList<>();
for (EslDailyDto d : mList)
{
if (d.getHomeTitle().toLowerCase().contains(keyword.toLowerCase())
|| d.getHomeDescription().toLowerCase().contains(keyword.toLowerCase()))
{
list.add(d);
}
}
return list;
}
}
<file_sep>package son.nt.en.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by sonnt on 7/14/16.
*/
public class DataTimesUtil
{
private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DAY_MILLIS = 24 * HOUR_MILLIS;
public static String getTimeAgo(long time)
{
if (time < 1000000000000L)
{
// if timestamp given in seconds, convert to millis
time *= 1000;
}
long now = System.currentTimeMillis();
if (time > now || time <= 0)
{
return null;
}
// TODO: localize
final long diff = now - time;
if (diff < MINUTE_MILLIS)
{
return "just now";
}
else if (diff < 2 * MINUTE_MILLIS)
{
return "a minute ago";
}
else if (diff < 50 * MINUTE_MILLIS)
{
return diff / MINUTE_MILLIS + " minutes ago";
}
else if (diff < 90 * MINUTE_MILLIS)
{
return "an hour ago";
}
else if (diff < 24 * HOUR_MILLIS)
{
return diff / HOUR_MILLIS + " hours ago";
}
else if (diff < 48 * HOUR_MILLIS)
{
return "yesterday";
}
else
{
return diff / DAY_MILLIS + " days ago";
}
}
public static long convertDateToMilliseconds(String fromFormat, String sourceDate)
{
try
{
SimpleDateFormat sdfFrom = new SimpleDateFormat(fromFormat);
//SimpleDateFormat sdfTo = new SimpleDateFormat(toFormat);
Date date = sdfFrom.parse(sourceDate);
//String convertedDate = sdfTo.format(date);
return date.getTime();
}
catch (Exception e)
{
e.printStackTrace();
}
return 0L;
}
}
<file_sep>package son.nt.en.home;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.List;
import son.nt.en.base.BaseFragment;
/**
* Created by sonnt on 7/11/16.
*/
public class HomeAdapter extends FragmentPagerAdapter {
private List<BaseFragment> mFragments;
public HomeAdapter(FragmentManager fm) {
super(fm);
}
public HomeAdapter (FragmentManager fm, List<BaseFragment> mFragments)
{
super(fm);
this.mFragments = mFragments;
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments == null ? 0 : mFragments.size();
}
public void addFragment(BaseFragment fragment) {
mFragments.add(fragment);
notifyDataSetChanged();
}
@Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
<file_sep>package son.nt.en.elite;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.widget.ProgressBar;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import com.squareup.otto.Subscribe;
import org.parceler.Parcels;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import son.nt.en.FireBaseConstant;
import son.nt.en.MyApplication;
import son.nt.en.R;
import son.nt.en.base.BaseInjectActivity;
import son.nt.en.elite.content.EliteContentActivity;
import son.nt.en.elite.di.DaggerEliteComponent;
import son.nt.en.elite.di.ElitePresenterModule;
import son.nt.en.otto.OttoBus;
import son.nt.en.utils.Logger;
public class EliteDailyActivity extends BaseInjectActivity implements ContractDailyElite.View
{
public static final String TAG = EliteDailyActivity.class.getSimpleName();
private GridLayoutManager mLinearLayoutManager;
@BindView(R.id.CoordinatorLayoutChat)
CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.progressBar) ProgressBar mProgressBar;
@BindView(R.id.messageRecyclerView) RecyclerView mMessageRecyclerView;
@Inject DatabaseReference mFirebaseDatabaseReference;
private AdapterEliteDaily mAdapter;
@Inject
EliteDailyPresenter mPresenter;
@Override
public void injectPresenter()
{
//inject
DaggerEliteComponent.builder().elitePresenterModule(new ElitePresenterModule(this))//
.appComponent(((MyApplication)getApplication()).getAppComponent())
.build()//
.inject(this);
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
OttoBus.register(this);
setContentView(R.layout.activity_elite_daily);
ButterKnife.bind(this);
getSupportActionBar().setTitle("Reading");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mLinearLayoutManager = new GridLayoutManager(this, 1);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
mAdapter = new AdapterEliteDaily(this);
// mProgressBar.setVisibility(ProgressBar.INVISIBLE);
// New child entries
// mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
mFirebaseDatabaseReference.child(FireBaseConstant.TABLE_ELITE_DAILY).addValueEventListener(valueEventListener);
mMessageRecyclerView.setAdapter(mAdapter);
mPresenter.onStart();
}
@Override
protected void onDestroy()
{
OttoBus.unRegister(this);
super.onDestroy();
}
ValueEventListener valueEventListener = new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
List<EliteDto> list = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
EliteDto post = postSnapshot.getValue(EliteDto.class);
list.add(post);
}
Logger.debug(TAG, ">>>" + "list:" + list.size());
mAdapter.setData(list);
mMessageRecyclerView.scrollToPosition(0);
}
@Override
public void onCancelled(DatabaseError databaseError)
{
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
}
};
@Subscribe
public void getClick(BusElite busElite)
{
EliteDto eliteDto = mAdapter.mValues.get(busElite.pos);
Intent intent = new Intent(this, EliteContentActivity.class);
intent.putExtra("data", Parcels.wrap(eliteDto));
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home)
{
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package son.nt.en.chat;
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
/**
* Created by sonnt on 7/13/16.
*/
public class ChatPresenter implements ChatContract.Presenter
{
private ChatContract.View mView;
private FirebaseAuth mFirebaseAuth;
private DatabaseReference mDatabaseReference;
public ChatPresenter(@NonNull ChatContract.View view, @NonNull FirebaseAuth mFirebaseAuth,
@NonNull DatabaseReference mDatabaseReference)
{
this.mView = view;
this.mFirebaseAuth = mFirebaseAuth;
this.mDatabaseReference = mDatabaseReference;
}
@Override
public void onStart()
{
}
@Override
public void sendMessage(String s)
{
final FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
if (currentUser == null)
{
mView.userDoNotLogin(s);
return;
}
// FriendlyMessage friendlyMessage = new FriendlyMessage(s, currentUser.getDisplayName(),
// currentUser.getPhotoUrl() != null ? currentUser.getPhotoUrl().toString() : "");
FriendlyMessage friendlyMessage = new FriendlyMessage(currentUser.getUid(), s, currentUser.getDisplayName(),
currentUser.getPhotoUrl() != null ? currentUser.getPhotoUrl().toString() : "",
System.currentTimeMillis());
mDatabaseReference.child(ChatFragment.MESSAGES_CHILD).push().setValue(friendlyMessage)
.addOnCompleteListener(new OnCompleteListener<Void>()
{
@Override
public void onComplete(@NonNull Task<Void> task)
{
mView.clearMessage("");
}
}).addOnFailureListener(new OnFailureListener()
{
@Override
public void onFailure(@NonNull Exception e)
{
}
});
}
}
<file_sep>package son.nt.en.elite;
/**
* Created by sonnt on 7/20/16.
*/
public class EliteContentDto {
public String id;
public String content;
public EliteContentDto() {
}
public EliteContentDto(String id, String content) {
this.id = id;
this.content = content;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
<file_sep>package son.nt.en.hellochao;
import java.util.List;
import son.nt.en.base.IAudioFile;
/**
* Created by sonnt on 7/14/16.
*/
public class HelloChaoSentences implements IAudioFile
{
public String text;
public String audio;
public String translate;
public HelloChaoSentences() {
}
public HelloChaoSentences(String text, String audio, String translate) {
this.text = text;
this.audio = audio;
this.translate = translate;
}
public String getText() {
return text;
}
public String getAudio() {
return audio;
}
public String getTranslate() {
return translate;
}
@Override
public String getTitle() {
return text;
}
@Override
public String getLinkMp3() {
return audio;
}
@Override
public String getImage() {
return null;
}
@Override
public String getDescription() {
return translate;
}
@Override
public List<String> getGroup() {
return null;
}
@Override
public Long getDuration() {
return null;
}
@Override
public List<String> getTags() {
return null;
}
}
<file_sep>package son.nt.en.esl;
import java.util.List;
import rx.Observer;
import son.nt.en.base.IBasePresenter;
/**
* Created by sonnt on 7/14/16.
*/
public interface EslDailyContract
{
interface View
{
void resultSearch(List<EslDailyDto> mList);
void setVisibility(boolean b);
}
interface Presenter extends IBasePresenter
{
void onDestroy();
void afterTextChanged(String s);
}
interface IRepository
{
void getData(Observer<List<EslDailyDto>> callback);
void doSearch4(String s, Observer<List<EslDailyDto>> callback);
List<EslDailyDto> doSearch3(String filter);
}
}
<file_sep>package son.nt.en.service;
/**
* Created by sonnt on 5/26/16.
*/
public class GoPlayer {
public static final int DO_PLAY = 1;
public static final int DO_PAUSE = 2;
public int command;
public int pos;
public String title;
public String des;
public String image;
public GoPlayer(int command) {
this.command = command;
}
public GoPlayer(int command, int pos) {
this.command = command;
this.pos = pos;
}
public GoPlayer(int command, String title, String des, String image) {
this.command = command;
this.title = title;
this.des = des;
this.image = image;
}
}
<file_sep>apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'me.tatarka.retrolambda'
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId "son.nt.en"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"
compile "com.android.support:cardview-v7:$rootProject.supportLibraryVersion"
compile "com.android.support:design:$rootProject.supportLibraryVersion"
compile "com.android.support:recyclerview-v7:$rootProject.supportLibraryVersion"
// Google
compile 'com.google.android.gms:play-services-auth:9.0.0'
compile 'com.google.firebase:firebase-database:9.0.0'
compile 'com.google.firebase:firebase-auth:9.0.0'
compile 'com.google.firebase:firebase-config:9.0.0'
compile 'com.google.android.gms:play-services-appinvite:9.0.0'
compile 'com.google.firebase:firebase-messaging:9.0.0'
compile 'com.google.android.gms:play-services-ads:9.0.0'
compile 'com.google.firebase:firebase-crash:9.0.0'
// Firebase UI
compile 'com.firebaseui:firebase-ui-database:0.4.0'
compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'com.jakewharton:butterknife:8.2.1'
apt 'com.jakewharton:butterknife-compiler:8.2.1'
compile 'de.hdodenhof:circleimageview:1.3.0'
compile 'com.squareup:otto:1.3.8'
compile 'org.jsoup:jsoup:1.9.2'
compile 'org.parceler:parceler-api:1.1.5'
apt 'org.parceler:parceler:1.1.5'
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.5'
//flex-box
compile 'com.google.android:flexbox:0.2.3'
//test
testCompile 'org.mockito:mockito-all:1.10.19'
//dagger 2
apt 'com.google.dagger:dagger-compiler:2.0'
compile 'com.google.dagger:dagger:2.0'
provided 'javax.annotation:jsr250-api:1.0'
}
<file_sep>package son.nt.en.test;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import son.nt.en.R;
/**
* Created by sonnt on 8/11/16.
*/
public class Dagger2Activity extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = Dagger2Activity.class.getSimpleName();
@BindView(R.id.btn1)
Button btn1;
@BindView(R.id.btn2)
TextView btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dagger2);
ButterKnife.bind(this);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1: {
break;
}
case R.id.btn2: {
break;
}
}
}
}
<file_sep>package son.nt.en.hellochao;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import son.nt.en.R;
import son.nt.en.otto.OttoBus;
/**
* Created by Sonnt on 7/7/15.
*/
public class AdapterHelloChao extends RecyclerView.Adapter<AdapterHelloChao.ViewHolder>
{
private static final String TAG = AdapterHelloChao.class.getSimpleName();
public List<HelloChaoSentences> mValues;
Context context;
private final WeakReference<Context> contextWeakReference;
private int previous = 0;
public AdapterHelloChao(Context cx)
{
this.context = cx;
this.contextWeakReference = new WeakReference<>(cx);
}
public void setData(List<HelloChaoSentences> mValues)
{
this.mValues = mValues;
notifyDataSetChanged();
}
public HelloChaoSentences getItem(int position)
{
return mValues.get(position);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_hello_chao, viewGroup,
false);
return new ViewHolder(view);
}
// public void setNewPos(int pos)
// {
// mValues.get(previous).setPlaying(false);
// notifyItemChanged(previous);
// mValues.get(pos).setPlaying(true);
// notifyItemChanged(pos);
//
// previous = pos;
// }
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position)
{
HelloChaoSentences HelloChaoSentences = mValues.get(position);
final HelloChaoSentences dto = HelloChaoSentences;
String no = String.valueOf(position).trim();
if (no.length() == 1)
{
no = no + " ";
}
else if (no.length() == 2)
{
no = no + " ";
}
viewHolder.createdTimeTextView.setText(no);
viewHolder.messageTextView.setText(dto.text);
viewHolder.messengerTextView.setText(dto.translate);
// if (HelloChaoSentences.isPlaying())
// {
// viewHolder.view.setBackgroundResource(R.drawable.d_row_speaking);
// viewHolder.imageView.setVisibility(View.VISIBLE);
// }
// else
// {
// viewHolder.imageView.setVisibility(View.GONE);
// viewHolder.view.setBackgroundResource(android.R.color.transparent);
// }
// Glide.with(context).load(HelloChaoSentences.getImage()).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL)
// .into(viewHolder.imageGroup);
}
@Override
public int getItemCount()
{
return mValues == null ? 0 : mValues.size();
}
// public static class ViewHolder extends RecyclerView.ViewHolder
// {
// ImageView imageView;
// ImageView imageGroup;
// TextView txtName;
// View view;
// TextView txtNo;
//
// public ViewHolder(View itemView)
// {
// super(itemView);
// this.view = itemView.findViewById(R.id.row_voice_main);
// this.imageView = (ImageView) itemView.findViewById(R.id.row_voice_playing);
// this.imageGroup = (ImageView) itemView.findViewById(R.id.row_voice_rival);
// this.txtName = (TextView) itemView.findViewById(R.id.row_voice_text);
// txtNo = (TextView) itemView.findViewById(R.id.row_voice_no);
//
// this.view.setOnClickListener(new View.OnClickListener()
// {
// @Override
// public void onClick(View v)
// {
// /**
// * @see MusicPackDetailsActivity#itemClick(GoAdapterHelloChao)
// */
// OttoBus.post(new GoAdapterHelloChao(getAdapterPosition()));
//
// }
// });
//
// }
// }
public static class ViewHolder extends RecyclerView.ViewHolder
{
public TextView messageTextView;
public TextView messengerTextView;
public TextView createdTimeTextView;
public CircleImageView messengerImageView;
public CircleImageView levelImageView;
public ViewHolder(View v)
{
super(v);
messageTextView = (TextView) itemView.findViewById(R.id.messageTextView);
messengerTextView = (TextView) itemView.findViewById(R.id.messengerTextView);
createdTimeTextView = (TextView) itemView.findViewById(R.id.createdTimeTextView);
messengerImageView = (CircleImageView) itemView.findViewById(R.id.messengerImageView);
levelImageView = (CircleImageView) itemView.findViewById(R.id.levelImageView);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OttoBus.post(new BusSentence(getAdapterPosition()));
}
});
}
}
}
<file_sep>package son.nt.en.chat;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import son.nt.en.R;
import son.nt.en.base.BaseFragment;
import son.nt.en.login.LoginActivity;
import son.nt.en.utils.DataTimesUtil;
import son.nt.en.utils.Logger;
/**
* Created by sonnt on 7/11/16.
*/
public class ChatFragment extends BaseFragment implements ChatContract.View
{
public static final String FRIENDLY_MSG_LENGTH = "friendly_msg_length";
public static final int REQUEST_LOGIN = 1000;
private static final String TAG = ChatFragment.class
.getSimpleName();
// Firebase instance variables
private DatabaseReference mFirebaseDatabaseReference;
private FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder> mFirebaseAdapter;
public static final String MESSAGES_CHILD = "messages";
private static final int REQUEST_INVITE = 1;
public static final int DEFAULT_MSG_LENGTH_LIMIT = 10;
public static final String ANONYMOUS = "anonymous";
private static final String MESSAGE_SENT_EVENT = "message_sent";
private String mUsername;
private String mPhotoUrl;
private SharedPreferences mSharedPreferences;
private GoogleApiClient mGoogleApiClient;
private Button mSendButton;
private RecyclerView mMessageRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ProgressBar mProgressBar;
private EditText mMessageEditText;
@BindView(R.id.CoordinatorLayoutChat)
CoordinatorLayout mCoordinatorLayout;
private ChatContract.Presenter mPresenter;
public static ChatFragment newInstance()
{
ChatFragment f = new ChatFragment();
return f;
}
public static class MessageViewHolder extends RecyclerView.ViewHolder
{
public TextView messageTextView;
public TextView messengerTextView;
public TextView createdTimeTextView;
public CircleImageView messengerImageView;
public CircleImageView levelImageView;
public MessageViewHolder(View v)
{
super(v);
messageTextView = (TextView) itemView.findViewById(R.id.messageTextView);
messengerTextView = (TextView) itemView.findViewById(R.id.messengerTextView);
createdTimeTextView = (TextView) itemView.findViewById(R.id.createdTimeTextView);
messengerImageView = (CircleImageView) itemView.findViewById(R.id.messengerImageView);
levelImageView = (CircleImageView) itemView.findViewById(R.id.levelImageView);
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mPresenter = new ChatPresenter(this, FirebaseAuth.getInstance(), FirebaseDatabase.getInstance().getReference());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState)
{
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
View view = inflater.inflate(R.layout.fragment_chat, container, false);
ButterKnife.bind(this, view);
// Initialize ProgressBar and RecyclerView.
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mMessageRecyclerView = (RecyclerView) view.findViewById(R.id.messageRecyclerView);
mLinearLayoutManager = new LinearLayoutManager(getActivity());
mLinearLayoutManager.setStackFromEnd(true);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
// mProgressBar.setVisibility(ProgressBar.INVISIBLE);
// New child entries
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(FriendlyMessage.class,
R.layout.row_message, MessageViewHolder.class, mFirebaseDatabaseReference.child(MESSAGES_CHILD))
{
@Override
protected void populateViewHolder(MessageViewHolder viewHolder, FriendlyMessage friendlyMessage,
int position)
{
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
viewHolder.messageTextView.setText(friendlyMessage.getText());
viewHolder.messengerTextView.setText(friendlyMessage.getName());
viewHolder.createdTimeTextView.setText(friendlyMessage.getCreatedTime() == null ? "Once upon a time"
: DataTimesUtil.getTimeAgo(friendlyMessage.getCreatedTime()));
if (friendlyMessage.getPhotoUrl() == null)
{
viewHolder.messengerImageView.setImageDrawable(
ContextCompat.getDrawable(getContext(), R.drawable.ic_account_circle_black_36dp));
}
else
{
Glide.with(getContext()).load(friendlyMessage.getPhotoUrl()).into(viewHolder.messengerImageView);
}
Glide.with(getContext()).load("http://Img.softnyx.net/1/gb/about/rank_1.gif")
.diskCacheStrategy(DiskCacheStrategy.ALL).into(viewHolder.levelImageView);
}
};
mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver()
{
@Override
public void onItemRangeInserted(int positionStart, int itemCount)
{
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = mFirebaseAdapter.getItemCount();
int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the
//œ user is at the bottom of the list, scroll to the bottom
// of the list to show the newly added message.
if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
&& lastVisiblePosition == (positionStart - 1)))
{
mMessageRecyclerView.scrollToPosition(positionStart);
}
}
});
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
mMessageRecyclerView.setAdapter(mFirebaseAdapter);
mMessageEditText = (EditText) view.findViewById(R.id.messageEditText);
// mMessageEditText.setFilters(new InputFilter[]
// { new InputFilter.LengthFilter(mSharedPreferences.getInt(FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT)) });
mMessageEditText.addTextChangedListener(new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
if (charSequence.toString().trim().length() > 0)
{
mSendButton.setEnabled(true);
}
else
{
mSendButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable editable)
{
}
});
mSendButton = (Button) view.findViewById(R.id.sendButton);
mSendButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
mPresenter.sendMessage(mMessageEditText.getText().toString());
//
// FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername,
// mPhotoUrl);
// mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(friendlyMessage)
// .addOnFailureListener(new OnFailureListener()
// {
// @Override
// public void onFailure(@NonNull Exception e)
// {
// Logger.debug(TAG, ">>>" + "onFailure:" + e.toString());
// }
// });
// mMessageEditText.setText("");
}
});
return view;
}
@Override
public void onResume()
{
super.onResume();
mPresenter.onStart();
}
@Override
public void userDoNotLogin(String s)
{
Snackbar.make(mSendButton, "Please login first", Snackbar.LENGTH_LONG)
.setAction("Login", new View.OnClickListener()
{
@Override
public void onClick(View v)
{
startActivityForResult(new Intent(getActivity(), LoginActivity.class), REQUEST_LOGIN);
}
}).show();
}
@Override
public void clearMessage(String s)
{
mMessageEditText.setText(s);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
{
switch (requestCode)
{
case REQUEST_LOGIN:
{
Logger.debug(TAG, ">>>" + "onActivityResult REQUEST_LOGIN");
mPresenter.sendMessage(mMessageEditText.getText().toString());
break;
}
}
}
}
}
<file_sep>package son.nt.en.google_client_api;
import dagger.Component;
import son.nt.en.HomeActivity;
import son.nt.en.di.scoped.ActivityScoped;
import son.nt.en.firebase.FireBaseModule;
import son.nt.en.login.LoginActivity;
/**
* Created by sonnt on 8/20/16.
*/
@ActivityScoped
@Component(modules = {GoogleApiClientModule.class, FireBaseModule.class})
public interface GoogleApiComponent {
void inject(LoginActivity loginActivity);
void inject(HomeActivity loginActivity);
}
<file_sep>package son.nt.en.esl;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.otto.Subscribe;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import son.nt.en.R;
import son.nt.en.base.BaseFragment;
import son.nt.en.otto.OttoBus;
import son.nt.en.service.GoPlayer;
import son.nt.en.service.MusicService;
/**
* Created by sonnt on 7/15/16.
*/
public class EslDaiLyFragment extends BaseFragment implements View.OnClickListener, TextWatcher, EslDailyContract.View
{
public static final String TAG = EslDaiLyFragment.class.getSimpleName();
private RecyclerView mMessageRecyclerView;
private ProgressBar mProgressBar;
@BindView(R.id.CoordinatorLayoutChat)
CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.txt_search)
EditText txtSearch;
@BindView(R.id.btn_clear)
View btnClear;
private AdapterEslDaily mAdapter;
boolean isBind = false;
MusicService mPlayService;
EslDailyContract.Presenter mPresenter;
@BindView(R.id.player_play)
ImageView mImgPlay;
@BindView(R.id.img_track)
ImageView mImgTrack;
@BindView(R.id.txt_title)
TextView mTxtTitle;
@BindView(R.id.txt_des)
TextView mTxtDes;
public static EslDaiLyFragment newInstace()
{
EslDaiLyFragment f = new EslDaiLyFragment();
return f;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
OttoBus.register(this);
MusicService.bindToMe(getContext(), serviceConnectionPlayer);
final FireBaseRepository repo = new FireBaseRepository(FirebaseDatabase.getInstance().getReference());
mPresenter = new EslDailyPresenter(this, repo);
mPresenter.onStart();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_hello_chao, container, false);
ButterKnife.bind(this, view);
// Initialize ProgressBar and RecyclerView.
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mMessageRecyclerView = (RecyclerView) view.findViewById(R.id.messageRecyclerView);
GridLayoutManager mLinearLayoutManager = new GridLayoutManager(getActivity(), 1);
// mLinearLayoutManager.setStackFromEnd(true);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
mAdapter = new AdapterEslDaily(getActivity());
mMessageRecyclerView.setAdapter(mAdapter);
//search
btnClear.setOnClickListener(this);
txtSearch.addTextChangedListener(this);
mImgPlay.setOnClickListener(this);
return view;
}
@Override
public void onDestroy()
{
OttoBus.unRegister(this);
getActivity().unbindService(serviceConnectionPlayer);
mPresenter.onDestroy();
super.onDestroy();
}
ServiceConnection serviceConnectionPlayer = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
MusicService.LocalBinder localBinder = (MusicService.LocalBinder) service;
mPlayService = localBinder.getService();
isBind = true;
}
@Override
public void onServiceDisconnected(ComponentName name)
{
isBind = false;
mPlayService = null;
}
};
/**
* who calls this {@link son.nt.en.esl.AdapterEslDaily.ViewHolder#ViewHolder(View)}
*
* @param busSentence
*/
@Subscribe
public void getSelection(BusEsl busSentence)
{
if (mPlayService != null)
{
mPlayService.setDataToService(mAdapter.mValues);
mPlayService.playAtPos(busSentence.pos);
}
}
/**
* called from {@link MusicService#play()}
*
* @param goPlayer
*/
@Subscribe
public void getControlFromService(GoPlayer goPlayer)
{
mTxtTitle.setText(goPlayer.title);
mTxtDes.setText(goPlayer.des);
mImgPlay.setImageResource(
goPlayer.command == GoPlayer.DO_PLAY ? R.drawable.icon_paused : R.drawable.icon_played);
if (goPlayer.image != null)
{
Glide.with(this).load(goPlayer.image).fitCenter().into(mImgTrack);
}
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btn_clear:
{
txtSearch.setText("");
break;
}
case R.id.player_play:
{
if (mPlayService != null)
{
mPlayService.play();
}
break;
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
@Override
public void afterTextChanged(Editable s)
{
mPresenter.afterTextChanged(s.toString());
}
@Override
public void resultSearch(List<EslDailyDto> list)
{
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
mAdapter.setData(list);
mMessageRecyclerView.scrollToPosition(0);
}
@Override
public void setVisibility(boolean b)
{
btnClear.setVisibility(b ? View.VISIBLE : View.GONE);
}
}
<file_sep>package son.nt.en.service;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import java.util.ArrayList;
import java.util.List;
import son.nt.en.base.IAudioFile;
import son.nt.en.otto.OttoBus;
import son.nt.en.service.notification.INotification;
import son.nt.en.service.notification.NotificationImpl;
import son.nt.en.utils.Logger;
public class MusicService extends Service
{
INotification iNotification;
Playback iPlayback;
public static final String TAG = "MusicService";
public static final String ACTION_TOGGLE_PLAYBACK = "com.example.android.musicplayer.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.example.android.musicplayer.action.PLAY";
public static final String ACTION_PAUSE = "com.example.android.musicplayer.action.PAUSE";
public static final String ACTION_STOP = "com.example.android.musicplayer.action.STOP";
public static final String ACTION_SKIP = "com.example.android.musicplayer.action.SKIP";
public static final String ACTION_REWIND = "com.example.android.musicplayer.action.REWIND";
public static final String ACTION_URL = "com.example.android.musicplayer.action.URL";
public static Intent getService(Context context)
{
return new Intent(context, MusicService.class);
}
public static void bindToMe(Context context, ServiceConnection musicServiceConnection)
{
context.bindService(MusicService.getService(context), musicServiceConnection, Context.BIND_AUTO_CREATE);
}
public class LocalBinder extends Binder
{
public MusicService getService()
{
return MusicService.this;
}
}
enum State
{
Fetching, Stopped, Playing, Paused, Preparing
}
State mState = State.Stopped;
LocalBinder localBinder = new LocalBinder();
MediaPlayer mediaPlayer;
AudioManager audioManager;
boolean isStreaming;
String songTitle;
IAudioFile currentItem;
int currentPos = 0;
float currentVolume = 0.7f;
List<IAudioFile> listMusic = new ArrayList<>();
MusicPlayback.Callback musicPlayBackCallback;
public MusicService()
{
Logger.debug(TAG, ">>>" + "MusicService");
}
private void setupMediaPlayerIfNeeded()
{
Logger.debug(TAG, ">>>" + "setupMediaPlayerIfNeeded");
if (mediaPlayer == null)
{
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnPreparedListener(onPreparedListener);
mediaPlayer.setOnCompletionListener(onCompletionListener);
mediaPlayer.setOnErrorListener(onErrorListener);
}
else
{
mediaPlayer.reset();
}
}
@Override
public void onCreate()
{
super.onCreate();
Logger.debug(TAG, ">>>" + "onCreate");
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
iNotification = new NotificationImpl(this, this);
IntentFilter filter = new IntentFilter();
filter.addAction(NotificationImpl.ACTION_NEXT);
filter.addAction(NotificationImpl.ACTION_PREV);
filter.addAction(NotificationImpl.ACTION_PLAY);
filter.addAction(NotificationImpl.ACTION_CLOSE);
registerReceiver(receiver, filter);
}
@Override
public void onDestroy()
{
unregisterReceiver(receiver);
super.onDestroy();
}
public void processTogglePlayback()
{
if (mState == State.Paused || mState == State.Stopped)
{
processPlayRequest();
}
else
{
processPauseRequest();
}
}
public void processPlayRequest()
{
Logger.debug(TAG, ">>>" + "processPlayRequest");
if (mState == State.Stopped)
{
if (!listMusic.isEmpty() && currentItem != null)
{
currentItem = listMusic.get(currentPos);
playNextSong(currentItem);
}
}
else if (mState == State.Paused)
{
mState = State.Playing;
// setupAsForeGroundCustom(currentItem);
play();
}
}
public void playAtPos(int pos)
{
currentPos = pos;
if (!listMusic.isEmpty())
{
currentItem = listMusic.get(currentPos);
playNextSong(currentItem);
// play();
}
}
public void processPauseRequest()
{
Logger.debug(TAG, ">>>" + "processPauseRequest");
if (mState == State.Playing)
{
mState = State.Paused;
mediaPlayer.pause();
relaxResource(false);
}
}
public void processAddRequest(IAudioFile audioFile)
{
Logger.debug(TAG, ">>>" + "processAddRequest");
listMusic.clear();
currentPos = 0;
this.currentItem = audioFile;
playNextSong(audioFile);
}
public void playNextSong(IAudioFile currentItem)
{
String url = currentItem.getLinkMp3();
Logger.debug(TAG, ">>>" + "playNextSong:" + url);
if (musicPlayBackCallback != null)
{
musicPlayBackCallback.onPreparing(currentItem);
}
mState = State.Stopped;
relaxResource(false);
try
{
setupMediaPlayerIfNeeded();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
isStreaming = url.startsWith("http:") || url.startsWith("https:");
songTitle = url;
mState = State.Preparing;
// setupAsForeGroundCustom(currentItem);
/**
* @see onPreparedListener
*/
mediaPlayer.prepareAsync();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void setDataToService(List<? extends IAudioFile> list)
{
Logger.debug(TAG, ">>>" + "setDataToService:" + list.size());
if (list == null || list.size() == 0)
{
return;
}
this.listMusic.clear();
this.listMusic.addAll(list);
// if (type == 1)
// {
//
// this.listMusic.clear();
// this.listMusic.addAll(list);
// } else
// {
// this.listEsl.clear();
// this.listEsl.addAll(list);
// }
currentPos = 0;
currentItem = listMusic.get(currentPos);
// playNextSong(currentItem);
}
void relaxResource(boolean isReleaseMediaPlayer)
{
stopForeground(true);
if (isReleaseMediaPlayer && mediaPlayer != null)
{
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
}
public void play()
{
if (mediaPlayer.isPlaying())
{
iNotification.doPause();
mediaPlayer.pause();
OttoBus.post(new GoPlayer(GoPlayer.DO_PAUSE, currentItem.getTitle(), currentItem.getDescription(), currentItem.getImage()));
return;
}
if (!mediaPlayer.isPlaying())
{
iNotification.doPlay();
OttoBus.post(new GoPlayer(GoPlayer.DO_PLAY, currentItem.getTitle(), currentItem.getDescription(), currentItem.getImage()));
mediaPlayer.start();
}
}
@Override
public IBinder onBind(Intent intent)
{
Logger.debug(TAG, ">>>" + "onBind");
return localBinder;
}
MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer mediaPlayer)
{
Logger.debug(TAG, ">>>" + "onPrepared");
if (musicPlayBackCallback != null)
{
musicPlayBackCallback.onPlaying(currentItem);
}
mState = State.Playing;
iNotification.setData(currentItem);
// updateNotification(currentItem);
// setupAsForeGroundCustom(currentItem);
play();
}
};
MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mediaPlayer)
{
if (listMusic.isEmpty())
{
return;
}
currentPos++;
if (currentPos == listMusic.size())
{
currentPos = 0;
}
currentItem = listMusic.get(currentPos);
playNextSong(currentItem);
}
};
MediaPlayer.OnErrorListener onErrorListener = new MediaPlayer.OnErrorListener()
{
@Override
public boolean onError(MediaPlayer mediaPlayer, int i,
int i1)
{
// if (listMusic.isEmpty())
// {
// return false;
// }
// currentPos++;
// if (currentPos == listMusic.size())
// {
// currentPos = 0;
// }
// currentItem = listMusic.get(currentPos);
// playNextSong(currentItem);
return true;
}
};
public void setMusicPlayBackCallback(MusicPlayback.Callback cb)
{
this.musicPlayBackCallback = cb;
}
private final BroadcastReceiver receiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (action.equals(NotificationImpl.ACTION_PLAY))
{
play();
}
else if (action.equals(NotificationImpl.ACTION_NEXT))
{
playAtPos(currentPos ++);
}
else if (action.equals(NotificationImpl.ACTION_PREV))
{
playAtPos(currentPos --);
}
else if (action.equals(NotificationImpl.ACTION_CLOSE))
{
relaxResource(true);
// if (mediaPlayer != null && mediaPlayer.isPlaying())
// {
// mediaPlayer.stop();
// mediaPlayer.reset();
// mediaPlayer.release();
// mediaPlayer = null;
// }
// stopForeground(true);
}
}
};
}
<file_sep>package son.nt.en.elite;
import org.parceler.Parcel;
/**
* Created by sonnt on 7/20/16.
*/
@Parcel
public class EliteDto {
public String id;
public String title;
public String image;
public String linkDetail;
public String des;
public String authPic;
public String authName;
public long publishTime;
public String content;
public EliteDto() {
}
public EliteDto(String id, String title, String image, String linkDetail, String des, String authPic, String authName, long publishTime, String content) {
this.id = id;
this.title = title;
this.image = image;
this.linkDetail = linkDetail;
this.des = des;
this.authPic = authPic;
this.authName = authName;
this.publishTime = publishTime;
this.content = content;
}
}
<file_sep>package son.nt.en.elite.di;
import com.google.firebase.database.DatabaseReference;
import dagger.Module;
import dagger.Provides;
import son.nt.en.elite.ContractDailyElite;
import son.nt.en.elite.EliteRepository;
/**
* Created by sonnt on 8/15/16.
* This module is used to create {@link son.nt.en.elite.EliteDailyPresenter}
*/
@Module
public class ElitePresenterModule
{
private ContractDailyElite.View mView;
public ElitePresenterModule(ContractDailyElite.View mView)
{
this.mView = mView;
}
@Provides
ContractDailyElite.View provideView ()
{
return mView;
}
@Provides
ContractDailyElite.Repository provideRepository (DatabaseReference databaseReference)
{
return new EliteRepository(databaseReference);
}
}
<file_sep>package son.nt.en.elite;
import com.google.firebase.database.DatabaseReference;
import javax.inject.Inject;
/**
* Created by sonnt on 8/15/16.
*/
public class EliteRepository implements ContractDailyElite.Repository
{
private DatabaseReference mDatabaseReference;
@Inject
public EliteRepository(DatabaseReference mDatabaseReference)
{
this.mDatabaseReference = mDatabaseReference;
}
@Override
public void getData()
{
}
}
| 2bc9a6e2e611f095e029f30d76d36279a564557b | [
"Java",
"Gradle"
] | 30 | Java | thanhsontube/SampleCodeTest | 18a0d125d3511f8112becf09ea954ac4e06f741f | c5d5c0885ad6c47e9f7ea65e4648997faa54f9fa | |
refs/heads/master | <repo_name>GalibShaik/InsuranceProject<file_sep>/target/cucumber-html/report.js
$(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("file:src/test/java/test/LoginFunction.feature");
formatter.feature({
"name": "Login Functionality in Banking Application",
"description": "",
"keyword": "Feature",
"tags": [
{
"name": "@Login"
}
]
});
formatter.scenarioOutline({
"name": "Valid Login on the AUT",
"description": "",
"keyword": "Scenario Outline",
"tags": [
{
"name": "@Sanity"
}
]
});
formatter.step({
"name": "User is on the Login Page of the Bank Application",
"keyword": "Given "
});
formatter.step({
"name": "User enters correct user name \"\u003cname\u003e\" and password \"\<PASSWORD>\"",
"keyword": "When "
});
formatter.step({
"name": "Verify that manager Id is displayed on the Home Page",
"keyword": "Then "
});
formatter.examples({
"name": "",
"description": "",
"keyword": "Examples",
"rows": [
{
"cells": [
"name",
"password"
]
},
{
"cells": [
"mngr285669",
"mYpUnEz"
]
}
]
});
formatter.scenario({
"name": "Valid Login on the AUT",
"description": "",
"keyword": "Scenario Outline",
"tags": [
{
"name": "@Login"
},
{
"name": "@Sanity"
}
]
});
formatter.before({
"status": "passed"
});
formatter.step({
"name": "User is on the Login Page of the Bank Application",
"keyword": "Given "
});
formatter.match({
"location": "LoginStepDef.user_is_on_the_login_page_of_the_bank_application()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "User enters correct user name \"mngr285669\" and password \"<PASSWORD>\"",
"keyword": "When "
});
formatter.match({
"location": "LoginStepDef.user_enters_correct_user_name_something_and_password_something(String,String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "Verify that manager Id is displayed on the Home Page",
"keyword": "Then "
});
formatter.match({
"location": "LoginStepDef.verify_that_manager_id_is_displayed_on_the_home_page()"
});
formatter.result({
"status": "passed"
});
formatter.after({
"status": "passed"
});
formatter.scenarioOutline({
"name": "Valid Login on the AUT",
"description": "",
"keyword": "Scenario Outline",
"tags": [
{
"name": "@Regression"
}
]
});
formatter.step({
"name": "User is on the Login Page of the Bank Application",
"keyword": "Given "
});
formatter.step({
"name": "User enters correct user name \"\u003cname\u003e\" and password \"\<PASSWORD>\"",
"keyword": "When "
});
formatter.step({
"name": "Verify that manager Id is displayed on the Home Page",
"keyword": "Then "
});
formatter.examples({
"name": "",
"description": "",
"keyword": "Examples",
"rows": [
{
"cells": [
"name",
"password"
]
},
{
"cells": [
"<PASSWORD>669",
"<PASSWORD>"
]
}
]
});
formatter.scenario({
"name": "Valid Login on the AUT",
"description": "",
"keyword": "Scenario Outline",
"tags": [
{
"name": "@Login"
},
{
"name": "@Regression"
}
]
});
formatter.before({
"status": "passed"
});
formatter.step({
"name": "User is on the Login Page of the Bank Application",
"keyword": "Given "
});
formatter.match({
"location": "LoginStepDef.user_is_on_the_login_page_of_the_bank_application()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "User enters correct user name \"mngr285669\" and password \"<PASSWORD>\"",
"keyword": "When "
});
formatter.match({
"location": "LoginStepDef.user_enters_correct_user_name_something_and_password_something(String,String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "Verify that manager Id is displayed on the Home Page",
"keyword": "Then "
});
formatter.match({
"location": "LoginStepDef.verify_that_manager_id_is_displayed_on_the_home_page()"
});
formatter.result({
"status": "passed"
});
formatter.after({
"status": "passed"
});
formatter.scenarioOutline({
"name": "Valid Login on the AUT",
"description": "",
"keyword": "Scenario Outline",
"tags": [
{
"name": "@Regression"
}
]
});
formatter.step({
"name": "User is on the Login Page of the Bank Application",
"keyword": "Given "
});
formatter.step({
"name": "User enters correct user name \"\u003cname\u003e\" and password \"\<PASSWORD>\"",
"keyword": "When "
});
formatter.step({
"name": "Verify that manager Id is displayed on the Home Page",
"keyword": "Then "
});
formatter.examples({
"name": "",
"description": "",
"keyword": "Examples",
"rows": [
{
"cells": [
"name",
"password"
]
},
{
"cells": [
"mngr285669",
"<PASSWORD>"
]
}
]
});
formatter.scenario({
"name": "Valid Login on the AUT",
"description": "",
"keyword": "Scenario Outline",
"tags": [
{
"name": "@Login"
},
{
"name": "@Regression"
}
]
});
formatter.before({
"status": "passed"
});
formatter.step({
"name": "User is on the Login Page of the Bank Application",
"keyword": "Given "
});
formatter.match({
"location": "LoginStepDef.user_is_on_the_login_page_of_the_bank_application()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "User enters correct user name \"mngr285669\" and password \"<PASSWORD>\"",
"keyword": "When "
});
formatter.match({
"location": "LoginStepDef.user_enters_correct_user_name_something_and_password_something(String,String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "Verify that manager Id is displayed on the Home Page",
"keyword": "Then "
});
formatter.match({
"location": "LoginStepDef.verify_that_manager_id_is_displayed_on_the_home_page()"
});
formatter.result({
"status": "passed"
});
formatter.after({
"status": "passed"
});
}); | 9d797b2e635633304049327ec98359371df800b9 | [
"JavaScript"
] | 1 | JavaScript | GalibShaik/InsuranceProject | 8cf956b96d2f40e21725bf6f2b049561952de61c | be4c339e89556ed4912bf33efa9c90bdb7f9f4c6 | |
refs/heads/master | <repo_name>Sakawa/cilkscreen-atom<file_sep>/examples/simple-race/simple-race.c
/*
* simple-race.cilk
*
* Copyright (C) 2009-2011 Intel Corporation. All Rights Reserved.
*
* The source code contained or described herein and all
* documents related to the source code ("Material") are owned by
* Intel Corporation or its suppliers or licensors. Title to the
* Material remains with Intel Corporation or its suppliers and
* licensors. The Material is protected by worldwide copyright
* laws and treaty provisions. No part of the Material may be
* used, copied, reproduced, modified, published, uploaded,
* posted, transmitted, distributed, or disclosed in any way
* except as expressly provided in the license provided with the
* Materials. No license under any patent, copyright, trade
* secret or other intellectual property right is granted to or
* conferred upon you by disclosure or delivery of the Materials,
* either expressly, by implication, inducement, estoppel or
* otherwise, except as expressly provided in the license
* provided with the Materials.
*
* This file implements a simple Intel Cilk Plus program with a known race
* condition to demonstrate the Cilkscreen race detector.
*/
#include <stdlib.h>
#include <stdio.h>
#include <cilk/cilk.h>
#include <unistd.h>
int x;
void race(void) {
x = 0;
}
void race1(void) {
x = 1;
}
void race2(void) {
x = 2;
}
void race3(void) {
x = 3;
}
void test(void) {
cilk_spawn race();
cilk_spawn race1();
}
void test1(void) {
cilk_for (int i = 0; i < 10; i++) {
x = i;
}
}
void test2(void) {
cilk_spawn race2();
cilk_spawn race3();
}
int main(int argc, char *argv[]) {
for (int i = 0; i < 100000; i++) {
test();
}
sleep(2); // artificially add sleep time
test1();
test2();
printf("done: x = %d\n", x);
return 0;
}
<file_sep>/examples/simple-race/Makefile
#
# Makefile for the simple-race example.
#
CXX = clang
CXXFLAGS = -O3 -ftapir
DFLAGS = -O0 -ftapir -g -fsanitize=cilk
TARGET = simple-race
SRC = simple-race.c
.PHONY: all
all: $(TARGET)
$(TARGET): $(SRC)
$(CXX) -o $@ $(CXXFLAGS) $^
.PHONY: cilksan
cilksan: $(SRC)
$(CXX) -o cilksan $(DFLAGS) $^
./cilksan
.PHONY: clean
clean:
rm -f $(TARGET) cilkscreen
<file_sep>/README.md
# Cilkpride package (beta)
This package is designed to help programmers using the Cilk threading library keep track of their code as they are writing code in Atom. Currently, the plugin automatically runs cilksan in the background and report the results to the users, notifying them if race conditions appear. Results are refreshed every time a file is modified, so that users are told immediately if race conditions exist, and can take the appropriate steps to correct the error.
There are also some added features designed for MIT's 6.172 class, allowing students to edit code locally but evaluate their applications remotely on Athena.
## Setting up the package
In order to notify the package that you are writing a project with Cilk, you must place a configuration file `cilkpride-conf.json` in the top-level directory of the project. The configuration file should have a few settings:
```JSON
{
"username": "Username for SSH login, usually your Athena login",
"remoteBaseDir": "full directory path of the project directory on the remote instance",
"cilksanCommand": "Enter a Make command that will compile (with cilksan enabled) and run the executable.",
"sshEnabled": true,
"hostname": "Hostname for running cilk on a remote server - usually athena.dialup.mit.edu",
"port": 22,
"launchInstance": "boolean: only true if you want to use 6.172's Azure VM",
"localBaseDir": "Full directory path of the project directory on your local computer (ie C:/Users/me/Desktop/my-project)",
"remoteBaseDir": "Full directory path of the project directory on the remote instance (ie /afs/athena.mit.edu/user/g/c/gchau/my-project)",
"syncIgnoreFile": ["/cilkpride-conf.json", "other files to ignore"],
"syncIgnoreDir": ["/.git", "/log.awsrun", "/log.cqrun", "other directories to ignore"]
}
```
You can automatically generate a template configuration file in a folder by pressing "Register Cilk project" on the status bar, located to the bottom-left of the Atom window. Once this is done, the package will periodically run cilksan on the executable generated by the command specified in `cilksanCommand` - make sure that this command both makes an cilksan-enabled executable and runs it. The status bar icon will show the package status for the current file open.
Note: If you are using SSH (which you probably are), every time a file is modified, the plugin will upload it to the remote server and try to recompile it. You can also sync local -> remote by pressing CTRL+ALT+G, while syncing remote -> local can be done by pressing CTRL+ALT+J. Beware as these commands will overwrite your files and there is no confirmation before doing so.
| 467f014774636e73ad2476f920a631df3cbc3a7e | [
"Markdown",
"C",
"Makefile"
] | 3 | C | Sakawa/cilkscreen-atom | e3c9ae0671f98c8b9e90bde558f89dffe4be90c9 | b2ca6622c8d88151f089ff44149447490c0e00a4 | |
refs/heads/master | <file_sep>package com.example.jadwalsholatkotlin.model
import com.google.gson.annotations.SerializedName
data class ResponseTeam(
@field:SerializedName("sports")
val sports: List<SportsItem>? = null
)<file_sep>package com.example.jadwalsholatkotlin
import com.example.jadwalsholatkotlin.model.ResponseTeam
import com.example.jadwalsholatkotlin.network.ApiClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainPresenter (model : MainInterface.View) : MainInterface.Presenter{
var view : MainInterface.View = model
override fun getDataTeams() {
val apiInterface = ApiClient.create()
apiInterface.getData().enqueue(object : Callback<ResponseTeam> {
override fun onResponse(call: Call<ResponseTeam>, response: Response<ResponseTeam>) {
val responseTeam = response.body()
view.showData(responseTeam?.sports!!)
}
override fun onFailure(call: Call<ResponseTeam>, t: Throwable) {
}
})
}
}<file_sep>package com.example.jadwalsholatkotlin.model
import com.google.gson.annotations.SerializedName
data class SportsItem(
@field:SerializedName("idSport")
val idSport: String? = null,
@field:SerializedName("strSport")
val strSport: String? = null,
@field:SerializedName("strSportThumb")
val strSportThumb: String? = null,
@field:SerializedName("strSportDescription")
val strSportDescription: String? = null
)<file_sep>package com.example.jadwalsholatkotlin
import com.example.jadwalsholatkotlin.model.SportsItem
interface MainInterface {
interface View {
fun showData(data: List<SportsItem>)
}
interface Presenter {
fun getDataTeams()
}
}<file_sep>package com.example.jadwalsholatkotlin.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.example.jadwalsholatkotlin.R
import com.example.jadwalsholatkotlin.model.SportsItem
import kotlinx.android.synthetic.main.item_team.view.*
class MainAdapter (val context: Context, val result : List<SportsItem>) : RecyclerView.Adapter<MainAdapter.ViewHolder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): MainAdapter.ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_team, p0, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return result.size
}
override fun onBindViewHolder(p0: MainAdapter.ViewHolder, p1: Int) {
p0.bindItems(result[p1])
}
class ViewHolder(view : View) : RecyclerView.ViewHolder(view) {
val textTitle = view.tv_teamTitle
val textDetail = view.tv_teamDetail
val gambar = view.img_team
fun bindItems(item : SportsItem) {
textTitle.text = item.strSport
textDetail.text = item.strSportDescription
Glide.with(itemView.context)
.load(item.strSportThumb)
.into(gambar)
}
}
}<file_sep>package com.example.jadwalsholatkotlin.network
import com.example.jadwalsholatkotlin.model.ResponseTeam
import retrofit2.Call
import retrofit2.http.GET
interface ApiInterface {
@GET("api/v1/json/1/all_sports.php")
fun getData() : Call<ResponseTeam>
}<file_sep>package com.example.jadwalsholatkotlin.network
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ApiClient {
private val BASE_URL = "https://www.thesportsdb.com/"
fun create() : ApiInterface{
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(ApiInterface::class.java!!)
}
}<file_sep>package com.example.jadwalsholatkotlin
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import com.example.jadwalsholatkotlin.adapter.MainAdapter
import com.example.jadwalsholatkotlin.model.SportsItem
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), MainInterface.View {
val presenter = MainPresenter(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
presenter.getDataTeams()
}
override fun showData(data: List<SportsItem>) {
rec_main.adapter = MainAdapter(this, data)
rec_main.layoutManager = LinearLayoutManager(this)
}
}
| 6ba8807ae954a0e75d4fe9a60d50fe0fe8d324c3 | [
"Kotlin"
] | 8 | Kotlin | fatihsyams/RetrofitMVP | 1d557ee5434206f2af91d46b5bc5f0b34397a71a | 356bd07a453755e03ea050b1ac31657c0bf3d10f | |
refs/heads/master | <repo_name>awill139/cmpen417<file_sep>/417 Lab 4 HLS Starter Code/conv_algo.py
width=4
kwidth=3
image = [1,1,1,1,2,10,20,2,3,30,40,3,4,4,4,4]
kernel = [1,1,1,1,2,1,1,1,1];
Output= [118,128,69,6,147,157,76,9,89,89,55,7,12,12,8,4];
out=[]
for i in range(width):
for j in range(width):
psum=0
for k in range(min(kwidth,width-i)):
for l in range(min(kwidth,width-j)):
print(k,l)
psum+=image[(i+k)*width+j+l]*kernel[k*kwidth+l]
out.append(psum)
print(out)
<file_sep>/417 Lab 4 HLS Starter Code/convolution.cpp
class imageClass
{
int *imageData;
public:
imageClass(int ima[IMAGE_WIDTH*IMAGE_WIDTH]){
imageData=ima;
}
// initialize use a pointer to an array
int getValue(int y, int x){
if(x >= IMAGE_WIDTH || y >= IMAGE_WIDTH){
return(0);
}
else{
return(imageData[y*IMAGE_WIDTH+x]);
}
}
void print();
};
void fpga_convolution(int image[IMAGE_WIDTH*IMAGE_WIDTH], int kernel[KERNEL_WIDTH*KERNEL_WIDTH], int output[OUTPUT_WIDTH*OUTPUT_WIDTH]){
#pragma HLS INTERFACE m_axi port=image offset=slave depth=65536
#pragma HLS INTERFACE m_axi port=kernel offset=slave depth=121
#pragma HLS INTERFACE m_axi port=output offset=slave depth=65536
#pragma HLS INTERFACE s_axilite port=return
// Perform your convolution here (i.e., set the correct values in the "output" array)
int imageIndex=0;
int kernelIndex=0;
int sum=0;
cout <<"0 element is: ";
cout << image[0];
cout << "\n start\n";
imageClass imageInstance = imageClass(image);
for(int imageY=0; imageY < IMAGE_WIDTH; imageY++){ //These two loops iterate through
for(int imageX=0; imageX < IMAGE_WIDTH; imageX++){ //every value in the image.
imageIndex=imageY*IMAGE_WIDTH+imageX;
//for every value in the image iterate through the kernel and multiply by its corresponding value
sum=0;
for(int kernelY=0; kernelY < KERNEL_WIDTH; kernelY++){
for(int kernelX=0; kernelX < KERNEL_WIDTH; kernelX++){
kernelIndex=kernelY*KERNEL_WIDTH+kernelX;
sum += kernel[kernelIndex]*imageInstance.getValue(imageY+kernelY, imageX+kernelX);
}
}
cout << sum << ", ";
output[imageIndex] = sum;
}
cout <<"\n";
}
return; // Don't remove or add any of your own returns
}
| 13adc8083d2a1aa24b4c5363a95b2202179f0670 | [
"Python",
"C++"
] | 2 | Python | awill139/cmpen417 | 434c07e9e73158244b6dc63c0d28b2b7d0499113 | de9a8116bab4df71f1259853dbcd16ead0c2db7d | |
refs/heads/master | <repo_name>thompsonson/beddit-python<file_sep>/README.rst
beddit-python
============================
.. image:: https://travis-ci.org/giginet/beddit-python.svg?branch=master
:target: https://travis-ci.org/giginet/beddit-python
.. image:: https://coveralls.io/repos/github/giginet/beddit-python/badge.svg?branch=master
:target: https://coveralls.io/github/giginet/beddit-python?branch=master
API Client for Beddit_ in Python.
.. _Beddit: http://www.beddit.com
Read `API Documentation`_ for detail.
.. _API Documentation: https://github.com/beddit/beddit-api
Installation
---------------------
.. code:: sh
pip install beddit-python
Usage
--------------
List sleep scores per day
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: python
from datetime import datetime
from beddit.client import BedditClient
client = BedditClient('<EMAIL>', password)
start_date = datetime(2016, 7, 1)
end_date = datetime(2016, 7, 31)
sleeps = client.get_sleeps(start=start_date, end=end_date)
for sleep in sleeps:
print(sleep.date.strftime('%Y-%m-%d'), sleep.property.total_sleep_score)
.. code:: txt
2016-07-01 75
2016-07-02 92
....
Get user information
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: python
import os
from beddit.client import BedditClient
client = BedditClient(os.environ.get('BEDDIT_USERNAME'), os.environ.get('BEDDIT_PASSWORD'))
user = client.get_user()
print(user.name)
print(user.height)
print(user.weight)
Supported Python
------------------------
Python 2.7, 3.3, 3.4, 3.5
LICENSE
----------------
MIT License
<file_sep>/beddit/group.py
from datetime import datetime
from .user import User
class PendingInvite(object):
def __init__(self, response_object):
self.created = datetime.utcfromtimestamp(response_object['created'])
self.created_by = response_object['created_by']
self.email = response_object['email']
class Group(object):
def __init__(self, response_object):
self.id = int(response_object['id'])
self.created = datetime.utcfromtimestamp(response_object['created'])
self.members = [User(user) for user in response_object['members']]
self.pending_invites = [PendingInvite(invitation) for invitation in response_object['pending_invites']]
<file_sep>/.coveragerc
[report]
include =
beddit/*.py
tests/*.py
omit =
beddit/__init__.py
tests/__init__.py
*/compatibility.py
exclude_lines =
pragma: no cover
if __name__ == .__main__.:
<file_sep>/tests/test_group.py
import unittest
import json
import os
from datetime import datetime
from beddit.group import Group
BASE_DIR = os.path.dirname(__file__)
class GroupTest(unittest.TestCase):
@property
def group_response(self):
return json.load(open(os.path.join(BASE_DIR, 'fixtures/group.json')))
def test_group(self):
group = Group(self.group_response)
self.assertEqual(group.id, 1234)
self.assertEqual(group.created, datetime.utcfromtimestamp(1371472503.646541))
self.assertEqual(len(group.members), 1)
self.assertEqual(len(group.pending_invites), 1)
pending_invite = group.pending_invites[0]
self.assertEqual(pending_invite.created, datetime.utcfromtimestamp(1371472503.646541))
self.assertEqual(pending_invite.created_by, 132)
self.assertEqual(pending_invite.email, '<EMAIL>')
<file_sep>/tests/test_session.py
import unittest
import json
import os
from datetime import datetime
from pytz import timezone
from beddit.session import Session
BASE_DIR = os.path.dirname(__file__)
class SessionTest(unittest.TestCase):
@property
def session_response(self):
return json.load(open(os.path.join(BASE_DIR, 'fixtures/session.json')))
def test_session(self):
raw = self.session_response[0]
session = Session(raw)
jst = timezone('Asia/Tokyo')
self.assertEqual(session.timezone, jst)
self.assertEqual(session.id, raw['id'])
self.assertEqual(session.start, datetime.fromtimestamp(raw['start_timestamp'], tz=jst))
self.assertEqual(session.end, datetime.fromtimestamp(raw['end_timestamp'], tz=jst))
self.assertEqual(session.updated, datetime.fromtimestamp(raw['updated'], tz=jst))
self.assertEqual(session.hardware, raw['hardware'])
self.assertEqual(session.frame_length, raw['frame_length'])
self.assertEqual(session.error_code, raw['error_code'])
self.assertEqual(session.sampled_tracks, {})
self.assertEqual(len(session.respiration_cycle_amplitudes), 7976)
self.assertEqual(len(session.heartbeat), 5963)
self.assertEqual(len(session.heart_rate), 460)
self.assertEqual(len(session.signal_high_percentile), 544)
self.assertEqual(len(session.repiration_cycles), 0)
self.assertEqual(len(session.events), 2)
self.assertEqual(len(session.actigram), 744)
self.assertEqual(len(session.sensor_status), 1)
self.assertEqual(len(session.snoring_events), 10)
self.assertEqual(len(session.activity_segment_length), 303)
self.assertEqual(len(session.high_activity_intervals), 113)
self.assertEqual(len(session.activity_segment_variation), 303)
def test_sampled_tracks(self):
response = json.load(open(os.path.join(BASE_DIR, 'fixtures/session_sample.json')))
session = Session(response)
tracks = session.sampled_tracks
self.assertEqual(tracks['normal'].samples_per_frame, 28)
self.assertEqual(tracks['normal'].data_url, 'https://bedditcloud-sleepdata...')
self.assertEqual(tracks['normal'].data_type, 'uint16')
self.assertEqual(tracks['noise'].samples_per_frame, 2)
self.assertEqual(tracks['noise'].data_url, 'https://bedditcloud-sleepdata...')
self.assertEqual(tracks['noise'].data_type, 'float32')
<file_sep>/beddit/sleep.py
from datetime import datetime
from enum import Enum
from pytz import timezone
class SleepStage(Enum):
Away = 65
Sleep = 83
RestlessSleep = 82
Awake = 87
NoSignal = 78
GapInMeasurement = 71
class Presence(Enum):
Away = 65
Present = 80
End = 78
class Sleep(object):
class Property(object):
def __init__(self, properties):
for p in properties:
score = int(properties[p])
setattr(self, p, score)
def __init__(self, response_object):
self.timezone = timezone(response_object['timezone'])
self.date = datetime.strptime(response_object['date'], '%Y-%m-%d').replace(tzinfo=self.timezone)
self.start = datetime.fromtimestamp(response_object['start_timestamp'], tz=self.timezone)
self.end = datetime.fromtimestamp(response_object['end_timestamp'], tz=self.timezone)
self.session_range_start = datetime.fromtimestamp(response_object['session_range_start'], tz=self.timezone)
self.session_range_end = datetime.fromtimestamp(response_object['session_range_end'], tz=self.timezone)
self.updated = datetime.fromtimestamp(response_object['updated'], tz=self.timezone)
# properties
self.property = self.Property(response_object['properties'])
time_value_tracks = response_object['time_value_tracks']
self.actigram = {datetime.fromtimestamp(float(timestamp), tz=self.timezone): float(value)
for timestamp, value in time_value_tracks['actigram_epochwise']['items']}
self.sleep_event = {datetime.fromtimestamp(float(timestamp), tz=self.timezone): SleepStage(value)
for timestamp, value in time_value_tracks['sleep_stages']['items']}
self.presence = {datetime.fromtimestamp(float(timestamp), tz=self.timezone): Presence(value)
for timestamp, value in time_value_tracks['presence']['items']}
self.snoring_episodes = {datetime.fromtimestamp(float(timestamp), tz=self.timezone): value
for timestamp, value in time_value_tracks['presence']['items']}
self.nap_periods = {datetime.fromtimestamp(float(timestamp), tz=self.timezone): float(value)
for timestamp, value in time_value_tracks['nap_periods']['items']}
self.heart_rate_curve = {datetime.fromtimestamp(float(timestamp), tz=self.timezone): float(value)
for timestamp, value in time_value_tracks['heart_rate_curve']['items']}
self.sleep_cycles = {datetime.fromtimestamp(float(timestamp), tz=self.timezone): float(value)
for timestamp, value in time_value_tracks['sleep_cycles']['items']}
<file_sep>/beddit/user.py
from datetime import datetime, timedelta
from enum import Enum
class Sex(Enum):
Unknown = None
Male = 'male'
Female = 'female'
class User(object):
def __init__(self, response_object):
self.id = response_object['id']
self.email = response_object['email']
self.name = response_object['name']
self.date_of_birth = datetime.strptime(response_object['date_of_birth'], '%Y-%m-%d')
self.sex = Sex(response_object['sex'])
self.weight = float(response_object['weight'])
self.height = float(response_object['height'])
self.sleep_time_goal = timedelta(seconds=response_object['sleep_time_goal'])
self.tip_audiences = response_object['tip_audiences']
self.created = datetime.utcfromtimestamp(response_object['created'])
self.updated = datetime.utcfromtimestamp(response_object['updated'])
<file_sep>/tox.ini
[tox]
envlist =
py{27,33,34,35}
[testenv]
basepython =
py27: python2.7
py33: python3.3
py34: python3.4
py35: python3.5
deps=
py27: enum34
py27: mock
py33: enum34
-rrequirements.txt
coverage
commands =
{envbindir}/coverage run --source=beddit runtests.py []
coverage report
<file_sep>/tests/__init__.py
from tests import test_client
from tests import test_group
from tests import test_session
from tests import test_sleep
from tests import test_user
<file_sep>/tests/test_sleep.py
import unittest
import json
import os
from datetime import datetime
from pytz import timezone
from beddit.sleep import Sleep
BASE_DIR = os.path.dirname(__file__)
class SleepTest(unittest.TestCase):
@property
def sleep_response(self):
return json.load(open(os.path.join(BASE_DIR, 'fixtures/sleep.json')))
def test_sleep(self):
raw = self.sleep_response[0]
sleep = Sleep(raw)
jst = timezone('Asia/Tokyo')
self.assertEqual(sleep.timezone, jst)
self.assertEqual(sleep.date, datetime(2016, 8, 16).replace(tzinfo=jst))
self.assertEqual(sleep.start, datetime.fromtimestamp(raw['start_timestamp'], tz=jst))
self.assertEqual(sleep.end, datetime.fromtimestamp(raw['end_timestamp'], tz=jst))
self.assertEqual(sleep.session_range_start, datetime.fromtimestamp(raw['session_range_start'], tz=jst))
self.assertEqual(sleep.session_range_end, datetime.fromtimestamp(raw['session_range_end'], tz=jst))
self.assertEqual(sleep.updated, datetime.fromtimestamp(raw['updated'], tz=jst))
self.assertEqual(len(sleep.actigram), 497)
self.assertEqual(len(sleep.sleep_event), 21)
self.assertEqual(len(sleep.presence), 20)
self.assertEqual(len(sleep.snoring_episodes), 20)
self.assertEqual(len(sleep.nap_periods), 0)
self.assertEqual(len(sleep.heart_rate_curve), 89)
self.assertEqual(len(sleep.sleep_cycles), 146)
properties = [
"sleep_latency",
"sleep_time_target",
"total_sleep_score",
"sensor_status",
"sleep_score_version",
"short_term_average_respiration_rate",
"primary_sleep_period_away_episode_duration",
"primary_sleep_period_away_episode_count",
"total_nap_duration",
"average_respiration_rate",
"total_snoring_episode_duration",
"activity_index",
"signal_amplitude",
"short_term_resting_heart_rate",
"evening_HRV_index",
"stage_duration_W",
"clipping_duration",
"single_person_setup",
"resting_heart_rate",
"all_night_HRV_index",
"stage_duration_N",
"stage_duration_A",
"stage_duration_G",
"morning_HRV_index",
"stage_duration_R",
"stage_duration_S",
"sleep_efficiency"
]
for p in properties:
self.assertTrue(hasattr(sleep.property, p))
<file_sep>/beddit/client.py
import requests
import time
import json
from .user import User
from .group import Group
from .sleep import Sleep
from .session import Session
from .compatibility import urljoin
def auth_required(func):
def _is_logged_in(self, *args, **kwargs):
if not self.access_token or not self.user_id:
raise BedditClient.AuthError('authentication is required')
return func(self, *args, **kwargs)
return _is_logged_in
def datetime_to_timestamp(datetime):
return time.mktime(datetime.timetuple())
class BedditClient(object):
class ArgumentError(BaseException):
pass
class AuthError(BaseException):
pass
class APIError(BaseException):
pass
BASE_URL = 'https://cloudapi.beddit.com'
access_token = None
user_id = None
@classmethod
def build_full_path(cls, path):
return urljoin(cls.BASE_URL, path)
def __init__(self, username=None, password=<PASSWORD>, access_token=None, user_id=None):
if access_token and user_id:
self.user_id = user_id
self.access_token = access_token
elif username and password:
payload = {
'grant_type': 'password',
'username': username,
'password': <PASSWORD>
}
endpoint = BedditClient.build_full_path('/api/v1/auth/authorize')
r = requests.post(endpoint, data=payload)
if r.status_code == 200:
response_object = r.json()
self.access_token = response_object['access_token']
self.user_id = response_object['user']
else:
response = r.json()
if response['description']:
raise BedditClient.AuthError(response['description'])
else:
raise BedditClient.AuthError('Authentication is failed')
else:
raise BedditClient.ArgumentError('you must either use both access_token and user_id or both username and password')
@property
def _headers(self):
return {'Authorization': "UserToken {}".format(self.access_token)}
def _get_with_auth(self, path, params={}):
endpoint = BedditClient.build_full_path(path)
r = requests.get(endpoint,
params=params,
headers=self._headers)
return r
def _post_with_auth(self, path, params={}):
endpoint = BedditClient.build_full_path(path)
r = requests.post(endpoint,
data=params,
headers=self._headers)
return r
def _put_with_auth(self, path, params={}):
endpoint = BedditClient.build_full_path(path)
r = requests.put(endpoint,
data=params,
headers=self._headers)
return r
@auth_required
def get_sleeps(self, user_id=None, start=None, end=None, updated_after=None, limit=None, reverse=False):
params = {}
if start:
params['start_date'] = start.strftime('%Y-%m-%d')
if end:
params['end_date'] = end.strftime('%Y-%m-%d')
if updated_after:
params['updated_after'] = updated_after.timestamp()
if limit:
params['limit'] = limit
if reverse:
params['reverse'] = 'yes'
if not user_id:
user_id = self.user_id
path = "/api/v1/user/{}/sleep".format(user_id)
r = self._get_with_auth(path, params=params)
if r.status_code == 200:
return [Sleep(sleep) for sleep in r.json()]
else:
raise BedditClient.APIError(r.json()['description'])
@auth_required
def get_sessions(self, start=None, end=None, updated_after=None):
params = {}
if updated_after and not start and not end:
params['updated_after'] = datetime_to_timestamp(updated_after)
elif not updated_after and start and end:
params['start_timestamp'] = datetime_to_timestamp(start)
params['end_timestamp'] = datetime_to_timestamp(end)
else:
raise BedditClient.ArgumentError('you must either use the updated_after or both start and end.')
path = "/api/v1/user/{}/session".format(self.user_id)
r = self._get_with_auth(path, params=params)
if r.status_code == 200:
return [Session(session) for session in r.json()]
else:
raise BedditClient.APIError(r.json()['description'])
@classmethod
def reset_password(cls, email):
path = "/api/v1/user/password_reset"
endpoint = BedditClient.build_full_path(path)
r = requests.post(endpoint, data={'email': email})
if r.status_code == 200:
return True
else:
raise BedditClient.APIError(r.status_code)
@auth_required
def get_user(self, user_id=None):
if not user_id:
user_id = self.user_id
path = "/api/v1/user/{}".format(user_id)
r = self._get_with_auth(path)
if r.status_code == 200:
return User(r.json())
else:
raise BedditClient.APIError(r.json()['description'])
@auth_required
def update_user(self, user_id=None, **params):
if not user_id:
user_id = self.user_id
path = "/api/v1/user/{}".format(user_id)
r = self._put_with_auth(path, params=json.dumps(params))
if r.status_code == 200:
return User(r.json())
else:
raise BedditClient.APIError(r.json()['description'])
@auth_required
def get_groups(self, user_id=None):
if not user_id:
user_id = self.user_id
path = "/api/v1/user/{}/group".format(user_id)
r = self._get_with_auth(path)
if r.status_code == 200:
return [Group(group) for group in r.json()]
else:
raise BedditClient.APIError(r.json()['description'])
@auth_required
def invite_to_group(self, email, group_id=None):
if group_id:
path = "/api/v1/group/{}/invite".format(group_id)
else:
path = "/api/v1/group/new/invite"
r = self._post_with_auth(path, params={'email': email})
if r.status_code == 200:
return [Group(group) for group in r.json()]
else:
raise BedditClient.APIError(r.json()['description'])
@auth_required
def remove_group_invite(self, group_id, user_id):
path = '/api/v1/group/{}/member/{}/remove'.format(group_id, user_id)
r = self._post_with_auth(path)
if r.status_code == 200:
return [Group(group) for group in r.json()]
else:
raise BedditClient.APIError(r.json()['description'])
<file_sep>/beddit/session.py
from datetime import datetime, timedelta
from enum import Enum
from pytz import timezone
class SensorStatus(Enum):
Operational = 1
Interference = 2
Unclear = 3
class SampledTrack(object):
def __init__(self, obj):
self.samples_per_frame = obj['samples_per_frame']
self.data_url = obj.get('data_url', None)
self.data_type = obj['data_type']
class Session(object):
def __init__(self, response_object):
self.timezone = timezone(response_object['timezone'])
self.id = response_object['id']
self.start = datetime.fromtimestamp(response_object['start_timestamp'], tz=self.timezone)
self.end = datetime.fromtimestamp(response_object['end_timestamp'], tz=self.timezone)
self.hardware = response_object.get("hardware", None)
self.software = response_object["software"]
self.frame_length = response_object.get("frame_length", None)
self.error_code = response_object.get("error_code", None)
self.sampled_tracks = {key: SampledTrack(value) for key, value in response_object.get('sampled_tracks', {}).items()}
time_value_tracks = response_object['time_value_tracks']
def parse(name, initializer=float):
if name in time_value_tracks:
def datetime_from_start(timestamp):
td = timedelta(seconds=timestamp)
return self.start + td
value = {datetime_from_start(float(timestamp)): initializer(v)
for timestamp, v in time_value_tracks[name]['items']}
setattr(self, name, value)
else:
setattr(self, name, [])
parse('respiration_cycle_amplitudes')
parse('heartbeat')
parse('heart_rate')
parse('signal_high_percentile')
parse('repiration_cycles')
parse('events')
parse('actigram')
parse('sensor_status', initializer=SensorStatus)
parse('snoring_events')
parse('activity_segment_length')
parse('high_activity_intervals')
parse('activity_segment_variation')
self.updated = datetime.fromtimestamp(response_object['updated'], tz=self.timezone)
<file_sep>/tests/test_client.py
import unittest
import os
import json
import datetime
from tests.compatibility import patch, Mock
from beddit.client import BedditClient
from beddit.sleep import Sleep
from beddit.session import Session
from beddit.user import User
from beddit.group import Group
BASE_DIR = os.path.dirname(__file__)
def authenticated(testcase):
def _inner(self, *args, **kwargs):
response = Mock()
response.json.side_effect = lambda: {'user': 10000, 'access_token': 'dummytoken'}
response.status_code = 200
payload = {
'grant_type': 'password',
'username': 'username',
'password': '<PASSWORD>'
}
with patch('requests.post', return_value=response) as post:
retval = testcase(self, *args, **kwargs)
post.assert_called_with(BedditClient.build_full_path('api/v1/auth/authorize'), data=payload)
return retval
return _inner
class BedditClientTest(unittest.TestCase):
@property
def _default_client(self):
return BedditClient('username', 'password')
@authenticated
def test_authenticate(self):
client = self._default_client
self.assertEqual(client.user_id, 10000)
self.assertEqual(client.access_token, 'dummytoken')
def test_authentication_error(self):
response = Mock()
response.status_code = 400
response.json.side_effect = lambda: {'description': 'auth_error'}
with patch('requests.post', return_value=response):
self.assertRaises(BedditClient.AuthError, BedditClient, 'username', 'password')
def test_argument_error(self):
self.assertRaises(BedditClient.ArgumentError, BedditClient, 'username')
@authenticated
def test_get_sleep(self):
client = self._default_client
timestamp = 1471761649
endpoint = BedditClient.build_full_path('/api/v1/user/10000/sleep')
response = Mock()
response.status_code = 200
sleep_object = json.load(open(os.path.join(BASE_DIR, 'fixtures/sleep.json')))
response.json = lambda: sleep_object
with patch('requests.get', return_value=response) as get:
sleeps = client.get_sleeps(
start=datetime.datetime.utcfromtimestamp(timestamp),
end=datetime.datetime.utcfromtimestamp(timestamp),
limit=10,
reverse=True
)
self.assertEqual(len(sleeps), 1)
self.assertEqual(type(sleeps[0]), Sleep)
args, kwargs = get.call_args
self.assertEqual(args[0], endpoint)
self.assertDictEqual(kwargs['params'], {
'start_date': '2016-08-21',
'end_date': '2016-08-21',
'limit': 10,
'reverse': 'yes'
})
@authenticated
def test_get_session(self):
client = self._default_client
timestamp = 1471761649
endpoint = BedditClient.build_full_path('/api/v1/user/10000/session')
response = Mock()
response.status_code = 200
session_object = json.load(open(os.path.join(BASE_DIR, 'fixtures/session.json')))
response.json = lambda: session_object
dt = datetime.datetime.fromtimestamp(timestamp)
with patch('requests.get', return_value=response) as get:
sessions = client.get_sessions(updated_after=dt)
self.assertEqual(len(sessions), 1)
self.assertEqual(type(sessions[0]), Session)
args, kwargs = get.call_args
self.assertEqual(args[0], endpoint)
self.assertDictEqual(kwargs['params'], {
'updated_after': timestamp
})
@authenticated
def test_get_session_with_invalid_argument(self):
client = self._default_client
self.assertRaises(BedditClient.ArgumentError, client.get_sessions)
self.assertRaises(BedditClient.ArgumentError, client.get_sessions, start=datetime.datetime.now)
self.assertRaises(BedditClient.ArgumentError, client.get_sessions, end=datetime.datetime.now)
def test_reset_password(self):
response = Mock()
response.status_code = 200
with patch('requests.post', return_value=response) as post:
result = BedditClient.reset_password('<EMAIL>')
self.assertTrue(result)
post.assert_called_once_with(BedditClient.build_full_path('/api/v1/user/password_reset'),
data={'email': '<EMAIL>'})
@authenticated
def test_get_user(self):
client = self._default_client
endpoint = BedditClient.build_full_path('/api/v1/user/10000')
response = Mock()
response.status_code = 200
user_object = json.load(open(os.path.join(BASE_DIR, 'fixtures/user.json')))
response.json = lambda: user_object
with patch('requests.get', return_value=response) as get:
user = client.get_user()
self.assertEqual(type(user), User)
args = get.call_args[0]
self.assertEqual(args[0], endpoint)
@authenticated
def test_update_user(self):
client = self._default_client
endpoint = BedditClient.build_full_path('/api/v1/user/10000')
response = Mock()
response.status_code = 200
user_object = json.load(open(os.path.join(BASE_DIR, 'fixtures/user.json')))
response.json = lambda: user_object
with patch('requests.put', return_value=response) as put:
user = client.update_user(name='foo')
self.assertEqual(type(user), User)
args = put.call_args[0]
self.assertEqual(args[0], endpoint)
@authenticated
def test_get_group(self):
client = self._default_client
endpoint = BedditClient.build_full_path('/api/v1/user/10000/group')
response = Mock()
response.status_code = 200
group_object = json.load(open(os.path.join(BASE_DIR, 'fixtures/group.json')))
response.json = lambda: [group_object]
with patch('requests.get', return_value=response) as get:
groups = client.get_groups()
self.assertEqual(type(groups[0]), Group)
args = get.call_args[0]
self.assertEqual(args[0], endpoint)
@authenticated
def test_invite_to_group(self):
client = self._default_client
endpoint = BedditClient.build_full_path('/api/v1/group/new/invite')
response = Mock()
response.status_code = 200
group_object = json.load(open(os.path.join(BASE_DIR, 'fixtures/group.json')))
response.json = lambda: [group_object]
with patch('requests.post', return_value=response) as post:
groups = client.invite_to_group(email="<EMAIL>")
self.assertEqual(type(groups[0]), Group)
args, kwargs = post.call_args
self.assertEqual(args[0], endpoint)
self.assertDictEqual(kwargs['data'], {
'email': '<EMAIL>'
})
@authenticated
def test_remove_group_invite(self):
client = self._default_client
endpoint = BedditClient.build_full_path('/api/v1/group/200/member/10000/remove')
response = Mock()
response.status_code = 200
group_object = json.load(open(os.path.join(BASE_DIR, 'fixtures/group.json')))
response.json = lambda: [group_object]
with patch('requests.post', return_value=response) as post:
groups = client.remove_group_invite(group_id=200, user_id=10000)
self.assertEqual(type(groups[0]), Group)
args = post.call_args[0]
self.assertEqual(args[0], endpoint)
<file_sep>/tests/test_user.py
import unittest
import json
import os
from datetime import datetime, timedelta
from beddit.user import User, Sex
BASE_DIR = os.path.dirname(__file__)
class UserTest(unittest.TestCase):
@property
def user_response(self):
return json.load(open(os.path.join(BASE_DIR, 'fixtures/user.json')))
def test_user(self):
user = User(self.user_response)
self.assertEqual(user.id, 10000)
self.assertEqual(user.updated, datetime.utcfromtimestamp(1471356194))
self.assertEqual(user.weight, 60.0)
self.assertEqual(user.height, 175.0)
self.assertEqual(user.sleep_time_goal, timedelta(seconds=27000))
self.assertIn('general', user.tip_audiences)
self.assertEqual(user.sex, Sex.Unknown)
self.assertEqual(user.date_of_birth, datetime(1990, 1, 1))
self.assertEqual(user.email, '<EMAIL>')
self.assertEqual(user.created, datetime.utcfromtimestamp(1468327763))
| ec89b224fea80f96713bf9d149653765bd1bd0d9 | [
"Python",
"reStructuredText",
"INI"
] | 14 | reStructuredText | thompsonson/beddit-python | c6fde02abb8c79f4a3824929fa98f1531c7c756a | 0dbdeee88b3560de3fb63fcbeb743d2cbe8480e5 | |
refs/heads/master | <repo_name>vgovilkar/EulerChallange<file_sep>/README.md
EulerChallange
==============
Python solutions to Euler Challange
<file_sep>/NthPrime.py
#!/usr/local/bin/python2.7
import sys
import math
def NthPrime(num):
pnos=[2]
piter=1
i=3
while(len(pnos)<num):
prime=True
for x in pnos:
if(x>math.sqrt(i)):
break;
if(i%x==0):
prime=False;
if(prime):
pnos.append(i)
i+=2
return pnos[-1]
if(__name__=='__main__'):
print NthPrime(int((sys.argv)[1]))
<file_sep>/lcm.py
#!/usr/local/bin/python2.7
pnos = {2:0,3:0,5:0,7:0,11:0,13:0,17:0,19:0};
def maxprimeFactorization(num):
for i in pnos.keys():
times=0;
while(num%i==0):
times+=1;
num=num/i;
if(pnos[i]<times):
pnos[i]=times;
for i in range(2,20):
maxprimeFactorization(i);
print pnos;
product = 1;
for x in pnos.keys():
while(pnos[x]!=0):
product*=x;
pnos[x]-=1;
print product;
<file_sep>/prime sieve.py
#!/usr/local/bin/python2.7
import math;
numcap=2000000;
def multremover(i):
def innerremover(x):
if(x!=i):
return x % i != 0;
else:
return True;
return innerremover
#Eurotothenes sieve
def sieve(numlist):
for i in numlist:
if(i>math.trunc(math.sqrt(numcap))+1):
break;
numlist=filter(multremover(i), numlist);
return numlist;
numlist=range(2,numcap);
print "hi";
numlist=sieve(numlist);
def add(x,y): return x+y
print reduce(add, numlist);<file_sep>/prime_sieve_efficient.py
#!/usr/local/bin/python2.7
import math;
num=2000000;
binArray= [True]*(num+1);
def wipeMultiples(myNum, myList):
for i in range(myNum*2,num+1,myNum):
myList[i]=False;
for i in range(2, math.trunc(math.sqrt(num))+1):
wipeMultiples(i,binArray);
def add(x,y): return x+y
print reduce(add, [x for x in range(2,num+1) if binArray[x]]);<file_sep>/pythagoreantriplets.py
#!/usr/local/bin/python2.7
for i in range(1,998):
for j in range(1,999-i):
k=1000-i-j;
if(i*i+j*j==k*k):
print i,j,k
print i*j*k;<file_sep>/largestPrimeFactor.py
#!/usr/local/bin/python2.7
import sys
import math
def LargestPrimeFactor(num):
pnos = [2];
upper = math.trunc(math.sqrt(num))
for i in range (3, upper, 2):
prime=True;
for x in pnos:
if(i%x==0):
prime=False;
if(prime):
pnos.append(i);
return (pnos[-1]);
if(__name__=='__main__'):
print(LargestPrimeFactor(int((sys.argv)[1]))) | 22a6234b140747c7909301332dd2860a214a9402 | [
"Markdown",
"Python"
] | 7 | Markdown | vgovilkar/EulerChallange | 78ea642548dfcf9baf81c0be0baa509cf92606de | c0eaa3f7879e86ef924935b9dc7b7b99eec1f444 | |
refs/heads/master | <repo_name>strangelarry/HostsQuick<file_sep>/hostsview.py
from gi.repository import Gtk
class HostsTextView(Gtk.TextView):
def __init__(self):
super(Gtk.TextView, self).__init__()
self.buffer_list = {}
def add_to_buffer(self, hosts_name, editable):
buffer = Gtk.TextBuffer()
self.buffer_list[hosts_name] = (buffer, editable)
def remove_from_buffer(self, hosts_name):
if hosts_name in self.buffer_list:
del self.buffer_list[hosts_name]
def set_buffer_content(self, hosts_name, content):
buffer, editable = self.buffer_list.get(hosts_name)
if buffer is not None:
buffer.set_text(content)
def get_buffer_content(self, hosts_name):
buffer, editable = self.buffer_list.get(hosts_name)
if buffer is not None:
content = buffer.get_text(*buffer.get_bounds(), True)
return content
return None
def set_buffer(self, hosts_name):
buffer, editable = self.buffer_list.get(hosts_name)
if buffer is None:
return
super().set_buffer(buffer)
super().set_editable(editable)
def get_buffer(self):
return super().get_buffer()
def has_hosts(self, hosts_name):
return hosts_name in self.buffer_list
class HostsListStore(Gtk.ListStore):
def __init__(self, *args):
super().__init__(*args)
self.current_treeiter = None
def remove(self, treeiter):
if treeiter is None:
return
super().remove(treeiter)
if len(self) == 0:
self.current_treeiter = None
class HostsInputDialog(Gtk.Dialog):
def __init__(self, parent, title):
Gtk.Dialog.__init__(self, title, parent, 0,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OK, Gtk.ResponseType.OK))
self.entry = Gtk.Entry()
box = self.get_content_area()
box.add(self.entry)
self.show_all()
def get_entry(self):
return self.entry.get_text()
def set_entry_visible(self, visible):
self.entry.set_visibility(visible)
<file_sep>/button_event.py
from hostsview import HostsInputDialog
from gi.repository import Gtk
from loader import HostsLoader
import sys
def on_menu_choose_hosts(obj, window, hosts_name):
if not obj.get_active():
return
window.choose_type = 'menu'
choose_hosts(window, hosts_name)
def on_window_choose_hosts(obj, window):
window.choose_type = 'window'
model = window.host_store
treeiter = model.current_treeiter
hosts_name = ''
if treeiter is not None:
hosts_name = model[treeiter][0]
choose_hosts(window, hosts_name)
def choose_hosts(window, hosts_name=''):
if window.choose_type is None or hosts_name == '':
return
current_hosts = HostsLoader.get_current_hosts()
if current_hosts == hosts_name:
return
if HostsLoader.set_hosts(hosts_name):
column = window.host_tree.get_column(0)
column.set_title('Hosts List---->' + hosts_name)
current_hosts = HostsLoader.get_current_hosts()
set_menu_hosts(window, current_hosts)
return
dialog = HostsInputDialog(window, 'input root password')
dialog.set_entry_visible(False)
response = dialog.run()
passwd = dialog.get_entry()
if response == Gtk.ResponseType.OK:
HostsLoader.set_sudo_passwd(passwd)
if not HostsLoader.set_hosts(hosts_name):
warn = Gtk.MessageDialog(window, 0, Gtk.MessageType.ERROR,
Gtk.ButtonsType.CANCEL, '密码不正确!')
warn.run()
warn.destroy()
else:
column = window.host_tree.get_column(0)
column.set_title('Hosts List---->' + hosts_name)
elif response == Gtk.ResponseType.CANCEL:
pass
current_hosts = HostsLoader.get_current_hosts()
set_menu_hosts(window, current_hosts)
dialog.destroy()
def create_hosts(obj, window):
model = window.host_store
textview = window.textview
dialog = HostsInputDialog(window, 'input hosts name')
response = dialog.run()
hosts_name = dialog.get_entry()
if response == Gtk.ResponseType.OK:
if hosts_name == '' or textview.has_hosts(hosts_name):
warn = Gtk.MessageDialog(window, 0, Gtk.MessageType.ERROR,
Gtk.ButtonsType.CANCEL, '输入为空或者hosts已存在!')
warn.run()
warn.destroy()
else:
model.append([hosts_name])
textview.add_to_buffer(hosts_name, True)
HostsLoader.add_hosts(hosts_name)
group = window.menu.get_children()[0].get_group()
hosts_item = Gtk.RadioMenuItem.new_with_label(group, hosts_name)
window.menu.insert(hosts_item, len(window.menu.get_children())-2)
hosts_item.connect('activate', on_menu_choose_hosts, window, hosts_name)
hosts_item.show()
elif response == Gtk.ResponseType.CANCEL:
pass
dialog.destroy()
def delete_hosts(obj, window):
model = window.host_store
textview = window.textview
treeiter = model.current_treeiter
if treeiter is not None:
hosts_name = model[treeiter][0]
if hosts_name == HostsLoader.SYS_HOSTS:
warn = Gtk.MessageDialog(window, 0, Gtk.MessageType.ERROR,
Gtk.ButtonsType.OK, '系统默认hosts不能删除!')
warn.run()
warn.destroy()
return
textview.remove_from_buffer(hosts_name)
model.remove(treeiter)
for item in window.menu.get_children():
if hosts_name == item.get_label():
window.menu.remove(item)
window.menu.show_all()
break
HostsLoader.delete_hosts(hosts_name)
def save_content(obj, window):
model = window.host_store
textview = window.textview
treeiter = model.current_treeiter
if treeiter is not None:
hosts_name = model[treeiter][0]
if hosts_name == HostsLoader.SYS_HOSTS:
return
content = textview.get_buffer_content(hosts_name)
HostsLoader.write_hosts(hosts_name, content)
def clear_content(obj, window):
model = window.host_store
textview = window.textview
treeiter = model.current_treeiter
if treeiter is not None:
hosts_name = model[treeiter][0]
if hosts_name == HostsLoader.SYS_HOSTS:
return
textview.set_buffer_content(hosts_name, '')
def reload_content(obj, window):
model = window.host_store
textview = window.textview
treeiter = model.current_treeiter
if treeiter is not None:
hosts_name = model[treeiter][0]
if hosts_name == HostsLoader.SYS_HOSTS:
return
content = HostsLoader.read_hosts(hosts_name)
textview.set_buffer_content(hosts_name, content)
def on_host_tree_selection_changed(obj, window):
model = window.host_store
textview = window.textview
_, treeiter = obj.get_selected()
if treeiter is not None:
model.current_treeiter = treeiter
hosts_name = model[treeiter][0]
textview.set_buffer(hosts_name)
def set_menu_hosts(window, hosts_name):
for item in window.menu.get_children():
if hosts_name == item.get_label():
if not item.get_active():
item.set_active(True)
break
def quit_app(obj):
sys.exit(0)
<file_sep>/loader.py
import os
import glob
class HostsLoader(object):
HOSTS_FOLDER = './hosts'
HOSTS_FILES = []
SYS_HOSTS = 'sys'
SUDO_PASSWD = ''
HOSTS_REAL = '/etc/hosts'
@classmethod
def init(cls):
if not os.path.exists(cls.HOSTS_FOLDER):
os.mkdir(cls.HOSTS_FOLDER)
if not cls.HOSTS_FILES:
cls.HOSTS_FILES = glob.glob(cls.HOSTS_FOLDER + '/hosts.*')
sys_hosts = cls.get_hosts_file(cls.SYS_HOSTS)
if sys_hosts in cls.HOSTS_FILES:
cls.HOSTS_FILES.remove(sys_hosts)
else:
with open('/etc/hosts') as f:
content = f.read()
cls.write_hosts(cls.SYS_HOSTS, content)
cls.HOSTS_FILES.insert(0, sys_hosts)
@classmethod
def get_hosts_file(cls, hosts_name):
return cls.HOSTS_FOLDER + '/hosts.' + hosts_name
@classmethod
def add_hosts(cls, hosts_name):
hosts_file = cls.get_hosts_file(hosts_name)
cls.HOSTS_FILES.append(hosts_file)
cls.write_hosts(hosts_name)
@classmethod
def write_hosts(cls, hosts_name, content=''):
hosts_file = cls.get_hosts_file(hosts_name)
with open(hosts_file, 'w+') as f:
f.write(content)
@classmethod
def read_hosts(cls, hosts_name):
hosts_file = cls.get_hosts_file(hosts_name)
with open(hosts_file) as f:
content = f.read()
return content
@classmethod
def delete_hosts(cls, hosts_name):
hosts_file = cls.get_hosts_file(hosts_name)
try:
os.remove(hosts_file)
except:
pass
@classmethod
def load_hosts(cls):
return [os.path.basename(hosts_name).split('.')[1] for hosts_name in cls.HOSTS_FILES]
@classmethod
def set_sudo_passwd(cls, passwd):
cls.SUDO_PASSWD = <PASSWORD>
@classmethod
def set_hosts(cls, hosts_name):
hosts_file = cls.get_hosts_file(hosts_name)
result = os.system('echo %s|sudo -S ln -sf %s /etc/hosts'
% (cls.SUDO_PASSWD, os.path.abspath(hosts_file)))
return not bool(result)
@classmethod
def get_current_hosts(cls):
realpath = os.path.realpath(cls.HOSTS_REAL)
try:
hosts_name = os.path.basename(realpath).split('.')[1]
return hosts_name
except:
return None
<file_sep>/main.py
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, AppIndicator3
from button_event import *
from hostsview import HostsTextView, HostsListStore
from loader import HostsLoader
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, app):
Gtk.Window.__init__(self, title='HostsQuick', application=app)
self.set_default_size(800, 600)
self.set_border_width(10)
self.appindicator_id = 'HostsQuick'
self.indicator = AppIndicator3.Indicator.new(self.appindicator_id, 'whatever',
AppIndicator3.IndicatorCategory.SYSTEM_SERVICES)
self.menu = Gtk.Menu()
self.outer_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
self.add(self.outer_box)
self.left_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self.left_box.set_size_request(250, 600)
self.host_store = HostsListStore(str)
self.host_tree = Gtk.TreeView(self.host_store)
self.right_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self.right_box.set_size_request(550, 600)
self.textview = HostsTextView()
self.outer_box.pack_start(self.left_box, True, True, 0)
self.outer_box.pack_start(self.right_box, True, True, 0)
self.choose_type = None
HostsLoader.init()
self.init_hosts()
self.create_leftbox()
self.create_rightbox()
self.create_indicator()
self.init_others()
self.set_position(Gtk.WindowPosition.CENTER)
def create_leftbox(self):
renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("Hosts List", renderer, text=0)
self.host_tree.append_column(column)
self.left_box.pack_start(self.host_tree, True, True, 0)
select = self.host_tree.get_selection()
select.connect("changed", on_host_tree_selection_changed, self)
button_choose = Gtk.Button(label='Choose')
button_choose.connect('clicked', on_window_choose_hosts, self)
button_create = Gtk.Button(label='Create')
button_create.connect('clicked', create_hosts, self)
button_delete = Gtk.Button(label='Delete')
button_delete.connect('clicked', delete_hosts, self)
vbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
vbox.pack_start(button_choose, False, False, 0)
vbox.pack_start(button_create, False, False, 0)
vbox.pack_start(button_delete, False, False, 0)
self.left_box.pack_start(vbox, False, True, 0)
def create_rightbox(self):
scrolledwindow = Gtk.ScrolledWindow()
scrolledwindow.set_hexpand(True)
scrolledwindow.set_vexpand(True)
scrolledwindow.add(self.textview)
self.right_box.pack_start(scrolledwindow, True, True, 0)
button_save = Gtk.Button(label='Save')
button_save.connect('clicked', save_content, self)
button_clear = Gtk.Button(label='Clear')
button_clear.connect('clicked', clear_content, self)
button_reload = Gtk.Button(label='Reload')
button_reload.connect('clicked', reload_content, self)
vbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
vbox.pack_end(button_reload, False, False, 0)
vbox.pack_end(button_clear, False, False, 0)
vbox.pack_end(button_save, False, False, 0)
self.right_box.pack_start(vbox, False, True, 0)
def init_hosts(self):
hosts = HostsLoader.load_hosts()
for host in hosts:
self.host_store.append([host])
if host == HostsLoader.SYS_HOSTS:
self.textview.add_to_buffer(host, False)
else:
self.textview.add_to_buffer(host, True)
content = HostsLoader.read_hosts(host)
self.textview.set_buffer_content(host, content)
def init_others(self):
current_hosts = HostsLoader.get_current_hosts()
if current_hosts is not None:
self.host_tree.get_column(0).set_title('Hosts List---->' + current_hosts)
def create_indicator(self):
self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
group = []
current_hosts = HostsLoader.get_current_hosts()
for hosts_name in HostsLoader.load_hosts():
hosts_item = Gtk.RadioMenuItem.new_with_label(group, hosts_name)
group = hosts_item.get_group()
self.menu.append(hosts_item)
if hosts_name == current_hosts:
hosts_item.set_active(True)
hosts_item.connect('activate', on_menu_choose_hosts, self, hosts_name)
separator = Gtk.SeparatorMenuItem()
item_quit = Gtk.MenuItem('Quit')
item_quit.connect('activate', quit_app)
self.menu.append(separator)
self.menu.append(item_quit)
self.menu.show_all()
self.indicator.set_menu(self.menu)
class MyApplication(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self)
def do_activate(self):
win = MainWindow(self)
win.show_all()
def do_startup(self):
Gtk.Application.do_startup(self)
if __name__ == '__main__':
app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)
| 53d820daf66284606191f12aa313cb45827228f8 | [
"Python"
] | 4 | Python | strangelarry/HostsQuick | 617e5d31862045dabcd97d23708ebaff7de50c16 | 0c10dd5953302729ebd5559c68ec3a86a87638db | |
refs/heads/master | <file_sep><?php
namespace CristianVuolo\Paginas\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Pagina extends Model
{
protected $table = 'cv_paginas';
public function storePagina()
{
$request = request();
$model = new $this;
if($request->pagina_vinculada === '1'){
$model->pagina = $request->pagina;
}
$model->nome = $request->nome;
$model->titulo = ucwords($request->nome);
$model->slug = slug($request->nome, 'cv_paginas');
$model->descricao = $request->descricao;
$model->resumo = $request->resumo;
if($request->file) {
$model->file = $this->upload($request->file('file'));
}
$model->conteudo = $request->conteudo;
$model->views = 0;
$model->save();
}
public function updatePagina($id)
{
$request = request();
$model = $this->find($id);
$model->nome = $request->nome;
$model->titulo = ucwords($request->nome);
$model->descricao = $request->descricao;
$model->resumo = $request->resumo;
if($request->file) {
$model->file = $this->upload($request->file('file'));
}
if($request->pagina != ''){
$model->pagina = $request->pagina;
}
$model->conteudo = $request->conteudo;
$model->save();
}
public function deletePagina($id)
{
$pagina = $this->find($id);
$pagina->delete();
}
public static function bySlug($slug)
{
$t = new self;
return $t->where('slug', $slug)->first();
}
public function upload($file)
{
$file->move(public_path(config('CvConfigs.cv_page.upload.3.path')), $file->getClientOriginalName());
return $file->getClientOriginalName();
}
}
<file_sep><?php
return [
'has_upload' => [999],
'cannot_delete' => [999,1000],
'upload' => [
999 => [
'path' => 'uploads/pages',
'name' => 'Input Name',
'link_name' => 'Btn Name',
],
],
];<file_sep><?php
Route::group(['prefix' => 'controle/paginas/', 'namespace' => 'CristianVuolo\\Paginas\\Controllers', 'middleware' => ['web', 'admin']], function () {
Route::get('/', ['as' => 'admin.pagina.gerenciar', 'uses' => 'PaginaController@gerenciar']);
Route::get('/novo', ['as' => 'admin.pagina.novo', 'uses' => 'PaginaController@novo']);
Route::get('/alterar/{id}', ['as' => 'admin.pagina.alterar', 'uses' => 'PaginaController@alterar']);
Route::post('/store', ['as' => 'admin.pagina.store', 'uses' => 'PaginaController@store']);
Route::put('/update/{id}', ['as' => 'admin.pagina.update', 'uses' => 'PaginaController@update']);
Route::get('/delete/{id}', ['as' => 'admin.pagina.delete', 'uses' => 'PaginaController@delete']);
});
Route::group(['prefix' => '/pagina/', 'namespace' => 'CristianVuolo\\Paginas\\Controllers', 'middleware' => ['web']], function () {
Route::get('{slug}', ['as' => 'front.pagina.pagina', 'uses' => 'FrontPaginaController@pagina']);
});<file_sep><?php
namespace CristianVuolo\Paginas\Providers;
use Illuminate\Support\ServiceProvider;
class PaginasServiceProvider extends ServiceProvider
{
public function boot()
{
$this->publishes([__DIR__ . '/../../resources/publish/migrations/' => base_path('database/migrations')], 'migrations');
$this->publishes([__DIR__ . '/../../resources/publish/views/' => base_path('resources/views/cv')], 'views');
$this->publishes([__DIR__ . '/../../resources/publish/config/' => base_path('config\CvConfigs')], 'views');
$this->loadViewsFrom(__DIR__ . '/../../resources/views/paginas', 'paginas');
require __DIR__ . '/../../resources/routes/routes.php';
}
public function register()
{
}
}<file_sep><?php
namespace CristianVuolo\Paginas\Controllers;
use CristianVuolo\Paginas\Models\Pagina;
class FrontPaginaController extends Controller
{
/**
* @var Pagina
*/
private $model;
public function __construct(Pagina $model)
{
$this->model = $model;
}
public function pagina($slug)
{
$pagina = $this->model->whereSlug($slug);
if ($pagina->count() === 1) {
$pagina = $pagina->first();
$pagina->increment('views');
$view = [
'title' => $pagina->titulo,
'pagina' => $pagina,
];
return view('cv.paginas.pagina', $view);
}
abort(404);
}
}<file_sep><?php
namespace CristianVuolo\Paginas\Controllers;
use CristianVuolo\Paginas\Models\Pagina;
class PaginaController extends Controller
{
/**
* @var Pagina
*/
private $model;
public function __construct(Pagina $model)
{
$this->model = $model;
}
public function gerenciar()
{
$view = [
'title' => 'Gerenciar Páginas',
'paginas' => $this->model->where('block', '<>', '1')->get(),
];
return view('paginas::paginas.gerenciar', $view);
}
public function novo()
{
$view = [
'title' => 'Cadastrar Nova Página',
'pagina' => new $this->model,
'paginasNotRegistred' => [],
];
return view('paginas::paginas.form', $view);
}
public function alterar($id)
{
$view = [
'title' => 'Alterar Página',
'pagina' => $this->model->find($id)
];
return view('paginas::paginas.form', $view);
}
public function store()
{
$this->validatePagina();
$this->model->storePagina();
return redirect()->route('admin.pagina.gerenciar')->with('ok', 'Página Cadastrada');
}
public function update($id)
{
$this->validatePagina($id);
$this->model->updatePagina($id);
return redirect()->route('admin.pagina.gerenciar')->with('ok', 'Página Alterada');
}
public function delete($id)
{
if ($this->model->find($id)->block != 1) {
$this->model->deletePagina($id);
return redirect()->route('admin.pagina.gerenciar')->with('ok', 'Página Removida');
}
return redirect()->back()->with('erro', 'Essa Página não pode ser Removida');
}
private function validatePagina($id = null)
{
$rules = [
'nome' => 'required',
'descricao' => 'required',
'conteudo' => 'required',
];
$messages = [
'required' => 'Campo Obrigatório'
];
$this->validate(request(), $rules, $messages);
}
} | 5db6f3a93dc452217df57c879b1014ef6684cc4a | [
"PHP"
] | 6 | PHP | cristianvuolo/paginas | f1fe2ba92f41bfca42f4e5a01e16085d9da94e33 | 6b09cc91c97b763336c669a3e2ad855f814f31b9 | |
refs/heads/master | <repo_name>Rajprasaddora/Sign_Up_Page<file_sep>/app/src/main/java/com/example/android/sign_up_page/MainActivity.java
package com.example.android.sign_up_page;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b;
EditText name1,email1,pass1;
String name;
String email;
String pass;
RadioButton male;
RadioButton female;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button);
name1 = (EditText) findViewById(R.id.name);
male = (RadioButton) findViewById(R.id.maleid);
female = (RadioButton) findViewById(R.id.femaleid);
email1 = (EditText) findViewById(R.id.email);
pass1 = (EditText) findViewById(R.id.pass);
}
public void raj(View v)
{
name=name1.getText().toString();
email=email1.getText().toString();
pass=<PASSWORD>().<PASSWORD>();
String gend;
if(male.isChecked())
{
gend ="male";
}
else
gend ="female";
Toast.makeText(MainActivity.this,"Welcome",Toast.LENGTH_LONG).show();
Intent ras=new Intent(MainActivity.this, Main2Activity.class);
startActivity(ras);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
Toast.makeText(MainActivity.this,"changing orientation to Landscape is not recommended",Toast.LENGTH_LONG).show();
}
}
| 6f46143428334b42474888d185721ff68dcd4b07 | [
"Java"
] | 1 | Java | Rajprasaddora/Sign_Up_Page | b4476a53b1312e4064b20b2744e7e7e4ab730310 | 663eb6a9b861e6e9969e6cc1619190ce4d16e188 | |
refs/heads/master | <repo_name>soulmonk/template-jersey-spring-jpa<file_sep>/src/main/java/com/ricardoborillo/test/dao/UsersDAO.java
package com.ricardoborillo.test.dao;
import java.util.List;
import com.ricardoborillo.test.model.User;
public interface UsersDAO
{
List<User> getUsers();
void removeUser(Integer id);
User addUser(User user);
void updateUser(User user);
}<file_sep>/src/main/java/com/ricardoborillo/test/services/rest/UsersResource.java
package com.ricardoborillo.test.services.rest;
import java.util.Collections;
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.core.MediaType;
import com.ricardoborillo.test.model.User;
import com.ricardoborillo.test.services.UsersService;
import com.sun.jersey.api.core.InjectParam;
@Path("users")
public class UsersResource
{
@InjectParam
private UsersService usersService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public RestResponse getAll()
{
return new RestResponse(true, usersService.getUsuarios());
}
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public RestResponse remove(@PathParam("id") String id)
{
usersService.removeUser(Integer.parseInt(id));
return new RestResponse(true);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public RestResponse add(User user)
{
User newUser = usersService.addUser(user);
return new RestResponse(true, Collections.singletonList(newUser));
}
@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public RestResponse update(User user)
{
usersService.updateUser(user);
return new RestResponse(true, Collections.singletonList(user));
}
}
| d5080d0c6822b6584fb4ff91b5245680291dcd53 | [
"Java"
] | 2 | Java | soulmonk/template-jersey-spring-jpa | 217321d58358982e0c15aa02026a771a874d1ff3 | 176265126cb0955ffd2dda7c5926d05ee43e3e94 | |
refs/heads/master | <repo_name>memoryeun72/memoryeun72.github.io<file_sep>/pages/get-started.js
import Nav from '../components/nav';
export default () => {
return ( <>
<Nav/>
<h1>시작하기</h1>
<p>npm을 통해 CLI를 설치합니다. </p>
</>
)
} | 14fbeefabba0c07d24d3597785b08833138d1c6a | [
"JavaScript"
] | 1 | JavaScript | memoryeun72/memoryeun72.github.io | bb23e76ac114717b77a9c5207731800fa0f662b3 | 4241800f8fa9e67d1e2bc482f112f73e0f94451b | |
refs/heads/master | <file_sep>install:
npm i
npm install axios
npm install net-snmp
run:
npm start<file_sep>var express = require('express');
var router = express.Router();
var snmp = require ('net-snmp');
var hostip = "127.0.0.1";
var options = {
port: '4161'
};
var session = snmp.createSession(hostip, "public", options);
var maxRepetitions = 20;
var musics = [];
var re;
var hosts = [
'127.0.0.1',
'192.168.1.67',
'192.168.1.1',
];
//var oid = "1.3.6.1.4.1.2";
var mount = [[],[],[],[]];
var oids = [
"1.3.6.1.4.1.2.1"
];
var nonRepeaters = 0;
/* GET home page. */
router.get('/', function(req, res, next) {
re = res;
// The maxRepetitions argument is optional, and will be ignored unless using
// SNMP verison 2c
//session.table(oid, maxRepetitions, getMusics);
session.getBulk (oids, nonRepeaters,60, function (error, varbinds) {
if (error) {
console.error (error.toString ());
} else {
// step through the non-repeaters which are single varbinds
for (var i = 0; i < nonRepeaters; i++) {
if (i >= varbinds.length)
break;
if (snmp.isVarbindError (varbinds[i]))
console.error (snmp.varbindError (varbinds[i]));
else
console.log (varbinds[i].oid + "|" + varbinds[i].value);
}
// then step through the repeaters which are varbind arrays
for (var i = nonRepeaters; i < varbinds.length; i++) {
for (var j = 0, nm = ((varbinds[i].length)/4), p = 0, m = 0; j < varbinds[i].length; j++, p++) {
if (snmp.isVarbindError (varbinds[i][j]))
console.error (snmp.varbindError (varbinds[i][j]));
else {
console.log ((varbinds[i].length) + '------' + varbinds[i][j].value.toString() + '------' + j);
if(p === nm) { p = 0; m++ }
mount[m].push(varbinds[i][j].value.toString());
console.log (varbinds[i][j].oid + "|" + varbinds[i][j].value);
}
}
}
for (var i = 0; i < mount[0].length; i++){
var music = {
id: mount[0][i],
artist: mount[1][i],
title: mount[2][i],
path: mount[3][i]
}
musics.push(music);
}
mount = [[],[],[],[]];
}
res.jsonp(musics);
musics = [];
});
});
/* GET home page. */
router.get('/music/:musica', function(req, res, next) {
// The maxRepetitions argument is optional, and will be ignored unless using
// SNMP verison 2c
var varbinds = [
{
oid: "1.3.6.1.4.1.1.0",
type: snmp.ObjectType.OctetString,
value: '*path*' + req.params.musica
}
];
session.set (varbinds, (error, varbinds) => {
if (error) {
console.error (error.toString ());
} else {
for (var i = 0; i < varbinds.length; i++) {
// for version 2c we must check each OID for an error condition
if (snmp.isVarbindError (varbinds[i]))
console.error (snmp.varbindError (varbinds[i]));
else
console.log (varbinds[i].oid + "|" + varbinds[i].value);
session.get(["1.3.6.1.4.1.3.0"], (error, varbinds) => {
if (error) { console.error (error.toString ());
} else {
for (var i = 0; i < varbinds.length; i++) {
// for version 2c we must check each OID for an error condition
if (snmp.isVarbindError (varbinds[i]))
console.error (snmp.varbindError (varbinds[i]));
else {
res.send( varbinds[i].value.toString() );
console.log (varbinds[i].oid + "|" + varbinds[i].value);
}
}
}
});
}
}
});
});
/* GET home page. */
router.get('/hosts', function(req, res, next) {
// The maxRepetitions argument is optional, and will be ignored unless using
// SNMP verison 2c
res.jsonp(hosts)
});
/* GET home page. */
router.post('/hostip', function(req, res, next) {
hostip = req.body.host;
session = snmp.createSession(hostip, "public", options);
// The maxRepetitions argument is optional, and will be ignored unless using
// SNMP verison 2c
res.send({'udp':'done'})
});
/* GET home page. */
router.get('/sysname', function(req, res, next) {
session.get(["1.3.6.1.2.1.1.5.0"], (error, varbinds) => {
if (error) {
console.error (error.toString ());
} else {
for (var i = 0; i < varbinds.length; i++) {
// for version 2c we must check each OID for an error condition
if (snmp.isVarbindError (varbinds[i]))
console.error (snmp.varbindError (varbinds[i]));
else {
res.send( varbinds[i].value.toString() );
console.log (varbinds[i].oid + "|" + varbinds[i].value);
}
}
}
});
});
module.exports = router;<file_sep>const Host = require('../models/hosts');
var Hosts = module.exports;
//Devolve lista dos Hosts
Hosts.listar = () => {
return Host
.find()
.exec();
}
//Devolve lista dos Hosts
Hosts.consultar = id => {
return Host
.findOne({_id: id})
.exec();
}
//Devolve lista dos Hosts
Hosts.contar = () => {
return Host
.countDocuments()
.exec();
}
Hosts.inserir = host => {
var novo = new Host(host);
return novo.save();
}<file_sep>install:
npm i
npm install axios
npm install os
npm install mpg123
npm install net-snmp
run:
node jssnmpd<file_sep>var snmp = require('net-snmp');
var os = require('os');
var mpg = require('mpg123');
player = new mpg.MpgPlayer();
// Default options
var options = {
port: 4161,
disableAuthorization: true,
transport: "udp4"
};
var lastMusic = "default.mp3"
var pause = false;
var callback = function (error, data) {
if ( error ) {
console.error (error);
} else {
if (data.pdu.varbinds[0].value) {
name = data.pdu.varbinds[0].value.toString();
if(name.includes('*path*')) {
var nome = name.slice(6);
console.log (lastMusic + ' ' + nome);
if(lastMusic != nome) {
player.play('./musicas/'+ nome);
pause = false;
} else if (pause) {
player.pause();
} else {
player.pause();
pause = true;
}
}
}
// console.log (JSON.stringify(data, null, 2));
}
};
agent = snmp.createAgent (options, callback);
var mib = agent.getMib();
console.log('SNMP agent running on port: ' + options.port)
player.on('resume', function(data){
mib.setScalarValue ("playedLength", a = parseInt(player.length));
})
// Create a module store, load a MIB module, and fetch its JSON representation
var store = snmp.createModuleStore ();
store.loadFromFile ("/usr/local/share/snmp/mibs/SNMPv2-MIB.txt");
//var jsonModule = store.getModule ("SNMPv2-MIB");
// Fetch MIB providers, create an agent, and register the providers with your agent
var providersMIB = store.getProvidersForModule ("SNMPv2-MIB");
mib.registerProviders (providersMIB);
// Create a module store, load a MIB module, and fetch its JSON representation
var store = snmp.createModuleStore ();
store.loadFromFile ("/usr/local/share/snmp/mibs/SNMPv2-SMI.txt");
//var jsonModule = store.getModule ("SNMPv2-SMI");
// Fetch SMI providers, create an agent, and register the providers with your agent
var providersSMI = store.getProvidersForModule ("SNMPv2-SMI");
mib.registerProviders (providersSMI);
// Create a module store, load a MIB module, and fetch its JSON representation
var store = snmp.createModuleStore ();
store.loadFromFile ("/usr/local/share/snmp/mibs/SNMPv2-CONF.txt");
//var jsonModule = store.getModule ("SNMPv2-CONF");
// Fetch CONF providers, create an agent, and register the providers with your agent
var providersCONF = store.getProvidersForModule ("SNMPv2-CONF");
mib.registerProviders (providersCONF);
// Create a module store, load a MIB module, and fetch its JSON representation
var store = snmp.createModuleStore ();
store.loadFromFile ("/usr/local/share/snmp/mibs/SNMPv2-TC.txt");
//var jsonModule = store.getModule ("SNMPv2-TC");
// Fetch TC providers, create an agent, and register the providers with your agent
var providersTC = store.getProvidersForModule ("SNMPv2-TC");
mib.registerProviders (providersTC);
var play = {
name: "playedMusic",
type: snmp.MibProviderType.Scalar,
oid: "1.3.6.1.4.1.1",
scalarType: snmp.ObjectType.OctetString,
handler: function (mibRequest) {
var nome = mibRequest.instanceNode.value.slice(6);
lastMusic = nome;
mibRequest.done ();
}
};
var size = {
name: "playedLength",
type: snmp.MibProviderType.Scalar,
oid: "1.3.6.1.4.1.3",
scalarType: snmp.ObjectType.Integer,
handler: function (mibRequest) {
mibRequest.done ();
}
};
var musicsTable = {
name: "playListTable",
type: snmp.MibProviderType.Table,
oid: "1.3.6.1.4.1.2",
tableColumns: [
{
number: 1,
name: "musicIndex",
type: snmp.ObjectType.Integer
},
{
number: 2,
name: "musicArtist",
type: snmp.ObjectType.OctetString
},
{
number: 3,
name: "musicTitle",
type: snmp.ObjectType.OctetString
},
{
number: 4,
name: "musicPath",
type: snmp.ObjectType.OctetString
}
],
tableIndex: [
{
columnName: "musicIndex"
}
]
};
mib.registerProvider (play);
mib.registerProvider (size);
mib.registerProvider (musicsTable);
mib.setScalarValue ("playedMusic", "default.mp3");
mib.setScalarValue ("playedLength", 0);
mib.addTableRow ("playListTable", [1, "<NAME>", "Escape", "PinaColada.mp3"]);
mib.addTableRow ("playListTable", [2, "Toploader", "Dancing in the Moonlight", "DancingInTheMoonlight.mp3"]);
mib.addTableRow ("playListTable", [3, "Tame Impala", "BorderLine", "Borderline.mp3"]);
mib.addTableRow ("playListTable", [4, "Kodaline", "HighHopes", "HighHopes.mp3"]);
mib.addTableRow ("playListTable", [5, "<NAME>", "God's Gonna Cut You Down", "GodsGonnaCutYouDown.mp3"]);
mib.addTableRow ("playListTable", [6, "<NAME>", "Summer Of '69", "SummerOf69.mp3"]);
mib.addTableRow ("playListTable", [7, "<NAME>", "Runaway", "Runaway.mp3"]);
mib.addTableRow ("playListTable", [8, "<NAME>", "When a blind man cries", "Whenablindmancries.mp3"]);
mib.addTableRow ("playListTable", [9, "R.E.M.", "Losing My Religion", "LosingMyReligion.mp3"]);
mib.addTableRow ("playListTable", [10, "System Of A Down", "Lonely Day", "LonelyDay.mp3"]);
mib.addTableRow ("playListTable", [11, "Linkin Park", "Breaking The Habit", "BreakingtheHabit.mp3"]);
mib.addTableRow ("playListTable", [12, "Linkin Park", "In The End", "InTheEnd.mp3"]);
mib.addTableRow ("playListTable", [13, "Red Hot Chili Peppers", "Can't Stop", "CantStop.mp3"]);
mib.addTableRow ("playListTable", [14, "Foo Fighters", "The Pretender", "ThePretender.mp3"]);
mib.addTableRow ("playListTable", [15, "System Of A Down", "Toxicity", "Toxicity.mp3"]);
// Start manipulating the MIB through the registered providers using the `Mib` API calls
mib.setScalarValue ("sysDescr", "The most powerful system you can think of");
mib.setScalarValue ("sysName", os.hostname());
mib.addTableRow ("sysOREntry", [1, "1.3.6.1.4.1.47491.192.168.127.12", "I've dreamed up this MIB", 20]);
<file_sep># Remote-Music-Player
A simple player, over snmp protocol. This project contains a vue js interface, a node js api and a snmp agent in javascript.
## How to set up
You should run the snmp agent in the remote device and control it through the web interface.
| 7539c05592f2e662449183c7e3b0f024a652cb88 | [
"JavaScript",
"Makefile",
"Markdown"
] | 6 | Makefile | tymoshchuk19/Remote-Music-Player | 2668a6fba9aa8e87734fe894b76046b56569e915 | e0e73f0826d6d148c77c4168deaddcfcedf6eac8 | |
refs/heads/master | <repo_name>carloslores/lab-react-ironcontacts<file_sep>/starter-code/src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import contacts from './contacts.json'
import './App.css';
import Listcontacts from './components/Listcontacts';
import Table from "./components/Table"
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<div>{contacts[0].name}</div>
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<Table />
</div>
);
// return actors Math.floor(Math.random() * 16777215
}
}
export default App;
| cd730e8b81fb89efac2dffe19dd771c536b749d9 | [
"JavaScript"
] | 1 | JavaScript | carloslores/lab-react-ironcontacts | 3932f16dd0cabb038b16f911f86ded4cafb695b0 | c413ddb1464fdea946db33489be75cf259cf6cba | |
refs/heads/master | <file_sep>package cn.edu.nju.onlineexam.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* Created by user on 2017/11/20.
*
*/
@Entity
public class Relation_PaperAndProblem {
@Id
@GeneratedValue
private long id;
@Column
private long paperId;
@Column
private long studentId;
@Column
private long problemId;
@Column
private String stAnswer;
public Relation_PaperAndProblem(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getPaperId() {
return paperId;
}
public void setPaperId(long paperId) {
this.paperId = paperId;
}
public long getProblemId() {
return problemId;
}
public void setProblemId(long problemId) {
this.problemId = problemId;
}
public String getStAnswer() {
return stAnswer;
}
public void setStAnswer(String stAnswer) {
this.stAnswer = stAnswer;
}
public long getStudentId() {
return studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
}
<file_sep>package cn.edu.nju.onlineexam.Util;
import java.util.List;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
/**
* Created by mac on 2017/12/13.
*/
public class MailUtil {
public static void send(String txt,String sub,String receiver) throws Exception{
Properties props = new Properties();
props.setProperty("mail.debug", "false");
props.setProperty("mail.smtp.ssl.enable", "true");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.host", "smtp.163.com");
props.setProperty("mail.transport.protocol", "smtp");
Session session = Session.getInstance(props);
Message msg = new MimeMessage(session);
msg.setSubject(sub);
msg.setText(txt);
msg.setFrom(new InternetAddress("<EMAIL>"));
Transport transport = session.getTransport();
transport.connect("<EMAIL>", "zhouyao123");
transport.sendMessage(msg, new Address[] {new InternetAddress(receiver)});
transport.close();
}
public static void main(String[] args) throws Exception{
send("1","1","<EMAIL>");
}
}
<file_sep>import Vue from 'vue'
import Router from 'vue-router'
import Maps from './map'
Vue.use(Router)
// 实际路由设置
const router = new Router(Maps)
// 验证登录
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// TODO
console.log('requires auth')
// 向后端获取是否登录的信息来设置 loggedIn 这里先默认为 true
let loggedIn = true
// if not, redirect to login page.
if (!loggedIn) {
next({
path: '/teacher/login'
// query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // 确保一定要调用 next()
}
})
export default router
<file_sep>package cn.edu.nju.onlineexam.service;
import cn.edu.nju.onlineexam.Exception.LoginInvalidException;
import cn.edu.nju.onlineexam.Repository.TeacherRepository;
import cn.edu.nju.onlineexam.entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.xml.ws.Action;
@Service
public class TeacherServiceImpl implements TeacherService{
@Autowired
private TeacherRepository teacherRepository;
@Override
public Teacher register(Teacher teacher) {
return teacherRepository.save(teacher);
}
@Override
public void delete(Long id) {
teacherRepository.delete(id);
}
@Override
public Teacher update(Teacher teacher) {
return teacherRepository.save(teacher);
}
@Override
public Teacher findTeacherById(Long id) {
return teacherRepository.findOne(id);
}
@Override
public Teacher findTeacherByAccount(String account) {
return teacherRepository.findByAccount(account);
}
@Override
public Teacher login(String account, String password) throws LoginInvalidException {
Teacher teacher = teacherRepository.findByAccount(account);
if(teacher == null)
throw new LoginInvalidException("email is not valid");
if(!password.equals(teacher.getPassword()))
throw new LoginInvalidException("password is not valid");
return teacher;
}
}
<file_sep>package cn.edu.nju.onlineexam.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* Created by user on 2017/11/20.
*
*/
@Entity
public class Problem {
@Id
@GeneratedValue
private long id;
@Column
private String content;
@Column
private String A;
@Column
private String B;
@Column
private String C;
@Column
private String D;
@Column
private String answer;
public Problem(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getA() {
return A;
}
public void setA(String a) {
A = a;
}
public String getB() {
return B;
}
public void setB(String b) {
B = b;
}
public String getC() {
return C;
}
public void setC(String c) {
C = c;
}
public String getD() {
return D;
}
public void setD(String d) {
D = d;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
<file_sep>package cn.edu.nju.onlineexam.service;
import cn.edu.nju.onlineexam.Exception.LoginInvalidException;
import cn.edu.nju.onlineexam.Repository.StudentRepository;
import cn.edu.nju.onlineexam.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by user on 2017/11/20.
*
*/
@Service
public class StudentServiceImpl implements StudentService{
@Autowired
private StudentRepository studentRepository;
@Override
public Student register(Student st) {
return studentRepository.save(st);
}
@Override
public void delete(Long id) {
studentRepository.delete(id);
}
@Override
public Student update(Student st) {
return studentRepository.save(st);
}
@Override
public Student findStudentById(long id) {
return studentRepository.findOne(id);
}
@Override
public Student findStudentByEmail(String email) {
return studentRepository.findByEmail(email);
}
@Override
public List<Student> findStudentByGrade(int s_grade) {
return studentRepository.findByGrade(s_grade);
}
@Override
public List<Student> findStudentByGradeAndClass(int s_grade, int s_class) {
return studentRepository.findByGradeAndStudentClass(s_grade,s_class);
}
@Override
public Student login(String email, String password) throws LoginInvalidException{
Student student = studentRepository.findByEmail(email);
if(student == null)
throw new LoginInvalidException("email is not valid");
if(!password.equals(student.getPassword()))
throw new LoginInvalidException("password is not valid");
return student;
}
}
<file_sep>package cn.edu.nju.onlineexam.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Relation_ExamAndProblem {
@Id
@GeneratedValue
private long id;
/**
* 某场考试的id
*/
@Column
private long examId;
/**
* 该场考试的题目id
*/
@Column
private long problemId;
public Relation_ExamAndProblem(){}
public long getExamId() {
return examId;
}
public void setExamId(long examId) {
this.examId = examId;
}
public long getProblemId() {
return problemId;
}
public void setProblemId(long problemId) {
this.problemId = problemId;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
<file_sep>package cn.edu.nju.onlineexam.Repository;
import cn.edu.nju.onlineexam.entity.Relation_StudentAndExam;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface Relation_StudentAndExamRepository extends JpaRepository<Relation_StudentAndExam,Long>{
public List<Relation_StudentAndExam> findByStId(long studentId);
public List<Relation_StudentAndExam> findByExamineId(long examId);
public Relation_StudentAndExam findByStIdAndExamineId(long studentId, long examId);
}
<file_sep>package cn.edu.nju.onlineexam.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Teacher {
@Id
@GeneratedValue
private long id;
/**
* 教师工号
*/
@Column
private String account;
/**
* 教师登录密码
*/
@Column
private String password;
/**
* 教师所教课程
*/
@Column
private String courses;
public Teacher(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getCourses() {
return courses;
}
public void setCourses(String courses) {
this.courses = courses;
}
}
<file_sep>package cn.edu.nju.onlineexam.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* Created by user on 2017/11/20.
*
*/
@Entity
public class Exam {
@Id
@GeneratedValue
private long id;
/**
* 考试名称
*/
@Column
private String name;
/**
* 试题数目
*/
@Column
private int number;
/**
* 每题分值
*/
@Column
private int value;
/**
* 考试开始时间
*/
@Column
private String start_time;
/**
* 考试结束时间
*/
@Column
private String end_time;
/**
* 发起这场考试的老师id
*/
@Column
private long teacherId;
/**
* 考试状态
* 0表示未开始
* 1表示进行中
* 2表示已结束
* 3表示已弃考
*/
@Column
private int status;
public Exam() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getStart_time() {
return start_time;
}
public void setStart_time(String start_time) {
this.start_time = start_time;
}
public String getEnd_time() {
return end_time;
}
public void setEnd_time(String end_time) {
this.end_time = end_time;
}
public long getTeacherId() {
return teacherId;
}
public void setTeacherId(long teacherId) {
this.teacherId = teacherId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
<file_sep>package cn.edu.nju.onlineexam.service;
import cn.edu.nju.onlineexam.Exception.LoginInvalidException;
import cn.edu.nju.onlineexam.entity.Teacher;
public interface TeacherService {
public Teacher register(Teacher teacher);
public void delete(Long id);
public Teacher update(Teacher teacher);
public Teacher findTeacherById(Long id);
public Teacher findTeacherByAccount(String account);
public Teacher login(String email, String passWord) throws LoginInvalidException;
}
<file_sep>package cn.edu.nju.onlineexam.Repository;
import cn.edu.nju.onlineexam.entity.Relation_PaperAndProblem;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface Relation_PaperAndProblemRepository extends JpaRepository<Relation_PaperAndProblem,Long>{
public List<Relation_PaperAndProblem> findByPaperIdAndStudentId(long paperId, long stId);
public List<Relation_PaperAndProblem> findByPaperId(long paperId);
public Relation_PaperAndProblem findByProblemId(long problemId);
}
<file_sep>package cn.edu.nju.onlineexam.Repository;
import cn.edu.nju.onlineexam.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface StudentRepository extends JpaRepository<Student,Long> {
public Student findByEmail(String email);
public List<Student> findByGrade(int grade);
public List<Student> findByGradeAndStudentClass(int grade, int studentClass);
}
<file_sep>package cn.edu.nju.onlineexam.Repository;
import cn.edu.nju.onlineexam.entity.Paper;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PaperRepository extends JpaRepository<Paper,Long>{
public Paper findByExamIdAndStId(long examId, long studentId);
}
<file_sep>package cn.edu.nju.onlineexam.DTO;
import cn.edu.nju.onlineexam.entity.Problem;
import java.util.List;
public class PaperDTO {
private String examName;
private String studentName;
private String studentNo;
private List<Problem> problems;
private String studentAnswers;
private int mark;
private int value;
public List<Problem> getProblems() {
return problems;
}
public void setProblems(List<Problem> problems) {
this.problems = problems;
}
public String getExamName() {
return examName;
}
public void setExamName(String name) {
this.examName = name;
}
public String getStudentAnswers() {
return studentAnswers;
}
public void setStudentAnswers(String studentAnswers) {
this.studentAnswers = studentAnswers;
}
public int getMark() {
return mark;
}
public void setMark(int mark) {
this.mark = mark;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
}
}
<file_sep>package cn.edu.nju.onlineexam.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* Created by user on 2017/11/20
* .
*/
@Entity
public class Relation_StudentAndExam {
@Id
@GeneratedValue
private long id;
@Column
private long stId;
@Column
private long examineId;
/**
* 考试状态
* 0表示未开始
* 1表示进行中
* 2表示已结束
* 3表示已弃考
*/
@Column
private int status;
public Relation_StudentAndExam(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getStId() {
return stId;
}
public void setStId(long stId) {
this.stId = stId;
}
public long getExamineId() {
return examineId;
}
public void setExamineId(long examineId) {
this.examineId = examineId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
<file_sep>const Dist = {
template: '<router-view></router-view>'
}
export default {
mode: 'history',
routes: [
{
path: 'login',
name: 'LoginPage',
component (resolve) {
require(['@/page/auth/LoginPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: '/teacher',
component: Dist,
children: [
{
path: 'login',
name: 'teacherLoginPage',
component (resolve) {
require(['@/page/auth/LoginPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'register',
name: 'RegisterTeacherPage',
component (resolve) {
require(['@/page/auth/RegisterTeacherPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'question/:teacherId',
name: 'QuestionListPage',
component (resolve) {
require(['@/page/teacher/QuestionListPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'question/detail/:teacherId/:examId',
name: 'QuestionListDetailPage',
component (resolve) {
require(['@/page/teacher/QuestionListDetailPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'question/upload/:teacherId/:examId',
name: 'QuestionUploadPage',
component (resolve) {
require(['@/page/teacher/QuestionUploadPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'exam/generate/:teacherId',
name: 'ExamGenerate',
component (resolve) {
require(['@/page/teacher/ExamGeneratePage'], resolve)
},
meta: { requiresAuth: false }
}
]
},
{
path: '/student',
component: Dist,
children: [
{
path: 'login',
name: 'studentLoginPage',
component (resolve) {
require(['@/page/auth/LoginPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'register',
name: 'RegisterStudentPage',
component (resolve) {
require(['@/page/auth/RegisterStudentPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'exam/list/:studentId',
name: 'ExamList',
component (resolve) {
require(['@/page/student/ExamListPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'exam/:studentId/:examId/question/:questionId/:first',
name: 'ExamQuestion',
props: true,
component (resolve) {
require(['@/page/student/ExamQuestionPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'exam/:examId/check/:answer/:mark',
name: 'ExamCheck',
props: true,
component (resolve) {
require(['@/page/student/ExamCheckPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'exam/:studentId/list/:examId/info',
name: 'ExamInfo',
props: true,
component (resolve) {
require(['@/page/student/ExamInfoPage'], resolve)
},
meta: { requiresAuth: false }
},
{
path: 'exam/:studentId/:examId/paper',
name: 'ExamPaper',
props: true,
component (resolve) {
require(['@/page/student/ExamPaperPage'], resolve)
},
meta: { requiresAuth: false }
}
]
}
]
}
| 0cf2efb25601569c0e468b7a03d3ef1b57b142d9 | [
"JavaScript",
"Java"
] | 17 | Java | zhangchengyao/OnlineExam | 29a65c8db36ed7ccc30ea18dd483e946b7134e91 | 99a6e5f06865e5fa05909e2c7bb33e83b7dcbe0f | |
refs/heads/master | <file_sep>var axios = require("axios");
const dotenv = require('dotenv').config();
var moment = require('moment');
var keys = require("./keys.js");
var Spotify = require('node-spotify-api');
var fs = require("fs");
var filePath = "./random.txt";
var delimeter = ',';
// process.env now has the keys and values you defined in your .env file.
function runLiri(command, inputParam) {
if (command === "concert-this") {
// Run the axios.get function...
// The axios.get function takes in a URL and returns a promise (just like $.ajax)
axios.get("https://rest.bandsintown.com/artists/" + inputParam + "/events?app_id=codingbootcamp").then(
function (response) {
response.data.forEach(function (value) {
console.log('Venue Name: ' + value.venue.name);
console.log('Venue Location: ' + value.venue.city + ', ' + value.venue.country);
console.log('Date of Event: ' + moment(value.datetime).format("MM-DD-YYYY"));
console.log('--------------------');
});
},
function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an object that comes back with details pertaining to the error that occurred.
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log("Error", error.message);
}
console.log(error.config);
}
);
} else if (command === "spotify-this-song") {
if (inputParam === undefined) {
inputParam = "Ace of Base The Sign";
console.log("You did not specify a parameter. We defaulted to: " + inputParam + ". Enjoy!!")
}
var spotify = new Spotify(keys.spotify);
var spotify = new Spotify({
id: keys.spotify.id,
secret: keys.spotify.secret
});
spotify.search({
type: 'track',
query: inputParam
}, function (err, data) {
if (err) {
return console.log('Error occurred: ' + err);
}
data.tracks.items.forEach(function (value) {
value.artists.forEach(function (artists) {
console.log("Artist(s): " + artists.name);
});
console.log("Song Name: " + value.name);
console.log("Spotify preview: " + value.album.external_urls.spotify);
console.log("Album name: " + value.album.name);
console.log('--------------------');
});
});
} else if (command === "movie-this") {
if (inputParam === undefined) {
inputParam = "<NAME>";
}
axios.get(
"https://www.omdbapi.com/?t=" + inputParam + "&y=&plot=short&apikey=trilogy"
).then(
function (response) {
console.log("Title: " + response.data.Title);
console.log("Year: " + response.data.Year);
response.data.Ratings.forEach(function (value) {
if (value.Source === "Internet Movie Database") {
console.log("IMDB Rating: " + value.Value);
}
if (value.Source === "Rotten Tomatoes") {
console.log("Rotten Tomatoes Rating: " + value.Value);
}
});
console.log("Country: " + response.data.Country);
console.log("Language: " + response.data.Language);
console.log("Plot: " + response.data.Plot);
console.log("Actors: " + response.data.Actors);
},
function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an object that comes back with details pertaining to the error that occurred.
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log("Error", error.message);
}
console.log(error.config);
}
);
} else if (command === "do-what-it-says") {
fs.readFile(filePath, 'UTF8', function (error, data) {
if (error) {
return console.log(error);
}
var stringArr = data.split(delimeter);
runLiri(stringArr[0], stringArr[1]);
});
}
}
var command ="";
var inputParam ="";
process.argv.forEach(function(value,index){
if (index ===2){
command = value;
}
//concatenates the input parameters from the command line
if (index > 2){
inputParam += value + ' ';
}
});
inputParam = inputParam.trim();
runLiri(command, inputParam);
| e5edf4de3d02f1918cdeee7932495f47caed1f28 | [
"JavaScript"
] | 1 | JavaScript | chrisfernandes123/liri-node-app | dd51d856fde7f9519e379c349848d213cd220b5b | 6767d67740720d901ed2ab098f1f481f3afbcff2 | |
refs/heads/master | <repo_name>karenalo13/SeminarCts<file_sep>/state/src/ro/ase/cts/v2Componente/Libera.java
package ro.ase.cts.v2Componente;
public class Libera implements Stare{
@Override
public void afisareDescriere() {
System.out.println("suntem in stare libera");
}
}
<file_sep>/state/src/ro/ase/cts/componente/Libera.java
package ro.ase.cts.componente;
public class Libera implements StareMasa {
@Override
public void modificaStare(Masa masa) {
if(!(masa.getStareMasa() instanceof Libera ))
{
System.out.println("Masa cu nr "+masa.getNume()+" a fost eliberata");
masa.setStareMasa(this);
}
else
{
System.out.println("Masa este deja libera");
}
}
}
<file_sep>/flyweight/src/ro/ase/cts/componente/FlyweightAbstract.java
package ro.ase.cts.componente;
public interface FlyweightAbstract {
void afisareInformatii(Rezervare rezervare);
}
<file_sep>/composite/src/ro/ase/cts/main/main.java
package ro.ase.cts.main;
import ro.ase.cts.componente.Element;
import ro.ase.cts.componente.IOptiuneMeniu;
import ro.ase.cts.componente.Sectiune;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
IOptiuneMeniu meniu = new Sectiune("Meniu restaurant");
IOptiuneMeniu optiune1 = new Sectiune("Bauturi");
IOptiuneMeniu optiune2 = new Sectiune("Desert");
IOptiuneMeniu item1 = new Element("Frappe");
IOptiuneMeniu item2 = new Element("Apa plata");
IOptiuneMeniu item3 = new Element("Papanasi");
try {
optiune1.adaugaNod(item1);
optiune1.adaugaNod(item2);
optiune2.adaugaNod(item3);
meniu.adaugaNod(optiune1);
meniu.adaugaNod(optiune2);
meniu.descriere();
optiune1.stergeNod(item1);
optiune2.adaugaNod(item1);
meniu.descriere();
} catch (Exception e) {
// TODO: handle exception
}
}
}
<file_sep>/seminar_single_factory/src/ro/ase/cts/componente/CategoriiMedicamente.java
package ro.ase.cts.componente;
public enum CategoriiMedicamente {
raceala,
durere,
body
}
<file_sep>/builder/src/ro/ase/cts/componenteV1/Builder.java
package ro.ase.cts.componenteV1;
public interface Builder {
Rezervare build();
}
<file_sep>/command/src/ro/ase/cts/componente/Retragere.java
package ro.ase.cts.componente;
public class Retragere extends Command{
public Retragere(ContBancar cont,int suma) {
super(cont,suma);
// TODO Auto-generated constructor stub
}
@Override
public void executa() {
super.getCont().retragere(super.getSuma());
}
}
<file_sep>/state/src/ro/ase/cts/componente/Ocupata.java
package ro.ase.cts.componente;
public class Ocupata implements StareMasa {
@Override
public void modificaStare(Masa masa) {
if(!(masa.getStareMasa() instanceof Ocupata))
{
masa.setStareMasa(this);
System.out.println("Masa cu numarul "+masa.getNume()+ " s-a ocupat");
}
else
{
System.out.println("Masa este ocupata");
}
}
}
<file_sep>/command/src/ro/ase/cts/componente/Constituire.java
package ro.ase.cts.componente;
public class Constituire extends Command {
public Constituire(ContBancar cont, int suma) {
super(cont,suma);
// TODO Auto-generated constructor stub
}
@Override
public void executa() {
super.getCont().constituire(super.getSuma());
}
}
<file_sep>/penultimul_seminar/src/penultimul_seminar/grupa/TestCaseGetPromovabilitate.java
package penultimul_seminar.grupa;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import penultimul_seminar.clase.Grupa;
import penultimul_seminar.clase.IStudent;
public class TestCaseGetPromovabilitate {
private IStudent studentStub= new StudentStub();
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
Grupa grupa = new Grupa(1010);
grupa.adaugaStudent(studentStub);
assertEquals(1,grupa.getPromovabilitate(), 0.01f);
}
}
<file_sep>/seminar2/src/ro/ase/cts/main/Main.java
package ro.ase.cts.main;
import java.io.FileNotFoundException;
import java.util.List;
import ro.ase.cts.clase.Angajat;
import ro.ase.cts.clase.Aplicant;
import ro.ase.cts.clase.Proiect;
import ro.ase.cts.clase.Student;
import ro.ase.cts.readers.AplicantReader;
import ro.ase.cts.readers.ReadAngajati;
import ro.ase.cts.readers.ReadStudents;
public class Main {
public static List<Aplicant> citesteAplicanti(AplicantReader reader) throws NumberFormatException, FileNotFoundException{
return reader.citesteAplicanti();
}
public static void main(String[] args) {
List<Aplicant> listaAplicanti;
try {
listaAplicanti =citesteAplicanti(new ReadStudents("studenti.txt"));
for(Aplicant angajat:listaAplicanti) {
System.out.println(angajat.toString());
angajat.afiseazaStatus(new Proiect(80));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(Angajat.getSmaFinantare());
System.out.print(Student.getSmaFinantare());
}
}
<file_sep>/builder/src/ro/ase/cts/main/MainV2.java
package ro.ase.cts.main;
import ro.ase.cts.componenteV2.Rezervare;
import ro.ase.cts.componenteV2.RezervareBuilder;
public class MainV2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
RezervareBuilder builder=new RezervareBuilder();
builder.setBautura(true);
builder.setCod(2);
Rezervare rezervare1=builder.build();
builder.setBautura(false).setCod(5).setMancare(true);
Rezervare rezervare2=builder.build();
System.out.println(rezervare1.toString());
System.out.println(rezervare2.toString());
}
}
<file_sep>/Template/src/ro/ase/cts/componente/SpectatorPeluza.java
package ro.ase.cts.componente;
public class SpectatorPeluza extends SpectatorAbstract{
@Override
public void asezareLaCoada() {
System.out.println("spectatorul de peluza s-a asezat la coada");
}
@Override
public void prezintaBilet() {
System.out.println("spectatorul de peluza a prezentat biletul");
}
@Override
public void intrarePeStadion() {
System.out.println("spectatorul a intrat in peluza");
}
@Override
public void ocupareLoc() {
System.out.println("spectatorul de peluza a ocupat un loc");
}
@Override
public void realizareControlCorporal() {
System.out.println("spectatorul de peluza a fost controlat");
}
}
<file_sep>/Decorator/src/ro/ase/cts/componente/ICard.java
package ro.ase.cts.componente;
public interface ICard {
void platesteFizic();
void platesteOnline();
String getDetinatorCard() ;
}
<file_sep>/observer/src/ro/ase/cts/componente/Observer.java
package ro.ase.cts.componente;
public interface Observer {
public void receptionareMesaj(String mesaj);
}
<file_sep>/prototype/src/ro/ase/cts/componente/Bilet.java
package ro.ase.cts.componente;
public class Bilet implements AbstractPrototype{
private int cod;
private String echipa1;
private String echipa2;
private String data;
public Bilet(int cod, String echipa1, String echipa2, String data) {
super();
this.cod = cod;
this.echipa1 = echipa1;
this.echipa2 = echipa2;
this.data = data;
}
private Bilet() {
super();
}
public int getCod() {
return cod;
}
public void setCod(int cod) {
this.cod = cod;
}
@Override
public String toString() {
return "Bilet [cod=" + cod + ", echipa1=" + echipa1 + ", echipa2=" + echipa2 + ", data=" + data + "]";
}
@Override
public AbstractPrototype copiaza() {
// TODO Auto-generated method stub
Bilet copie=new Bilet();
copie.cod=this.cod;
copie.data=this.data;
copie.echipa1=this.echipa1;
copie.echipa2=this.echipa2;
return copie;
}
}
<file_sep>/penultimul_seminar/src/penultimul_seminar/suite/SuitaCompleta.java
package penultimul_seminar.suite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import penultimul_seminar.grupa.GrupaTest;
import penultimul_seminar.grupa.GrupaTestSetUp;
import penultimul_seminar.grupa.GrupaWithFakeTest;
import penultimul_seminar.grupa.TestCaseDummy;
import penultimul_seminar.grupa.TestCaseGetPromovabilitate;
@RunWith(Suite.class)
@SuiteClasses({GrupaTest.class, GrupaTestSetUp.class, GrupaWithFakeTest.class,
TestCaseGetPromovabilitate.class, TestCaseDummy.class})
public class SuitaCompleta {
}<file_sep>/adapterClase/src/ro/ase/cts/componente/Leasing.java
package ro.ase.cts.componente;
public class Leasing {
public void OferaLeasing(String nume, Float suma) {
System.out.println("Clientul "+nume+" a primit suma de "+suma);
}
}
<file_sep>/prototype/src/ro/ase/cts/componente/AbstractPrototype.java
package ro.ase.cts.componente;
public interface AbstractPrototype {
AbstractPrototype copiaza();
}
<file_sep>/builder/src/ro/ase/cts/main/MainInner.java
package ro.ase.cts.main;
import ro.ase.cts.inner.Rezervare;
public class MainInner {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Rezervare rez1=Rezervare.builder();
}
}
<file_sep>/state/src/ro/ase/cts/componente/Rezervata.java
package ro.ase.cts.componente;
public class Rezervata implements StareMasa{
@Override
public void modificaStare(Masa masa) {
if( masa.getStareMasa() instanceof Libera) {
System.out.println("Masa a fost rezervata " +masa.getNume());
masa.setStareMasa(new Rezervata());
}
else {
System.out.println("Actiune imposibil de realizat");
}
}
}
<file_sep>/seminar_single_factory/src/ro/acs/cts/method_factory/FactoryRaceala.java
package ro.acs.cts.method_factory;
public class FactoryRaceala implements FactoryCategorie{
@Override
public Categorie createCategorie(float pret) {
// TODO Auto-generated method stub
return new Raceala(pret);
}
}
<file_sep>/state/src/ro/ase/cts/componente/StareMasa.java
package ro.ase.cts.componente;
public interface StareMasa {
void modificaStare(Masa masa);
}
<file_sep>/Decorator/src/ro/ase/cts/componente/AbstractDecorator.java
package ro.ase.cts.componente;
public abstract class AbstractDecorator implements ICard{
private ICard iCard;
public AbstractDecorator(ICard iCard) {
super();
this.iCard = iCard;
}
@Override
public void platesteFizic() {
this.iCard.platesteFizic();
}
@Override
public void platesteOnline() {
this.iCard.platesteOnline();
}
public abstract void platesteContactless();
@Override
public String getDetinatorCard() {
return iCard.getDetinatorCard();
}
public ICard getiCard() {
return iCard;
}
public void setiCard(ICard iCard) {
this.iCard = iCard;
}
}
<file_sep>/builder/src/ro/ase/cts/inner/Builder.java
package ro.ase.cts.inner;
public interface Builder {
Rezervare build();
}
<file_sep>/Template/src/ro/ase/cts/main/Main.java
package ro.ase.cts.main;
import ro.ase.cts.componente.Spectator;
import ro.ase.cts.componente.SpectatorAbstract;
import ro.ase.cts.componente.SpectatorPeluza;
public class Main {
public static void main(String[] args) {
SpectatorAbstract spec=new Spectator();
spec.intrareaSpectatoruluiPeStadion();
SpectatorAbstract peluza=new SpectatorPeluza();
peluza.intrareaSpectatoruluiPeStadion();
}
}
<file_sep>/state/src/ro/ase/cts/v2Componente/Ocupata.java
package ro.ase.cts.v2Componente;
public class Ocupata implements Stare {
@Override
public void afisareDescriere() {
System.out.println("suntem in stare ocupata");
}
}
<file_sep>/facade/src/facade/ro/ase/cts/componente/Pat.java
package facade.ro.ase.cts.componente;
public class Pat {
private int numar;
private boolean liber;
public Pat(int numar, boolean liber) {
super();
this.numar = numar;
this.liber = liber;
}
public int getNumar() {
return numar;
}
public boolean isLiber() {
return liber;
}
public void setLiber(boolean liber) {
this.liber = liber;
}
}
<file_sep>/seminar3/src/ro/ase/cts/main/main.java
package ro.ase.cts.main;
import ro.ase.cts.clase.cabinetVeterinar;
import ro.ase.cts.clase.cabinetVeterinarLazy;
import ro.ase.cts.exercitiu.Iad;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
// cabinetVeterinar clinica1= cabinetVeterinar.getInstance();
// cabinetVeterinar clinica2= cabinetVeterinar.getInstance();
// System.out.println(clinica1.toString());
// System.out.println(clinica2.toString());
// cabinetVeterinarLazy clinica1= cabinetVeterinarLazy.getInstance("ClinicaMea","<NAME>",4,4444.4f);
// cabinetVeterinarLazy clinica2= cabinetVeterinarLazy.getInstance("ClinicaMea2","<NAME>",6,41444.4f);
// clinica1.setAdresa("Bucuresti");
// clinica2.setBuget(6000.66f);
//
// System.out.println(clinica1.toString());
// System.out.println(clinica2.toString());
Iad primulLocInCarePoposim= Iad.getInstance("sus",3000,900.75f);
Iad zonaFierbinte= Iad.getInstance("mai sus",2000,1755.65f);
System.out.println(zonaFierbinte.toString());
System.out.println(primulLocInCarePoposim.toString());
primulLocInCarePoposim.setLocatie("In ceruri");
zonaFierbinte.setTemperaturaMaxima(6666.66f);
System.out.println(zonaFierbinte.toString());
System.out.println(primulLocInCarePoposim.toString());
}
}
<file_sep>/composite/src/ro/ase/cts/componente/Element.java
package ro.ase.cts.componente;
public class Element implements IOptiuneMeniu{
private String nume;
public Element(String nume){
this.nume=nume;
}
@Override
public void stergeNod(IOptiuneMeniu optiune) throws Exception {
throw new Exception("NU este implementata");
}
@Override
public void adaugaNod(IOptiuneMeniu optiune) throws Exception {
throw new Exception("NU este implementata");
}
@Override
public IOptiuneMeniu getNod(int index) throws Exception {
throw new Exception("NU este implementata");
}
@Override
public void descriere() {
System.out.println(" Item: " + nume);
}
}
<file_sep>/adapterClase/src/ro/ase/cts/main/Main.java
package ro.ase.cts.main;
import ro.ase.cts.componente.AdapterClase;
import ro.ase.cts.componente.InterfataCredit;
public class Main {
public static void OferaInfoCredit(InterfataCredit interfataCredit,String nume , Float suma) {
interfataCredit.acordaCredit(nume, suma);
}
public static void main(String[] args) {
AdapterClase adapter=new AdapterClase();
OferaInfoCredit(adapter,"regele",100f);
}
}
<file_sep>/builder/src/ro/ase/cts/main/MainV1.java
package ro.ase.cts.main;
import ro.ase.cts.componenteV1.Rezervare;
import ro.ase.cts.componenteV1.RezervareBuilder;
public class MainV1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Rezervare rezervare1=new RezervareBuilder().setBautura(true).setCod(4).build();
Rezervare rezervare2=new RezervareBuilder().setMancare(true).setCod(7).build();
System.out.println(rezervare1.toString());
System.out.println(rezervare2.toString());
}
}
<file_sep>/command/src/ro/ase/cts/componente/ContBancar.java
package ro.ase.cts.componente;
public class ContBancar {
private int sumaCont;
private String detinator;
public ContBancar(String detinator) {
super();
this.sumaCont = 0;
this.detinator = detinator;
}
public void constituire(int sumaRetrasa) {
sumaCont=sumaRetrasa;
System.out.println(" Cont Constituit");
}
public void retragere(int sumaRetrasa) {
if(sumaRetrasa> sumaCont) {System.out.println("Nu se poate retrage");
}
else {
sumaCont=sumaCont-sumaRetrasa;
System.out.println("Suma retrasa");
}
}
public void depunere(int sumaDepusa) {
sumaCont=sumaCont+sumaDepusa;
System.out.println("Suma depusa");
}
}
<file_sep>/builder/src/ro/ase/cts/componenteV2/RezervareBuilder.java
package ro.ase.cts.componenteV2;
import ro.ase.cts.componenteV2.Rezervare;
public class RezervareBuilder implements Builder {
private boolean mancare;
private boolean scaun;
private boolean muzica;
private boolean bautura;
private String genMuzica;
private int cod;
public RezervareBuilder() {
super();
this.mancare = false;
this.scaun = false;
this.muzica = false;
this.bautura = false;
this.genMuzica = "clasica";
this.cod = 1;
}
public RezervareBuilder(int cod) {
super();
this.mancare = false;
this.scaun = false;
this.muzica = false;
this.bautura = false;
this.genMuzica = "clasica";
this.cod = cod;
}
public RezervareBuilder setMancare(boolean mancare) {
this.mancare = mancare;
return this;
}
public RezervareBuilder setScaun(boolean scaun) {
this.scaun = scaun;
return this;
}
public RezervareBuilder setMuzica(boolean muzica) {
this.muzica = muzica;
return this;
}
public RezervareBuilder setBautura(boolean bautura) {
this.bautura = bautura;
return this;
}
public RezervareBuilder setGenMuzica(String genMuzica) {
this.genMuzica = genMuzica;
return this;
}
public RezervareBuilder setCod(int cod) {
this.cod = cod;
return this;
}
@Override
public Rezervare build() {
// TODO Auto-generated method stub
return new Rezervare(mancare,scaun,muzica,bautura,genMuzica,cod);
}
}
<file_sep>/command/src/ro/ase/cts/componente/Depunere.java
package ro.ase.cts.componente;
public class Depunere extends Command{
public Depunere(ContBancar cont,int suma) {
super(cont,suma);
// TODO Auto-generated constructor stub
}
@Override
public void executa() {
super.getCont().depunere(super.getSuma());
}
}
<file_sep>/penultimul_seminar/src/penultimul_seminar/grupa/SuitaCustom.java
package penultimul_seminar.grupa;
import org.junit.experimental.categories.Category;
import org.junit.experimental.categories.Categories;
import org.junit.experimental.categories.Categories.ExcludeCategory;
import org.junit.experimental.categories.Categories.IncludeCategory;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import penultimul_seminar.suite.categorii.TesteGetPromovabilitate;
import penultimul_seminar.suite.categorii.TesteNormale;
@RunWith(Categories.class)
@SuiteClasses({ GrupaTest.class, GrupaTestSetUp.class, GrupaWithFakeTest.class, TestCaseDummy.class,
TestCaseGetPromovabilitate.class })
@IncludeCategory({TesteGetPromovabilitate.class})
@ExcludeCategory({TesteNormale.class})
public class SuitaCustom {
}<file_sep>/state/src/ro/ase/cts/v2Main/Main.java
package ro.ase.cts.v2Main;
import ro.ase.cts.v2Componente.Masa;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Masa masa=new Masa(1);
masa.rezervaMasa();
masa.rezervaMasa();
masa.ocupaMasa();
masa.elibereazaMasa();
}
}
<file_sep>/seminar1/src/package_clase/Zebra.java
package package_clase;
public class Zebra extends Animal{
private int numar_dungi;
public Zebra(String nume, float greutate) {
super(nume, greutate);
// TODO Auto-generated constructor stub
}
public Zebra(String nume, float greutate, int numar_dungi) {
super(nume, greutate);
this.numar_dungi = numar_dungi;
}
public int getNumar_dungi() {
return numar_dungi;
}
public void setNumar_dungi(int numar_dungi) {
this.numar_dungi = numar_dungi;
}
}
<file_sep>/SeminarTestare1/src/test/StudentTest.java
package test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import pachet.Student;
public class StudentTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testConstructorNumeCorect() {
String nume="Vasile";
Student stud=new Student(nume);
assertEquals(nume,stud.getNume());
}
@Test
public void testVerificareAddNota() {
Student student=new Student();
int nota=8;
student.adaugaNota(nota);
assertEquals(nota,student.getNota(0));
}
@Test
public void testDimensiuneListaCorecta() {
Student student=new Student();
int nota=8;
student.adaugaNota(nota);
assertEquals(1,student.getNote().size());
}
@Test
public void testMedie() {
Student student=new Student();
int nota=8;
student.adaugaNota(nota);
assertEquals(8f,student.calculeazaMedie(),0.001f);
}
@Test
public void testMedieMultipleNote() {
Student student=new Student();
int nota=8;
int nota2=9;
student.adaugaNota(nota);
student.adaugaNota(nota2);
assertEquals(8.5f,student.calculeazaMedie(),0.001f);
}
@Test
public void testMedieFaraNote() {
Student student=new Student();
assertEquals(0f,student.calculeazaMedie(),0.001f);
}
@Test (expected=IndexOutOfBoundsException.class)
public void testVerificaGetNota() {
Student student=new Student();
int nota=8;
int nota2=9;
student.adaugaNota(nota);
student.adaugaNota(nota2);
assertEquals(nota,student.getNota(-1)) ;
}
@Test
public void testVerificaGetNotaJU3() {
Student student=new Student();
int nota=8;
student.adaugaNota(nota);
try { int s=student.getNota(-1) ;
fail("Aici nu trebuie sa ajungem");}
catch(IndexOutOfBoundsException eroare) {
}
}
@Test
public void testVerificaRestanta() {
Student student=new Student();
int nota1=8;
int nota2=3;
int nota3=8;
student.adaugaNota(nota1);
student.adaugaNota(nota2);
student.adaugaNota(nota3);
assertTrue(student.areRestante()) ;
}
@Test
public void testVerificaRestantaFalse() {
Student student=new Student();
int nota1=8;
int nota2=6;
int nota3=8;
student.adaugaNota(nota1);
student.adaugaNota(nota2);
student.adaugaNota(nota3);
assertFalse(student.areRestante()) ;
}
}
<file_sep>/strategy/src/ro/ase/cts/componente/Cash.java
package ro.ase.cts.componente;
public class Cash implements ModPlata {
@Override
public void plateste(double sumaPlatita) {
System.out.println("suma "+ sumaPlatita+" a fost platita cash" );
}
}
<file_sep>/seminar_single_factory/src/ro/acs/cts/main/main_factoryMethod.java
package ro.acs.cts.main;
import ro.acs.cts.method_factory.FactoryCategorie;
import ro.acs.cts.method_factory.FactoryDurere;
import ro.acs.cts.method_factory.FactoryGripa;
import ro.acs.cts.method_factory.Categorie;
import ro.acs.cts.method_factory.FactoryBody;
public class main_factoryMethod {
public static FactoryCategorie getTipFactory() {
return new FactoryGripa();
}
public static void printeazaCategorie(FactoryCategorie factoryCategorie,float pret) {
Categorie categorie=factoryCategorie.createCategorie(pret);
System.out.println(categorie.toString());
}
public static void main(String[] args) {
printeazaCategorie(getTipFactory(), 30);
}
}
<file_sep>/adapter/src/ro/ase/cts/componente/InterfataCredit.java
package ro.ase.cts.componente;
public interface InterfataCredit {
void acordaCredit(String numeClient, float suma);
}
<file_sep>/Decorator/src/ro/ase/cts/componente/Card.java
package ro.ase.cts.componente;
public class Card implements ICard {
String detinatorCard;
public Card(String detinatorCard) {
super();
this.detinatorCard = detinatorCard;
}
@Override
public void platesteFizic() {
System.out.println(this.detinatorCard+" a platit fizic");
}
@Override
public void platesteOnline() {
// TODO Auto-generated method stub
System.out.println(this.detinatorCard+" a platit online");
}
public String getDetinatorCard() {
return detinatorCard;
}
public void setDetinatorCard(String detinatorCard) {
this.detinatorCard = detinatorCard;
}
}
<file_sep>/state/src/ro/ase/cts/main/Main.java
package ro.ase.cts.main;
import ro.ase.cts.componente.Masa;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Masa masa=new Masa("1");
masa.rezervareMasa();
masa.rezervareMasa();
masa.ocupaMasa();
masa.eliberareMasa();
}
}
| cdb9fae65aa79692708d753147f2447e946e8fab | [
"Java"
] | 44 | Java | karenalo13/SeminarCts | cb134974584a9a6622335163027507c2e5580dad | e316241cefb86d9970477b316e6dfa463c512fa3 | |
refs/heads/master | <file_sep>package com.dmitrykazanbaev.alfa3task.service;
import com.dmitrykazanbaev.alfa3task.model.Branch;
import com.dmitrykazanbaev.alfa3task.model.BranchWithDistance;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public interface BranchCrudRepository extends CrudRepository<Branch, Integer> {
@Query(value = "select \n" +
" br.*, \n" +
" round(\n" +
" 2 * 6371000 * asin(\n" +
" sqrt(\n" +
" power(\n" +
" sin(\n" +
" (radians(:givenLat) - radians(br.lat))/ 2.0\n" +
" ), \n" +
" 2.0\n" +
" )+ cos(radians(:givenLat))* cos(radians(br.lat))* power(\n" +
" sin(\n" +
" (radians(:givenLon) - radians(br.lon))/ 2.0\n" +
" ), \n" +
" 2.0\n" +
" )\n" +
" )\n" +
" )\n" +
" ) as distance \n" +
"from \n" +
" branches br \n" +
"order by \n" +
" distance \n" +
"limit \n" +
" 1",
nativeQuery = true)
BranchWithDistance getClosestBranch(@Param("givenLat") BigDecimal givenLat, @Param("givenLon") BigDecimal givenLon);
}
<file_sep>package com.dmitrykazanbaev.alfa3task;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Alfa3taskApplication {
public static void main(String[] args) {
SpringApplication.run(Alfa3taskApplication.class, args);
}
}
<file_sep>package com.dmitrykazanbaev.alfa3task.model;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class BranchWithPrediction {
@JsonUnwrapped
private Branch branch;
private Integer dayOfWeek;
private Integer hourOfDay;
private Long predicting;
}
<file_sep>package com.dmitrykazanbaev.alfa3task.controller;
import com.dmitrykazanbaev.alfa3task.exception.ApiError;
import com.dmitrykazanbaev.alfa3task.exception.NotFoundBranchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class BranchesExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler
public ResponseEntity<Object> handle(NotFoundBranchException exception) {
return new ResponseEntity<>(new ApiError("branch not found"), HttpStatus.NOT_FOUND);
}
}
<file_sep>package com.dmitrykazanbaev.alfa3task.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.math.BigDecimal;
@Entity
@Table(name = "branches")
@Data
public class Branch {
@Id
private Integer id;
@Column
private String title;
@Column
private BigDecimal lon;
@Column
private BigDecimal lat;
@Column
private String address;
}
<file_sep>package com.dmitrykazanbaev.alfa3task.model;
import java.math.BigDecimal;
public interface BranchWithDistance {
Integer getId();
String getTitle();
BigDecimal getLon();
BigDecimal getLat();
String getAddress();
Long getDistance();
}
<file_sep>package com.dmitrykazanbaev.alfa3task.model;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalTime;
@Entity
@Table(name = "queue_log")
@Data
public class QueueLog {
@Column
private LocalDate data;
@Column
private LocalTime startTimeOfWait;
@Column
private LocalTime endTimeOfWait;
@Column
private LocalTime endTimeOfService;
@ManyToOne(targetEntity = Branch.class)
private Integer branchesId;
@Id
private Integer id;
}
| a4081d68110743dda90d1bef3236977ab9e48e6a | [
"Java"
] | 7 | Java | dmitrykazanbaev/alfa3task | 221822df9ebf931f81b7b96620e765d685a3188a | a82d9a22ffe3966b9c57af57c58f89e2547efacb | |
refs/heads/master | <file_sep>CC = gcc
CFLAGS = -c -Wall
PROFILE_FLAGS = -fprofile-arcs -ftest-coverage
TST_LIBS = -lcheck -lm -lpthread -lrt -lsubunit
COV_LIBS = -lgcov -coverage
SRC_DIR= src
TST_DIR= tests
SRC_FILES = $(addprefix $(SRC_DIR)/, *.c)
TST_FILES = $(addprefix $(TST_DIR)/, *.c)
GCOV = gcovr
GCONV_FLAGS = -s -d
all: coverage
point.o: $(SRC_FILES) $(addprefix $(SRC_DIR)/, point.h)
$(CC) $(CFLAGS) $(PROFILE_FLAGS) $(SRC_FILES)
check_point.o: $(TST_FILES)
$(CC) $(CFLAGS) $(PROFILE_FLAGS) $(TST_FILES)
check_point_tests: point.o check_point.o
$(CC) point.o check_point.o $(TST_LIBS) $(COV_LIBS) -o check_point_tests
test: check_point_tests
./check_point_tests
coverage: test
$(GCOV) $(GCONV_FLAGS)
coverage_report.html: test
$(GCOV) $(GCONV_FLAGS) -o coverage_report.html
.PHONY: clean all
clean:
-rm -rf *.o *.html *.gcda *.gcno check_point_tests
<file_sep>#include "mesinkar.h"
#include "mesinkata.h"
#include <stdio.h>
boolean EndKata;
Kata CKata;
void IgnoreBlank(){
while (CC == BLANK){
ADV();
}
}
void STARTKATA(){
START();
IgnoreBlank();
if (CC == MARK){
EndKata = true;
} else {
EndKata = false;
ADVKATA();
}
}
void ADVKATA(){
IgnoreBlank();
if (CC == MARK && !EndKata){
EndKata = true;
} else{
SalinKata();
IgnoreBlank();
}
}
void SalinKata(){
int i = 0;
while ((CC != MARK) && (CC != BLANK) && i != NMax) {
CKata.TabKata[i] = CC;
ADV();
i++;
}
CKata.Length = (i < NMax) ? i : NMax;
}<file_sep>#include <stdio.h>
#include "arraypos.h"
#include "boolean.h"
void MakeEmpty (TabInt * T){
IdxType i;
for(i=IdxMin; i <= IdxMax; i++){
T->TI[i] = ValUndef;
}
return;
}
int NbElmt (TabInt T){
IdxType i, count=0;
for(i=IdxMin; i < IdxMax+1; i++){
if (T.TI[i] != ValUndef){
count++;
} else {
break;
}
}
return count - IdxMin;
}
int MaxNbEl (TabInt T){
return (IdxMax-IdxMin+1);
}
IdxType GetFirstIdx (TabInt T){
return IdxMin;
}
IdxType GetLastIdx (TabInt T){
return IdxMin+NbElmt(T)-1;
}
boolean IsIdxValid (TabInt T, IdxType i){
return (i >= IdxMin && i <= IdxMax);
}
boolean IsIdxEff (TabInt T, IdxType i){
return (i >= GetFirstIdx(T) && i <= GetLastIdx(T));
}
boolean IsEmpty (TabInt T){
return (NbElmt(T) == 0);
}
boolean IsFull (TabInt T){
return (NbElmt(T) == MaxNbEl(T));
}
void BacaIsi (TabInt * T){
MakeEmpty(T);
int N;
while (true){
scanf("%d\n", &N);
if (N >= 0 && N <= MaxNbEl(*T)){
break;
}
}
if (N > 0){
int i=IdxMin;
for(i=IdxMin;i < N; i++){
scanf("%d\n", &(T->TI[i]));
}
}
return;
}
void TulisIsiTab (TabInt T){
printf("[");
if (!IsEmpty(T)){
int i;
for (i=GetFirstIdx(T); i <= GetLastIdx(T); i++){
printf("%d", T.TI[i]);
if (i != GetLastIdx(T)){
printf(",");
}
}
}
printf("]");
return;
}
TabInt PlusMinusTab (TabInt T1, TabInt T2, boolean plus){
TabInt result;
MakeEmpty(&result);
int i;
for(i=GetFirstIdx(T1); i <= GetLastIdx(T1); i++){
if (plus){
Elmt(result, i) = Elmt(T1, i)+(Elmt(T2, i) != ValUndef ? Elmt(T2, i) : 0);
} else {
Elmt(result, i) = Elmt(T1, i)-(Elmt(T2, i) != ValUndef ? Elmt(T2, i) : 0);
}
}
return result;
}
boolean IsEQ (TabInt T1, TabInt T2){
if (NbElmt(T1) != NbElmt(T2)){
return false;
}
boolean result = (NbElmt(T1) == NbElmt(T2));
int i;
for(i=GetFirstIdx(T1); i <= GetLastIdx(T1); i++){
result = result && (Elmt(T1, i) == Elmt(T2, i));
}
return result;
}
IdxType Search1 (TabInt T, ElType X){
if (IsEmpty(T)){
return IdxUndef;
}
int i,result=IdxUndef;
for(i=GetFirstIdx(T); i <= GetLastIdx(T); i++){
if (Elmt(T, i) == X){
result = i;
break;
}
}
return result;
}
boolean SearchB (TabInt T, ElType X){
if (IsEmpty(T)){
return false;
}
boolean found = false;
int i;
for(i=GetFirstIdx(T); i <= GetLastIdx(T); i++){
if (Elmt(T, i) == X){
found = true;
break;
}
}
return found;
}
void MaxMin (TabInt T, ElType * Max, ElType * Min){
int nmax, nmin, i;
nmin = Elmt(T, GetFirstIdx(T));
nmax = Elmt(T, GetFirstIdx(T));
for(i=GetFirstIdx(T); i <= GetLastIdx(T); i++){
if (Elmt(T,i) > nmax){
nmax = Elmt(T,i);
} else if (Elmt(T,i) < nmin) {
nmin = Elmt(T,i);
}
}
*Max = nmax;
*Min = nmin;
return;
}
ElType SumTab (TabInt T){
if (IsEmpty(T)){
return 0;
}
int i,sum = 0;
for(i=GetFirstIdx(T); i <= GetLastIdx(T); i++){
sum += Elmt(T,i);
}
return sum;
}
int CountX (TabInt T, ElType X){
if (IsEmpty(T)){
return 0;
}
int i,count=0;
for(i=GetFirstIdx(T); i <= GetLastIdx(T); i++){
if(Elmt(T,i) == X){
count += 1;
}
};
return count;
}
boolean IsAllGenap (TabInt T){
boolean genap = true;
int i = GetFirstIdx(T);
while(genap && i <= GetLastIdx(T)){
genap = (genap & (Elmt(T,i)%2 == 0));
i++;
}
return genap;
}
void Sort (TabInt * T, boolean asc){
int i, j;
IdxType key;
for (i = GetFirstIdx(*T) + 1; i <= GetLastIdx(*T); i++){
key = Elmt(*T, i);
j = i-1;
while (j >= GetFirstIdx(*T) && ((!asc && Elmt(*T,j) < key) || (asc && Elmt(*T,j) > key))){
Elmt(*T,j+1) = Elmt(*T, j);
j--;
}
Elmt(*T,j+1) = key;
}
return;
}
void AddAsLastEl (TabInt * T, ElType X){
if (!IsFull(*T)) {
T->TI[(GetLastIdx(*T)+1)] = X;
}
return;
}
void DelLastEl (TabInt * T, ElType * X){
if (IsEmpty(*T)) return;
*X = T->TI[GetLastIdx(*T)];
T->TI[GetLastIdx(*T)] = ValUndef;
return;
}<file_sep>#include "bintree.h"
#include <stdio.h>
#include <stdlib.h>
int main() {
int N; //2^N
scanf("%d", &N);
if (N <= 0){
printf("Jumlah masukan tidak sesuai\n");
return 0;
}
int temp = N;
while (N%2 == 0){
N /= 2;
}
if (N != 1){
printf("Jumlah masukan tidak sesuai\n");
return 0;
}
int limit = (temp*2)-1;
BinTree arr[limit];
int i, j;
for (i=0;i<temp;i++){
int X;
scanf("%d", &X);
BinTree t = Tree(X,Nil,Nil);
arr[i] = t;
}
j = 0;
while (temp < limit){
BinTree t1, t2, t;
t1 = arr[j];
t2 = arr[j+1];
t = Tree((Akar(t1)+Akar(t2)), t1, t2);
arr[temp] = t;
j += 2;
temp += 1;
}
PrintTree(arr[limit-1], 2);
}<file_sep>#include <stdio.h>
#include <stdbool.h>
/*
NIM : 13519002
Nama : <NAME>
Tanggal : 27 Agustus 2020
Topik praktikum : Pengenalan C
Deskripsi : Program IP mahasiswa
*/
/* P r o t o t y p e */
bool IsWithinRange(float x, float min, float max);
/* V a r i a b e l G l o b a l: tidak perlu ada */
int main(){
/* Nama yang dipakai */
int mhsw = 0, lulus = 0;
float iptotal = 0.0F, ip;
/* Baca */
while (true){
scanf("%f", &ip);
if (ip == -999.0F){
break;
} else if (IsWithinRange(ip, 0.0F, 4.0F)) {
iptotal += ip;
mhsw += 1;
if (IsWithinRange(ip, 2.75F, 4.0F)){
lulus += 1;
}
}
}
if (mhsw != 0){
printf("%d\n%d\n%d\n%.2f", mhsw, lulus, mhsw-lulus, (iptotal/mhsw));
} else {
printf("Tidak ada data");
}
}
bool IsWithinRange(float x, float min, float max){
return ((x >= min) && (x <= max));
}<file_sep>#include <stdio.h>
/*
NIM : 13519002
Nama : <NAME>
Tanggal : 27 Agustus 2020
Topik praktikum : Pengenalan C
Deskripsi : Mengonversi Suhu
*/
/* V a r i a b e l G l o b a l: tidak perlu ada */
int main(){
/* Nama yang dipakai */
float c;
char suhu;
/* Baca */
scanf("%f\n %c", &c, &suhu);
/* Aplikasi Rumus dan Output */
if (suhu == 'R'){
printf("%.2f", 0.8F*c);
} else if (suhu == 'F') {
printf("%.2f", 1.8F*c+32);
} else if (suhu == 'K') {
printf("%.2f", c+273.15F);
}
}<file_sep>#include "stacklist.h"
#include "boolean.h"
#include <stdio.h>
#include <stdlib.h>
void Alokasi (address *P, infotype X){
*P = (address) malloc (sizeof(ElmtStack));
if (*P != Nil){
Info(*P) = X;
Next(*P) = Nil;
}
}
void Dealokasi (address P){
free(P);
}
boolean IsEmpty (Stack S){
return Top(S) == Nil;
}
void CreateEmpty (Stack * S){
Top(*S) = Nil;
}
void Push (Stack * S, infotype X){
address A;
Alokasi(&A, X);
if (A == Nil) return;
address first = Top(*S);
Next(A) = first;
Top(*S) = A;
}
void Pop (Stack * S, infotype * X){
*X = InfoTop(*S);
address deleted = Top(*S);
Top(*S) = Next(deleted);
}<file_sep>#include "bintree.h"
void InvertBtree(BinTree *P){
if (!IsTreeEmpty(*P)){
InvertBtree(&(Left(*P)));
InvertBtree(&(Right(*P)));
*P = Tree(Akar(*P), Right(*P), Left(*P));
}
}<file_sep>#include "listdp.h"
#include "boolean.h"
#include <stdio.h>
#include <stdlib.h>
boolean IsEmpty (List L){
return (First(L) == Nil) && (Last(L) == Nil);
}
void CreateEmpty (List *L){
First(*L) = Nil;
Last(*L) = Nil;
}
address Alokasi (infotype X){
address result;
result = (address) malloc (sizeof(ElmtList));
if (result != Nil){
Info(result) = X;
Next(result) = Nil;
Prev(result) = Nil;
}
return result;
}
void Dealokasi (address P){
free(P);
}
address Search (List L, infotype X){
address now = First(L);
while(now != Nil && Info(now)!=X){
now = Next(now);
}
return now;
}
void InsVFirst (List *L, infotype X){
address newfirst = Alokasi(X);
if (newfirst != Nil){
if (First(*L) == Nil){
Last(*L) = newfirst;
} else {
Prev(First(*L)) = newfirst;
}
Next(newfirst) = First(*L);
First(*L) = newfirst;
}
}
void InsVLast (List *L, infotype X){
address newlast = Alokasi(X);
if (newlast != Nil){
if (Last(*L) == Nil){
First(*L) = newlast;
} else {
Next(Last(*L)) = newlast;
}
Prev(newlast) = Last(*L);
Last(*L) = newlast;
}
}
void DelVFirst (List *L, infotype *X){
address deleted = First(*L);
*X = Info(deleted);
if (First(*L) == Last(*L)){
First(*L) = Nil;
Last(*L) = Nil;
return;
}
Prev(Next(deleted)) = Nil;
First(*L) = Next(deleted);
Dealokasi(deleted);
}
void DelVLast (List *L, infotype *X){
address deleted = Last(*L);
*X = Info(deleted);
if (First(*L) == Last(*L)){
First(*L) = Nil;
Last(*L) = Nil;
return;
}
Next(Prev(deleted)) = Nil;
Last(*L) = Prev(deleted);
Dealokasi(deleted);
}
void InsertFirst (List *L, address P){
address newfirst = P;
if (First(*L) == Nil){
Last(*L) = newfirst;
} else {
Prev(First(*L)) = newfirst;
}
Next(newfirst) = First(*L);
First(*L) = newfirst;
}
void InsertLast (List *L, address P){
address newlast = P;
if (Last(*L) == Nil){
First(*L) = newlast;
} else {
Next(Last(*L)) = newlast;
}
Prev(newlast) = Last(*L);
Last(*L) = newlast;
}
void InsertAfter (List *L, address P, address Prec){
if (Prec == Last(*L)){
InsertLast(L, P);
} else {
Next(P) = Next(Prec);
Prev(Next(Prec)) = P;
Prev(P) = Prec;
Next(Prec) = P;
}
}
void InsertBefore (List *L, address P, address Succ){
if (Succ == First(*L)){
InsertFirst(L, P);
} else {
Prev(P) = Prev(Succ);
Next(Prev(Succ)) = P;
Next(P) = Succ;
Prev(Succ) = P;
}
}
void DelFirst (List *L, address *P){
*P = First(*L);
First(*L) = Next(*P);
if (First(*L)==Nil){
Last(*L) = Nil;
} else {
Prev(First(*L)) = Nil;
}
}
void DelLast (List *L, address *P){
*P = Last(*L);
Last(*L) = Prev(*P);
if(Last(*L)==Nil){
First(*L) = Nil;
} else {
Next(Last(*L)) = Nil;
}
}
void DelAfter (List *L, address *Pdel, address Prec){
*Pdel = Next(Prec);
if ((*Pdel) == First(*L)){
DelFirst(L, Pdel);
} else if ((*Pdel) == Last(*L)){
DelLast(L, Pdel);
} else {
Prev(Next(*Pdel)) = Prec;
Next(Prec) = Next(*Pdel);
}
}
void DelP (List *L, infotype X){
address cari = Search(*L, X);
if (cari != Nil){
if (cari == First(*L)){
DelFirst(L, &cari);
} else if (cari == Last(*L)){
DelLast(L, &cari);
} else {
address dummy;
DelAfter(L, &dummy, Prev(cari));
}
}
}
void DelBefore (List *L, address *Pdel, address Succ){
*Pdel = Prev(Succ);
if(*Pdel == First(*L)){
DelFirst(L, Pdel);
}else{
DelAfter(L, Pdel, Prev(*Pdel));
}
}
void PrintForward (List L){
printf("[");
if (!IsEmpty(L)){
address now = First(L);
while (now != Nil) {
printf("%d", Info(now));
now = Next(now);
if (now != Nil)
printf(",");
}
}
printf("]");
}
void PrintBackward (List L){
printf("[");
if (!IsEmpty(L)){
address now = Last(L);
while (now != Nil) {
printf("%d", Info(now));
now = Prev(now);
if (now != Nil)
printf(",");
}
}
printf("]");
}<file_sep>#include <stdio.h>
#include <stdbool.h>
/*
NIM : 13519002
Nama : <NAME>
Tanggal : 27 Agustus 2020
Topik praktikum : Pengenalan C
Deskripsi : Program Beasiswa
*/
/* V a r i a b e l G l o b a l: tidak perlu ada */
int main(){
/* Nama yang dipakai */
float ip, pot;
/* Baca */
scanf("%f\n%f", &ip, &pot);
/* Aplikasi */
if (ip >= 3.5F){
printf("%d", 4);
} else if (ip < 3.5F && pot < 1.0F){
printf("%d", 1);
} else if (pot >= 1.0F && pot < 5.0F && ip < 3.5){
if (ip < 2.0F){
printf("%d", 2);
} else {
printf("%d", 3);
}
} else {
printf("%d", 0);
}
}<file_sep>#include "queuelist.h"
#include "boolean.h"
#include <stdio.h>
#include <stdlib.h>
void Alokasi (address *P, infotype X){
*P = (address) malloc (sizeof(ElmtQueue));
if (*P != Nil){
Info(*P) = X;
Next(*P) = Nil;
}
}
void Dealokasi (address P){
free(P);
}
boolean IsEmpty (Queue Q){
return Head(Q) == Nil && Tail(Q) == Nil;
}
int NbElmt(Queue Q){
int n = 0;
if (!IsEmpty(Q)){
address now = Head(Q);
while (now != Nil){
n++;
now = Next(now);
}
}
return n;
}
void CreateEmpty(Queue * Q){
Head(*Q) = Nil;
Tail(*Q) = Nil;
}
void Enqueue (Queue * Q, infotype X){
address A;
Alokasi(&A, X);
if (A == Nil) return;
if (IsEmpty(*Q)){
Head(*Q) = A;
Tail(*Q) = A;
} else {
Next(A) = Nil;
Next(Tail(*Q)) = A;
Tail(*Q) = A;
}
}
void Dequeue(Queue * Q, infotype * X){
*X = InfoHead(*Q);
Head(*Q) = Next(Head(*Q));
if (Head(*Q) == Nil){
Tail(*Q) = Nil;
}
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "boolean.h"
#include "listsirkuler.h"
boolean IsEmpty (List L){
return First(L) == Nil;
}
void CreateEmpty (List *L){
First(*L) = Nil;
}
address Alokasi (infotype X){
address P;
P = (address) malloc (sizeof(ElmtList));
if (P != Nil){
Info(P) = X;
Next(P) = Nil;
}
return P;
}
void Dealokasi (address P){
free(P);
}
address Search (List L, infotype X){
address P = First(L);
if (P == Nil) return Nil;
while(Next(P) != First(L) && Info(P) != X){
P = Next(P);
}
if (Info(P) == X) return P;
return Nil;
}
void InsVFirst (List *L, infotype X){
address P = Alokasi(X);
if (P != Nil){
if (IsEmpty(*L)){
First(*L) = P;
Next(P) = P;
} else {
address Q = First(*L);
Next(P) = First(*L);
while(Next(Q) != First(*L)){
Q = Next(Q);
}
Next(Q) = P;
First(*L) = P;
}
}
}
void InsVLast (List *L, infotype X){
InsVFirst(L, X);
First(*L) = Next(First(*L));
}
void DelVFirst (List *L, infotype * X){
First(*L) = Next(First(*L));
DelVLast(L, X);
}
void DelVLast (List *L, infotype * X){
address P;
address Q = First(*L);
while (Next(Next(Q)) != First(*L)){
Q = Next(Q);
}
P = Next(Q);
*X = Info(P);
if (Next(Q) == First(*L)){
CreateEmpty(L);
} else {
Next(Q) = First(*L);
}
Dealokasi(P);
}
void InsertFirst (List *L, address P){
if (IsEmpty(*L)){
First(*L) = P;
Next(P) = P;
} else {
address Q = First(*L);
Next(P) = First(*L);
while (Next(Q) != First(*L)){
Q = Next(Q);
}
Next(Q) = P;
First(*L) = P;
}
}
void InsertLast (List *L, address P){
InsertFirst(L, P);
First(*L) = Next(P);
}
void InsertAfter (List *L, address P, address Prec){
address Q = First(*L);
First(*L) = Next(Prec);
InsertFirst(L, P);
First(*L) = Q;
}
void DelFirst (List *L, address *P){
First(*L) = Next(First(*L));
DelLast(L, P);
}
void DelLast (List *L, address *P){
address R = First(*L);
address Q = R;
while (Next(Next(Q)) != R){
Q = Next(Q);
}
*P = Next(Q);
if (Next(Q) == R){
CreateEmpty(L);
} else {
Next(Q) = R;
}
}
void DelAfter (List *L, address *Pdel, address Prec){
address P = First(*L);
First(*L) = Next(Next(Prec));
DelLast(L, Pdel);
First(*L) = P;
}
void DelP (List *L, infotype X){
if(!IsEmpty(*L)){
address Prec = First(*L);
address dummy;
if(Info(Prec) == X){
DelFirst(L, &dummy);
} else {
while (Next(Prec) != First(*L) && Info(Next(Prec)) != X){
Prec = Next(Prec);
}
if (Next(Prec) != First(*L)){
DelAfter(L, &dummy, Prec);
}
}
}
}
void PrintInfo (List L){
printf("[");
if (!IsEmpty(L)){
address P = First(L);
printf("%d", Info(P));
while (Next(P) != First(L)){
P = Next(P);
printf(",%d", Info(P));
}
}
printf("]");
}
<file_sep>#include <stdio.h>
#include <stdbool.h>
/*
NIM : 13519002
Nama : <NAME>
Tanggal : 27 Agustus 2020
Topik praktikum : Pengenalan C
Deskripsi : Gambar Belah Ketupat
*/
/* P r o t o t y p e */
bool IsValid(int x);
void GambarBelahKetupat(int x);
/* V a r i a b e l G l o b a l: tidak perlu ada */
int main(){
/* Nama yang dipakai */
int n;
/* Baca */
scanf("%d", &n);
if (IsValid(n) != true) {
printf("Masukan tidak valid");
return 0;
}
GambarBelahKetupat(n);
}
bool IsValid(int x){
return ((x % 2 == 1) && (x > 0));
}
void GambarBelahKetupat(int x){
if (x == 1){
printf("*");
return;
}
int i,j;
for(i = 1; i <= x; i++) {
if (i % 2 == 0) continue;
for(j = 1; j <= (x-i)/2; j++)
printf(" ");
for(j = 1; j <= i; j++)
printf("*");
printf("\n");
}
for(i = 1; i <= x; i++) {
if (i % 2 == 1) continue;
for(j = 1; j <= i/2; j++)
printf(" ");
for(j = 1; j <= x-i; j++)
printf("*");
printf("\n");
}
}<file_sep>#include "garis.h"
#include "point.h"
#include <stdio.h>
int main(){
GARIS garis, garis2;
BacaGARIS(&garis);
TulisGARIS(garis);printf("\n");
BacaGARIS(&garis2);
TulisGARIS(garis2);printf("\n");
if (IsTegakLurus(garis, garis2)) printf("yes");printf("\n");
return 0;
}<file_sep>#include <stdio.h>
/*
NIM : 13519002
Nama : <NAME>
Tanggal : 27 Agustus 2020
Topik praktikum : Pengenalan C
Deskripsi : Nilai maksimal 3 bilangan
*/
/* P r o t o t y p e */
int maks(int a, int b);
/* V a r i a b e l G l o b a l: tidak perlu ada */
int main(){
/* Nama yang dipakai */
int bil1, bil2, bil3, bilmaks;
/* Baca */
scanf("%d\n%d\n%d", &bil1, &bil2, &bil3);
/* Maksimum */
bilmaks = maks(maks(bil1, bil2), bil3);
/* Output */
printf("%d", bilmaks);
}
int maks(int a, int b){
return ((a > b) ? a : b);
} | 796d91f2051502609a61b5ffaea464c72b1013dd | [
"C",
"Makefile"
] | 15 | Makefile | ravielze/alstrukdat-2020 | 015dffc0455ff93f8cb8b392c9aeebf9a76c4b4e | 15723e87288a5c938930429c3bb2cea47b644be2 | |
refs/heads/master | <repo_name>suarezcumare/rankmi-api<file_sep>/spec/models/tree_spec.rb
# == Schema Information
#
# Table name: trees
#
# id :integer not null, primary key
# area :string
# nota :float
# created_at :datetime not null
# updated_at :datetime not null
# ancestry :string
#
require 'rails_helper'
RSpec.describe Tree, type: :model do
context 'validations' do
it "should presence_of a area" do
should validate_presence_of(:area)
end
it "should presence_of a nota" do
should validate_presence_of(:nota)
end
end
describe "#sibling_count" do
let (:management) { FactoryGirl.create(:tree, area: "Management", nota: 0) }
it "when is siblings, returns the number in the tree" do
management_1 = management.children.create(area: "management 1", nota: 1)
management_2 = management.children.create(area: "management 2", nota: 2)
expect(management_1.sibling_count - 1).to eq 1
end
it "when is not siblings, returns the number of siblings in the tree" do
expect(management.sibling_count - 1).to eq 0
end
end
describe "#sibling_notas" do
let (:management) { FactoryGirl.create(:tree, area: "Management", nota: 1) }
it "when is siblings, returns the number in the tree" do
management_1 = management.children.create(area: "management 1", nota: 5)
management_2 = management.children.create(area: "management 2", nota: 2)
expect(management_2.sibling_notas).to eq 7
end
it "when is not siblings, returns the number of siblings in the tree" do
expect(management.sibling_notas).to eq 1
end
end
describe "#as_json" do
context 'when is elements' do
let (:management) { FactoryGirl.create(:tree, area: "Management", nota: 1) }
it "when is siblings, returns the number in the tree" do
management_1 = management.children.create(area: "management 1", nota: 5)
management_2 = management.children.create(area: "management 2", nota: 2)
_tree = Tree.as_json
expect(_tree.count).to eq 1
expect(_tree.first[:hijos].count).to eq 2
end
end
context 'when is not elements' do
Tree.destroy_all
it "when is not siblings, returns the number of siblings in the tree" do
_tree = Tree.as_json
expect(_tree).to eq []
expect(_tree.count).to eq 0
end
end
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :trees, only: [:index, :update] do
post :create_child
end
end
<file_sep>/palindrome.rb
#palindromo
#solucion, sin mucho que decir
#Solo en dada la palabra si es igual al contrario y al reverse, retorna palindromo
def palindromo(text)
if text.downcase == text.downcase.reverse
"palindrome"
else
"no palindrome"
end
end
#Dado un numero, retornar el valor de la posicion en un archivo de excel.
#solucion
#En esta solucion com te comente ruby tiene para hacer el recorrido sin problemas, lo que hice fue iterar hasta el numero
#que necesitaba y al final solo obtener el valor necesitado, teniendo la constante de hash guarda al ejecutar la app
#se ejecutara una vez, lo demas ya seria solo buscar la solucion rapida y sencilla
h = {}
('a'..'zzz').each_with_index{|w, i| h[i+1] = w }
def excel(number)
h[number]
end
#.- Crear un algoritmo al cual se le deba ingresar un array de n números enteros, más un numero de resultado, ejemplo: Input: numbers={2, 7, 11, 15}, target=9 Este algoritmo debe ser capaz de encontrar dos números dentro del array que sumados sean igual al numero target,obviamente el algoritmo no puede ser un for que vaya sumando todos los números de uno en uno, debe tener mayor inteligencia.El resultado debe indicar la posición del array de los números que sumados dan el resultado esperado, ejemplo: Output: index1=1, index2=2
#solucion
#en ruby existe combination par aun numero de valores, entonces recorro todas las posibles opciones y
#alli lo que hago es iterar por cada una de ella y obtener lo que necesito al final
#numbers( [2, 7, 11, 15], 9)
def numbers(array = [], sum = 0)
value = array.combination(2).find_all { |x, y| x + y == sum } || []
if value.count > 0
puts "index1=#{array.index(value.first[0])}, index2=#{array.index(value.first[1])}"
else
puts "index1=-1, index2=-1, sin solucion"
end
end
<file_sep>/spec/requests/trees_spec.rb
require 'rails_helper'
RSpec.describe "Trees", type: :request do
describe "GET /trees" do
context 'when tree not exists' do
Tree.destroy_all
it "return ok but with 0 element" do
get trees_path
expect(response).to have_http_status(200)
expect(json["response"].length).to equal(0)
end
end
context 'when tree exists' do
let (:management) { FactoryGirl.create(:tree, area: "Management", nota: 0) }
it "return ok" do
management_1 = management.children.create(area: "management 1", nota: 1)
management_2 = management.children.create(area: "management 2", nota: 2)
get trees_path
expect(response).to have_http_status(200)
expect(json["response"].length).to equal(1)
expect(json["response"][0]["hijos"].length).to equal(2)
end
end
end
describe "Put /update/:id" do
let!(:management) { create(:tree) }
let(:valid_attributes) { {"tree": { "nota": 10.0 } } }
context 'when tree exists' do
let (:management) { FactoryGirl.create(:tree, area: "Management", nota: 0) }
it "return " do
management_1 = management.children.create(area: "management 1", nota: 1)
management_2 = management.children.create(area: "management 2", nota: 2)
put tree_path(management_2.id), params: valid_attributes
average = (management_1.nota + management_2.reload.nota) / 2
expect(json["response"]["id"]).to eq (management_2.id)
expect(json["response"]["area"]).to eq (management_2.area)
expect(json["response"]["nota"].to_f).to eq(10.0)
expect(Tree.first.nota).to eq(average)
end
end
context 'when tree not exists' do
let(:invalid_attributes) { {"tree": {"nota": 3.1 } } }
it "return ok but errors" do
put tree_path(100), params: invalid_attributes
expect(json["status"]).to eq("not_found")
end
end
end
describe "Put /tree/:id/create_child" do
let!(:management) { create(:tree) }
let(:valid_attributes) { {"tree": { "area": "nombre", "nota": 3.1 } } }
context 'when tree exists' do
let (:management) { FactoryGirl.create(:tree, area: "Management", nota: 0) }
it "return " do
management_1 = management.children.create(area: "management 1", nota: 1)
management_2 = management.children.create(area: "management 2", nota: 2)
post tree_create_child_path(management_2.id), params: valid_attributes
average = (management_1.nota + management_2.reload.nota) / 2
expect(json["response"]["area"]).to eq ("nombre")
expect(json["response"]["nota"].to_f).to eq(3.1)
expect(Tree.first.nota).to eq(average)
end
end
context 'when tree not exists' do
let(:invalid_attributes) { {"tree": {"nota": 3.1 } } }
it "return ok but errors" do
post tree_create_child_path(management.id), params: invalid_attributes
expect(json["response"]["area"][0..17]).to eq( [I18n.t("activerecord.errors.models.tree.attributes.area.blank")] )
end
end
end
end
<file_sep>/db/data/20171015211217_tree_example.rb
class TreeExample < SeedMigration::Migration
def up
management = Tree.create(area: "Gerencia", nota: 11)
management_1 = management.children.create(area: "Gerencia 1", nota: 12)
management_2 = management.children.create(area: "Gerencia 2", nota: 13)
management_1.children.create(area: "Gerencia 1 - 1", nota: 14)
management_1.children.create(area: "Gerencia 1 - 2", nota: 15)
management_2.children.create(area: "Gerencia 2 - 1", nota: 16)
management_2.children.create(area: "Gerencia 2 - 2", nota: 17)
end
def down
Tree.destroy_all
end
end
<file_sep>/README.md
# README
#### It's a test made by [**<NAME>**](https://www.linkedin.com/in/suarezcumare) to Rankmi company.
---
#### About this:
* Ruby 2.4.0
* Rails 5.1.4
* PG
* Rspec
* Anotate
* seed_migration
* ancestry
---
#### Instructions:
"Se requiere crear un api utilizando RoR que permita almacenar los resultados para una
jerarquía de N niveles con 0 a N áreas hijo por area padre. (las tablas creadas deben
ser poblada con seeds o como se estime conveniente).
- El api debe tener un endpoint que retorne la jerarquía de áreas creada con sus
respectivas notas ya calculadas. Debe responder en formato json con una estructura
similar a la siguiente: https://sc-rankmi.herokuapp.com/trees
- Generar un endpoint que permite agregar un nuevo hijo a un área ya creada. Al crearse
el nuevo hijo se debe recalcular la nota de las áreas superiores.
(https://sc-rankmi.herokuapp.com/trees/:id
- Generar un endpoint que permita cambiar un área dentro de la jerarquía. Los resultados
deben ser recalculados al realizarse el cambio.."
(https://sc-rankmi.herokuapp.com/trees/:id/create_child
---
#### Link to the test:
- [**Here**](https://sc-rankmi.herokuapp.com/trees)
---
<file_sep>/app/models/tree.rb
# == Schema Information
#
# Table name: trees
#
# id :integer not null, primary key
# area :string
# nota :float
# created_at :datetime not null
# updated_at :datetime not null
# ancestry :string
#
class Tree < ApplicationRecord
has_ancestry
validates :area, presence: true
validates :nota, presence: true
after_commit :update_parent, on: [:create, :update]
def self.as_json(options={}, hash=nil)
hash ||= arrange(options)
current_hast = []
hash.each do |node, children|
branch = {id: node.id, area: node.area, nota: node.nota}
branch[:hijos] = as_json(options, children) unless children.empty?
current_hast << branch
end
current_hast
rescue SomeError
return []
end
def sibling_notas
siblings.pluck(:nota).sum
rescue SomeError
return 0
end
def sibling_count
siblings.count
rescue SomeError
return 1
end
private
def update_parent(child=self)
update_notas(child)
end
def update_notas(child)
if child.has_parent?
parent = child.parent
average = child.sibling_notas / child.sibling_count
parent.update_columns(nota: average)
update_notas(parent)
end
end
end
<file_sep>/spec/factories/tree.rb
FactoryGirl.define do
factory :tree, :class => 'Tree' do
area { Faker::Name.title}
nota { Faker::Number.decimal(2, 3) }
end
end
| 09d0b043b1c2e05e33ac001691bec62b5d698b04 | [
"Markdown",
"Ruby"
] | 8 | Ruby | suarezcumare/rankmi-api | 5ce55fa11a47d0761b291e0bbd110b427851b849 | 214bfeae29635035352af8bc51a86ac9f9b35eb4 | |
refs/heads/master | <repo_name>Selezeznyaka/Ajax-test<file_sep>/js/index.js
// =include ./video-play.js
// =include ./feedback-scroll.js
// =include ./nav-menu.js
// =include ./services.js
// =include ./team-cards.js
<file_sep>/js/script.js
$(function(){
var output = $('#output'); // блок вывода информации
$('#btn').on('click', function(){
$.ajax({
url: 'handler.php', // путь к php-обработчику
type: 'POST', // метод передачи данных
dataType: 'json', // тип ожидаемых данных в ответе
data: {key: 1}, // данные, которые передаем на сервер
beforeSend: function(){ // Функция вызывается перед отправкой запроса
output.text('Запрос отправлен. Ждите ответа.');
},
error: function(req, text, error){ // отслеживание ошибок во время выполнения ajax-запроса
output.text('Хьюстон, У нас проблемы! ' + text + ' | ' + error);
},
complete: function(){ // функция вызывается по окончании запроса
output.append('<p>Запрос полностью завершен!</p>');
},
success: function(json){ // функция, которая будет вызвана в случае удачного завершения запроса к серверу
// json - переменная, содержащая данные ответа от сервера. Обзывайте её как угодно ;)
output.html(json); // выводим на страницу данные, полученные с сервера
}
});
});
});<file_sep>/js/services.js
const arrowElem = document.getElementsByClassName('services-about__drop-down-arrow');
const toogleItem = document.getElementsByClassName('services-about__item');
document.addEventListener('click', (event) => {
let target = event.target;
for (let i = 0; i < arrowElem.length; i++) {
if (arrowElem[i] === target) {
[].forEach.call(toogleItem, (elem) => {
elem.classList.remove('services-about__item--active');
});
toogleItem[i].classList.toggle('services-about__item--active');
}
}
});
<file_sep>/js/video-play.js
const video = document.getElementById('video-file');
const playBtn = document.getElementById('play-button');
const playBtnSign = document.getElementById('play-button-sign');
function playVideo() {
video.play().then(() => {
!video.controls ? video.controls = true : console.log('norm');
}).then(() => {
if (video.controls) {
playBtn.style.display = 'none';
playBtnSign.style.display = 'none';
}
});
}
document.addEventListener('click', (event) => {
let target = event.target;
console.log();
if (target === video || target === playBtn) {
playVideo();
}
});
<file_sep>/js/team-cards.js
const photos = document.getElementsByClassName('team-cards__photo');
const description = document.getElementsByClassName('description--team-cards');
const teamCards = document.getElementsByClassName('team-cards')[0];
console.log(getComputedStyle(teamCards));
document.addEventListener('click', setUnsetActiveClass);
function setUnsetActiveClass(event) {
let target = event.target;
for (let i = 0; i < photos.length; i++) {
if (photos[i] === target) {
[].forEach.call(photos, (elem) => {
elem.classList.remove('team-cards__photo--active');
});
[].forEach.call(description, (elem) => {
elem.classList.remove('description--team-cards--active');
});
photos[i].classList.add('team-cards__photo--active');
description[i].classList.add('description--team-cards--active');
}
}
}
| 205f3f4c292e011fd0983ec1918b1248efabcff2 | [
"JavaScript"
] | 5 | JavaScript | Selezeznyaka/Ajax-test | 9c4672ed3bdd5200fc6055d32efe46f4c24f69a6 | b7bc0e0200cf4686f08de929b72bab62b5cba44a | |
refs/heads/master | <file_sep>/*
* Write a function WITH NO CALLBACKS that,
* (1) reads a GitHub username from a `readFilePath`
* (the username will be the first line of the file)
* (2) then, sends a request to the GitHub API for the user's profile
* (3) then, writes the JSON response of the API to `writeFilePath`
*
* HINT: We exported some similar promise-returning functions in previous exercises
*/
var fs = require('fs');
var Promise = require('bluebird');
var fetchProfileAndWriteToFile = function(readFilePath, writeFilePath) {
// return fs.readfile(readFilePath)
// if (err)
//throw error
//else, return user
//.then sends a request to the GitHub API for the user's profile
//return something
//fs.get
//.then, writes the JSON response of the API to `writeFilePath`
//return something
//fs.writeFile
return fs.readFile(readFilePath)
.then(function(existingUsername) {
if (existingUsername){
throw new Error('User already exists!');
} else {
return readFilePath;
}
})
.then(function(newUsername){
return fs.get(newUsername);
}
.then(function(writeFile){
return fs.writeFile(writeFilePath);
}))
};
// Export these functions so we can test them
module.exports = {
fetchProfileAndWriteToFile: fetchProfileAndWriteToFile
};
| cb4aa39bd029627a27bfdb20dcf1560e42a7d57e | [
"JavaScript"
] | 1 | JavaScript | arnold1105/promises | 4cf975b0e50fbec4a8f7a627e00da4c759b0e3fc | 80e9f61e32d8bd6be42b41eccbe2fc271ce6e3b0 | |
refs/heads/master | <repo_name>terjr/nrfjprog.sh<file_sep>/nrfjprog.sh
#!/bin/bash
read -d '' USAGE <<- EOF
nrfprog.sh
This is a loose shell port of the nrfjprog.exe program distributed by Nordic,
which relies on JLinkExe to interface with the JLink hardware.
usage:
nrfjprog.sh action hexfile
where action is one of
--reset
--pin-reset
--erase-all
--flash
--flash-softdevice
EOF
TOOLCHAIN_PREFIX=arm-none-eabi
# assume the tools are on the system path
TOOLCHAIN_PATH=
OBJCOPY=$TOOLCHAIN_PATH$TOOLCHAIN_PREFIX-objcopy
OBJDUMP=$TOOLCHAIN_PATH$TOOLCHAIN_PREFIX-objdump
JLINK_OPTIONS="-device nrf51822 -if swd -speed 1000"
HEX=$2
# assume there's an out and bin file next to the hexfile
OUT=${HEX/.hex/.out}
BIN=${HEX/.hex/.bin}
JLINK="JLinkExe $JLINK_OPTIONS"
JLINKGDBSERVER="JLinkGDBServer $JLINK_OPTIONS"
# the script commands come from Makefile.posix, distributed with nrf51-pure-gcc
TMPSCRIPT=/tmp/tmp_$$.jlink
TMPBIN=/tmp/tmp_$$.bin
if [ "$1" = "--reset" ]; then
echo ""
echo "resetting..."
echo "------------"
echo ""
echo "r" > $TMPSCRIPT
echo "g" >> $TMPSCRIPT
echo "exit" >> $TMPSCRIPT
$JLINK $TMPSCRIPT
rm $TMPSCRIPT
elif [ "$1" = "--pin-reset" ]; then
echo "resetting with pin..."
echo "w4 40000544 1" > $TMPSCRIPT
echo "r" >> $TMPSCRIPT
echo "exit" >> $TMPSCRIPT
$JLINK $TMPSCRIPT
rm $TMPSCRIPT
elif [ "$1" = "--erase-all" ]; then
echo ""
echo "perfoming full erase..."
echo "-----------------------"
echo ""
echo "w4 4001e504 2" > $TMPSCRIPT
echo "w4 4001e50c 1" >> $TMPSCRIPT
echo "sleep 100" >> $TMPSCRIPT
echo "r" >> $TMPSCRIPT
echo "exit" >> $TMPSCRIPT
$JLINK $TMPSCRIPT
rm $TMPSCRIPT
elif [ "$1" = "--flash" ]; then
echo ""
echo "flashing $BIN..."
echo "------------------------------------------"
echo ""
FLASH_START_ADDRESS=`$OBJDUMP -h $OUT -j .text | grep .text | awk '{print $4}'`
echo "r" > $TMPSCRIPT
echo "loadbin $BIN $FLASH_START_ADDRESS" >> $TMPSCRIPT
echo "r" >> $TMPSCRIPT
echo "g" >> $TMPSCRIPT
echo "exit" >> $TMPSCRIPT
$JLINK $TMPSCRIPT
rm $TMPSCRIPT
elif [ "$1" = "--flash-softdevice" ]; then
echo ""
echo "flashing softdevice $HEX..."
echo "------------------------------------------"
echo ""
$OBJCOPY -Iihex -Obinary $HEX $TMPBIN
# Write to NVMC to enable erase, do erase all, wait for completion. reset
echo "w4 4001e504 2" > $TMPSCRIPT
echo "w4 4001e50c 1" >> $TMPSCRIPT
echo "sleep 100" >> $TMPSCRIPT
echo "r" >> $TMPSCRIPT
# Write to NVMC to enable write. Write mainpart, write UICR. Assumes device is erased.
echo "w4 4001e504 1" > $TMPSCRIPT
echo "loadbin $TMPBIN 0" >> $TMPSCRIPT
echo "r" >> $TMPSCRIPT
echo "g" >> $TMPSCRIPT
echo "exit" >> $TMPSCRIPT
$JLINK $TMPSCRIPT
rm $TMPSCRIPT
rm $TMPBIN
else
echo "$USAGE"
fi
| e8ab7d9426ad35fa37f45bc7d28d426b6d9a82f2 | [
"Shell"
] | 1 | Shell | terjr/nrfjprog.sh | 186be8f09fb89b973a9ca8d7635b6049954b6d4c | 587d8565ee18947fc1753c101d86cddfba204e21 | |
refs/heads/master | <repo_name>swb1999/paging-JS<file_sep>/js/index.js
function pagingJs(ele,options) {
var def = {
length: 0, // 数据总长度
pageNum: 5, // 显示几页
amount: 8, // 一页显示几条
}
this.set = this.extend({}, def, options); // 扩展默认参数
this.targetNode = typeof ele === "string" ? document.querySelector(ele) : ele;
this.firstPage = 1; // 起始页
this.lastPage = Math.ceil(this.set.length / this.set.amount); // 最后一页
this.currentPage = 1; // 当前页
this.sub(1); // 生成分页
this.addHigh(this.currentPage); // 给当前页添加高量
this.toggleNode(); // 显示隐藏省略号
this.bindEvent(); // 绑定事件
}
pagingJs.prototype = {
constructor: pagingJs,
bindEvent:function(){
var firstNode = this.targetNode.childNodes[0].firstChild,
lastNode = this.targetNode.childNodes[0].lastChild;
this.targetNode.addEventListener("click",function(e){
var event = e || event,
target = e.target || event.srcElement;
if(!isNaN(target.innerText)){
this.sub(target.innerText*1);
}else if(target.innerText === "«"){
this.currentPage > 1 && (this.sub(--this.currentPage))
}else if(target.innerText === "»"){
this.currentPage < this.lastPage && (this.sub(++this.currentPage));
}
this.addHigh(this.currentPage);
this.toggleNode();
}.bind(this),false);
},
addHigh:function(page){
this.targetNode.querySelectorAll("li").forEach(function(item){
if(item.innerText == page){
item.classList.add("high");
}else{
item.classList.remove("high");
}
})
},
toggleNode:function(){
var firstS = this.targetNode.querySelectorAll(".first"),
lastS = this.targetNode.querySelectorAll(".last");
(this.currentPage >= this.set.pageNum) ? this.addStyle(firstS,"display:block;") : this.addStyle(firstS,"display:none;");
(this.firstPage <= this.lastPage - this.set.pageNum) ? this.addStyle(lastS,"display:block;") : this.addStyle(lastS,"display:none;");
},
addStyle:function(dom,style){
for(var i=0,len=dom.length;i<len;i++){
dom[i].style.cssText = style;
}
},
sub: function(page) {
if(page > this.lastPage){return}
this.firstPage = page >= this.set.pageNum ? page - Math.floor(this.set.pageNum / 2) : 1;
(this.firstPage > this.lastPage - this.set.pageNum) && (this.firstPage = this.lastPage - this.set.pageNum + 1);
this.createNode(this.setPage(this.set.length, this.set.amount, this.set.pageNum, this.firstPage),this.lastPage);
this.currentPage = page;
},
createNode:function(pagesNode,lastPage){
this.targetNode.innerHTML = "<ul class='nav-list'><li>«</li><li class='first'>1</li><li class='first'>···</li>"+pagesNode+"<li class='last'>···</li><li class='last'>"+lastPage+"</li><li>»</li></ul>";
},
setPage: function(len, amount, pageNum, firstPage) {
var pagesNode = "",
page = Math.ceil(len / amount),
begin = page <= pageNum ? 1 : firstPage,
end = page <= pageNum ? page : firstPage + pageNum;
for (var i = begin; i < end; i++) {
pagesNode += "<li>"+i+"</li>";
}
return pagesNode;
},
extend: function() {
for (var i = 1, len = arguments.length; i < len; i++) {
for (key in arguments[i]) {
arguments[0][key] = arguments[i][key];
}
}
return arguments[0];
}
} | a61147e2164536e8754db7db99222623252ea6e9 | [
"JavaScript"
] | 1 | JavaScript | swb1999/paging-JS | 2c7f4015edf96f25a34a5e97e16f4451c888be72 | 8516415f643c40c40479a600056ac1ca42b734d9 | |
refs/heads/master | <repo_name>danicobryan/cmsi282-algorithms<file_sep>/Select.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Calendar;
public class Select {
public static void main (String [] args) throws IOException{
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String s = stdIn.readLine();
ArrayList<Integer> data = new ArrayList<Integer>();
while (s != null){
data.add(Integer.parseInt(s));
s = stdIn.readLine();
}
try{
int k = Integer.parseInt(args[0]);
if(k > data.size() || k < 1){
System.out.println("BAD DATA");
System.exit(0);
}
//long startTime = System.currentTimeMillis();
System.out.println(quicksort(data, 0, data.size() - 1, k));
//long endTime = System.currentTimeMillis();
//long totalTime = endTime - startTime;
//System.out.println("Current time is : " + totalTime);
} catch(Exception e){
System.out.println("BAD DATA");
}
}
private static int randPartition(ArrayList<Integer> data, int left, int right){
Random rand = new Random();
int pivotIndex = rand.nextInt((right - left) + 1) + left;
while(left < right){
while(left < pivotIndex){
if(data.get(left) > data.get(pivotIndex)){
swap(data, left, pivotIndex);
pivotIndex = left;
} else {
left++;
}
}
while(right > pivotIndex){
if(data.get(right) < data.get(pivotIndex)){
swap(data, right, pivotIndex);
pivotIndex = right;
} else {
right--;
}
}
}
return pivotIndex;
}
private static int quicksort(ArrayList<Integer> data, int start, int end, int k){
int pivot = randPartition(data, start, end);
if(pivot == k - 1){
return data.get(pivot);
} else if(pivot > k - 1){
return quicksort(data, start, pivot - 1, k);
} else {
return quicksort(data, pivot + 1, end, k);
}
}
private static void swap(ArrayList<Integer> data, int i, int j){
int temp = data.get(i);
data.set(i, data.get(j));
data.set(j, temp);
}
} | aa869a2e083f0338bf64d39cc7ae97cbbd1c1eb4 | [
"Java"
] | 1 | Java | danicobryan/cmsi282-algorithms | 7acee81231e4beabf266297dc62e02b48855f49e | 4c98cd990e65a2b778c779ee94145af1e3f713c4 | |
refs/heads/master | <repo_name>rohan-dhar/runnr<file_sep>/JS/vectr.js
/********************************************************************************
Vectr.js: A general purpose JavaScript library for Vector operations.
Developed by <NAME>
**********************************************************************************/
//Main global constructor/
window.Vectr = function(p1, p2){
//If coordinates are provided as discreet parameters
if(typeof p1 === "number" || typeof p1 === "string" || typeof p2 === "number" || typeof p2 === "string"){
this.x = ( !isNaN(p1) ) ? Number(p1) : 0;
this.y = ( !isNaN(p2) ) ? Number(p2) : 0;
//If coordinates or angle and magnitude are provided as an object
}else if(typeof p1 === "object"){
if(p1.x || p1.x === 0 || p1.y || p1.y === 0){
this.x = ( !isNaN(p1.x) ) ? Number(p1.x) : 0;
this.y = ( !isNaN(p1.y) ) ? Number(p1.y) : 0;
}else if(p1.magnitude && (p1.angleDeg || p1.angle || p1.angle === 0 || p1.angleDeg === 0)){
//If the angle is provided in degrees
//If both angle and angleDeg are provided, angleDeg is given prefernece
if(p1.angleDeg || p1.angleDeg === 0){
this.x = p1.magnitude * Math.cos(this.toRadian(p1.angleDeg));
this.y = p1.magnitude * Math.sin(p1.angleDeg * Math.PI / 180);
}else{
this.x = p1.magnitude * Math.cos(p1.angle);
this.y = p1.magnitude * Math.sin(p1.angle);
}
}
//If nothing is provided
}else{
this.x = 0;
this.y = 0;
}
}
/********************************************************************************
Helper Methods OR zero Vectr methods
Used to provide general utility and do not perform and vector operations
**********************************************************************************/
Vectr.toDegree = function(rad) {
(isNaN(rad)) ? rad = 1 : rad = Number(rad);
return rad * 180 / Math.PI;
};
Vectr.toRadian = function(deg) {
(isNaN(deg)) ? deg = 1 : deg = Number(deg);
return deg * Math.PI / 180;
}
/********************************************************************************
Vectr representation methods
Used to get a Vectr is a particular format
**********************************************************************************/
Vectr.prototype.magnitude = function(){
return Math.sqrt(this.x*this.x + this.y*this.y); //Math.pow avoided due to performance limitations
}
Vectr.prototype.angle = function(deg){
if(deg){
return Vectr.toDegree(Math.atan2(this.x , this.y));
}else{
return Math.atan2(this.x , this.y);
}
}
Vectr.prototype.direction = function(deg){
return this.angle(deg);
};
Vectr.prototype.verticalAngle = function(deg){
return this.angle(deg) - (deg) ? 90 : Math.PI/2;
}
Vectr.prototype.getAs = function(type, angleAndMag, deg){
if(type.toLowerCase() === "array"){
if(angleAndMag){
if(deg){
return [this.angle(true), this.magnitude()]
}else{
return [this.angle(), this.magnitude()];
}
}else{
return [this.x, this.y];
}
}else if(type.toLowerCase() === "object"){
if(angleAndMag){
if(deg){
return {angle: this.angle(true), magnitude: this.magnitude()};
}else{
return {angle: this.angle(), magnitude: this.magnitude()};
}
}else{
return {x: this.x, y: this.y}
}
}else{
if(angleAndMag){
if(deg){
return "angle: "+this.angle(true)+", magnitude: "+this.magnitude();
}else{
return "angle: "+this.angle()+", magnitude: "+this.magnitude();
}
}else{
return "x: "+this.x+", y: "+this.y;
}
}
}
/********************************************************************************
Single Vectr operation methods
Used to perform common single Vectr operations
**********************************************************************************/
Vectr.prototype.normalize = function(onNew){
var magnitude = this.magnitude();
return this.divide(magnitude, onNew);
}
Vectr.prototype.invert = function(onNew){
if(onNew){
return new Vectr(-this.x, -this.y);
}else{
this.x = -this.x;
this.y = -this.y;
return this;
}
}
Vectr.prototype.invertX = function(onNew){
if(onNew){
return new Vectr(-this.x, this.y);
}else{
this.x = -this.x;
return this;
}
}
Vectr.prototype.invertY = function(onNew){
if(onNew){
return new Vectr(this.x, -this.y);
}else{
this.y = -this.y;
return this;
}
}
Vectr.prototype.abs = function(onNew){
if(onNew){
return new Vectr(Math.abs(this.x), Math.abs(this.y));
}else{
this.x = Math.abs(this.x);
this.y = Math.abs(this.y);
return this;
}
}
Vectr.prototype.absX = function(onNew){
if(onNew){
return new Vectr(Math.abs(this.x), this.y);
}else{
this.x = Math.abs(this.x);
return this;
}
}
Vectr.prototype.absY = function(onNew){
if(onNew){
return new Vectr(this.x, Math.abs(this.y));
}else{
this.y = Math.abs(this.y);
return this;
}
}
Vectr.prototype.roundOff = function(onNew){
if(onNew){
return new Vectr(Math.round(this.x), Math.round(this.y));
}else{
this.x = Math.round(this.x);
this.y = Math.round(this.y);
}
}
Vectr.prototype.roundOffX = function(onNew){
if(onNew){
return new Vectr(Math.round(this.x),this.y);
}else{
this.x = Math.round(this.x);
}
}
Vectr.prototype.roundOffY = function(onNew){
if(onNew){
return new Vectr(this.x, Math.round(this.y));
}else{
this.y = Math.round(this.y);
}
}
Vectr.prototype.swapXY = function(){
var t = this.x;
this.x = this.y;
this.y = t;
}
Vectr.prototype.rotateTo = function(angle, deg, onNew){
if(isNaN(angle)){
return false;
}
if(deg){
angle = Vectr.toRadian(Number(angle));
}
var mag = this.magnitude();
var x = mag * Math.sin(angle), y = mag * Math.cos(angle);
if(onNew){
return new Vectr(x, y);
}else{
this.x = x;
this.y = y;
return this;
}
}
Vectr.prototype.rotateBy = function(angle, deg, onNew){
if(isNaN(angle)){
return false;
}
if(deg){
angle = Vectr.toRadian(Number(angle));
}
angle += this.angle();
return this.rotateTo(angle, false, onNew);
}
/********************************************************************************
Vectr arithmetic methods
Used to perform common arethmetic operations on Vectrs
**********************************************************************************/
Vectr.prototype.operation = function(conf){
//Unpacking the supplied object
var x = conf.x, y = conf.y, n = conf.operant, onNew = conf.onNew, opt = conf.operation;
if(opt === "+"){
if(n instanceof Vectr){
if(onNew){
if(x && y){
return new Vectr(this.x + n.x, this.y + n.y);
}else if(x){
return new Vectr(this.x + n.x, this.y);
}else if(y){
return new Vectr(this.x, this.y + n.y);
}else{
return false;
}
}else{
if(x){
this.x += n.x;
}
if(y){
this.y += n.y;
}
return this;
}
}else if(!isNaN(n)){
n = Number(n);
if(onNew){
if(x && y){
return new Vectr(this.x + n, this.y + n);
}else if(x){
return new Vectr(this.x + n, this.y);
}else if(y){
return new Vectr(this.x, this.y + n);
}else{
return false;
}
}else{
if(x){
this.x += n;
}
if(y){
this.y += n;
}
return this;
}
}else{
return false;
}
}else if(opt === "*"){
if(n instanceof Vectr){
if(onNew){
if(x && y){
return new Vectr(this.x * n.x, this.y * n.y);
}else if(x){
return new Vectr(this.x * n.x, this.y);
}else if(y){
return new Vectr(this.x, this.y * n.y);
}else{
return false;
}
}else{
if(x){
this.x *= n.x;
}
if(y){
this.y *= n.y;
}
return this;
}
}else if(!isNaN(n)){
n = Number(n);
if(onNew){
if(x && y){
return new Vectr(this.x * n, this.y * n);
}else if(x){
return new Vectr(this.x * n, this.y);
}else if(y){
return new Vectr(this.x, this.y * n);
}else{
return false;
}
}else{
if(x){
this.x *= n;
}
if(y){
this.y *= n;
}
return this;
}
}else{
return false;
}
}else if(opt === "-"){
if(n instanceof Vectr){
if(onNew){
if(x && y){
return new Vectr(this.x - n.x, this.y - n.y);
}else if(x){
return new Vectr(this.x - n.x, this.y);
}else if(y){
return new Vectr(this.x, this.y - n.y);
}else{
return false;
}
}else{
if(x){
this.x -= n.x;
}
if(y){
this.y -= n.y;
}
return this;
}
}else if(!isNaN(n)){
n = Number(n);
if(onNew){
if(x && y){
return new Vectr(this.x - n, this.y - n);
}else if(x){
return new Vectr(this.x - n, this.y);
}else if(y){
return new Vectr(this.x, this.y - n);
}else{
return false;
}
}else{
if(x){
this.x -= n;
}
if(y){
this.y -= n;
}
return this;
}
}else{
return false;
}
}else if(opt === "/"){
if(n instanceof Vectr){
if(onNew){
if(x && y){
return new Vectr(this.x / n.x, this.y / n.y);
}else if(x){
return new Vectr(this.x / n.x, this.y);
}else if(y){
return new Vectr(this.x, this.y / n.y);
}else{
return false;
}
}else{
if(x){
this.x /= n.x;
}
if(y){
this.y /= n.y;
}
return this;
}
}else if(!isNaN(n)){
n = Number(n);
if(onNew){
if(x && y){
return new Vectr(this.x / n, this.y / n);
}else if(x){
return new Vectr(this.x / n, this.y);
}else if(y){
return new Vectr(this.x, this.y / n);
}else{
return false;
}
}else{
if(x){
this.x /= n;
}
if(y){
this.y /= n;
}
return this;
}
}else{
return false;
}
}else{
return false;
}
}
//Wrapper to operation: ADDITION
Vectr.prototype.add = function(n, onNew){
return this.operation({
operation: "+",
operant: n,
x: true,
y: true,
onNew: onNew
});
}
Vectr.prototype.addX = function(n, onNew){
return this.operation({
operation: "+",
operant: n,
x: true,
y: false,
onNew: onNew
});
}
Vectr.prototype.addY = function(n, onNew){
return this.operation({
operation: "+",
operant: n,
x: false,
y: true,
onNew: onNew
});
}
//Wrapper to operation: MULTIPLICATION
Vectr.prototype.multiply = function(n, onNew){
return this.operation({
operation: "*",
operant: n,
x: true,
y: true,
onNew: onNew
});
}
Vectr.prototype.multiplyX = function(n, onNew){
return this.operation({
operation: "*",
operant: n,
x: true,
y: false,
onNew: onNew
});
}
Vectr.prototype.multiplyY = function(n, onNew){
return this.operation({
operation: "*",
operant: n,
x: false,
y: true,
onNew: onNew
});
}
//Wrapper to operation: SUBTRACTION
Vectr.prototype.subtract = function(n, onNew){
return this.operation({
operation: "-",
operant: n,
x: true,
y: true,
onNew: onNew
});
}
Vectr.prototype.subtractX = function(n, onNew){
return this.operation({
operation: "-",
operant: n,
x: true,
y: false,
onNew: onNew
});
}
Vectr.prototype.subtractY = function(n, onNew){
return this.operation({
operation: "-",
operant: n,
x: false,
y: true,
onNew: onNew
});
}
//Wrapper to operation: DIVISION
Vectr.prototype.divide = function(n, onNew){
return this.operation({
operation: "/",
operant: n,
x: true,
y: true,
onNew: onNew
});
}
Vectr.prototype.divideX = function(n, onNew){
return this.operation({
operation: "/",
operant: n,
x: true,
y: false,
onNew: onNew
});
}
Vectr.prototype.divideY = function(n, onNew){
return this.operation({
operation: "/",
operant: n,
x: false,
y: true,
onNew: onNew
});
}
Vectr.prototype.dotProduct = function(vec){
if(!vec instanceof Vectr){
return false;
}
return this.multiply(vec, true).magnitude();
}
Vectr.prototype.crossProduct = function(vec, onNew){
if(!vec instanceof Vectr){
return false;
}
return this.magnitude() * vec.magnitude() * Math.sin(this.angleBetween(vec));
}
/********************************************************************************
General Vectr methods
Used to perform other common operations on Vectrs
**********************************************************************************/
Vectr.prototype.distanceX = function(vec, abs){
if(!vec instanceof Vectr){
return false;
}
if(abs){
return Math.abs(this.x - vec.x);
}else{
return this.x - vec.x;
}
}
Vectr.prototype.distanceY = function(vec, abs){
if(!vec instanceof Vectr){
return false;
}
if(abs){
return Math.abs(this.y - vec.y);
}else{
return this.y - vec.y;
}
}
Vectr.prototype.distance = function(vec){
if(!vec instanceof Vectr){
return false;
}
return this.subtract(vec, true).magnitude();
}
Vectr.prototype.angleBetween = function(vec, deg){
if(!vec instanceof Vectr){
return false;
}
var theta = Math.acos(this.dotProduct(vec)/(this.magnitude() * vec.magnitude()));
if(deg){
return Vectr.toDegree(theta);
}else{
return theta;
}
}
Vectr.prototype.project = function(vec){
if(!vec instanceof Vectr){
return false;
}
var scaleFactor = this.magnitude() * Math.cos(this.angleBetween(vec));
return vec.normalize(true).multiply(scaleFactor);
}
<file_sep>/JS/script.js
function rand(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
var can, ctx, $can;
var conf = {
groundHeight: 4,
waterHeight: 4,
gravity: 1.5,
tileSide: 60,
worldColor: "#D0F4F7",
cloudDensity: 22, // No of Clouds in 500 px
cloudTopRange: [0, 90],
cloudWidth: 128,
cloudHeight: 71,
enemySide: 50,
maxGameSpeed: 17,
minPlayerLeftIncrement: 3,
minPlayerRightIncrement: 1,
tileType: "ground",
}
var tileImages = {
underGround: "underGroundTile.png",
ground: "groundTile.png",
underWater: "underWaterTile.png",
water: "waterTile.png",
};
var playerImages = {
1: "p1.png",
2: "p2.png",
3: "p3.png",
4: "p4.png",
5: "p5.png",
6: "p6.png",
7: "p7.png",
8: "p8.png",
9: "p9.png",
10: "p1.png",
11: "p1.png",
};
var cloudImages = {
1: "cloud1.png",
2: "cloud2.png",
3: "cloud3.png",
};
var enemyImages = {
1: "enemy1.png",
2: "enemy2.png",
3: "enemy3.png",
};
var totalLoadCount = Object.keys(tileImages).length + Object.keys(playerImages).length + Object.keys(enemyImages).length + Object.keys(cloudImages).length, totalLoaded = 0;
function Tile(type, x, side){
this.type = type || "ground";
this.side = side || conf.tileSide;
this.x = x;
}
Tile.prototype.draw = function() {
var tile, underTile, height;
if(this.type == "water"){
tile = tileImages.water;
underTile = tileImages.underWater;
height = conf.waterHeight;
}else{
tile = tileImages.ground;
underTile = tileImages.underGround;
height = conf.groundHeight;
}
for(var i = 0; i < height; i++){
ctx.drawImage(underTile, this.x, can.height - (i*this.side), this.side, this.side);
}
ctx.drawImage(tile, this.x, can.height - ((height)*this.side), this.side, this.side);
}
Tile.prototype.move = function(){
if(this.x < -this.side){
var maxX = 0;
var l = tiles.length;
while(l--){
if(tiles[l].x > maxX){
maxX = tiles[l].x;
}
}
this.x = maxX + this.side - player.gameSpeed;
}else{
this.x -= player.gameSpeed;
}
}
function Cloud(type, x, y, speed, width, height){
this.type = type;
this.x = x;
this.y = y;
this.width = width || conf.cloudWidth;
this.height = height || conf.cloudHeight;
this.speed = speed;
}
Cloud.prototype.draw = function(){
ctx.drawImage(this.type, this.x, this.y, this.width, this.height);
}
Cloud.prototype.move = function(){
if(this.x < -this.width){
var maxX = 0;
var l = clouds.length;
while(l--){
if(clouds[l].x > maxX){
maxX = clouds[l].x;
}
}
this.x = maxX + this.width - this.speed;
}else{
this.x -= this.speed;
}
}
var clouds = [];
function Enemy(type, orientation, length, x, y, side){
this.type = type;
this.orientation = orientation;
this.length = length;
this.x = x;
this.y = y;
this.side = side || conf.enemySide;
}
Enemy.prototype.draw = function(){
if(this.orientation == "horizontal"){
for(var i = 0; i < this.length; i++){
ctx.drawImage(this.type, this.x + (this.side * i), this.y, this.side, this.side);
}
}else{
for(var i = 0; i < this.length; i++){
ctx.drawImage(this.type, this.x, this.y - (this.side * i), this.side, this.side);
}
}
}
Enemy.prototype.move = function(){
var i = enemies.indexOf(this);
if(this.orientation == "horizontal"){
if(this.x < -this.side * this.length){
enemies.splice(i, 1);
}else{
this.x -= player.gameSpeed;
}
}else{
if(this.x < -this.side){
enemies.splice(i, 1);
}else{
this.x -= player.gameSpeed;
}
}
}
var enemies = [];
var initPlayerSettings = {
gameSpeed: 6,
movementSpeed: 5,
leftIncrement: 8,
rightIncrement: 8,
bounceSpeed: 26,
}
var player = {
gameSpeed: 0,
movementSpeed: 0,
leftIncrement: 0,
rightIncrement: 0,
bounceSpeed: 0,
minX: 0,
maxX: 0,
x: 0,
y: 0,
groundLevel: 0,
currentSprite: 1,
time: 0,
width: 72,
height: 97,
inMotion: false,
movingTo: 0,
inBounce: false,
ySpeed: 0,
setup: function(){
this.gameSpeed = initPlayerSettings.gameSpeed;
this.movementSpeed = initPlayerSettings.movementSpeed;
this.leftIncrement = initPlayerSettings.leftIncrement;
this.rightIncrement = initPlayerSettings.rightIncrement;
this.bounceSpeed = initPlayerSettings.bounceSpeed;
this.minX = can.width * 3/10 - (this.width / 2);
this.maxX = can.width * 7/10 - (this.width / 2);
this.x = can.width / 2 - (this.width / 2);
this.y = can.height - ((conf.groundHeight+1) * conf.tileSide) - 30;
this.groundLevel = can.height - ((conf.groundHeight+1) * conf.tileSide) - 30;
},
draw: function(){
this.time++;
if(player.time >= 35/player.gameSpeed){
player.currentSprite++;
if(player.currentSprite == 11){
player.currentSprite = 1;
}
player.time = 0;
}
if(player.inMotion){
if(player.x < player.movingTo && player.x + player.movementSpeed <= player.movingTo){
player.x += player.movementSpeed;
}else if(player.x > player.movingTo && player.x - player.movementSpeed >= player.movingTo){
player.x -= player.movementSpeed;
}else{
player.inMotion = false;
}
}
if(player.inBounce){
if(player.y - player.ySpeed < player.groundLevel){
player.ySpeed -= conf.gravity;
player.y -= player.ySpeed;
}else if(player.y < player.groundLevel){
player.y = player.groundLevel;
player.inBounce = false;
}else{
player.y = player.groundLevel;
player.inBounce = false;
}
}
ctx.drawImage(playerImages[player.currentSprite], player.x, player.y, this.width, this.height);
},
move: function(where){
if(where === "left"){
if(player.x - player.leftIncrement > player.minX){
player.x -= player.leftIncrement;
}
}else if(where === "right"){
if(player.x + player.rightIncrement < player.maxX){
player.x += player.rightIncrement;
}
}else if(where == "up" && !player.inBounce){
player.ySpeed = player.bounceSpeed;
player.y--;
player.inBounce = true;
}else if(where == "down" && player.inBounce){
if(Math.sign(player.speed) === -1){
player.ySpeed *= 20;
}else if(Math.sign(player.speed) === 1){
player.ySpeed *= -20
}else{
player.ySpeed = -20;
}
}
},
checkCollision: function(){
var l = enemies.length;
var hasCollided = false;
while(l--){
var e = enemies[l];
if(e.orientation == "horizontal"){
if(player.x + player.width - 8 >= e.x && player.x <= e.x + (e.side * e.length) && player.y >= e.y - e.side){
hasCollided = true;
break;
}
}else{
if(player.x + player.width - 8 >= e.x && player.x <= e.x + e.side && player.y >= e.y - (e.side * e.length) ){
hasCollided = true;
break;
}
}
}
return hasCollided;
}
}
var tiles = [];
var lastEnemy = 0;
var game = {
status: false,
score: 0,
timeStarted: 0,
animationId: 0,
setWorldSize: function(){
can.height = window.innerHeight;
can.width = window.innerWidth;
},
loadImagesFromObject: function(obj){
var loaders = {};
var url = "";
for(img in obj){
loaders[img] = new Image();
$(loaders[img]).load(function(){
var that = this;
for(item in obj){
if(obj[item] == that.src.substr(that.src.lastIndexOf("/") + 1)){
obj[item] = that;
totalLoaded++;
$("#load-bar-prog").width((totalLoaded/totalLoadCount*100)+"%")
if(totalLoaded == totalLoadCount){
game.init();
$("#load-bar-base").animate({
"opacity": "0"
}, 400);
setTimeout(function(){
$("#load-bar-base").css("display","none")
$("#load-head").text("Runnr");
$("#start-btn").css("display","block").animate({
"opacity": "1"
}, 400);
}, 400);
}
break;
}
}
});
loaders[img].src = "IMG/"+obj[img];
}
},
loadAssets: function(){
this.loadImagesFromObject(tileImages);
this.loadImagesFromObject(playerImages);
this.loadImagesFromObject(cloudImages);
this.loadImagesFromObject(enemyImages);
},
init: function(){
player.setup();
tiles = [];
clouds = [];
enemies = [];
game.score = 0;
var nos = (can.width / conf.tileSide) + 2;
for(var i = 0; i < nos; i++){
tiles.push(new Tile(conf.tileType, i*conf.tileSide, conf.tileSide));
}
nos = conf.cloudDensity * can.width/500;
for(var i = 0; i < nos; i++){
var ch = rand(1, 3);
var denom = rand(2, 5);
clouds.push(new Cloud(cloudImages[ch], rand(0, can.width), rand(conf.cloudTopRange[0], conf.cloudTopRange[1]), player.gameSpeed / denom));
}
clouds.push(new Cloud(cloudImages[1], can.width + conf.cloudWidth, conf.cloudTopRange[0]));
},
animate: function(){
ctx.fillStyle = conf.worldColor;
ctx.fillRect(0, 0, can.width, can.height);
var l = tiles.length;
var scoreMultiplier = 1;
while(l--){
tiles[l].draw();
tiles[l].move();
}
var l = clouds.length;
while(l--){
clouds[l].draw();
clouds[l].move();
}
var l = enemies.length;
while(l--){
enemies[l].draw();
enemies[l].move();
}
player.draw();
var timePassed = Date.now() - game.timeStarted;
if(player.checkCollision()){
game.over();
}
var randomizer;
if(timePassed > 12000){
randomizer = rand(-155, -100);
scoreMultiplier = 1.2;
}else if(timePassed > 30000){
randomizer = rand(-210, -140);
scoreMultiplier = 1.6;
}else if(timePassed > 60000){
randomizer = rand(-280, -190);
scoreMultiplier = 1.9;
}else{
randomizer = rand(-100, 0);
}
if(lastEnemy >= (710 + randomizer)/player.gameSpeed){
var ch = rand(1, 3);
var change = rand(-10, 10);
side = conf.enemySide + change;
var y = can.height - ((conf.groundHeight) * conf.tileSide) - side;
var ori = rand(1, 2);
var len = rand(1, 3);
if(ori == 1){
ori = "horizontal";
}else{
ori = "vertical";
}
enemies.push(new Enemy(enemyImages[ch], ori, len, can.width + side * len, y, side));
lastEnemy = 0;
}else{
lastEnemy++;
}
if(timePassed > 15000 && player.gameSpeed < conf.maxGameSpeed){
player.gameSpeed += 0.005;
if(player.rightIncrement >= conf.minPlayerRightIncrement){
player.rightIncrement -= 0.0035;
}else{
player.rightIncrement = conf.minPlayerRightIncrement;
}
if(player.rightIncrement >= conf.minPlayerRightIncrement){
player.rightIncrement -= 0.0035;
}else{
player.rightIncrement = conf.minPlayerRightIncrement;
}
}
if(game.status){
game.score = timePassed/1000;
game.score *= scoreMultiplier;
game.score = Math.round(game.score * 10) / 10;
$(".game-sidebar-stat-score .game-sidebar-stat-data").text((game.score));
requestAnimationFrame(game.animate);
}
},
start: function(){
$("#load-screen, #screen-score").animate({
"opacity": "0"
}, 400);
$(".game-sidebar").css("display", "block").animate({
"opacity": "1"
}, 400);
game.status = true;
setTimeout(function(){
$("#load-screen").css({
"display": "none",
"background-color": "rgba(79,166,255, 0.8)",
});
$("#screen-score").css("display", "none");
game.timeStarted = Date.now();
game.animationId = requestAnimationFrame(game.animate);
}, 400);
},
setup: function(){
$can = $("<canvas id='game-world'></canvas>");
$("body").append($can);
can = $can[0];
ctx = can.getContext("2d");
this.setWorldSize();
this.loadAssets();
},
over: function(){
game.status = false;
$("#game-score-stat").text(game.score);
$("#screen-score").css("display", "block").animate({
"opacity": "1"
}, 400);
$("#load-head").text("Game Over!");
$("#start-btn").text("Play again");
$(".game-sidebar").animate({
"opacity": "0"
}, 400);
setTimeout(function(){
$(".game-sidebar").css({
"display": "none",
});
}, 400);
$("#load-screen").css("display","block").animate({
"opacity": "1"
}, 400);
game.init();
}
}
$(document).ready(function(){
game.setup();
$("#start-btn").click(function(){
if(!game.status){
game.start();
}
});
$(".game-sidebar-act-end").click(function(){
if(game.status){
game.start();
}
});
var leftIntr = false, rightIntr = false;
$(document).on("keyup", function(e){
if(e.keyCode == 37){
if(leftIntr !== false){
clearInterval(leftIntr);
leftIntr = false;
}
}
if(e.keyCode == 39){
if(rightIntr !== false){
clearInterval(rightIntr);
rightIntr = false;
}
}
});
$(document).on("keydown", function(e){
if(e.keyCode == 37){
if(leftIntr === false){
leftIntr = setInterval(function(){
player.move("left");
}, 17);
}
}
if(e.keyCode == 39){
if(rightIntr === false){
rightIntr = setInterval(function(){
player.move("right");
}, 17);
}
}
if(e.keyCode == 38){
player.move("up");
}
if(e.keyCode == 40){
player.move("down");
}
});
});<file_sep>/readme.md
<h1>Runnr</h1>
An endless runner game developed using HTML 5 <code>canvas</code> API.
<h3>Installation</h3>
Just clone the git repo and run the <code>index.html</code> in any HTML 5 supporting web browser to check the project out!
| 6a0cb193c45cb231a3f322bf67f8b69f6fe30bd0 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | rohan-dhar/runnr | 55fd74987eb513d71c2678caa37e195ec15ce647 | b62e9a1fca091b04798003c08bb9b35c5e979cca | |
refs/heads/master | <repo_name>ytxfate/authority_manager_front<file_sep>/src/api/authority/user_manager.js
import request from '@/utils/request'
export function getUsersInfo(params, data) {
return request({
url: '/authority/get_users_info',
method: 'post',
params,
data
})
}
export function deleteUser(params) {
return request({
url: '/authority/delete_user',
method: 'get',
params
})
}
export function getAllRoles() {
return request({
url: '/authority/get_all_roles',
method: 'get'
})
}
export function getUserRoles(params) {
return request({
url: '/authority/get_user_roles',
method: 'get',
params
})
}
export function userRelateRoles(data) {
return request({
url: '/authority/user_relate_roles',
method: 'post',
data
})
}
<file_sep>/src/utils/request.js
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
// do something before request is sent
if (store.getters.token) {
config.headers['Authorization'] = store.getters.token
}
return config
},
error => {
return Promise.reject(error)
}
)
let isRefreshing = false
let requests = []
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
if (res.code === 200) {
return res
} else if (res.code === 1200) {
Message({
message: res.msg || '请登录',
type: 'warning',
duration: 2 * 1000
})
store.dispatch('user/resetToken').then(() => {
setTimeout(() => location.reload(), 2000)
})
} else if (res.code === 1102) {
const config = response.config
if (!isRefreshing) {
isRefreshing = true
store.dispatch('user/refreshToken').then(res => {
config.headers['Authorization'] = res.jwt
config.baseURL = ''
requests.forEach(cd => cd(res.jwt))
requests = []
service(response.config)
}).catch(() => {
Message({
message: '刷新认证信息失败,请重新登录',
type: 'warning',
duration: 2 * 1000
})
store.dispatch('user/resetToken').then(() => {
setTimeout(() => location.reload(), 2000)
})
}).finally(() => {
isRefreshing = false
})
} else {
// 正在刷新token,将返回一个未执行resolve的promise
return new Promise((resolve) => {
// 将resolve放进队列,用一个函数形式来保存,等token刷新后直接执行
requests.push(() => {
config.baseURL = ''
config.headers['Authorization'] = store.getters.token
resolve(service(config))
})
})
}
} else {
Message({
message: res.msg || 'Error',
type: 'error',
duration: 5 * 1000
})
return Promise.reject(new Error(res.message || 'Error'))
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
<file_sep>/README.md
# authority_manager_front
权限管理系统简单实现 -- 前端部分(基于 vue-element_admin 开发)<file_sep>/src/api/authority/menu_manager.js
import request from '@/utils/request'
export function getMenus(params, data) {
return request({
url: '/authority/get_menus_info',
method: 'post',
params,
data
})
}
export function addMenu(data) {
return request({
url: '/authority/add_menu',
method: 'post',
data
})
}
export function getDepthMenus(params) {
return request({
url: '/authority/get_depth_menus',
method: 'get',
params
})
}
export function deleteMenu(params) {
return request({
url: '/authority/delete_menu',
method: 'get',
params
})
}
export function editMenu(data) {
return request({
url: '/authority/edit_menu',
method: 'post',
data
})
}
<file_sep>/src/api/authority/role_manager.js
import request from '@/utils/request'
export function getRoles(params, data) {
return request({
url: '/authority/get_roles_info',
method: 'post',
params,
data
})
}
export function addRole(data) {
return request({
url: '/authority/add_role',
method: 'post',
data
})
}
export function deleteRole(params) {
return request({
url: '/authority/delete_role',
method: 'get',
params
})
}
export function editRole(data) {
return request({
url: '/authority/edit_role',
method: 'post',
data
})
}
export function getMenuListTree() {
return request({
url: '/authority/get_menu_list_tree',
method: 'get'
})
}
export function roleRelateMenus(data) {
return request({
url: '/authority/role_relate_menus',
method: 'post',
data
})
}
export function getRelatedMenuIds(params) {
return request({
url: '/authority/get_related_menu_ids',
method: 'get',
params
})
}
| 4b2bcfc16b8083c07dfa0f623f5ef50a6cc4ac80 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | ytxfate/authority_manager_front | 65085a44f8186d11cb7ccc9b74a96f6001186ee8 | d04b30642a4e8542a5d42eec5451024887eb2c26 | |
refs/heads/master | <file_sep>const NAVS = [
{ id:1, path:"/",text:"Vue3Todos" },
]
export {
NAVS
}<file_sep>## Vue3.0 初体验
TodoList
![cDDiU1.gif](https://z3.ax1x.com/2021/04/12/cDDiU1.gif)
给个start啦.... | a7dad64ce1661e4867389d61bbbb5407863db2f2 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | MonthlyGirl/Vue3-todos | 0d11278c04e5a705655b683949c49a8d626024bc | c34c99efab7f0a38d66f7aa36fa3b494434408b8 | |
refs/heads/master | <file_sep>__all__ = ["BaseWorker"]
from ApiRepl.BaseWorker import BaseWorker
<file_sep>/*queue*/
CREATE TABLE queue
(
`id` INT auto_increment NOT NULL,
`priority` INT DEFAULT 0,
`type` VARCHAR(64) NOT NULL,
`min` VARCHAR(64),
`max` VARCHAR(64),
`started` DATETIME,
`finished` DATETIME,
PRIMARY KEY (id)
);
CREATE TABLE errors
(
`id` INT auto_increment NOT NULL,
`state` VARCHAR(64) NOT NULL,
`error` TEXT,
`source` INT NOT NULL,
PRIMARY KEY (id)
);
/*FetchLog*/
CREATE TABLE fetchlog
(
`id` INT auto_increment NOT NULL,
`recordsadded` INT NOT NULL DEFAULT 0,
`timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`source` INT NOT NULL,
FOREIGN KEY (source) references queue(id) on delete cascade,
PRIMARY KEY (id)
);
<file_sep>insert into queue(type, min, max) values ("undefined","a","z");
<file_sep># ApiRepl
## What it is
If you want API data copied to your database, the workers should fetch for you elastically.
## Setup
### Database Requirement
use schema.sql to create a database, and load it with the types of information you need
### Subclass BaseWorker
see samples/usage.py for an example.
Create an api method and save method for your workflow by subclassing BaseWorker.
## Functionality (requirements)
* Splits update task into pieces
* Prioritizes pieces
* Can be paused and resumed
* Can scale across hosts easily using DB
* Good test coverage (soon :) )
## Usage
See Sample folder
<file_sep>"""
To demonstrate how to use this class, here is one way to use this tool.
"""
from ApiRepl import BaseWorker
import random
class PersonWorker(BaseWorker):
""" A fictional worker for a person api. """
def __init__(self, *args, **kwargs):
BaseWorker.__init__(self, *args, **kwargs)
def api(self):
""" Specalization for this api. """
self.finished=True
return {'TEST':'Success'}
def saveobj(item):
return item
def throttle():
"""Simulate a kill condition."""
return random.random() > 0.95
def test_specalization():
worker = PersonWorker(type="undefined")
for item in worker:
if item is 0 or throttle():
break
saveobj(item)
del worker
<file_sep>"""
To demonstrate how to use this class, here is one way to use this tool.
"""
import json
import urllib2
import random
import pymysql
from ApiRepl import BaseWorker
"""
Sample Schema:
Person:
- Name
- DOB
- Height
"""
class PersonWorker(BaseWorker):
""" A fictional worker for a person api. """
def __init__(self, *args, **kwargs):
BaseWorker.__init__(self, *args, **kwargs)
def api(self):
""" Specalization for this api. """
# get a list of names
people = json.load(urllib2.urlopen("api.people.com/"))
# toss out those out of range
lookup = [p for p in people.keys() if
p > self.last and p <= self.maximum]
if len(lookup) == 0:
# need to know when finished, so that it can resume or stop
self.finished = True
return 0
who = sorted(lookup)[0]
self.last = who
person = json.load(urllib2.urlopen(
"api.people.com/{item}".format(item=who)))
return person
def saveobj(item):
"""Save each object from the worker."""
# connect to database
cursor = pymysql.connect(host='localhost', db='fetch').cursor()
cursor.execute('insert into Person (Name, DOB, Height) values (%s %s %s)',
(item['Name'], item['DOB'], item['Height']))
def throttle():
"""Simulate a kill condition."""
return random.random() > 0.95
if __name__ == "__main__":
worker = PersonWorker(type="person")
for item in worker:
if item is 0 or throttle():
del worker
saveobj(item)
| 55caef4387d02a222bdbf99ddd8200e7cd072d00 | [
"Markdown",
"SQL",
"Python"
] | 6 | Python | birm/ApiRepl | 560c0c1a123dddebe7b66ffb357a0f8c5f10b0eb | b29d04c690dd0425739c1a84dd5eb0935a3bc76a | |
refs/heads/master | <repo_name>uesp/uesp-shadowkey<file_sep>/ParseModels/ParseModels/ParseModels.cpp
// ParseModels.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdarg.h>
#include <cstdint>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include "d:\\src\uesp\\EsoApps\\common\\devil\\include\\IL\\il.h"
#include "d:\\src\uesp\\EsoApps\\common\\devil\\include\\IL\\ilu.h"
#include "d:\\src\uesp\\EsoApps\\common\\devil\\include\\IL\\ilut.h"
#include "zlib.h"
typedef uint32_t dword;
typedef uint16_t word;
#define MODELSINDEX "c:\\downloads\\Shadowkey\\Shadowkey Release\\system\\apps\\6r51\\models.idx"
#define MODELSHUGE "c:\\downloads\\Shadowkey\\Shadowkey Release\\system\\apps\\6r51\\models.huge"
#define MODELSTXT "c:\\downloads\\Shadowkey\\Shadowkey Release\\system\\apps\\6r51\\models.txt"
#define MODELOUTPUTPATH "c:\\downloads\\Shadowkey\\models\\"
#define TEXTUREOUTPUTPATH "c:\\downloads\\Shadowkey\\ZippedTextures\\"
#define BITMAPOUTPUTPATH "c:\\downloads\\Shadowkey\\ZippedBmps\\"
#define ZIPPEDOUTPUTPATH "c:\\downloads\\Shadowkey\\Zipped\\"
#define MODELINPUTPATH "c:\\downloads\\Shadowkey\\Shadowkey Release\\system\\apps\\6r51\\"
#define MODELZTXFILESPEC "c:\\downloads\\Shadowkey\\Shadowkey Release\\system\\apps\\6r51\\*.ztx"
#define MODELZMPFILESPEC "c:\\downloads\\Shadowkey\\Shadowkey Release\\system\\apps\\6r51\\*.zmp"
#define MODELZFILESPEC "c:\\downloads\\Shadowkey\\Shadowkey Release\\system\\apps\\6r51\\*.z??"
const size_t MODEL_REC1_SIZE = 6;
const size_t MODEL_REC2_SIZE = 4;
const size_t MODEL_REC3_SIZE = 12;
const size_t MODEL_REC4_SIZE = 4;
const size_t MODEL_REC5_SIZE = 8;
struct modelindex_t
{
dword size;
dword offset;
};
struct color_t {
byte r;
byte g;
byte b;
};
struct coor_t {
word x;
word y;
word z;
};
struct uvcoor_t {
word u;
word v;
};
struct face_t {
word v[6];
};
struct modeldata_t
{
dword index;
dword fileOffset;
dword size1;
dword size2;
dword size3;
std::string name;
dword dataSize;
byte* pData;
word textureCount;
word textureWidth;
word textureHeight;
std::vector<coor_t> vertexes;
std::vector<uvcoor_t> uvcoors;
std::vector<face_t> faces;
std::vector<byte* > textures;
};
std::vector<modelindex_t> g_ModelIndex;
std::vector<modeldata_t> g_Models;
bool ReportError(const char* pMsg, ...)
{
va_list Args;
va_start(Args, pMsg);
vprintf(pMsg, Args);
printf("\n");
va_end(Args);
return false;
}
// trim from start
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
word WordSwap(const word s)
{
unsigned char b1, b2;
b1 = s & 255;
b2 = (s >> 8) & 255;
return (b1 << 8) + b2;
}
dword DwordSwap(const dword i)
{
unsigned char b1, b2, b3, b4;
b1 = i & 255;
b2 = (i >> 8) & 255;
b3 = (i >> 16) & 255;
b4 = (i >> 24) & 255;
return ((dword)b1 << 24) + ((dword)b2 << 16) + ((dword)b3 << 8) + b4;
}
bool ReadDword(FILE* pFile, dword& Output, const bool LittleEndian = true)
{
if (pFile == nullptr) return ReportError("Error: No file defined to read from!");
size_t ReadBytes = fread(&Output, 1, sizeof(dword), pFile);
if (ReadBytes != sizeof(dword)) return ReportError("Error: Only read %u of %u bytes from position 0x%X!", ReadBytes, sizeof(dword), ftell(pFile));
if (!LittleEndian) Output = DwordSwap(Output);
return true;
}
bool ReadWord(FILE* pFile, word& Output, const bool LittleEndian = true)
{
if (pFile == nullptr) return ReportError("Error: No file defined to read from!");
size_t ReadBytes = fread(&Output, 1, sizeof(word), pFile);
if (ReadBytes != sizeof(word)) return ReportError("Error: Only read %u of %u bytes from position 0x%X!", ReadBytes, sizeof(word), ftell(pFile));
if (!LittleEndian) Output = WordSwap(Output);
return true;
}
bool ParseDword(const byte* pData, dword& Output, const bool LittleEndian = true)
{
memcpy((void *)&Output, pData, sizeof(dword));
if (!LittleEndian) Output = DwordSwap(Output);
return true;
}
bool ParseWord(const byte* pData, word& Output, const bool LittleEndian = true)
{
memcpy((void *)&Output, pData, sizeof(word));
if (!LittleEndian) Output = WordSwap(Output);
return true;
}
bool HasExtension(const char* pFilename, const char* pExtension)
{
size_t extSize = strlen(pExtension);
size_t filenameSize = strlen(pFilename);
if (filenameSize < extSize) return false;
return _strnicmp(pFilename + filenameSize - extSize, pExtension, extSize) == 0;
}
bool InflateZlibBlock(byte* pOutputData, dword &OutputSize, const size_t MaxOutputSize, const byte* pInputData, const size_t InputSize, const bool Quiet = false)
{
z_stream Stream;
int Result;
Stream.zalloc = Z_NULL;
Stream.zfree = Z_NULL;
Stream.opaque = Z_NULL;
Stream.avail_in = 0;
Stream.next_in = Z_NULL;
Result = inflateInit(&Stream);
if (Result != Z_OK) return Quiet ? false : ReportError("Error: Failed to initialize the zlib stream!");
Stream.avail_in = InputSize;
Stream.avail_out = MaxOutputSize;
Stream.next_out = pOutputData;
Stream.next_in = (byte *)pInputData;
/* Decompress until deflate stream ends or end of block data */
do {
Result = inflate(&Stream, Z_NO_FLUSH);
switch (Result) {
case Z_BUF_ERROR:
if (Stream.avail_in == 0) Result = Z_STREAM_END;
break;
case Z_NEED_DICT:
Result = Z_DATA_ERROR; /* and fall through */
case Z_DATA_ERROR:
case Z_MEM_ERROR:
case Z_STREAM_ERROR:
//case Z_BUF_ERROR:
OutputSize = Stream.total_out;
inflateEnd(&Stream);
return Quiet ? false : ReportError("Error: Failed to uncompress data stream!");
};
} while (Result != Z_STREAM_END);
OutputSize = Stream.total_out;
inflateEnd(&Stream);
return true;
}
bool LoadModelIndex()
{
FILE* pFile = fopen(MODELSINDEX, "rb");
dword numModels = 0;
if (pFile == nullptr) return ReportError("Error: Failed to open models index file '%s'!", MODELSINDEX);
if (!ReadDword(pFile, numModels)) return ReportError("Error: Failed to read number of models from index file!");
g_ModelIndex.clear();
g_ModelIndex.reserve(numModels);
for (dword i = 0; i < numModels; ++i)
{
modelindex_t value;
if (!ReadDword(pFile, value.offset)) return ReportError("Error: Failed to read number model offset from index file at offset 0x%08X!", ftell(pFile));
if (!ReadDword(pFile, value.size)) return ReportError("Error: Failed to read number model size from index file at offset 0x%08X!", ftell(pFile));
g_ModelIndex.push_back(value);
}
printf("Found %d models in index file.\n", g_ModelIndex.size());
fclose(pFile);
return true;
}
bool LoadModelData(FILE* pFile, modelindex_t Index, const dword modelIndex)
{
modeldata_t Model;
Model.dataSize = Index.size;
Model.fileOffset = Index.offset;
Model.pData = new byte[Model.dataSize + 256];
Model.index = modelIndex;
if (Model.dataSize == 0)
{
g_Models.push_back(Model);
return true;
}
int seekErr = fseek(pFile, Index.offset, SEEK_SET);
if (seekErr != 0) return ReportError("%d) Error: Failed to seek to model data at offset 0x%08X!", modelIndex, Index.offset);
size_t bytesRead = fread(Model.pData, 1, Model.dataSize, pFile);
if (bytesRead != Model.dataSize) return ReportError("%d) Error: Only read %d of %d bytes from model at offset 0x%08X!", modelIndex, bytesRead, Model.dataSize, Index.offset);
g_Models.push_back(Model);
return true;
}
bool SaveRawModel(modeldata_t& Model)
{
char buffer[256];
snprintf(buffer, 255, "%s%d.dat", MODELOUTPUTPATH, Model.index);
FILE* pFile = fopen(buffer, "wb");
if (pFile == nullptr) return ReportError("Error: Failed to open file '%s' for output!", buffer);
size_t bytesWritten = fwrite(Model.pData, 1, Model.dataSize, pFile);
fclose(pFile);
if (bytesWritten != Model.dataSize) return ReportError("Error: Only wrote %d of %d bytes for model %d!", bytesWritten, Model.dataSize, Model.index);
snprintf(buffer, 255, "%s%s", MODELOUTPUTPATH, Model.name.c_str());
pFile = fopen(buffer, "wb");
if (pFile == nullptr) return ReportError("Error: Failed to open file '%s' for output!", buffer);
bytesWritten = fwrite(Model.pData, 1, Model.dataSize, pFile);
fclose(pFile);
if (bytesWritten != Model.dataSize) return ReportError("Error: Only wrote %d of %d bytes for model %d!", bytesWritten, Model.dataSize, Model.index);
return true;
}
bool SaveRawModels()
{
int successCount = 0;
for (auto &model : g_Models)
{
if (SaveRawModel(model)) ++successCount;
}
printf("Successfully saved %d of %d model data.\n", successCount, g_Models.size());
return true;
}
bool LoadModelData()
{
int successCount = 0;
FILE* pFile = fopen(MODELSHUGE, "rb");
if (pFile == nullptr) return ReportError("Error: Failed to open models data file '%s'!", MODELSHUGE);
g_Models.clear();
g_Models.reserve(g_ModelIndex.size());
for (size_t i = 0; i < g_ModelIndex.size(); ++i)
{
if (LoadModelData(pFile, g_ModelIndex[i], i)) ++successCount;
}
fclose(pFile);
printf("Successfully loaded %d of %d models!\n", successCount, g_ModelIndex.size());
return true;
}
bool LoadModelText()
{
char inputLine[256];
int errorCount = 0;
int lineCount = 0;
FILE* pFile = fopen(MODELSTXT, "rb");
if (pFile == nullptr) return ReportError("Error: Failed to open models text file '%s'!", MODELSTXT);
while (!feof(pFile))
{
char* pError = fgets(inputLine, 255, pFile);
++lineCount;
if (pError == nullptr)
{
if (feof(pFile)) break;
ReportError("Error: Failed reading line %d in models txt file!", lineCount);
++errorCount;
break;
}
char* pToken = strtok(inputLine, " ");
std::vector<char*> Tokens;
while (pToken)
{
Tokens.push_back(pToken);
pToken = strtok(nullptr, " ");
}
if (Tokens.size() < 5)
{
ReportError("Error: Only found %d tokens on line %d in models.txt file!", Tokens.size(), lineCount);
++errorCount;
continue;
}
else if (Tokens.size() > 5)
{
ReportError("Warning: Found %d tokens on line %d in models.txt file!", Tokens.size(), lineCount);
++errorCount;
}
dword index = strtoul(Tokens[0], nullptr, 10);
dword count = strtoul(Tokens[1], nullptr, 10);
dword size1 = strtoul(Tokens[2], nullptr, 10);
dword size2 = strtoul(Tokens[3], nullptr, 10);
char* pFilename = Tokens[4];
if (index < g_Models.size())
{
modeldata_t& model = g_Models[index];
model.size1 = count;
model.size2 = size1;
model.size3 = size2;
model.name = trim(std::string(pFilename));
}
else
{
ReportError("Error: Found invalid model index %u on line %d!", index, lineCount);
++errorCount;
}
}
fclose(pFile);
printf("Successfully loaded %d of %d lines from model txt file!\n", lineCount - errorCount, lineCount);
return true;
}
bool ParseModelData(modeldata_t& model)
{
word header[7];
dword sectionSizes[7];
byte* pData = model.pData;
size_t Offset = 0;
if (model.dataSize == 0) return true;
if (model.dataSize < 7 * 2) return ReportError("Error: Model %d data too small to parse 14 bytes of header data!", model.index);
ParseWord(pData + 0, header[0]);
ParseWord(pData + 2, header[1]);
ParseWord(pData + 4, header[2]);
ParseWord(pData + 6, header[3]);
ParseWord(pData + 8, header[4]);
ParseWord(pData + 10, header[5]);
ParseWord(pData + 12, header[6]);
Offset += 14;
sectionSizes[0] = 0;
sectionSizes[1] = header[1];
sectionSizes[2] = header[2] * 6;
sectionSizes[3] = header[3] * 4;
sectionSizes[4] = header[4] * 12;
sectionSizes[5] = 2;
sectionSizes[6] = header[6];
dword section2Size = (dword) sectionSizes[1] * (dword) sectionSizes[2];
if (Offset + section2Size > model.dataSize) return ReportError("Error: Model %d data overrun in vertex data (Offset 0x%08X, Size 0x%08X!", model.index, Offset, section2Size);
word numVertexes = section2Size / 6;
model.vertexes.reserve(numVertexes);
for (size_t i = 0; i < numVertexes; ++i)
{
coor_t coor;
ParseWord(pData + Offset + i * 6 + 0, coor.x);
ParseWord(pData + Offset + i * 6 + 2, coor.y);
ParseWord(pData + Offset + i * 6 + 4, coor.z);
model.vertexes.push_back(coor);
}
Offset += section2Size;
if (Offset + sectionSizes[3] > model.dataSize) return ReportError("Error: Model %d data overrun in UV data (Offset 0x%08X, Size 0x%08X!", model.index, Offset, sectionSizes[3]);
word numUVCoors = sectionSizes[3] / 4;
model.uvcoors.reserve(numVertexes);
for (size_t i = 0; i < numUVCoors; ++i)
{
uvcoor_t coor;
ParseWord(pData + Offset + i * 4 + 0, coor.u);
ParseWord(pData + Offset + i * 4 + 2, coor.v);
model.uvcoors.push_back(coor);
}
Offset += sectionSizes[3];
if (Offset + sectionSizes[4] > model.dataSize) return ReportError("Error: Model %d data overrun in face data (Offset 0x%08X, Size 0x%08X!", model.index, Offset, sectionSizes[4]);
word numFaces = sectionSizes[4] / 12;
model.faces.reserve(numFaces);
for (size_t i = 0; i < numFaces; ++i)
{
face_t face;
ParseWord(pData + Offset + i * 12 + 0, face.v[0]);
ParseWord(pData + Offset + i * 12 + 0, face.v[1]);
ParseWord(pData + Offset + i * 12 + 0, face.v[2]);
ParseWord(pData + Offset + i * 12 + 0, face.v[3]);
ParseWord(pData + Offset + i * 12 + 0, face.v[4]);
ParseWord(pData + Offset + i * 12 + 0, face.v[5]);
model.faces.push_back(face);
}
Offset += sectionSizes[4];
if (Offset + 6 > model.dataSize) return ReportError("Error: Model %d data overrun in texture header (Offset 0x%08X, Size 0x%08X!", model.index, Offset, 6);
word section5Header[3];
ParseWord(pData + Offset + 0, section5Header[0]);
ParseWord(pData + Offset + 2, section5Header[1]);
ParseWord(pData + Offset + 4, section5Header[2]);
Offset += 6;
model.textureCount = section5Header[0];
model.textureWidth = section5Header[1];
model.textureHeight = section5Header[2];
sectionSizes[5] *= (dword) section5Header[0] * (dword) section5Header[1] * (dword) section5Header[2];
if (Offset + sectionSizes[5] > model.dataSize) return ReportError("Error: Model %d data overrun in texture data (Offset 0x%08X, Size 0x%08X!", model.index, Offset, sectionSizes[5]);
for (size_t i = 0; i < model.textureCount; ++i)
{
byte* pTexture = pData + Offset + 2 * model.textureWidth * model.textureHeight * i;
model.textures.push_back(pTexture);
}
Offset += sectionSizes[5];
if (sectionSizes[6] != 1) ReportError("Warning: Model %d data section 6 size is %d.", model.index, sectionSizes[6]);
if (Offset + 2 > model.dataSize) return ReportError("Error: Model %d data overrun in footer header (Offset 0x%08X, Size 0x%08X!", model.index, Offset, 2);
word section6count;
ParseWord(pData + Offset, section6count);
Offset += 2;
dword section6Size = (dword) section6count * 6;
if (Offset + section6Size > model.dataSize) return ReportError("Error: Model %d data overrun in footer data (Offset 0x%08X, Size 0x%08X!", model.index, Offset, section6Size);
Offset += section6Size;
if (Offset != model.dataSize)
{
int leftOverBytes = model.dataSize - Offset;
ReportError("Warning: Model %d has 0x%08X bytes left over in data buffer!", model.index, leftOverBytes);
}
return true;
}
bool ParseModelData()
{
for (auto& model : g_Models)
{
ParseModelData(model);
}
return true;
}
bool CheckUVCoors()
{
int minUValue = 65536;
int maxUValue = 0;
int minVValue = 65536;
int maxVValue = 0;
int count = 0;
std::unordered_map<word, uvcoor_t> uValues;
std::unordered_map<word, uvcoor_t> vValues;
for (auto& model : g_Models)
{
if (uValues.find(model.textureWidth) == uValues.end()) uValues[model.textureWidth] = { 65535, 0 };
if (vValues.find(model.textureHeight) == vValues.end()) vValues[model.textureHeight] = { 65535, 0 };
uvcoor_t& uVal = uValues[model.textureWidth];
uvcoor_t& vVal = vValues[model.textureHeight];
for (auto& uv : model.uvcoors)
{
++count;
if (minUValue > uv.u) minUValue = uv.u;
if (minVValue > uv.v) minVValue = uv.v;
if (maxUValue < uv.u) maxUValue = uv.u;
if (maxVValue < uv.v) maxVValue = uv.v;
if (uVal.u > uv.u) uVal.u = uv.u;
if (uVal.v < uv.u) uVal.v = uv.u;
if (vVal.u > uv.v) vVal.u = uv.v;
if (vVal.v < uv.v) vVal.v = uv.v;
}
}
printf("Found %d UV coordinates.\n", count);
printf("U Coordinates = %d to %d\n", minUValue, maxUValue);
printf("V Coordinates = %d to %d\n", minVValue, maxVValue);
printf("U Coordinates (%d):\n", uValues.size());
for (auto& value : uValues)
{
word width = value.first;
uvcoor_t uv = value.second;
printf("\t%d = %d to %d\n", width, uv.u, uv.v);
}
printf("V Coordinates (%d):\n", vValues.size());
for (auto& value : vValues)
{
word width = value.first;
uvcoor_t uv = value.second;
printf("\t%d = %d to %d\n", width, uv.u, uv.v);
}
return true;
}
void TranslateColorWord(byte& r, byte& g, byte& b, const byte* pTexture)
{
r = ((pTexture[1] & 0x0f) << 4) + (pTexture[1] & 0x0f);
g = ((pTexture[0] & 0xf0) >> 4) + (pTexture[0] & 0xf0);
b = ((pTexture[0] & 0x0f) << 4) + (pTexture[0] & 0x0f);
}
dword TranslateColorIndex(byte& r, byte& g, byte& b, byte index, byte* pPalettte = nullptr)
{
if (pPalettte == nullptr) return -1;
r = pPalettte[index * 3 + 0];
g = pPalettte[index * 3 + 1];
b = pPalettte[index * 3 + 2];
return (dword)r + ((dword)g << 8) + ((dword)b << 16);
}
bool ExportTexture(const byte* pTexture, const dword width, const dword height, const dword modelIndex, const dword textureIndex, const std::string name)
{
if (height == 0 || width == 0) return true;
char OutputFilename[256];
//snprintf(OutputFilename, 250, "%s%d-%d.png", MODELOUTPUTPATH, modelIndex, textureIndex);
snprintf(OutputFilename, 250, "%s%s-%d.png", MODELOUTPUTPATH, name.c_str(), textureIndex);
byte* pOutputImage = new byte[height * width * 4 + 1024];
byte r, g, b;
size_t imageOffset = 0;
for (size_t y = 0; y < height; ++y)
{
for (size_t x = 0; x < width; ++x)
{
byte alpha = 0xff;
TranslateColorWord(r, g, b, pTexture);
if (r == 0xff && g == 0 && b == 0xff) alpha = 0;
imageOffset = (height - y - 1) * width * 4 + x * 4;
//imageOffset = y * width * 4 + x * 4;
pOutputImage[imageOffset + 0] = r;
pOutputImage[imageOffset + 1] = g;
pOutputImage[imageOffset + 2] = b;
pOutputImage[imageOffset + 3] = alpha;
pTexture += 2;
}
}
ilTexImage(width, height, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, pOutputImage);
ilSave(IL_PNG, OutputFilename);
delete[] pOutputImage;
return true;
}
bool ExportTextures()
{
for (auto& model : g_Models)
{
dword textureIndex = 0;
for (auto& texture : model.textures)
{
ExportTexture(texture, model.textureWidth, model.textureHeight, model.index, textureIndex, model.name);
++textureIndex;
}
}
return true;
}
bool ParseZtx(const byte* pData, const dword Size, const char* pFullFilename)
{
if (Size <= 0) return true;
dword numTextures = (dword) pData[0];
size_t offset = 1;
size_t width = 0x40*2;
size_t height = 0x40/2;
size_t imageSize = width * height;
char Drive[10], Dir[256], Filename[256], Extension[16];
char palFilename[256];
_splitpath(pFullFilename, Drive, Dir, Filename, Extension);
snprintf(palFilename, 255, "%s%s%s", MODELINPUTPATH, Filename, ".pal");
FILE* pFile = fopen(palFilename, "rb");
if (pFile == nullptr) return ReportError("Error: Failed to open palette file '%s' for reading!", palFilename);
byte PalData[768];
size_t bytesRead = fread(PalData, 1, 768, pFile);
fclose(pFile);
if (bytesRead != 768) return ReportError("Error: Only read %d of %d bytes from open palette file '%s' for reading!", bytesRead, 768, palFilename);
byte r, g, b;
byte index;
byte* pOutputImage = new byte[height * width * 4 + 1024];
for (dword i = 0; i < numTextures; ++i)
{
if (offset + imageSize > Size) return ReportError("Error: Buffer overflow in parsing ZTX texture #%d at offset 0x%X!", i, offset);
for (size_t y = 0; y < height; ++y)
{
for (size_t x = 0; x < width; ++x)
{
if (offset > Size) return ReportError("Error: Buffer overflow in parsing ZTX texture #%d at offset 0x%X!", i, offset);
index = pData[offset];
++offset;
TranslateColorIndex(r, g, b, index, PalData);
byte alpha = 0xff;
if (r == 0xff && g == 0 && b == 0xff) alpha = 0;
size_t imageOffset = (height - y - 1) * width * 4 + x * 4;
//imageOffset = y * width * 4 + x * 4;
pOutputImage[imageOffset + 0] = r;
pOutputImage[imageOffset + 1] = g;
pOutputImage[imageOffset + 2] = b;
pOutputImage[imageOffset + 3] = alpha;
}
}
char OutputFilename[256];
snprintf(OutputFilename, 255, "%s%s-%d.png", TEXTUREOUTPUTPATH, Filename, i);
printf("%s\n", OutputFilename);
ilTexImage(width, height, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, pOutputImage);
ilSave(IL_PNG, OutputFilename);
//offset += imageSize;
}
return true;
}
bool DecompressZFile(const char* pFilename, const char* pOutputPath)
{
char inputFilename[256];
char outputFilename[256];
dword decompressedSize;
snprintf(inputFilename, 255, "%s%s", MODELINPUTPATH, pFilename);
snprintf(outputFilename, 255, "%s%s", pOutputPath, pFilename);
FILE* pInputFile = fopen(inputFilename, "rb");
if (pInputFile == nullptr) return ReportError("Error: Failed to open file '%s' for reading!", inputFilename);
fseek(pInputFile, 0, SEEK_END);
dword compressedSize = ftell(pInputFile) - 4;
fseek(pInputFile, 0, SEEK_SET);
if (!ReadDword(pInputFile, decompressedSize)) return ReportError("Error: Failed to read 4 bytes from file '%s'!", inputFilename);
byte* pCompressedData = new byte[compressedSize + 1000];
byte* pDecompressedData = new byte[decompressedSize + 1000];
size_t bytesRead = fread(pCompressedData, 1, compressedSize, pInputFile);
if (bytesRead != compressedSize) return ReportError("Error: Only read %d of %d bytes from file '%s'!", bytesRead, compressedSize, inputFilename);
fclose(pInputFile);
dword decompressSizeResult = 0;
bool compressResult = InflateZlibBlock(pDecompressedData, decompressSizeResult, decompressedSize + 500, pCompressedData, compressedSize);
if (!compressResult) return ReportError("Error: Failed to decompressed file '%s'!", inputFilename);
FILE* pOutputFile = fopen(outputFilename, "wb");
if (pOutputFile == nullptr) return ReportError("Error: Failed to open file '%s' for output!", outputFilename);
fwrite(pDecompressedData, 1, decompressSizeResult, pOutputFile);
fclose(pOutputFile);
if (HasExtension(outputFilename, ".ztx"))
{
ParseZtx(pDecompressedData, decompressSizeResult, inputFilename);
}
delete[] pCompressedData;
delete[] pDecompressedData;
printf("Successfully decompressed file '%s'.\n", inputFilename);
return true;
}
bool DecompressZtx()
{
WIN32_FIND_DATA FindData;
HANDLE hFind = FindFirstFile(MODELZTXFILESPEC, &FindData);
if (hFind == INVALID_HANDLE_VALUE) return ReportError("Error: No files matching '%s' found!", MODELZTXFILESPEC);
do {
DecompressZFile(FindData.cFileName, TEXTUREOUTPUTPATH);
} while (FindNextFile(hFind, &FindData));
FindClose(hFind);
return true;
}
bool DecompressZmp()
{
WIN32_FIND_DATA FindData;
HANDLE hFind = FindFirstFile(MODELZMPFILESPEC, &FindData);
if (hFind == INVALID_HANDLE_VALUE) return ReportError("Error: No files matching '%s' found!", MODELZMPFILESPEC);
do {
DecompressZFile(FindData.cFileName, BITMAPOUTPUTPATH);
} while (FindNextFile(hFind, &FindData));
FindClose(hFind);
return true;
}
bool DecompressAll()
{
WIN32_FIND_DATA FindData;
HANDLE hFind = FindFirstFile(MODELZFILESPEC, &FindData);
if (hFind == INVALID_HANDLE_VALUE) return ReportError("Error: No files matching '%s' found!", MODELZFILESPEC);
do {
DecompressZFile(FindData.cFileName, ZIPPEDOUTPUTPATH);
} while (FindNextFile(hFind, &FindData));
FindClose(hFind);
return true;
}
int main()
{
ilInit();
iluInit();
ilEnable(IL_FILE_OVERWRITE);
DecompressZtx();
//DecompressZmp();
//DecompressAll();
return true;
LoadModelIndex();
LoadModelData();
LoadModelText();
//SaveRawModels();
ParseModelData();
CheckUVCoors();
ExportTextures();
return 0;
}
<file_sep>/ParseModels/ParseModels/ReadMe.txt
This program attempts to parse 3D model data from the Shadowkey MODELS.* files. It uses hard coded input and ouput
files so must be edited and recompiled in order to work on your computer.<file_sep>/ParseGlobalSpr/ParseGlobalSpr/ReadMe.txt
This program extracts image files from the Shadowkey GLOBAL.SPR file. It uses hard coded file input and
output locations so must be recompiled with Visual Studio C++ to work on your computer.<file_sep>/ParseGlobalSpr/ParseGlobalSpr/ParseGlobalSpr.cpp
// ParseGlobalSpr.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdarg.h>
#include <cstdint>
#include <string>
#include <unordered_map>
#include "d:\\src\uesp\\EsoApps\\common\\devil\\include\\IL\\il.h"
#include "d:\\src\uesp\\EsoApps\\common\\devil\\include\\IL\\ilu.h"
#include "d:\\src\uesp\\EsoApps\\common\\devil\\include\\IL\\ilut.h"
#define GLOBALSPR "c:\\Downloads\\Shadowkey\\global.spr"
#define OUTPUTPATH "c:\\Downloads\\Shadowkey\\images\\"
#define REFIMAGE1 "c:\\Downloads\\Shadowkey\\SK-narrative-COH1-2a.png"
#define REFIMAGE2 "c:\\Downloads\\Shadowkey\\images\\222a.png"
#define REFINDEX 222
#define OUTPUTPALETTE "c:\\Downloads\\Shadowkey\\global1.pal"
#define GLOBALPALETTE "c:\\Downloads\\Shadowkey\\global.pal"
#define TRANSPARENTINDEX 125
const int bytesPerPixel = 3; /// red, green, blue
const int fileHeaderSize = 14;
const int infoHeaderSize = 40;
typedef uint32_t dword;
typedef uint16_t word;
byte* pGlobalPal = nullptr;
bool ReportError(const char* pMsg, ...)
{
va_list Args;
va_start(Args, pMsg);
vprintf(pMsg, Args);
printf("\n");
va_end(Args);
return false;
}
word WordSwap(const word s)
{
unsigned char b1, b2;
b1 = s & 255;
b2 = (s >> 8) & 255;
return (b1 << 8) + b2;
}
dword DwordSwap(const dword i)
{
unsigned char b1, b2, b3, b4;
b1 = i & 255;
b2 = (i >> 8) & 255;
b3 = (i >> 16) & 255;
b4 = (i >> 24) & 255;
return ((dword)b1 << 24) + ((dword)b2 << 16) + ((dword)b3 << 8) + b4;
}
bool ReadDword(FILE* pFile, dword& Output, const bool LittleEndian)
{
if (pFile == nullptr) return ReportError("Error: No file defined to read from!");
size_t ReadBytes = fread(&Output, 1, sizeof(dword), pFile);
if (ReadBytes != sizeof(dword)) return ReportError("Error: Only read %u of %u bytes from position 0x%X!", ReadBytes, sizeof(dword), ftell(pFile));
if (!LittleEndian) Output = DwordSwap(Output);
return true;
}
bool ReadWord(FILE* pFile, word& Output, const bool LittleEndian)
{
if (pFile == nullptr) return ReportError("Error: No file defined to read from!");
size_t ReadBytes = fread(&Output, 1, sizeof(word), pFile);
if (ReadBytes != sizeof(word)) return ReportError("Error: Only read %u of %u bytes from position 0x%X!", ReadBytes, sizeof(word), ftell(pFile));
if (!LittleEndian) Output = WordSwap(Output);
return true;
}
dword TranslateColorIndex(byte& r, byte& g, byte& b, byte index, byte* pPalettte = nullptr)
{
if (pPalettte == nullptr) pPalettte = pGlobalPal;
if (pPalettte == nullptr) return -1;
r = pPalettte[index * 3 + 0];
g = pPalettte[index * 3 + 1];
b = pPalettte[index * 3 + 2];
return (dword)r + ((dword)g << 8) + ((dword)b << 16);
}
unsigned char* createBitmapFileHeader(int height, int width, int paddingSize) {
int fileSize = fileHeaderSize + infoHeaderSize + (bytesPerPixel*width + paddingSize) * height;
static unsigned char fileHeader[] = {
0,0, /// signature
0,0,0,0, /// image file size in bytes
0,0,0,0, /// reserved
0,0,0,0, /// start of pixel array
};
fileHeader[0] = (unsigned char)('B');
fileHeader[1] = (unsigned char)('M');
fileHeader[2] = (unsigned char)(fileSize);
fileHeader[3] = (unsigned char)(fileSize >> 8);
fileHeader[4] = (unsigned char)(fileSize >> 16);
fileHeader[5] = (unsigned char)(fileSize >> 24);
fileHeader[10] = (unsigned char)(fileHeaderSize + infoHeaderSize);
return fileHeader;
}
unsigned char* createBitmapInfoHeader(int height, int width) {
static unsigned char infoHeader[] = {
0,0,0,0, /// header size
0,0,0,0, /// image width
0,0,0,0, /// image height
0,0, /// number of color planes
0,0, /// bits per pixel
0,0,0,0, /// compression
0,0,0,0, /// image size
0,0,0,0, /// horizontal resolution
0,0,0,0, /// vertical resolution
0,0,0,0, /// colors in color table
0,0,0,0, /// important color count
};
infoHeader[0] = (unsigned char)(infoHeaderSize);
infoHeader[4] = (unsigned char)(width);
infoHeader[5] = (unsigned char)(width >> 8);
infoHeader[6] = (unsigned char)(width >> 16);
infoHeader[7] = (unsigned char)(width >> 24);
infoHeader[8] = (unsigned char)(height);
infoHeader[9] = (unsigned char)(height >> 8);
infoHeader[10] = (unsigned char)(height >> 16);
infoHeader[11] = (unsigned char)(height >> 24);
infoHeader[12] = (unsigned char)(1);
infoHeader[14] = (unsigned char)(bytesPerPixel * 8);
return infoHeader;
}
void generateBitmapImage(unsigned char *image, int width, int height, char* imageFileName) {
unsigned char padding[3] = { 0, 0, 0 };
int paddingSize = (4 - (width*bytesPerPixel) % 4) % 4;
unsigned char* fileHeader = createBitmapFileHeader(height, width, paddingSize);
unsigned char* infoHeader = createBitmapInfoHeader(height, width);
FILE* imageFile = fopen(imageFileName, "wb");
fwrite(fileHeader, 1, fileHeaderSize, imageFile);
fwrite(infoHeader, 1, infoHeaderSize, imageFile);
int i;
for (i = 0; i<height; i++) {
fwrite(image + (i*width*bytesPerPixel), bytesPerPixel, width, imageFile);
fwrite(padding, 1, paddingSize, imageFile);
}
fclose(imageFile);
}
bool ConvertRawPalette(byte* pRawPal, byte* pOutputPal)
{
for (size_t i = 0; i < 256; ++i)
{
byte b = ((pRawPal[i * 2] & 0x0f) << 4) + (pRawPal[i * 2] & 0x0f);
byte g = ((pRawPal[i * 2] & 0xf0) >> 4) + (pRawPal[i * 2] & 0xf0);
byte r = ((pRawPal[i*2 + 1] & 0x0f) << 4) + (pRawPal[i * 2 + 1] & 0x0f);
pOutputPal[i * 3 + 0] = r;
pOutputPal[i * 3 + 1] = g;
pOutputPal[i * 3 + 2] = b;
}
return true;
}
bool ReadImage(FILE* pFile)
{
static int imageIndex = 0;
FILE* pOutputFile;
char OutputFilename[256];
unsigned char ReadBytes[4096];
size_t OutputImageOffset = 0;
size_t OutputAlphaImageOffset = 0;
int imageReadSize = 0;
int imageY = 0;
unsigned char* pOutputImage = nullptr;
unsigned char* pOutputAlphaImage = nullptr;
word imageWidth = 0;
word imageHeight = 0;
byte RawPalette[0x200 + 100];
byte Palette[768 + 100];
++imageIndex;
long curPos = ftell(pFile);
printf("%d) Starting image at 0x%08X\n", imageIndex, curPos);
snprintf(OutputFilename, 250, "%s%d.raw", OUTPUTPATH, imageIndex);
pOutputFile = fopen(OutputFilename, "wb");
if (pOutputFile == nullptr) return ReportError("Error: Failed to open image file for output!");
if (!ReadWord(pFile, imageWidth, true)) return false;
if (!ReadWord(pFile, imageHeight, true)) return false;
imageReadSize += 4;
printf("\tFound image %d x %d\n", (int) imageWidth, (int) imageHeight);
int palBytesRead = fread(RawPalette, 1, 0x200, pFile);
if (palBytesRead != 0x200) return ReportError("\tError: Failed to read image palette data at 0x%08X!", ftell(pFile));
//int seekResult = fseek(pFile, 0x200, SEEK_CUR);
//if (seekResult != 0) return ReportError("\tError: Failed to seek past image header at 0x%08X!", ftell(pFile));
ConvertRawPalette(RawPalette, Palette);
imageReadSize += 0x200;
pOutputImage = new unsigned char[imageHeight * imageWidth * bytesPerPixel + 1024];
pOutputAlphaImage = new unsigned char[imageHeight * imageWidth * 4 + 1024];
while (!feof(pFile) && imageY < imageHeight)
{
++imageY;
//printf("\t%d) Reading line at 0x%08X\n", imageY, ftell(pFile));
word zeroSize = 0;
word lineSize = 0;
if (!ReadWord(pFile, zeroSize, true)) return false;
if (!ReadWord(pFile, lineSize, true)) return false;
imageReadSize += 4;
int readSize = lineSize - zeroSize;
//printf("\t\tZeros = 0x%X, LineSize = 0x%X, ReadSize = 0x%X\n", zeroSize, lineSize, readSize);
int bytesRead = fread(ReadBytes, 1, readSize, pFile);
imageReadSize += bytesRead;
if (bytesRead != readSize) return ReportError("\tError: Only read %d of %d bytes at at 0x%08X!", bytesRead, lineSize, ftell(pFile));
/* Flip image vertically */
OutputImageOffset = (imageHeight - imageY) * imageWidth * bytesPerPixel;
OutputAlphaImageOffset = (imageHeight - imageY) * imageWidth * 4;
for (int i = 0; i < imageWidth; ++i) {
pOutputImage[OutputImageOffset + i*bytesPerPixel] = 0xff;
pOutputImage[OutputImageOffset + i*bytesPerPixel + 1] = 0;
pOutputImage[OutputImageOffset + i*bytesPerPixel + 2] = 0xff;
pOutputAlphaImage[OutputAlphaImageOffset + i*4] = 0;
pOutputAlphaImage[OutputAlphaImageOffset + i*4 + 1] = 0;
pOutputAlphaImage[OutputAlphaImageOffset + i*4 + 2] = 0;
pOutputAlphaImage[OutputAlphaImageOffset + i*4 + 3] = 0;
}
size_t startOffset = 0;
size_t startAlphaOffset = 0;
if (zeroSize > 0)
{
startOffset = zeroSize * bytesPerPixel;
startAlphaOffset = zeroSize * 4;
}
for (int i = 0; i < readSize; ++i) {
byte r, g, b;
byte alpha = 0xff;
if (TranslateColorIndex(r, g, b, ReadBytes[i], Palette) >= 0)
{
if (r == 0xff && g == 0 && b == 0xff) alpha = 0;
pOutputImage[OutputImageOffset + startOffset + i*bytesPerPixel + 0] = b;
pOutputImage[OutputImageOffset + startOffset + i*bytesPerPixel + 1] = g;
pOutputImage[OutputImageOffset + startOffset + i*bytesPerPixel + 2] = r;
pOutputAlphaImage[OutputAlphaImageOffset + startAlphaOffset + i*4] = r;
pOutputAlphaImage[OutputAlphaImageOffset + startAlphaOffset + i*4 + 1] = g;
pOutputAlphaImage[OutputAlphaImageOffset + startAlphaOffset + i*4 + 2] = b;
pOutputAlphaImage[OutputAlphaImageOffset + startAlphaOffset + i*4 + 3] = alpha;
}
else
{
if (ReadBytes[i] == TRANSPARENTINDEX) alpha = 0;
pOutputImage[OutputImageOffset + startOffset + i*bytesPerPixel] = ReadBytes[i];
pOutputImage[OutputImageOffset + startOffset + i*bytesPerPixel + 1] = ReadBytes[i];
pOutputImage[OutputImageOffset + startOffset + i*bytesPerPixel + 2] = ReadBytes[i];
pOutputAlphaImage[OutputAlphaImageOffset + startAlphaOffset + i*4] = ReadBytes[i];
pOutputAlphaImage[OutputAlphaImageOffset + startAlphaOffset + i*4 + 1] = ReadBytes[i];
pOutputAlphaImage[OutputAlphaImageOffset + startAlphaOffset + i*4 + 2] = ReadBytes[i];
pOutputAlphaImage[OutputAlphaImageOffset + startAlphaOffset + i*4 + 3] = alpha;
}
}
//OutputImageOffset += imageWidth * bytesPerPixel;
fwrite(ReadBytes, 1, readSize, pOutputFile);
//seekResult = fseek(pFile, readSize, SEEK_CUR);
//if (seekResult != 0) return ReportError("\tError: Failed to seek past image line, 0x%X bytes at 0x%08X!", lineSize, ftell(pFile));
}
fclose(pOutputFile);
ilTexImage(imageWidth, imageHeight, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, pOutputAlphaImage);
snprintf(OutputFilename, 250, "%s%d.png", OUTPUTPATH, imageIndex);
ilSave(IL_PNG, OutputFilename);
snprintf(OutputFilename, 250, "%s%d.bmp", OUTPUTPATH, imageIndex);
generateBitmapImage(pOutputImage, imageWidth, imageHeight, OutputFilename);
delete[] pOutputImage;
delete[] pOutputAlphaImage;
curPos = ftell(pFile);
printf("\tFinished image at 0x%08X (read %d bytes)\n", curPos, imageReadSize);
return true;
}
bool TestParse()
{
FILE* pFile;
pFile = fopen(GLOBALSPR, "rb");
if (pFile == nullptr) return ReportError("Failed to open file!");
int seekResult = fseek(pFile, 0, SEEK_END);
if (seekResult != 0) return ReportError("Failed to seek to EOF!");
long fileSize = ftell(pFile);
fseek(pFile, 0, SEEK_SET);
seekResult = fseek(pFile, 0x600, SEEK_SET);
if (seekResult != 0) return ReportError("Failed to seek past file header!");
while (ReadImage(pFile))
{
}
long curPos = ftell(pFile);
long leftOverBytes = fileSize - curPos;
printf("Stopped reading images at file position 0x%08X (0x%X bytes left over).\n", curPos, leftOverBytes);
fclose(pFile);
return true;
}
bool CreatePalette()
{
ILuint ImageName1;
ILuint ImageName2;
ilGenImages(1, &ImageName1);
ilGenImages(1, &ImageName2);
ilBindImage(ImageName1);
auto loadResult1 = ilLoadImage(REFIMAGE1);
ILuint width1, height1;
width1 = ilGetInteger(IL_IMAGE_WIDTH);
height1 = ilGetInteger(IL_IMAGE_HEIGHT);
ILubyte * pImageData1 = ilGetData();
ilBindImage(ImageName2);
auto loadResult2 = ilLoadImage(REFIMAGE2);
ILuint width2, height2;
width2 = ilGetInteger(IL_IMAGE_WIDTH);
height2 = ilGetInteger(IL_IMAGE_HEIGHT);
ILubyte * pImageData2 = ilGetData();
if (!loadResult1) return ReportError("Error: Failed to load image '%s'!", REFIMAGE1);
if (!loadResult2) return ReportError("Error: Failed to load image '%s'!", REFIMAGE2);
ilBindImage(ImageName1);
//iluScale(width2, height2, 1);
width1 = ilGetInteger(IL_IMAGE_WIDTH);
height1 = ilGetInteger(IL_IMAGE_HEIGHT);
//pImageData1 = ilGetData();
ReportError("\tImage1 = %d x %d", width1, height1);
ReportError("\tImage2 = %d x %d", width2, height2);
size_t imageSize = width1 * height2;
ILubyte* pData1 = pImageData1;
ILubyte* pData2 = pImageData2;
std::unordered_map<byte, dword> ColorMap;
ReportError("Start Palette Creation..\n");
//imageSize = 1000;
dword x = 0;
dword y = 0;
dword errorCount = 0;
for (size_t i = 0; i < imageSize; ++i) {
byte grayScale = *pData2;
byte r = pData1[0];
byte g = pData1[1];
byte b = pData1[2];
dword color = (dword)r + ((dword)g << 8) + ((dword)b << 16);
//ReportError("\t(%d, %d) = #%d, (%d, %d, %d)", x, y, grayScale, r, g, b);
if (ColorMap.find(grayScale) != ColorMap.end()) {
dword origColor = ColorMap[grayScale];
if (origColor != color) {
ReportError("\tColor #%d Mismatch: 0x%06X != 0x%06X", grayScale, origColor, color);
++errorCount;
}
}
else {
ColorMap[grayScale] = color;
ReportError("\tColor #%d = 0x%06X", grayScale, color);
}
pData1 += 3;
pData2 += 3;
x++;
if (x >= width1) {
x = 0;
y++;
}
}
size_t count = ColorMap.size();
ReportError("Found %d color indexes with %d mismatches!", count, errorCount);
FILE* pFile = fopen(OUTPUTPALETTE, "wb");
for (size_t i = 0; i < 256; ++i)
{
dword color = 0;
if (ColorMap.find((byte) i) != ColorMap.end()) color = ColorMap[(byte)i];
fwrite((void *)&color, 1, 3, pFile);
}
fclose(pFile);
return true;
}
bool LoadGlobalPalette()
{
FILE* pFile = fopen(GLOBALPALETTE, "rb");
if (pFile == nullptr) return ReportError("Error: Failed to load global palette!");
pGlobalPal = new byte[768 + 16];
size_t bytesRead = fread(pGlobalPal, 1, 768, pFile);
fclose(pFile);
if (bytesRead != 768) return ReportError("Error: Only read %u of 768 bytes from global palette!", bytesRead);
return true;
}
int main()
{
ilInit();
iluInit();
ilEnable(IL_FILE_OVERWRITE);
LoadGlobalPalette();
TestParse();
//CreatePalette();
return 0;
}
| ea628649dc2897c17076bbe521507e4c1db38b1c | [
"Text",
"C++"
] | 4 | C++ | uesp/uesp-shadowkey | 444c1a8ed09756e323ea486aa3759fdd0e73828d | 7320ba238e73072f370ee539a278cccf04c161e2 | |
refs/heads/master | <file_sep>#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->createProjectButton, SIGNAL (released()), this, SLOT (createProject()));
connect(ui->openProjectButton, SIGNAL (released()), this, SLOT (openProject()));
}
void MainWindow::openProject() {
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Project"), "", tr("Project Files (*.tide)"));
//TODO: uncompress, initialize project from file
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::createProject() {
//TODO: create blank project
ui->stackedWidget->setCurrentIndex(1);
}
MainWindow::~MainWindow()
{
delete ui;
}
| 3ab65cb96b94e954aeed9c2a9ed6ce796739a5f7 | [
"C++"
] | 1 | C++ | lotide/lotide-daw | 24c389e076f0775ae5bad396ee0b79c1f10b3261 | 8dc6b1a42d331339fdc3cc9063b30b2aad6b642b | |
refs/heads/master | <file_sep># Ex.4 - Variables and Names
# - Write a comment above each line explaining to yourself in English what it does.
# - Read the .py file backwardç
# - Read the .py file out loud, saying even the characters
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are",cars,"cars avaiable.")
print("There are only",drivers,"drivers avaiable.")
print("There will be",cars_not_driven,"Empty cars today.")
print("We can transport",carpool_capacity,"people today.")
print("We have",passengers,"to carpool today.")
print("We need to put about",average_passengers_per_car,
"in each car.")
<file_sep># Learn_python
This repository aims to organize the readings and tutorials on learning Python 3.x.
> I suggest you copy the "*.ipynb" files on your desktop (including its folder content, if it is the case).
> In case you didn't install the Jupyter Notebook yet, I strongly recomend you to install the last Anaconda Package.
> You can find it here: https://www.anaconda.com/distribution/#download-section
> If you are not sure if you want to install the Anaconda and Jupyter Notebook right now, you can do as follows:
- Click the "*.ipynb" link on the repository's folder;
- Copy the web location that appears on your navigator (Ex: https://github.com/daviramalho/Learn_markdown/blob/master/ex_01/Learn-Markdown.ipynb);
- Go to the [nbviewer](https://nbviewer.jupyter.org/) homepage.
- Paste the link to check the full rendered Jupyter Notebook file on your web browser.
<file_sep>#Exercise 9 -printing, printing, printing #Use the comments here to print out
#the markdown comments on the
#Jupyter notebooks.
#------
#- Write down the code to apply more about the codes learnt;
#```python
#```code
#```
#------
#**<NAME>. \"Learn python 3 the hard way...\", 2017.
#Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
#With only the space the strings are printed into the same line.
print("Here are the days", days)
#Seems like the "\n" teels python to jump the string to the next line.
print("Here are the months", months)
#The more interesting here is that the the three double-quotes are used to
#write down any size of text inside of it. Seems like in this case the dot (".")
#should tell python to jump to the next line. You can check that by breaking the code.
#No. Try to understand why then the python jump the line...
print("""
There is something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")
<file_sep>#This will print some common text
print("I will now count my chickens.")
#Next will print some common text between the quotation mark.
#The division will be made first than the addition, thats why the result will be
#30.0
#There is a ".0" after the result because of the division, that turned the number
#into a floating number. Is it right? Not sure...
print("Hens",25+30/6)
#Next the result will be 97 because the order of the operations are:
#1st."*"
#2nd."%"
#3rd."-"
#Remember that "%" here means the rest of the division
print("Roosters",100-25*3%4)
#Next should only print common text again.
print("Now I will count the eggs.")
#Next the result should be 6.75 because the order of the operations are:
#1st."%"
#2nd."/"
#Than the operations follow the order of appearance
print(3+2+1-5+4%2-1/4+6)
#Next should print common text
print("Is it true that 3 + 2 < 5 - 7?")
#Next should print false because the result is false...
print(3+2<5-7)
print("What is 3 + 2?",3+2)
print("What is 5 - 7?",5-7)
print("Oh, that's why it's False.")
print("How about some more.")
#Next should print True or False if is is so...
print("Is it greater?",5>-2)
print("Is it greater or equal?",5>=-2)
print("Is it less or equal?",5<=-2)
<file_sep>print("Mary had a little lamb.")
#The ".format('snow')" command should add a string named "snow" inside the
#curly brackets inside the phrase.
print("Its fleece was white as {}.".format('snow')) #I just didn't understand
#how does it know to do that
#because there is any
#indication os variables
#inside that brackets
#If you print next code line instead of last one, will will receive an error
#reporting some tupla problem
#print("Its fleece was {} {} {} white as {}.".format('snow'))
#Maybe next strategy solve this tupla problem:
print("Its fleece was {} {} {} white as {}.".format('sweet','soft','and','snow'))
#So the string after ".format('')" should have the same quantity of data than
#The curly bracket inside the print string.
print("And everywhere that Mary went.")
print("."*10) #What'd that do? Repeat "." ten times.
end1="C"
end2="h"
end3="e"
end4="e"
end5="s"
end6="e"
end7="B"
end8="u"
end9="r"
end10="g"
end11="e"
end12="r"
#Watch that comma at the end. Try removing it to see what happens.
print(end1 + end2 + end3 + end4 + end5 + end6,end=' ') #I don't know what that
#",end=''"means. seems
#it's made to append
#multiple functions.
print(end7 + end8 + end9 + end10 + end11 + end12)
<file_sep>#Exercise 8 - Printing, Printing #Use the comments here to write markdonw
#comments into Jupyter Notebooks
#------
#- Here you'll learn how to print more complex string using ".format()"
#```python
#var="{} {} {} {}"
#print(var.format(x, y, z, w))
#```
#------
#**<NAME>., \"Learn Python 3 the hard way...\", 2017.
formatter = "{} {} {} {}"
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
#The strings, numbers or booleans should appear in the same order inside the
#previous defined variable.
print(formatter.format(True, False, False, True))
#Even the variable should show itself, if defined so.
print(formatter.format(formatter, formatter, formatter, formatter))
#The interesting here is the way the author uses the indentation (I think this
#is the name but I'm not sure). This is very useful and important.
print(formatter.format(
"Try your",
"Own text here",
"Maybe a poem",
"Or a song about fear"
))
<file_sep>types_of_people = 10
x = f"There are {types_of_people} types of people." #This is not a string.
#Previous one defines two variables with a numeric string, "types_of_people",
#inside another string, "x".The "f" before the string alows it to append the
#string inside the other.
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}." #There are two strings
#inside an string [1, 2]
#Now the "x" & "y" are variables so it doesn't need to use quotation mark (" or ')
#to ask to print that.
print(x)
print(y)
#Remember here the reason why to use the "f" before the string. Without it
#it wouldn't be possible to append the "x" vairable. The curly brackets ({})
#allows that to specify where the before defined variable should be appent.
print(f"I said: {x}") #This is an string inside an string [3]
print(f"I also said '{y}'") #This is an string inside an string. [4]
hilarious = False #This is an boolean value.
joke_evaluation = "Isn't that joke so funny?! {}" #This is not a string.
#Next line will add an sting inside a string, after that been write.
print(joke_evaluation.format(hilarious))
#Next will define two variables, "w" & "e".
w = "This is the left side of..."
e = "a string with right side."
#Than next one should append "w" & "e".
print(w + e)
| a38e078e3de5251c0699487eb238055483563b25 | [
"Markdown",
"Python"
] | 7 | Python | daviramalho/Learn_python | 10943cbd65b238ceb68ac328a46cd3699290731e | f4b8104b6f579519611f5400612dcaf9a383a50b | |
refs/heads/master | <file_sep># MessageForwarder
Forward (WhatsApp) messages from secondary phone to primary phone (Signal)
With WhatsApp's new Terms of Service update approaching on May 15th I thought it might be useful to have a trustworthy application that forwards messages
from a secondary phone to your primary phone so you do not miss out on (important) group chats. You might use your old phone just for WhatsApp
or other questionable apps. It stays at home all the time, that way there is not much activity on it and the collection of meaningful data can be somewhat limited.
At the moment the primary objective is to just forward messages from (group) chats to Signal.
This is what I personally need the most since it is utopian to expect all your work/uni/school/... colleagues to switch to Signal.
But if demand is there I would love to implement more options like WhatsApp to Telegram, Messenger to Signal, etc. and a reply funciton.
If you are interested in contributing to this project let me know, I would greatly appreciate your help!
Related articles:
(en) https://www.bbc.com/news/technology-55683745
(de) https://www.bayern3.de/whatsapp-datenschutz-aenderung-zustimmen-facebook-dsgvo
<file_sep>package com.example.messageforwarder.activities;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.messageforwarder.R;
import com.example.messageforwarder.onclicklisteners.AddForwardRule;
import com.example.messageforwarder.onclicklisteners.WhatsappToSignal;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class MainActivity extends AppCompatActivity {
public static Context mainContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainContext = getApplicationContext();
//topbar layout
setTopBarLayout();
//icons layout
ImageView arrowRight = findViewById(R.id.arrow_right);
ImageView whatsapp = findViewById(R.id.whatsappIcon);
ImageView signal = findViewById(R.id.signalIcon);
TextView whatsappToSignalLayer = findViewById(R.id.whatsappToSignalLayer);
setForwardRuleLayout(arrowRight, whatsapp, signal, whatsappToSignalLayer);
//add forward rule (display)
Boolean optionsDisplayed = new Boolean(false);
FloatingActionButton addForwardRuleBtn = findViewById(R.id.addForwardRule);
addForwardRuleBtn.setOnClickListener(new AddForwardRule(optionsDisplayed, arrowRight, whatsapp, signal, whatsappToSignalLayer));
//Rule:WhatsApp to Signal
whatsappToSignalLayer.setOnClickListener(new WhatsappToSignal(mainContext));
}
private int getScreenHeight() {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
return metrics.heightPixels;
}
private int getScreenWidth() {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
return metrics.widthPixels;
}
private void setTopBarLayout() {
int screenHeight = getScreenHeight();
TextView topBar = findViewById(R.id.topBar);
RelativeLayout.LayoutParams topBarParams = (RelativeLayout.LayoutParams)topBar.getLayoutParams();
topBarParams.height = screenHeight / 6;
topBar.setTextSize(screenHeight/(float)60);
}
private void setForwardRuleLayout(ImageView arrowRight, ImageView whatsapp, ImageView signal, TextView whatsappToSignalLayer) {
int screenHeight = getScreenHeight();
//load icons and set their layout
//arrow
RelativeLayout.LayoutParams iconParams = (RelativeLayout.LayoutParams)arrowRight.getLayoutParams();
iconParams.height = screenHeight / 9;
iconParams.width = getScreenHeight() / 9;
//whatsapp
iconParams = (RelativeLayout.LayoutParams)whatsapp.getLayoutParams();
iconParams.height = screenHeight / 9;
iconParams.width = getScreenHeight() / 9;
//signal
iconParams = (RelativeLayout.LayoutParams)signal.getLayoutParams();
iconParams.height = screenHeight / 9;
iconParams.width = getScreenHeight() / 9;
//WhatsApp to Signal Layer
iconParams = (RelativeLayout.LayoutParams)whatsappToSignalLayer.getLayoutParams();
iconParams.height = screenHeight / 9;
iconParams.width = screenHeight / 3 + 30; //30sp offset for margin between icons --> make relative
}
}
<file_sep>package com.example.messageforwarder.activities;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.messageforwarder.R;
public class NewRule extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_rule);
}
}
<file_sep>rootProject.name='MessageForwarder'
include ':app'
<file_sep>package com.example.messageforwarder.onclicklisteners;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class AddForwardRule implements View.OnClickListener {
private Boolean optionsDisplayed;
private ImageView arrowRight;
private ImageView whatsapp;
private ImageView signal;
private TextView whatsappToSignalLayer;
public AddForwardRule(Boolean optionsDisplayed, ImageView arrowRight, ImageView whatsapp,
ImageView signal, TextView whatsappToSignalLayer) {
this.optionsDisplayed = optionsDisplayed;
this.arrowRight = arrowRight;
this.whatsapp = whatsapp;
this.signal = signal;
this.whatsappToSignalLayer = whatsappToSignalLayer;
}
@Override
public void onClick(View v) {
displayWhatsappToSignal();
}
private void displayWhatsappToSignal() {
//set icon visibility based on if already displayed
if (optionsDisplayed) {
arrowRight.setVisibility(View.INVISIBLE);
whatsapp.setVisibility(View.INVISIBLE);
signal.setVisibility(View.INVISIBLE);
whatsappToSignalLayer.setVisibility(View.INVISIBLE);
whatsappToSignalLayer.setClickable(false);
} else {
arrowRight.setVisibility(View.VISIBLE);
whatsapp.setVisibility(View.VISIBLE);
signal.setVisibility(View.VISIBLE);
whatsappToSignalLayer.setVisibility(View.VISIBLE);
whatsappToSignalLayer.setClickable(true);
}
optionsDisplayed = !optionsDisplayed;
}
}
| af957ee264b7ae6451dcd87be2867e6e2d4c85e0 | [
"Markdown",
"Java",
"Gradle"
] | 5 | Markdown | mrinfinidy/MessageForwarder | 38ea6bd6e74a9410923ed3e7c1ed84f410141420 | bcec21d48b0ca59c27aecf1792555149d761349d | |
refs/heads/master | <file_sep>const highScoresList = document.getElementById('high-scores-list');
const highScores = JSON.parse(localStorage.getItem("highScores")) || [];
const title = document.getElementById('final-score');
if (highScores.length == 0) {
const p = document.createElement("p");
p.classList.add("no-score");
p.textContent = "Pas encore de score enregistré !";
title.parentNode.insertBefore(p, title.nextSibling);
} else {
const noScore = document.getElementsByClassName('no-score');
if (noScore.length != 0) {
noScore.parentNode.removeChild(noScore);
}
}
highScoresList.innerHTML =
highScores
.map( score => {
return `<li class="high-score">${score.name} - ${score.score}</li>`;
})
.join("");<file_sep>const username = document.getElementById('username');
const saveScoreButton = document.getElementById('save-score-button');
const mostRecentScore = localStorage.getItem('mostRecentScore');
const finalScore = document.getElementById('final-score');
// Retourne un tableau vide si pas de highScore dans le localStorage ou le tableau des meilleurs scores. JSON.parse() transforme une string en objet JavaScript.
const highScores = JSON.parse(localStorage.getItem('highScores')) || [];
const MAX_HIGH_SCORES = 5;
finalScore.innerText = mostRecentScore;
username.addEventListener('keyup', () => {
// Le bouton Enregistrer ne doit être actif que si l'utilisateur a renseigné son nom
saveScoreButton.disabled = !username.value;
})
saveScoreButton.addEventListener('click', event => {
event.preventDefault();
const score = {
score: mostRecentScore,
name: username.value
}
highScores.push(score); // On ajoute le score au tableau des meilleures scores
highScores.sort( (a, b) => {
return b.score - a.score; // Permet de mettre les scores les plus hauts en premier
})
highScores.splice(5); // On ne garde que les 5 scores les plus hauts
localStorage.setItem('highScores', JSON.stringify(highScores)); // JSON.stringify() transforme un objet JavaScript en string
window.location.assign("/");
})<file_sep>// VARIABLES
const question = document.getElementById('question');
const choices = Array.from(document.getElementsByClassName('choice-text'));
const progressText = document.getElementById('progress-text');
const scoreText = document.getElementById('score');
const progressBarFull = document.getElementById('progress-bar-full');
const loader = document.getElementById('loader');
const game = document.getElementById('game');
let currentQuestion = {};
let acceptingAnswers = false;
let score = 0;
let questionCounter = 0;
let availableQuestions = [];
let questions = [];
// INITIALISATION
fetch("https://opentdb.com/api.php?amount=10&difficulty=easy&type=multiple&encode=base64")
.then( response => {
return response.json();
})
.then( loadedQuestions => {
questions = loadedQuestions.results.map( loadedQuestion => {
const formattedQuestion = {
question: decodeURIComponent(escape(window.atob(loadedQuestion.question)))
}
const answerChoices = [ ...loadedQuestion.incorrect_answers];
for (let i = 0; i < answerChoices.length; i++) {
answerChoices[i] = choice = decodeURIComponent(escape(window.atob(answerChoices[i])));
}
formattedQuestion.answer = Math.floor(Math.random() * 3) + 1;
answerChoices.splice(formattedQuestion.answer - 1, 0, decodeURIComponent(escape(window.atob(loadedQuestion.correct_answer))));
answerChoices.forEach( (choice, index) => {
formattedQuestion["choice" + (index + 1)] = choice;
})
return formattedQuestion;
})
startGame();
})
.catch( error => {
alert("ERREUR ! Les questions n'ont pas pu être chargées. Merci de retourner à l'accueil et d'essayer de lancer une nouvelle partie !");
})
// CONSTANTES
const CORRECT_BONUS = 10;
const MAX_QUESTIONS = 10;
// FONCTIONS
startGame = () => {
questionCounter = 0;
score = 0;
availableQuestions = [...questions]; // Crée une copie du tableau de questions dans le tableau des questions disponibles. On fait pas availableQuestions = questions car sinon, en changeant le tableau availableQuestions, on changerait aussi le tableau d'origine
getNewQuestion();
game.classList.remove("hidden");
loader.classList.add("hidden");
}
getNewQuestion = () => {
if (availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) {
localStorage.setItem('mostRecentScore', score);
return window.location.assign('/end.html');
}
questionCounter++;
progressText.innerText = `Question ${questionCounter}/${MAX_QUESTIONS}`; // = progressText.innerText = "Question" + questionCounter + "/" + MAX_QUESTIONS;
progressBarFull.style.width = (questionCounter / MAX_QUESTIONS) * 100 + "%";
const questionIndex = Math.floor(Math.random() * availableQuestions.length);
currentQuestion = availableQuestions[questionIndex];
question.innerText = currentQuestion.question;
choices.forEach( choice => {
const number = choice.dataset['number']; // Récupéré grâce à l'attribut data-number dans le HTML
choice.innerText = currentQuestion['choice' + number] // On utilise la syntaxe [] au lieu de . pour pouvoir concaténer le numéro correspondant au choix
})
availableQuestions.splice(questionIndex, 1); // On supprime la question qui vient d'être posée du tableau des questions disponibles
acceptingAnswers = true;
}
choices.forEach(choice => {
choice.addEventListener('click', event => {
if (!acceptingAnswers) {
return;
};
acceptingAnswers = false;
const selectedChoice = event.target; // event.target est égal au <p class="choice-text"> du choix sélectionné
const selectedAnswer = selectedChoice.dataset["number"];
const classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect';
selectedChoice.parentElement.classList.add(classToApply);
if (classToApply == 'correct') {
incrementScore(CORRECT_BONUS);
}
setTimeout( () => {
selectedChoice.parentElement.classList.remove(classToApply);
getNewQuestion();
}, 1000);
})
})
incrementScore = number => {
score += number;
scoreText.innerText = score;
} | c59ab1e795e5aa6460c1d9cc76a13ffb4e079456 | [
"JavaScript"
] | 3 | JavaScript | Baptiste-76/Quick-Quiz | 08aae2c782d95e751e4a940523a93ffd01339c7c | 6ac9acdd9fdc528bd6967541f646e4e81958af5e | |
refs/heads/master | <repo_name>Fapiko/aerospike-test<file_sep>/main.go
package main
import (
"github.com/aerospike/aerospike-client-go"
"encoding/gob"
"bytes"
"log"
)
type TestObj struct {
Hello string
World string
pvtProperty string
}
func main() {
client, err := aerospike.NewClient("127.0.0.1", 3000)
panicOnError(err)
testObj := &TestObj{
Hello: "Arnold",
World: "Facepalmer",
pvtProperty: "Tralalala",
}
var encoded bytes.Buffer
encoder := gob.NewEncoder(&encoded)
encoder.Encode(testObj)
bins := aerospike.BinMap{
"test1": encoded.Bytes(),
"test2": 42,
}
key, err := aerospike.NewKey("test", "aerospike", "key")
panicOnError(err)
err = client.Put(nil, key, bins)
panicOnError(err)
// read it back!
rec, err := client.Get(nil, key)
panicOnError(err)
test1 := rec.Bins["test1"].([]byte)
buf := bytes.NewBuffer(test1)
var decodedObj TestObj
decoder := gob.NewDecoder(buf)
err = decoder.Decode(&decodedObj)
log.Println(decodedObj)
log.Println(decodedObj.pvtProperty)
}
func panicOnError(err error) {
if err != nil {
panic(err)
}
}
| 9a62b512bc9327c31c971bff148dad2859502f08 | [
"Go"
] | 1 | Go | Fapiko/aerospike-test | cda4d97bdfef69f7f529b5e213a9e3c41c6fa1f0 | cd365e3edef2268c5b9ca61de663051738a6dd4c | |
refs/heads/master | <file_sep>* A collection of vaarious tools
*** Conteents
1 Snow
This F90 program will generate a variety of line-fractals including the famous von-Koch Snowflake Curve.
However this is only as a test case. In Reality it is the prototype driver for enhancing [Danfront](https://github.com/dannyk96/danfe), an advancing front based unstructutred triangle mesh generator for finite elemeents.
2 Stations
An f90 test of data structures
3 flow
Flownet under dams - used as an Undergraduate teaching example c. 1996
<file_sep>#!/bin/bash
echo " build the 2 programs:"
echo " 1. flow.f90 the analysis code"
echo " This INCLUDEs solver.f90"
echo " 2. contour_ps.f90 "
echo " This takes the .pl mesh file and the flow.out file and produces"
echo " a postscript file called plotfile.ps"
echo 'To run you need a mesh in a file called <name>.pl'
echo ' and also a small file with the material properties in called <name>.in'
echo Note that currently this is hardcode as wall2.pl and wall2.in
gfortran -o contour_ps contour_ps.f90
gfortran -o flow flow.f90
echo
echo
echo " now run ./flow"
echo "the post-process with ./countour_ps"
#echo after running flow and subsequently contour_ps, try
B
#echo 'gs -sDEVICE=pdfwrite -sOutputFile="output.pdf" -dNOPAUSE -dEPSCrop -c "<</Orientation 2>> setpagedevice" -f "plotfile.ps" -c quit'
#echo or
#echo 'gs -dEPSCrop -c "<</Orientation 2>> setpagedevice" -f "plotfile.ps" -c quit'
<file_sep>These are a set of short `Fortran` programs written by __<NAME>__ (_<EMAIL>_).
They were written in support of teaching the second year undergraduate programming course for Civil Enginering Students at the University of Manchester, back in the mid 1990s
They all demenstate features in Fortan 90 that take it beyond the limitations of the ancient FORTRAN77 standard, including
_data structures_, _runtime allocatable arrays_, _recursive functions_, etc.
<file_sep>#!/bin/bash
#
# Build script for snow.exe
# Too small to bother with a makefile :-)
# <NAME> 31/03/15
# <EMAIL>
#
rm *.o *.mod
#FCC=$(FC)
F90=gfortran
$F90 -c -g segments.f90
$F90 -cpp -DPGPLOT -c -g plot.f90
$F90 -c -g snow.f90
echo 'note that we do not use afront.f90 (in a future release)'
$F90 -o snow snow.o segments.o plot.o -L$HOME/Documents/danfe/pgplot -lpgplot -lX11
echo try this:
echo 'echo -e "/XWIN\n3\n2\n.4\n3\n\n\n" | ./snow'
# notes on Salford FTN95
# ftn95 segments.f90 & ftn95 /CFPP /DEFINE SALFORD 1 plot.f90 & ftn95 snow.f90 /LINK
<file_sep>
# For Open MPI use, e.g., OMPI_FC=gfortran and for MPICH2, e.g., -f90=gfortran
export PATH := /usr/local/gfortran-bin/bin:$(PATH)
export LIBRARY_PATH := /usr/lib/x86_64-linux-gnu
FC= mpif90.mpich -fcoarray=lib
CAFLIB=-L /home/dan/git/opencoarrays/mpi -lcaf_mpi
.PHONY: clean
default: hw-coarray
APPS= hello hello_s from_g95 hw-coarray
all: $(APPS)
hello_s: hello.f90
gfortran -fcoarray=single -o $@ $^
hello: hello.f90
$(FC) $< -o $@ $(CAFLIB) -lmpich
from_g95: from_g95.f90
$(FC) $< -o $@ $(CAFLIB) -lmpich
hw-coarray: hw-coarray.f90
$(FC) $< -o $@ $(CAFLIB) -lmpich
clean:
-rm $(APPS)
| d497198671eb32e9d1b059ba3aa1887cb97635ba | [
"Markdown",
"Makefile",
"Shell"
] | 5 | Markdown | dannyk96/sandbox | 9c18ca9b01117383a22ad53dc19041e6acfdc19c | 6fcbe3c9bac38ce79ef31eb89c794dc6362c3760 | |
refs/heads/master | <repo_name>Anusha-Vijay/MQTT<file_sep>/src/main/java/org/mqtt/api/MessageBean.java
package org.mqtt.api;
/**
* Created by Anushavijay on 10/7/16.
*/
public class MessageBean {
}
| 0edfdfda76468ed9fbf785f3f6bf17ab5f5b6af4 | [
"Java"
] | 1 | Java | Anusha-Vijay/MQTT | 29325a48dc24afea33c41976d5457b2260fe487f | 1e6f448b64185a46acaa80e32cc6633b45c50f04 | |
refs/heads/main | <repo_name>vivekchauhan12000/frontend_react<file_sep>/src/components/DonorForm.js
import React,{useState} from 'react'
import {useHistory} from "react-router-dom"
import Axios from "axios"
const url="https://apiplasma.herokuapp.com/api/Donor"
function DonorForm() {
let history = useHistory();
const[data,setData]=useState({
name:"",
email:"",
phone:"",
city:"",
address:"",
bloodType:"",
covidStatus:"",
hadCovid:""
});
const handleOnSubmit=(e)=>{
const newData={...data}
newData[e.target.id]=e.target.value
setData(newData);
console.log(newData);
}
const onsubmit=(e)=>{
e.preventDefault();
Axios.post(url,{
name:data.name,
location:data.city,
address:data.address,
phone:data.phone,
email:data.email,
bloodType:data.bloodType,
covidStatus:data.covidStatus,
hadCovid:data.hadCovid
}).then(res=>{
console.log(res.data);
});
setData({ name:"",
email:"",
phone:"",
city:"",
address:"",
bloodType:"",
covidStatus:"",
hadCovid:""})
history.push('/')
}
return (
<div className="container">
<form>
<h2>Donor Form</h2>
<div className="mb-3">
<h5>Email</h5>
<input type="email" onChange={(e)=>handleOnSubmit(e)} value={data.email} className="form-control" id="email"/>
</div>
<div className="mb-3">
<h5>Name</h5>
<input type="text" onChange={(e)=>handleOnSubmit(e)} value={data.name} className="form-control" id="name"/>
</div>
<div className="mb-3">
<h5>Number</h5>
<input type="number" onChange={(e)=>handleOnSubmit(e)} value={data.phone} className="form-control" id="phone"/>
</div>
<div className="mb-3">
<h5>City</h5>
<input type="text" onChange={(e)=>handleOnSubmit(e)} value={data.city} className="form-control" id="city"/>
</div>
<div className="mb-3">
<h5>address</h5>
<input type="text" onChange={(e)=>handleOnSubmit(e)} value={data.address} className="form-control" id="address"/>
</div>
<div className="input-group mb-3">
<label class="input-group-text">Blood Group</label>
<select class="form-select" id="bloodType" required onChange={(e)=>handleOnSubmit(e)} value={data.bloodType}>
<option selected>Blood Group</option>
<option value="A+">A+</option>
<option value="A-">A-</option>
<option value="B+">B+</option>
<option value="B-">B-</option>
<option value="AB+">AB+</option>
<option value="AB-">AB-</option>
<option value="O+">O+</option>
<option value="O-">O-</option>
</select>
</div>
<div class="input-group mb-3">
<label class="input-group-text">covidStatus</label>
<select class="form-select" id="covidStatus" required onChange={(e)=>handleOnSubmit(e)} value={data.covidStatus}>
<option selected>covidStatus</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
<div class="input-group mb-3">
<label class="input-group-text">Had covid</label>
<select class="form-select" id="hadCovid" required onChange={(e)=>handleOnSubmit(e)} value={data.hadCovid}>
<option selected>had covid in past</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
<button type="submit" className="btn btn-primary" onClick={onsubmit}>Submit</button>
</form>
</div>
)
}
export default DonorForm
<file_sep>/src/Pages/Home.js
import React from 'react'
import DonorTab from "../components/DonorTab"
import Regist from "../components/RegiTab"
import Footer from "../components/Footer"
function Home() {
return (
<div className="container">
<div className="container row justify-content-center">
<div className="col"><DonorTab/></div>
<div className="col"><Regist/></div>
</div>
<Footer/>
</div>
)
}
export default Home
<file_sep>/src/components/RegiTab.js
import React from 'react'
import {useHistory} from "react-router-dom"
function RegiTab() {
let history = useHistory();
const redirect=()=>{
history.push('/DonorDetails');
}
return (
<div className="container">
<div className="bg-light p-5 rounded">
<h1>Register</h1>
<p className="lead">Your Plasma donation can save someone life</p>
<button className="btn btn-lg btn-danger" onClick={redirect}>Register as Donor»</button>
</div>
</div>
)
}
export default RegiTab
<file_sep>/src/components/DonorList.js
import React,{useState,useEffect} from 'react'
import Card from "../components/ListCard";
export default function DonorList() {
const [data, setData] = useState([]);
const [bloodGroup,setbloodGroup]=useState([""]);
const [city,setCity]=useState([""]);
const handleOnSubmit=(e)=>{
const newData=e.target.value
setbloodGroup(newData);
}
const Searchcity=(e)=>{
const newData=e.target.value
setCity(newData);
}
useEffect( async () => {
const response = await fetch("https://apiplasma.herokuapp.com/api/Donor");
const data = await response.json();
console.log(data);
await setData(data);
},[]);
return (
<div className="container">
<h2>Donor Search</h2>
<div>
<div className="input-group mb-3">
<label className="input-group-text">Search
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-search" viewBox="0 0 16 16">
<path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
</svg>
</label>
<select className="form-select" id="covidStatus" required onChange={(e)=>handleOnSubmit(e)} value={bloodGroup}>
<option selected value="">Blood Group</option>
<option value="A+">A+</option>
<option value="A-">A-</option>
<option value="B+">B+</option>
<option value="B-">B-</option>
<option value="AB+">AB+</option>
<option value="AB-">AB-</option>
<option value="O+">O+</option>
<option value="O-">O-</option>
</select>
<input type="text" placeholder="City" onChange={(e)=>Searchcity(e)} value={city} className="form-control" aria-label="Text input with dropdown button" />
</div>
</div>
{ data.filter((val)=>{
if(bloodGroup==""){
return val
}else if (val.bloodType.toLowerCase()==bloodGroup.toLowerCase()){
return val
}
}).filter((val)=>{
if(city==""){
return val
}else if (val.location.toLowerCase()==city.toLowerCase()){
return val
}
}).map((Donor) => (
<div key={Donor._id}> <Card name={Donor.name} loc={Donor.location} blood={Donor.bloodType} contact={Donor.phone}/></div>
))}
</div>
)
}
<file_sep>/src/components/Header.js
import React from 'react'
import {BrowserRouter as Router,Link} from "react-router-dom"
function Header() {
return (
<Router>
<div style={{background:"#0093E9",
backgroundImage: "linear-gradient(160deg, #0093E9 0%, #80D0C7 100%)"
}}>
<nav className="navbar navbar-expand-md navbar-light mb-4">
<div className="container-fluid">
<a className="navbar-brand" style={{color:"white"}} href="/">Logo Name</a>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon" />
</button>
<div className="collapse navbar-collapse" id="navbarCollapse">
<ul className="navbar-nav me-auto mb-2 mb-md-0">
<li className="nav-item">
<a style={{color:"white"}} className="nav-link active" aria-current="page" href="/Donorlist">
<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="currentColor" class="bi bi-droplet" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M7.21.8C7.69.295 8 0 8 0c.109.363.234.708.371 1.038.812 1.946 2.073 3.35 3.197 4.6C12.878 7.096 14 8.345 14 10a6 6 0 0 1-12 0C2 6.668 5.58 2.517 7.21.8zm.413 1.021A31.25 31.25 0 0 0 5.794 3.99c-.726.95-1.436 2.008-1.96 3.07C3.304 8.133 3 9.138 3 10a5 5 0 0 0 10 0c0-1.201-.796-2.157-2.181-3.7l-.03-.032C9.75 5.11 8.5 3.72 7.623 1.82z"/>
<path fill-rule="evenodd" d="M4.553 7.776c.82-1.641 1.717-2.753 2.093-3.13l.708.708c-.29.29-1.128 1.311-1.907 2.87l-.894-.448z"/>
</svg>Plasma Donor</a>
</li>
<li className="nav-item">
<a style={{color:"white"}} className="nav-link active" aria-current="page" href="/DonorDetails">
<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="currentColor" class="bi bi-person-plus-fill" viewBox="0 0 16 16">
<path d="M1 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H1zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/>
<path fill-rule="evenodd" d="M13.5 5a.5.5 0 0 1 .5.5V7h1.5a.5.5 0 0 1 0 1H14v1.5a.5.5 0 0 1-1 0V8h-1.5a.5.5 0 0 1 0-1H13V5.5a.5.5 0 0 1 .5-.5z"/>
</svg>
Donate Plasma</a>
</li>
<li className="nav-item">
<a style={{color:"white"}} className="nav-link active" aria-current="page" href="/ContactUs">
<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="currentColor" class="bi bi-person-lines-fill" viewBox="0 0 16 16">
<path d="M6 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm-5 6s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H1zM11 3.5a.5.5 0 0 1 .5-.5h4a.5.5 0 0 1 0 1h-4a.5.5 0 0 1-.5-.5zm.5 2.5a.5.5 0 0 0 0 1h4a.5.5 0 0 0 0-1h-4zm2 3a.5.5 0 0 0 0 1h2a.5.5 0 0 0 0-1h-2zm0 3a.5.5 0 0 0 0 1h2a.5.5 0 0 0 0-1h-2z"/>
</svg>
Contact Us</a>
</li>
</ul>
</div>
</div>
</nav>
</div>
</Router>
)
}
export default Header
<file_sep>/src/components/DonorTab.js
import React from 'react'
import {useHistory} from "react-router-dom"
function DonorTab() {
let history = useHistory();
const redirect=()=>{
history.push('/Donorlist');
}
return (
<div className="container">
<div className="bg-light p-5 rounded">
<h1>Plasma Donor</h1>
<p className="lead">Seach for donor near you location and contact it by given detail.Please register your Patient by filling the form given in link</p>
<button className="btn btn-lg btn-primary" onClick={redirect}>Search For Donor »</button>
</div>
</div>
)
}
export default DonorTab
<file_sep>/src/App.js
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import Header from "./components/Header"
import Home from "./Pages/Home"
import Footer from "./components/Footer"
import DonorForm from "./components/DonorForm"
import DonorList from "./components/DonorList"
import ContactUs from "./Pages/Contact"
import PatientForm from "./components/PatientForm"
import './App.css';
function App() {
return (
<Router>
<div className="App">
<Header/>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/DonorDetails" component={DonorForm} />
<Route exact path="/Donorlist" component={PatientForm}/>
<Route exact path="/ContactUs" component={ContactUs}/>
<Route exact path="/Donors" component={DonorList}/>
</Switch>
</div>
</Router>
);
}
export default App;
<file_sep>/src/components/PatientForm.js
import React,{useState} from 'react'
import {useHistory} from "react-router-dom"
import Axios from "axios"
import Popup from 'reactjs-popup';
const url="https://apiplasma.herokuapp.com/api/Patient"
function PatientForm() {
let history = useHistory();
//login logic
const[login,setlogin]=useState("");
const [islogin,setis]=useState("false");
const handleOnLogin=(e)=>{
const newLogin=e.target.value
setlogin(newLogin);
console.log(newLogin);
}
const onlogin=(e)=>{
e.preventDefault();
try {
Axios.post("https://apiplasma.herokuapp.com/api/Registered/login",{
phone:login,
}).then(res=>{
setis(res.data);
if(res.data=="true"){
history.push("/Donors")
}else{
history.push("/")
}
console.log(res.data);
})
} catch (error) {
console.log(error);
}
}
//OTP sending
const [OTP,setOTP]=useState("");
const handleOnOTP=(e)=>{
const newOTPcheck=e.target.value
setOTP(newOTPcheck);
console.log(newOTPcheck);
}
const onOTP=(e)=>{
e.preventDefault();
try {
Axios.post("https://api.globalshapersjaipur.com/otp/validate",{
"phone":String(data.phone),
"otp":String(OTP)
},{headers}).then(res=>{
console.log(res.status);
if (res.status==200) {
try {
Axios.post("https://apiplasma.herokuapp.com/api/Registered",{
phone:data.phone,
}).then(res=>{
console.log(res.data);
})
}catch (error) {
console.log(error);
}
}
else {
console.log("Please try again")
}
})
} catch (error) {
console.log(error);
}
}
//form data
const[data,setData]=useState({
name:"",
age:"",
sex:"",
city:"",
Hospital:"",
phone:"",
email:"",
bloodType:""
});
const handleOnSubmit=(e)=>{
const newData={...data}
newData[e.target.id]=e.target.value
setData(newData);
console.log(newData);
}
const onsubmit=(e)=>{
e.preventDefault();
Axios.post(url,{
name:data.name,
Hospital:data.Hospital,
phone:data.phone,
bloodType:data.bloodType,
}).then(res=>{
console.log(res.data);
});
// history.push('/Donors')
}
const otpurl="https://api.globalshapersjaipur.com/otp/generate"
const headers = {
'Content-Type': 'application/json',
'Accept':'*/*'
};
const otpSend=()=>{ Axios.post(
otpurl,
{
"phone":String(data.phone)
},
{headers}
).then(response => {
console.log("Success ========>", response);
})
.catch(error => {
console.log("Error ========>", error);
}
)
}
return (
<div>
<div className="container">
<form className="bg-light p-5 rounded">
<h2>Sign in with number</h2>
<div className="col-auto">
<label className="visually-hidden">Phone Number</label>
<input type="Number" className="form-control" id="Phone" onChange={(e)=>handleOnLogin(e)} value={login} placeholder="Registered Phone number"/>
</div>
<div className="col-auto">
<button type="submit" onClick={onlogin} className="btn btn-primary mb-3">
Sign in
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-box-arrow-in-right" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M6 3.5a.5.5 0 0 1 .5-.5h8a.5.5 0 0 1 .5.5v9a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5v-2a.5.5 0 0 0-1 0v2A1.5 1.5 0 0 0 6.5 14h8a1.5 1.5 0 0 0 1.5-1.5v-9A1.5 1.5 0 0 0 14.5 2h-8A1.5 1.5 0 0 0 5 3.5v2a.5.5 0 0 0 1 0v-2z"/>
<path fill-rule="evenodd" d="M11.854 8.354a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H1.5a.5.5 0 0 0 0 1h8.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3z"/>
</svg>
</button>
</div>
</form>
<form>
<h2>Register</h2>
<div className="mb-3">
<h5>Name</h5>
<input type="text" required onChange={(e)=>handleOnSubmit(e)} required value={data.name} className="form-control" id="name" required/>
</div>
<div className="mb-3">
<h5>Number</h5>
<input type="number" onChange={(e)=>handleOnSubmit(e)} required value={data.phone} className="form-control" id="phone" required/>
</div>
<div className="mb-3">
<h5>Hospital</h5>
<input type="text" onChange={(e)=>handleOnSubmit(e)} required value={data.Hospital} className="form-control" id="Hospital" required/>
</div>
<div className="mb-3">
<h5>BloodType</h5>
<input type="text" onChange={(e)=>handleOnSubmit(e)} required value={data.bloodType} className="form-control" id="bloodType" required/>
</div>
<button type="submit" className="btn btn-primary" onClick={onsubmit}>Register
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-award" viewBox="0 0 16 16">
<path d="M9.669.864 8 0 6.331.864l-1.858.282-.842 1.68-1.337 1.32L2.6 6l-.306 1.854 1.337 1.32.842 1.68 1.858.282L8 12l1.669-.864 1.858-.282.842-1.68 1.337-1.32L13.4 6l.306-1.854-1.337-1.32-.842-1.68L9.669.864zm1.196 1.193.684 1.365 1.086 1.072L12.387 6l.248 1.506-1.086 1.072-.684 1.365-1.51.229L8 10.874l-1.355-.702-1.51-.229-.684-1.365-1.086-1.072L3.614 6l-.25-1.506 1.087-1.072.684-1.365 1.51-.229L8 1.126l1.356.702 1.509.229z"/>
<path d="M4 11.794V16l4-1 4 1v-4.206l-2.018.306L8 13.126 6.018 12.1 4 11.794z"/>
</svg>
</button>
</form>
<div style={{margin:"10px"}}>
<Popup trigger={<button type="submit" className="btn btn-primary">Number Verification
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-sim-fill" viewBox="0 0 16 16">
<path d="M5 4.5a.5.5 0 0 1 .5-.5h2v2H5V4.5zM8.5 6V4h2a.5.5 0 0 1 .5.5V6H8.5zM5 7h6v2H5V7zm3.5 3H11v1.5a.5.5 0 0 1-.5.5h-2v-2zm-1 0v2h-2a.5.5 0 0 1-.5-.5V10h2.5z"/>
<path d="M3.5 0A1.5 1.5 0 0 0 2 1.5v13A1.5 1.5 0 0 0 3.5 16h9a1.5 1.5 0 0 0 1.5-1.5V3.414a1.5 1.5 0 0 0-.44-1.06L11.647.439A1.5 1.5 0 0 0 10.586 0H3.5zm2 3h5A1.5 1.5 0 0 1 12 4.5v7a1.5 1.5 0 0 1-1.5 1.5h-5A1.5 1.5 0 0 1 4 11.5v-7A1.5 1.5 0 0 1 5.5 3z"/>
</svg>
</button>} position="right center">
<div>
<form>
<h5>OTP</h5>
<input type="number" className="form-control" id="OTP" onChange={(e)=>handleOnOTP(e)} value={OTP}/>
<button type="submit" className="btn btn-primary" onClick={onOTP}>Submit</button>
</form>
</div>
</Popup>
<button className="btn btn-primary" onClick={otpSend}>Send OTP
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-phone" viewBox="0 0 16 16">
<path d="M11 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h6zM5 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H5z"/>
<path d="M8 14a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"/>
</svg>
</button>
</div>
</div>
</div>
)
}
export default PatientForm
| cc1d1ffb1ff4220ad5fd38d148f77c233191c8c6 | [
"JavaScript"
] | 8 | JavaScript | vivekchauhan12000/frontend_react | 21eb61a68a81fa9aa653cca0d8d281b9e1c7b6e8 | a7000365369bee799399f2acfe72ca148fb65911 | |
refs/heads/master | <repo_name>MJCoderMJCoder/mr-design.jp<file_sep>/static/js/main.js
/**
* Modules in this bundle
* @license
*
* undefined:
*
* jquery:
* license: MIT (http://opensource.org/licenses/MIT)
* author: jQuery Foundation and other contributors
* maintainers: dmethvin <<EMAIL>>, scott.gonzalez <<EMAIL>>, m_gol <<EMAIL>>, timmywil <<EMAIL>>
* homepage: http://jquery.com
* version: 2.2.4
*
* This header is generated by licensify (https://github.com/twada/licensify)
*/
require = function e(t, n, r) {
function i(s, a) {
if (!n[s]) {
if (!t[s]) {
var u = "function" == typeof require && require;
if (!a && u) return u(s, !0);
if (o) return o(s, !0);
var l = new Error("Cannot find module '" + s + "'");
throw l.code = "MODULE_NOT_FOUND", l
}
var c = n[s] = {
exports: {}
};
t[s][0].call(c.exports, function (e) {
var n = t[s][1][e];
return i(n ? n : e)
}, c, c.exports, e, t, n, r)
}
return n[s].exports
}
for (var o = "function" == typeof require && require, s = 0; s < r.length; s++) i(r[s]);
return i
}({
1: [function (e, t, n) {
"use strict";
t.exports = {
MAX_WIDTH_MOBILE: 768,
MAX_WIDTH_TABLET: 1024
}
}, {}],
2: [function (e, t, n) {
"use strict";
function r(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var i = function () {
function e(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
return function (t, n, r) {
return n && e(t.prototype, n), r && e(t, r), t
}
}();
t.exports = function () {
function e() {
r(this, e), console.info("Contact.constructor"), this.isSending = !1, this.$window = $(window), this.$messages = $(".message"), this.$forms = $(".form"), this.$buttons = $("#buttons button"), this.$name = $("#value-name .form"), this.$company = $("#value-company .form"), this.$tel = $("#value-tel .form"), this.$mail = $("#value-mail .form"), this.$comment = $("#value-comment .form"), $("#button-confirm").on("click", this.confirmClickHandler.bind(this)), $("#button-send").on("click", this.sendClickHandler.bind(this)), $("#button-back").on("click", this.backClickHandler.bind(this))
}
return i(e, [{
key: "confirmClickHandler",
value: function () {
return "" === this.$name.val() ? (alert("Please enter your name."), void this.$name.focus()) : "" === this.$mail.val() ? (alert("Please enter your email address."), void this.$mail.focus()) : "" === this.$comment.val() ? (alert("Please enter a comment."), void this.$comment.focus()) : (this.$window.scrollTop(0), this.$forms.attr("disabled", "disabled"), this.$forms.addClass("disabled"), this.$messages.hide(), this.$messages.eq(1).show(), this.$buttons.show(), void this.$buttons.eq(0).hide())
}
}, {
key: "sendClickHandler",
value: function () {
if (!this.isSending) {
this.isSending = !0;
var e = "/php/sendmail.php";
$.ajax({
type: "POST",
url: e,
data: {
name: this.$name.val(),
company: this.$company.val(),
tel: this.$tel.val(),
email: this.$mail.val(),
messege: this.$comment.val()
},
success: function (e) {
console.log("result: " + e), this.isSending = !1, this.$window.scrollTop(0), $("#form").hide(), $("#buttons").hide(), this.$messages.hide(), this.$messages.eq(2).show(), this.$window.resize()
}.bind(this),
error: function (e) {
console.log("result: " + e), this.isSending = !1, alert("Sending failed. Please try again later.")
}.bind(this)
})
}
}
}, {
key: "backClickHandler",
value: function () {
this.$window.scrollTop(0), this.$forms.attr("disabled", !1), this.$forms.removeClass("disabled"), this.$messages.hide(), this.$messages.eq(0).show(), this.$buttons.hide(), this.$buttons.eq(0).show()
}
}]), e
}()
}, {}],
3: [function (e, t, n) {
"use strict";
function r(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var i = function () {
function e(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
return function (t, n, r) {
return n && e(t.prototype, n), r && e(t, r), t
}
}(),
o = e("$es6/utils/Random.js");
t.exports = function () {
function e() {
r(this, e), console.info("Top.constructor"), this.$window = $(window), this.$header = $("header"), this.$main = $("#main"), this.$image = $(".image"), this.list = [], this.$image.each(function (e, t) {
0 === e && this.list.push(["movie", null, "/assets/movies/1/?color=white&loop=false"]), $(t).hide(), this.list.push(["image", $(t)]), e === Math.floor((this.$image.length - 1) / 2) && this.list.push(["movie", null, "/assets/movies/1/?color=black&loop=false"])
}.bind(this));
var t = $('<iframe id="movie" style="border:none" width="100%" height="100%"></iframe>');
this.$main.prepend(t);
for (var n = 0; n < this.list.length; n++) {
var i = this.list[n];
"movie" == i[0] && (i[1] = t)
}
$(document).on("black", function (e) {
this.showHeader(1)
}.bind(this)), $(document).on("white", function (e) {
this.showHeader(0)
}.bind(this)), this.preload(), this.sideMargin = parseInt(this.$header.css("margin-left")), this.$window.resize(this.resizeHandler.bind(this))
}
return i(e, [{
key: "preload",
value: function () {
console.info("Top.preload");
var e = this;
e.count = 0, this.list.forEach(function (t, n) {
if ("image" == t[0]) {
var r = t[1];
r.on("load", function () {
e.count++, e.count >= e.$image.length && e.loadComplete()
}), r.attr("src", r.attr("data-src"))
}
})
}
}, {
key: "loadComplete",
value: function () {
console.info("Top.loadComplete"), this.currentIdx = o.range(0, this.list.length - 1, !0), this.next()
}
}, {
key: "show",
value: function () {
var e = !1,
t = "";
if (this.$main.children().hide(), this.currentContent && (this.currentContent[1].css("z-index", 0), this.currentContent[1].show()), this.nextContent = this.list[this.currentIdx], "image" == this.nextContent[0]) {
this.resizeImage(this.nextContent[1]);
var n = this.nextContent[1].attr("data-invert-logo"),
r = this.nextContent[1].attr("data-invert-menu");
"0" === n && "0" === r ? this.showHeader(0) : "1" === n && "1" === r ? this.showHeader(1) : "1" === n && "0" === r ? this.showHeader(2) : "0" === n && "1" === r && this.showHeader(3)
} else t = this.nextContent[2], e = !0;
return this.nextContent[1].css("z-index", 1), this.nextContent[1].stop().fadeTo(0, 0).fadeTo(500, 1, function () {
$("iframe").attr("src", t)
}), this.currentContent = this.nextContent, this.resizeHandler(), e
}
}, {
key: "next",
value: function () {
this.currentIdx = (this.currentIdx + 1) % this.list.length;
var e = this.show(),
t = e ? 12e3 : 4e3;
setTimeout(this.next.bind(this), t)
}
}, {
key: "showHeader",
value: function (e) {
var t = $("header:eq(" + e + ")"),
n = $("header:not(:eq(" + e + "))");
n.css("z-index", 2), n.stop().fadeTo(500, 0), t.show(), t.css("z-index", 3), t.stop().fadeTo(500, 1)
}
}, {
key: "resizeHandler",
value: function () {
console.info("Top.resizeHandler"), this.$header.width(this.$window.width() - 2 * this.sideMargin), "image" == this.currentContent[0] && this.resizeImage(this.currentContent[1])
}
}, {
key: "resizeImage",
value: function (e) {
if (e) {
var t, n, r = this.$window.width(),
i = this.$window.height(),
o = e.attr("data-width"),
s = e.attr("data-height"),
a = e.attr("data-align-horizontal"),
u = e.attr("data-align-vertical");
r / i < o / s ? (t = o * (i / s), n = i) : (n = s * (r / o), t = r);
var l = (r - t) / 2,
c = (i - n) / 2;
switch (a) {
case "left":
l = 0;
break;
case "right":
l = r - t
}
switch (u) {
case "top":
c = 0;
break;
case "bottom":
c = i - n
}
e.css({
left: l,
top: c,
width: t,
height: n
})
}
}
}]), e
}()
}, {
"$es6/utils/Random.js": 13
}],
4: [function (e, t, n) {
"use strict";
function r(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var i = function () {
function e(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
return function (t, n, r) {
return n && e(t.prototype, n), r && e(t, r), t
}
}();
t.exports = function () {
function e() {
r(this, e), console.info("Footer.constructor"), this.$window = $(window), this.$body = $("html, body"), this.$footer = $("footer"), this.sideMargin = parseInt(this.$footer.css("margin-left")), $("#back-to-top a").on("click", function (e) {
e.preventDefault(), e.stopPropagation();
var t = this.$window.scrollTop(),
n = this.$window.height();
this.$body.scrollTop(Math.min(t, n)), this.$body.stop().animate({
scrollTop: 0
}, 400, "easeOutExpo")
}.bind(this)), ($("html#contact").length > 0 || $("html#news").length > 0) && (this.$window.resize(this.resizeHandler.bind(this)), this.resizeHandler())
}
return i(e, [{
key: "resizeHandler",
value: function () {
console.info("Footer.resizeHandler"), document.body.scrollHeight > this.$window.height() ? (this.$footer.removeClass("fix"), this.$footer.width("auto")) : (this.$footer.addClass("fix"), this.$footer.width(this.$window.width() - 2 * this.sideMargin))
}
}]), e
}()
}, {}],
5: [function (e, t, n) {
"use strict";
function r(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var i = function () {
function e(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
return function (t, n, r) {
return n && e(t.prototype, n), r && e(t, r), t
}
}();
t.exports = function () {
function e(t) {
if (r(this, e), console.info("GoogleMaps.constructor"), this.idList = t, this.GOOGLE_MAPS_ZOOM = 14, this.API_KEY = "<KEY>", window.google) this.gmapHandler();
else {
var n = document.createElement("script");
n.type = "text/javascript", n.defer = !0, n.async = !0, n.src = "https://maps.googleapis.com/maps/api/js?key=" + this.API_KEY + "&language=en&callback=gmapHandler", window.gmapHandler = this.gmapHandler.bind(this), $("head").append(n)
}
}
return i(e, [{
key: "gmapHandler",
value: function () {
console.info("GoogleMaps.gmapHandler"), this.idList.forEach(function (e, t) {
this.generateMap($("#" + e))
}.bind(this))
}
}, {
key: "generateMap",
value: function (e) {
console.info("GoogleMaps.generateMap");
var t = new google.maps.LatLng(Number(e.attr("data-lat")), Number(e.attr("data-lng"))),
n = {
zoom: this.GOOGLE_MAPS_ZOOM,
center: t,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: !0,
streetViewControl: !1,
zoomControl: !0,
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT,
style: google.maps.ZoomControlStyle.LARGE
},
styles: [{
stylers: [{
saturation: -100
}]
}]
},
r = new google.maps.Map(e.get(0), n),
i = (new google.maps.Marker({
map: r,
position: t,
title: e.attr("data-name"),
flat: !0
}), {
styles: [{
stylers: [{
saturation: 0
}]
}]
}),
o = {
styles: [{
stylers: [{
saturation: -100
}]
}]
},
s = !1;
e.mouseenter(function (e) {
s || (r.setOptions(i), s = !0)
}), e.mouseleave(function (e) {
s && (r.setOptions(o), s = !1)
})
}
}]), e
}()
}, {}],
6: [function (e, t, n) {
"use strict";
function r(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var i = function () {
function e(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
return function (t, n, r) {
return n && e(t.prototype, n), r && e(t, r), t
}
}();
t.exports = function () {
function e() {
r(this, e), console.info("Grid.constructor"), this.$window = $(window), this.$stage = $("#stage"), this.$grid = $("#grid"), this.$single = $("#single"), this.imageNum = $("#images .image").length, this.maxColumn = 3, void 0 === localStorage.mode && (localStorage.mode = "grid"), $("html").hasClass("mobile") && (localStorage.mode = "single"), this.imageNum <= 1 && $("#switch").hide(), $("html").css("overflow-y", "scroll"), this.preload(), this.$window.resize(this.resizeHandler.bind(this))
}
return i(e, [{
key: "preload",
value: function () {
console.info("Grid.preload"), this.$images = [];
var e = this,
t = 0;
$("#images .image").each(function (n, r) {
var i = $(r);
e.$images[n] = i, e.$stage.prepend(i), i.attr("src", i.attr("data-src")), i.on("load", function () {
t++, t >= e.imageNum && e.preloadComplete()
})
})
}
}, {
key: "preloadComplete",
value: function () {
console.info("Grid.preloadComplete"), this.$stage.css("background-color", "#fff"), this.$grid.on("click", this.gridSwitchHandler.bind(this)), this.$single.on("click", this.singleSwitchHandler.bind(this)), "grid" == localStorage.mode ? $("html").addClass("grid").removeClass("single") : $("html").removeClass("grid").addClass("single"), this.$images.forEach(function (e, t) {
e.show()
}), this.resizeHandler(), $("footer").show()
}
}, {
key: "gridSwitchHandler",
value: function (e) {
console.info("Grid.gridSwitchHandler"), e.preventDefault(), "grid" !== localStorage.mode && ($("html").addClass("grid").removeClass("single"), localStorage.mode = "grid", this.resizeHandler(), this.$stage.stop().fadeTo(0, 0).fadeTo(200, 1))
}
}, {
key: "singleSwitchHandler",
value: function (e) {
console.info("Grid.singleSwitchHandler"), e.preventDefault(), "grid" === localStorage.mode && ($("html").removeClass("grid").addClass("single"), localStorage.mode = "single", this.resizeHandler(), this.$stage.stop().fadeTo(0, 0).fadeTo(200, 1))
}
}, {
key: "resizeHandler",
value: function (e) {
console.info("Grid.resizeHandler");
var t = (this.$window.width(), this.$stage.width()),
n = 340,
r = 60,
i = 60,
o = Math.floor((t + r) / (n + r));
o = Math.min(o, this.maxColumn);
var s = t - r * (o - 1),
a = 0,
u = [],
l = [],
c = [];
this.$images.forEach(function (e, t) {
"true" == e.attr("data-pickup") ? c.push({
idx: t,
ele: e
}) : l.push({
idx: t,
ele: e
})
});
for (var f = [], d = Math.ceil(l.length / o), h = 0; h < d; h++) {
f[h] = [];
for (var p = 0; p < o; p++) {
var g = l.shift();
g && f[h].push(g)
}
}
for (; f.length > 0 || c.length > 0;) {
var m = f[0],
v = c[0];
if (m && v)
if (m.length < o) {
var y = c.shift();
u.push(y.ele)
} else if (m[0].idx < v.idx)
for (var b = f.shift(), x = 0; x < b.length; x++) u.push(b[x].ele);
else {
var w = c.shift();
u.push(w.ele)
} else if (m && !v)
for (var $ = f.shift(), C = 0; C < $.length; C++) u.push($[C].ele);
else if (!m && v) {
var T = c.shift();
u.push(T.ele)
}
}
var k = [],
E = !0,
S = !1,
j = void 0;
try {
for (var M, H = u[Symbol.iterator](); !(E = (M = H.next()).done); E = !0) {
var N = M.value,
D = "true" == N.attr("data-pickup") || "single" == localStorage.mode;
k.push(N);
var A = D ? 1 : o;
if (k.length >= A) {
var O = this.calcSizeAndPos(k, s, a, r);
a += O + i, console.log("currentY", a, "rowHeight", O), k = []
}
}
} catch (q) {
S = !0, j = q
} finally {
try {
!E && H["return"] && H["return"]()
} finally {
if (S) throw j
}
}
if (console.log("tempList", k.length), k.length > 0) {
s = t - r * (k.length - 1);
var I = this.calcSizeAndPos(k, s, a, r);
a += I + i
}
a -= i, this.$stage.css("height", a)
}
}, {
key: "calcSizeAndPos",
value: function (e, t, n, r) {
var i = 800,
o = 0,
s = !0,
a = !1,
u = void 0;
try {
for (var l, c = e[Symbol.iterator](); !(s = (l = c.next()).done); s = !0) {
var f = l.value,
d = parseInt(f.attr("data-width")),
h = parseInt(f.attr("data-height"));
o += d * (i / h)
}
} catch (p) {
a = !0, u = p
} finally {
try {
!s && c["return"] && c["return"]()
} finally {
if (a) throw u
}
}
var g = t / o,
m = 0,
v = 0,
y = 0,
b = !0,
x = !1,
w = void 0;
try {
for (var $, C = e[Symbol.iterator](); !(b = ($ = C.next()).done); b = !0) {
var T = $.value,
k = "true" == T.attr("data-pickup") || "single" == localStorage.mode,
E = parseInt(T.attr("data-width")) || T.width(),
S = parseInt(T.attr("data-height")) || T.height(),
j = g * (i / S);
k && (j = this.$stage.width() / E), m = E * j, v = S * j, T.css({
width: m,
height: v,
left: y,
top: n
}), y += m + r
}
} catch (p) {
x = !0, w = p
} finally {
try {
!b && C["return"] && C["return"]()
} finally {
if (x) throw w
}
}
return v
}
}]), e
}()
}, {}],
7: [function (e, t, n) {
"use strict";
function r(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var i = function () {
function e(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
return function (t, n, r) {
return n && e(t.prototype, n), r && e(t, r), t
}
}();
t.exports = function () {
function e() {
r(this, e), console.info("ImageList.constructor"), this.$window = $(window), this.$main = $("#main"), this.$items = $(".desktop .items"), this.$item = $(".desktop .items .item"), this.$window.resize(this.resizeHandler.bind(this)), this.resizeHandler(), this.$item.css("visibility", "visible")
}
return i(e, [{
key: "resizeHandler",
value: function () {
console.info("ImageList.resizeHandler");
var e = 60,
t = 340,
n = 60,
r = this.$window.width(),
i = r - 2 * e,
o = Math.floor(i / (t + n)),
s = i - (t + n) * o + n;
t += s / o, $(".desktop .items .item").each(function (e, n) {
var r = $(n),
i = r.find("img"),
o = parseInt(i.attr("width")),
s = parseInt(i.attr("height")),
a = t / o;
r.width(t), i.width(t), i.height(s * a)
}), this.$item.css("margin-right", n), this.$items.eq(o).css("margin-right", 0), this.$item.css("visibility", "visible")
}
}]), e
}()
}, {}],
8: [function (e, t, n) {
"use strict";
function r(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var i = function () {
function e(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
return function (t, n, r) {
return n && e(t.prototype, n), r && e(t, r), t
}
}();
t.exports = function () {
function e() {
r(this, e), console.info("SpMenu.constructor");
$(window);
this.$hamburger = $(".hamburger"), this.$closeMenu = $(".close-menu"), this.$main = $("#main"), this.$header = $("header"), this.$footer = $("footer"), this.$spMenu = $("#sp-menu"), this.hadClass = null, $(document).on("touchstart", ".hamburger", this.hamburgerHandler.bind(this)), $(document).on("touchstart", ".close-menu", this.closeHandler.bind(this)), $(document).on("click", ".hamburger", this.hamburgerHandler.bind(this)), $(document).on("click", ".close-menu", this.closeHandler.bind(this))
}
return i(e, [{
key: "hamburgerHandler",
value: function (e) {
console.log("hamburgerHandler"), e.preventDefault(), this.$header.hide(), this.$main.hide(), this.$footer.hide(), this.$spMenu.show()
}
}, {
key: "closeHandler",
value: function (e) {
console.log("closeHandler"), e.preventDefault(), this.$header.show(), this.$main.show(), this.$footer.show(), this.$spMenu.hide()
}
}]), e
}()
}, {}],
"C:\\Users\\bouze\\Dropbox\\tha\\works\\1508 MR_DESIGN\\dev\\site2\\dev\\assets\\es6\\libs\\jquery.easing.1.3": [function (e, t, n) {
jQuery.easing.jswing = jQuery.easing.swing, jQuery.extend(jQuery.easing, {
def: "easeOutQuad",
swing: function (e, t, n, r, i) {
return jQuery.easing[jQuery.easing.def](e, t, n, r, i)
},
easeInQuad: function (e, t, n, r, i) {
return r * (t /= i) * t + n
},
easeOutQuad: function (e, t, n, r, i) {
return -r * (t /= i) * (t - 2) + n
},
easeInOutQuad: function (e, t, n, r, i) {
return (t /= i / 2) < 1 ? r / 2 * t * t + n : -r / 2 * (--t * (t - 2) - 1) + n
},
easeInCubic: function (e, t, n, r, i) {
return r * (t /= i) * t * t + n
},
easeOutCubic: function (e, t, n, r, i) {
return r * ((t = t / i - 1) * t * t + 1) + n
},
easeInOutCubic: function (e, t, n, r, i) {
return (t /= i / 2) < 1 ? r / 2 * t * t * t + n : r / 2 * ((t -= 2) * t * t + 2) + n
},
easeInQuart: function (e, t, n, r, i) {
return r * (t /= i) * t * t * t + n
},
easeOutQuart: function (e, t, n, r, i) {
return -r * ((t = t / i - 1) * t * t * t - 1) + n
},
easeInOutQuart: function (e, t, n, r, i) {
return (t /= i / 2) < 1 ? r / 2 * t * t * t * t + n : -r / 2 * ((t -= 2) * t * t * t - 2) + n
},
easeInQuint: function (e, t, n, r, i) {
return r * (t /= i) * t * t * t * t + n
},
easeOutQuint: function (e, t, n, r, i) {
return r * ((t = t / i - 1) * t * t * t * t + 1) + n
},
easeInOutQuint: function (e, t, n, r, i) {
return (t /= i / 2) < 1 ? r / 2 * t * t * t * t * t + n : r / 2 * ((t -= 2) * t * t * t * t + 2) + n
},
easeInSine: function (e, t, n, r, i) {
return -r * Math.cos(t / i * (Math.PI / 2)) + r + n
},
easeOutSine: function (e, t, n, r, i) {
return r * Math.sin(t / i * (Math.PI / 2)) + n
},
easeInOutSine: function (e, t, n, r, i) {
return -r / 2 * (Math.cos(Math.PI * t / i) - 1) + n
},
easeInExpo: function (e, t, n, r, i) {
return 0 == t ? n : r * Math.pow(2, 10 * (t / i - 1)) + n
},
easeOutExpo: function (e, t, n, r, i) {
return t == i ? n + r : r * (-Math.pow(2, -10 * t / i) + 1) + n
},
easeInOutExpo: function (e, t, n, r, i) {
return 0 == t ? n : t == i ? n + r : (t /= i / 2) < 1 ? r / 2 * Math.pow(2, 10 * (t - 1)) + n : r / 2 * (-Math.pow(2, -10 * --t) + 2) + n
},
easeInCirc: function (e, t, n, r, i) {
return -r * (Math.sqrt(1 - (t /= i) * t) - 1) + n
},
easeOutCirc: function (e, t, n, r, i) {
return r * Math.sqrt(1 - (t = t / i - 1) * t) + n
},
easeInOutCirc: function (e, t, n, r, i) {
return (t /= i / 2) < 1 ? -r / 2 * (Math.sqrt(1 - t * t) - 1) + n : r / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + n
},
easeInElastic: function (e, t, n, r, i) {
var o = 1.70158,
s = 0,
a = r;
if (0 == t) return n;
if (1 == (t /= i)) return n + r;
if (s || (s = .3 * i), a < Math.abs(r)) {
a = r;
var o = s / 4
} else var o = s / (2 * Math.PI) * Math.asin(r / a);
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * i - o) * (2 * Math.PI) / s)) + n
},
easeOutElastic: function (e, t, n, r, i) {
var o = 1.70158,
s = 0,
a = r;
if (0 == t) return n;
if (1 == (t /= i)) return n + r;
if (s || (s = .3 * i), a < Math.abs(r)) {
a = r;
var o = s / 4
} else var o = s / (2 * Math.PI) * Math.asin(r / a);
return a * Math.pow(2, -10 * t) * Math.sin((t * i - o) * (2 * Math.PI) / s) + r + n
},
easeInOutElastic: function (e, t, n, r, i) {
var o = 1.70158,
s = 0,
a = r;
if (0 == t) return n;
if (2 == (t /= i / 2)) return n + r;
if (s || (s = i * (.3 * 1.5)), a < Math.abs(r)) {
a = r;
var o = s / 4
} else var o = s / (2 * Math.PI) * Math.asin(r / a);
return t < 1 ? -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * i - o) * (2 * Math.PI) / s)) + n : a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * i - o) * (2 * Math.PI) / s) * .5 + r + n
},
easeInBack: function (e, t, n, r, i, o) {
return void 0 == o && (o = 1.70158), r * (t /= i) * t * ((o + 1) * t - o) + n
},
easeOutBack: function (e, t, n, r, i, o) {
return void 0 == o && (o = 1.70158), r * ((t = t / i - 1) * t * ((o + 1) * t + o) + 1) + n
},
easeInOutBack: function (e, t, n, r, i, o) {
return void 0 == o && (o = 1.70158), (t /= i / 2) < 1 ? r / 2 * (t * t * (((o *= 1.525) + 1) * t - o)) + n : r / 2 * ((t -= 2) * t * (((o *= 1.525) + 1) * t + o) + 2) + n
},
easeInBounce: function (e, t, n, r, i) {
return r - jQuery.easing.easeOutBounce(e, i - t, 0, r, i) + n
},
easeOutBounce: function (e, t, n, r, i) {
return (t /= i) < 1 / 2.75 ? r * (7.5625 * t * t) + n : t < 2 / 2.75 ? r * (7.5625 * (t -= 1.5 / 2.75) * t + .75) + n : t < 2.5 / 2.75 ? r * (7.5625 * (t -= 2.25 / 2.75) * t + .9375) + n : r * (7.5625 * (t -= 2.625 / 2.75) * t + .984375) + n
},
easeInOutBounce: function (e, t, n, r, i) {
return t < i / 2 ? .5 * jQuery.easing.easeInBounce(e, 2 * t, 0, r, i) + n : .5 * jQuery.easing.easeOutBounce(e, 2 * t - i, 0, r, i) + .5 * r + n
}
})
}, {}],
9: [function (e, t, n) {
"use strict";
! function (e) {
e.fn.textshuffle = function (t) {
var n = {
str: "",
waitChar: "-",
charSpeed: 2,
moveFix: 1,
moveRange: 10,
moveTrigger: 12,
fps: 60
},
r = e.extend(n, t);
return this.each(function (t) {
var n, i, o, s, a, u, l, c, f, d = 33,
h = 126,
p = function () {
l = u, c = !0;
for (var e = a; e <= s; e++) {
if (0 != o[e] && null != o[e]) {
c = !1;
var t = o[e];
if (Math.abs(t) <= r.moveTrigger) {
var p = Math.min(Math.max(i.charCodeAt(e) + t, d), h);
l += String.fromCharCode(p)
} else l += r.waitChar;
t > 0 ? o[e] -= 1 : o[e] += 1
} else a == e - 1 && (a = e, u = i.substring(0, a)), l += i.charAt(e);
n.get(0).textContent = l
}
s <= i.length ? s += r.charSpeed : f = !0, c && f && (clearInterval(n.data("id")), n.html(n.data("html")), n.data("run", !1))
};
if (n = e(this), n.data("run") || n.data("html", n.html()), n.data("run", !0), n.html(r.str), r.str = n.text(), n.html(r.waitChar), r.str) {
i = r.str, o = [];
for (var g = 0; g <= r.str.length - 1; g++) {
var m = i.charAt(t);
" " != m ? o[g] = (r.moveFix + Math.round(Math.random() * r.moveRange)) * (Math.round(Math.random()) - .5) * 2 : o[g] = 0
}
s = 0, a = 0, u = "", clearInterval(n.data("id"));
var v = setInterval(p, 1e3 / r.fps);
n.data("id", v)
}
})
}
}(jQuery)
}, {}],
10: [function (e, t, n) {
"use strict";
location.href.indexOf("//mr-design.jp") > -1 && (window.console = {
log: function () {},
error: function () {},
dir: function () {},
time: function () {},
timeEnd: function () {},
info: function () {},
group: function () {},
warn: function () {},
trace: function () {},
debug: function () {}
}), window.localStorage || (window.localStorage = {});
e("$es6/Constants.js");
window.jQuery = e("jquery"), window.$ = window.jQuery, e("$es6/libs/jquery.easing.1.3"), /iPad/.test(navigator.userAgent) && $("meta[name='viewport']").attr("content", "width=device-width, initial-scale=1.0"), $(function () {
new(e("$es6/utils/MediaSwitch.js")), new(e("$es6/utils/TextEffect.js")), new(e("$es6/utils/MouseOverEffect.js")), new(e("$es6/common/Footer.js")), $("html#top").length > 0 && new(e("$es6/Top.js")), ($("html#products").length > 0 || $("html#works").length > 0) && new(e("$es6/common/ImageList.js")), ($("html#works-detail").length > 0 || $("html#products-detail").length > 0) && new(e("$es6/common/Grid.js")), $("html#about").length > 0 && new(e("$es6/common/GoogleMaps.js"))(["gmap0", "gmap1"]), $("html#contact").length > 0 && new(e("$es6/Contact.js")), $("html.mobile").length > 0 && new(e("$es6/common/SpMenu.js"))
})
}, {
"$es6/Constants.js": 1,
"$es6/Contact.js": 2,
"$es6/Top.js": 3,
"$es6/common/Footer.js": 4,
"$es6/common/GoogleMaps.js": 5,
"$es6/common/Grid.js": 6,
"$es6/common/ImageList.js": 7,
"$es6/common/SpMenu.js": 8,
"$es6/libs/jquery.easing.1.3": "C:\\Users\\bouze\\Dropbox\\tha\\works\\1508 MR_DESIGN\\dev\\site2\\dev\\assets\\es6\\libs\\jquery.easing.1.3",
"$es6/utils/MediaSwitch.js": 11,
"$es6/utils/MouseOverEffect.js": 12,
"$es6/utils/TextEffect.js": 14,
jquery: "jquery"
}],
11: [function (e, t, n) {
"use strict";
function r(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var i = function () {
function e(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
return function (t, n, r) {
return n && e(t.prototype, n), r && e(t, r), t
}
}(),
o = e("$es6/Constants.js");
t.exports = function () {
function e() {
r(this, e), console.info("MediaSwitch.constructor"), this.$window = $(window);
var t = this.getWidthInnerWidth();
this.isMobile = t <= o.MAX_WIDTH_MOBILE, this.isMobile ? ($("html").addClass("mobile"), $("html").removeClass("desktop")) : ($("html").removeClass("mobile"), $("html").addClass("desktop")), this.$window.on("resize", this, this.resizeHandler), this.resizeHandler()
}
return i(e, [{
key: "resizeHandler",
value: function (e) {
console.info("MediaSwitch.resizeHandler");
var t = e ? e.data : this,
n = t.getWidthInnerWidth(),
r = n <= o.MAX_WIDTH_MOBILE;
t.isMobile != r && (t.isMobile = r, t.isMobile ? ($("html").addClass("mobile"), $("html").removeClass("desktop")) : ($("html").removeClass("mobile"), $("html").addClass("desktop")), t.onMediaChange && t.onMediaChange())
}
}, {
key: "getWidthInnerWidth",
value: function () {
return document.documentElement.clientWidth || window.innerWidth || document.body.clientWidth
}
}, {
key: "dispose",
value: function () {
this.$window.off("resize", this.resizeHandler), this.$window = null, this.isMobile = null
}
}]), e
}()
}, {
"$es6/Constants.js": 1
}],
12: [function (e, t, n) {
"use strict";
function r(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var i = function () {
function e(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
return function (t, n, r) {
return n && e(t.prototype, n), r && e(t, r), t
}
}();
t.exports = function () {
function e() {
r(this, e), console.info("MouseOverEffect.constructor");
this.$targets = $(".mouse-over-effect"), this.$html = $("html"), $(document).on("mouseenter", ".mouse-over-effect", this.mouseEnterHandler1.bind(this)), $(document).on("mouseenter", ".mouse-over-effect-strong", this.mouseEnterHandler2.bind(this))
}
return i(e, [{
key: "mouseEnterHandler1",
value: function (e) {
this.$html.hasClass("desktop") && $(e.currentTarget).stop().fadeTo(0, .5).fadeTo(200, 1)
}
}, {
key: "mouseEnterHandler2",
value: function (e) {
this.$html.hasClass("desktop") && $(e.currentTarget).stop().fadeTo(0, 0).fadeTo(200, 1)
}
}]), e
}()
}, {}],
13: [function (e, t, n) {
"use strict";
t.exports = {
range: function (e, t) {
var n = !(arguments.length <= 2 || void 0 === arguments[2]) && arguments[2];
return n ? Math.round(Math.random() * (t - e) + e) : Math.random() * (t - e) + e
},
choice: function (e) {
var t = this.range(0, e.length - 1, !0);
return e[t]
},
chance: function (e, t) {
for (var n = MathUtil.sum(t), r = this.range(0, n), i = 0, o = 0; o < e.length; o++)
if (i = 0 !== o ? i + t[o - 1] : 0, i < r && r < i + t[o]) return e[o]
},
trueOrFalse: function () {
var e = arguments.length <= 0 || void 0 === arguments[0] ? .5 : arguments[0];
return Math.random() < e
},
zeroOrOne: function () {
var e = arguments.length <= 0 || void 0 === arguments[0] ? .5 : arguments[0];
return Math.random() < e ? 0 : 1
},
minusOrPlus: function () {
var e = arguments.length <= 0 || void 0 === arguments[0] ? .5 : arguments[0];
return Math.random() < e ? -1 : 1
}
}
}, {}],
14: [function (e, t, n) {
"use strict";
function r(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var i = function () {
function e(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
return function (t, n, r) {
return n && e(t.prototype, n), r && e(t, r), t
}
}();
e("$es6/libs/jquery.textshuffle.js"), t.exports = function () {
function e() {
r(this, e), console.info("TextEffect.constructor");
var t = this;
this.$targets = $(".text-effect"), this.$html = $("html"), $(".text-effect").each(function (e, n) {
$(n).parent().on("mouseenter", t, t.mouseEnterHandler)
})
}
return i(e, [{
key: "mouseEnterHandler",
value: function (e) {
$(this).find(".text-effect").each(function (t, n) {
e.data.$html.hasClass("desktop") && $(n).textshuffle({
str: $(n).attr("data-text")
})
})
}
}, {
key: "fastIntro",
value: function () {
console.info("TextEffect.fastIntro"), $(".text-effect").css("visibility", "visible")
}
}, {
key: "dispose",
value: function () {
console.info("TextEffect.dispose"), this.$targets && this.$targets.each(function (e, t) {
$(t).parent().off("mouseenter", this.mouseEnterHandler)
}), this.$targets = null
}
}]), e
}()
}, {
"$es6/libs/jquery.textshuffle.js": 9
}],
jquery: [function (e, t, n) {
/*!
* jQuery JavaScript Library v2.2.4
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-05-20T17:23Z
*/
! function (e, n) {
"object" == typeof t && "object" == typeof t.exports ? t.exports = e.document ? n(e, !0) : function (e) {
if (!e.document) throw new Error("jQuery requires a window with a document");
return n(e)
} : n(e)
}("undefined" != typeof window ? window : this, function (e, t) {
function n(e) {
var t = !!e && "length" in e && e.length,
n = oe.type(e);
return "function" !== n && !oe.isWindow(e) && ("array" === n || 0 === t || "number" == typeof t && t > 0 && t - 1 in e)
}
function r(e, t, n) {
if (oe.isFunction(t)) return oe.grep(e, function (e, r) {
return !!t.call(e, r, e) !== n
});
if (t.nodeType) return oe.grep(e, function (e) {
return e === t !== n
});
if ("string" == typeof t) {
if (ge.test(t)) return oe.filter(t, e, n);
t = oe.filter(t, e)
}
return oe.grep(e, function (e) {
return Z.call(t, e) > -1 !== n
})
}
function i(e, t) {
for (;
(e = e[t]) && 1 !== e.nodeType;);
return e
}
function o(e) {
var t = {};
return oe.each(e.match(we) || [], function (e, n) {
t[n] = !0
}), t
}
function s() {
Y.removeEventListener("DOMContentLoaded", s), e.removeEventListener("load", s), oe.ready()
}
function a() {
this.expando = oe.expando + a.uid++
}
function u(e, t, n) {
var r;
if (void 0 === n && 1 === e.nodeType)
if (r = "data-" + t.replace(je, "-$&").toLowerCase(), n = e.getAttribute(r), "string" == typeof n) {
try {
n = "true" === n || "false" !== n && ("null" === n ? null : +n + "" === n ? +n : Se.test(n) ? oe.parseJSON(n) : n)
} catch (i) {}
Ee.set(e, t, n)
} else n = void 0;
return n
}
function l(e, t, n, r) {
var i, o = 1,
s = 20,
a = r ? function () {
return r.cur()
} : function () {
return oe.css(e, t, "")
},
u = a(),
l = n && n[3] || (oe.cssNumber[t] ? "" : "px"),
c = (oe.cssNumber[t] || "px" !== l && +u) && He.exec(oe.css(e, t));
if (c && c[3] !== l) {
l = l || c[3], n = n || [], c = +u || 1;
do o = o || ".5", c /= o, oe.style(e, t, c + l); while (o !== (o = a() / u) && 1 !== o && --s)
}
return n && (c = +c || +u || 0, i = n[1] ? c + (n[1] + 1) * n[2] : +n[2], r && (r.unit = l, r.start = c, r.end = i)), i
}
function c(e, t) {
var n = "undefined" != typeof e.getElementsByTagName ? e.getElementsByTagName(t || "*") : "undefined" != typeof e.querySelectorAll ? e.querySelectorAll(t || "*") : [];
return void 0 === t || t && oe.nodeName(e, t) ? oe.merge([e], n) : n
}
function f(e, t) {
for (var n = 0, r = e.length; n < r; n++) ke.set(e[n], "globalEval", !t || ke.get(t[n], "globalEval"))
}
function d(e, t, n, r, i) {
for (var o, s, a, u, l, d, h = t.createDocumentFragment(), p = [], g = 0, m = e.length; g < m; g++)
if (o = e[g], o || 0 === o)
if ("object" === oe.type(o)) oe.merge(p, o.nodeType ? [o] : o);
else if (Le.test(o)) {
for (s = s || h.appendChild(t.createElement("div")), a = (Oe.exec(o) || ["", ""])[1].toLowerCase(), u = Ie[a] || Ie._default, s.innerHTML = u[1] + oe.htmlPrefilter(o) + u[2], d = u[0]; d--;) s = s.lastChild;
oe.merge(p, s.childNodes), s = h.firstChild, s.textContent = ""
} else p.push(t.createTextNode(o));
for (h.textContent = "", g = 0; o = p[g++];)
if (r && oe.inArray(o, r) > -1) i && i.push(o);
else if (l = oe.contains(o.ownerDocument, o), s = c(h.appendChild(o), "script"), l && f(s), n)
for (d = 0; o = s[d++];) qe.test(o.type || "") && n.push(o);
return h
}
function h() {
return !0
}
function p() {
return !1
}
function g() {
try {
return Y.activeElement
} catch (e) {}
}
function m(e, t, n, r, i, o) {
var s, a;
if ("object" == typeof t) {
"string" != typeof n && (r = r || n, n = void 0);
for (a in t) m(e, a, n, r, t[a], o);
return e
}
if (null == r && null == i ? (i = n, r = n = void 0) : null == i && ("string" == typeof n ? (i = r, r = void 0) : (i = r, r = n, n = void 0)), i === !1) i = p;
else if (!i) return e;
return 1 === o && (s = i, i = function (e) {
return oe().off(e), s.apply(this, arguments)
}, i.guid = s.guid || (s.guid = oe.guid++)), e.each(function () {
oe.event.add(this, t, i, r, n)
})
}
function v(e, t) {
return oe.nodeName(e, "table") && oe.nodeName(11 !== t.nodeType ? t : t.firstChild, "tr") ? e.getElementsByTagName("tbody")[0] || e.appendChild(e.ownerDocument.createElement("tbody")) : e
}
function y(e) {
return e.type = (null !== e.getAttribute("type")) + "/" + e.type, e
}
function b(e) {
var t = _e.exec(e.type);
return t ? e.type = t[1] : e.removeAttribute("type"), e
}
function x(e, t) {
var n, r, i, o, s, a, u, l;
if (1 === t.nodeType) {
if (ke.hasData(e) && (o = ke.access(e), s = ke.set(t, o), l = o.events)) {
delete s.handle, s.events = {};
for (i in l)
for (n = 0, r = l[i].length; n < r; n++) oe.event.add(t, i, l[i][n])
}
Ee.hasData(e) && (a = Ee.access(e), u = oe.extend({}, a), Ee.set(t, u))
}
}
function w(e, t) {
var n = t.nodeName.toLowerCase();
"input" === n && Ae.test(e.type) ? t.checked = e.checked : "input" !== n && "textarea" !== n || (t.defaultValue = e.defaultValue)
}
function $(e, t, n, r) {
t = J.apply([], t);
var i, o, s, a, u, l, f = 0,
h = e.length,
p = h - 1,
g = t[0],
m = oe.isFunction(g);
if (m || h > 1 && "string" == typeof g && !re.checkClone && Be.test(g)) return e.each(function (i) {
var o = e.eq(i);
m && (t[0] = g.call(this, i, o.html())), $(o, t, n, r)
});
if (h && (i = d(t, e[0].ownerDocument, !1, e, r), o = i.firstChild, 1 === i.childNodes.length && (i = o), o || r)) {
for (s = oe.map(c(i, "script"), y), a = s.length; f < h; f++) u = i, f !== p && (u = oe.clone(u, !0, !0), a && oe.merge(s, c(u, "script"))), n.call(e[f], u, f);
if (a)
for (l = s[s.length - 1].ownerDocument, oe.map(s, b), f = 0; f < a; f++) u = s[f], qe.test(u.type || "") && !ke.access(u, "globalEval") && oe.contains(l, u) && (u.src ? oe._evalUrl && oe._evalUrl(u.src) : oe.globalEval(u.textContent.replace(Ge, "")))
}
return e
}
function C(e, t, n) {
for (var r, i = t ? oe.filter(t, e) : e, o = 0; null != (r = i[o]); o++) n || 1 !== r.nodeType || oe.cleanData(c(r)), r.parentNode && (n && oe.contains(r.ownerDocument, r) && f(c(r, "script")), r.parentNode.removeChild(r));
return e
}
function T(e, t) {
var n = oe(t.createElement(e)).appendTo(t.body),
r = oe.css(n[0], "display");
return n.detach(), r
}
function k(e) {
var t = Y,
n = Qe[e];
return n || (n = T(e, t), "none" !== n && n || (Xe = (Xe || oe("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement), t = Xe[0].contentDocument, t.write(), t.close(), n = T(e, t), Xe.detach()), Qe[e] = n), n
}
function E(e, t, n) {
var r, i, o, s, a = e.style;
return n = n || Ve(e), s = n ? n.getPropertyValue(t) || n[t] : void 0, "" !== s && void 0 !== s || oe.contains(e.ownerDocument, e) || (s = oe.style(e, t)), n && !re.pixelMarginRight() && Ye.test(s) && Ue.test(t) && (r = a.width, i = a.minWidth, o = a.maxWidth, a.minWidth = a.maxWidth = a.width = s, s = n.width, a.width = r, a.minWidth = i, a.maxWidth = o), void 0 !== s ? s + "" : s
}
function S(e, t) {
return {
get: function () {
return e() ? void delete this.get : (this.get = t).apply(this, arguments)
}
}
}
function j(e) {
if (e in rt) return e;
for (var t = e[0].toUpperCase() + e.slice(1), n = nt.length; n--;)
if (e = nt[n] + t, e in rt) return e
}
function M(e, t, n) {
var r = He.exec(t);
return r ? Math.max(0, r[2] - (n || 0)) + (r[3] || "px") : t
}
function H(e, t, n, r, i) {
for (var o = n === (r ? "border" : "content") ? 4 : "width" === t ? 1 : 0, s = 0; o < 4; o += 2) "margin" === n && (s += oe.css(e, n + Ne[o], !0, i)), r ? ("content" === n && (s -= oe.css(e, "padding" + Ne[o], !0, i)), "margin" !== n && (s -= oe.css(e, "border" + Ne[o] + "Width", !0, i))) : (s += oe.css(e, "padding" + Ne[o], !0, i), "padding" !== n && (s += oe.css(e, "border" + Ne[o] + "Width", !0, i)));
return s
}
function N(e, t, n) {
var r = !0,
i = "width" === t ? e.offsetWidth : e.offsetHeight,
o = Ve(e),
s = "border-box" === oe.css(e, "boxSizing", !1, o);
if (i <= 0 || null == i) {
if (i = E(e, t, o), (i < 0 || null == i) && (i = e.style[t]), Ye.test(i)) return i;
r = s && (re.boxSizingReliable() || i === e.style[t]), i = parseFloat(i) || 0
}
return i + H(e, t, n || (s ? "border" : "content"), r, o) + "px"
}
function D(e, t) {
for (var n, r, i, o = [], s = 0, a = e.length; s < a; s++) r = e[s], r.style && (o[s] = ke.get(r, "olddisplay"), n = r.style.display, t ? (o[s] || "none" !== n || (r.style.display = ""), "" === r.style.display && De(r) && (o[s] = ke.access(r, "olddisplay", k(r.nodeName)))) : (i = De(r), "none" === n && i || ke.set(r, "olddisplay", i ? n : oe.css(r, "display"))));
for (s = 0; s < a; s++) r = e[s], r.style && (t && "none" !== r.style.display && "" !== r.style.display || (r.style.display = t ? o[s] || "" : "none"));
return e
}
function A(e, t, n, r, i) {
return new A.prototype.init(e, t, n, r, i)
}
function O() {
return e.setTimeout(function () {
it = void 0
}), it = oe.now()
}
function q(e, t) {
var n, r = 0,
i = {
height: e
};
for (t = t ? 1 : 0; r < 4; r += 2 - t) n = Ne[r], i["margin" + n] = i["padding" + n] = e;
return t && (i.opacity = i.width = e), i
}
function I(e, t, n) {
for (var r, i = (F.tweeners[t] || []).concat(F.tweeners["*"]), o = 0, s = i.length; o < s; o++)
if (r = i[o].call(n, t, e)) return r
}
function L(e, t, n) {
var r, i, o, s, a, u, l, c, f = this,
d = {},
h = e.style,
p = e.nodeType && De(e),
g = ke.get(e, "fxshow");
n.queue || (a = oe._queueHooks(e, "fx"), null == a.unqueued && (a.unqueued = 0, u = a.empty.fire, a.empty.fire = function () {
a.unqueued || u()
}), a.unqueued++, f.always(function () {
f.always(function () {
a.unqueued--, oe.queue(e, "fx").length || a.empty.fire()
})
})), 1 === e.nodeType && ("height" in t || "width" in t) && (n.overflow = [h.overflow, h.overflowX, h.overflowY], l = oe.css(e, "display"), c = "none" === l ? ke.get(e, "olddisplay") || k(e.nodeName) : l, "inline" === c && "none" === oe.css(e, "float") && (h.display = "inline-block")), n.overflow && (h.overflow = "hidden", f.always(function () {
h.overflow = n.overflow[0], h.overflowX = n.overflow[1], h.overflowY = n.overflow[2]
}));
for (r in t)
if (i = t[r], st.exec(i)) {
if (delete t[r], o = o || "toggle" === i, i === (p ? "hide" : "show")) {
if ("show" !== i || !g || void 0 === g[r]) continue;
p = !0
}
d[r] = g && g[r] || oe.style(e, r)
} else l = void 0;
if (oe.isEmptyObject(d)) "inline" === ("none" === l ? k(e.nodeName) : l) && (h.display = l);
else {
g ? "hidden" in g && (p = g.hidden) : g = ke.access(e, "fxshow", {}), o && (g.hidden = !p), p ? oe(e).show() : f.done(function () {
oe(e).hide()
}), f.done(function () {
var t;
ke.remove(e, "fxshow");
for (t in d) oe.style(e, t, d[t])
});
for (r in d) s = I(p ? g[r] : 0, r, f), r in g || (g[r] = s.start, p && (s.end = s.start, s.start = "width" === r || "height" === r ? 1 : 0))
}
}
function P(e, t) {
var n, r, i, o, s;
for (n in e)
if (r = oe.camelCase(n), i = t[r], o = e[n], oe.isArray(o) && (i = o[1], o = e[n] = o[0]), n !== r && (e[r] = o, delete e[n]), s = oe.cssHooks[r], s && "expand" in s) {
o = s.expand(o), delete e[r];
for (n in o) n in e || (e[n] = o[n], t[n] = i)
} else t[r] = i
}
function F(e, t, n) {
var r, i, o = 0,
s = F.prefilters.length,
a = oe.Deferred().always(function () {
delete u.elem
}),
u = function () {
if (i) return !1;
for (var t = it || O(), n = Math.max(0, l.startTime + l.duration - t), r = n / l.duration || 0, o = 1 - r, s = 0, u = l.tweens.length; s < u; s++) l.tweens[s].run(o);
return a.notifyWith(e, [l, o, n]), o < 1 && u ? n : (a.resolveWith(e, [l]), !1)
},
l = a.promise({
elem: e,
props: oe.extend({}, t),
opts: oe.extend(!0, {
specialEasing: {},
easing: oe.easing._default
}, n),
originalProperties: t,
originalOptions: n,
startTime: it || O(),
duration: n.duration,
tweens: [],
createTween: function (t, n) {
var r = oe.Tween(e, l.opts, t, n, l.opts.specialEasing[t] || l.opts.easing);
return l.tweens.push(r), r
},
stop: function (t) {
var n = 0,
r = t ? l.tweens.length : 0;
if (i) return this;
for (i = !0; n < r; n++) l.tweens[n].run(1);
return t ? (a.notifyWith(e, [l, 1, 0]), a.resolveWith(e, [l, t])) : a.rejectWith(e, [l, t]), this
}
}),
c = l.props;
for (P(c, l.opts.specialEasing); o < s; o++)
if (r = F.prefilters[o].call(l, e, c, l.opts)) return oe.isFunction(r.stop) && (oe._queueHooks(l.elem, l.opts.queue).stop = oe.proxy(r.stop, r)), r;
return oe.map(c, I, l), oe.isFunction(l.opts.start) && l.opts.start.call(e, l), oe.fx.timer(oe.extend(u, {
elem: e,
anim: l,
queue: l.opts.queue
})), l.progress(l.opts.progress).done(l.opts.done, l.opts.complete).fail(l.opts.fail).always(l.opts.always)
}
function R(e) {
return e.getAttribute && e.getAttribute("class") || ""
}
function z(e) {
return function (t, n) {
"string" != typeof t && (n = t, t = "*");
var r, i = 0,
o = t.toLowerCase().match(we) || [];
if (oe.isFunction(n))
for (; r = o[i++];) "+" === r[0] ? (r = r.slice(1) || "*", (e[r] = e[r] || []).unshift(n)) : (e[r] = e[r] || []).push(n)
}
}
function W(e, t, n, r) {
function i(a) {
var u;
return o[a] = !0, oe.each(e[a] || [], function (e, a) {
var l = a(t, n, r);
return "string" != typeof l || s || o[l] ? s ? !(u = l) : void 0 : (t.dataTypes.unshift(l), i(l), !1)
}), u
}
var o = {},
s = e === Et;
return i(t.dataTypes[0]) || !o["*"] && i("*")
}
function B(e, t) {
var n, r, i = oe.ajaxSettings.flatOptions || {};
for (n in t) void 0 !== t[n] && ((i[n] ? e : r || (r = {}))[n] = t[n]);
return r && oe.extend(!0, e, r), e
}
function _(e, t, n) {
for (var r, i, o, s, a = e.contents, u = e.dataTypes;
"*" === u[0];) u.shift(), void 0 === r && (r = e.mimeType || t.getResponseHeader("Content-Type"));
if (r)
for (i in a)
if (a[i] && a[i].test(r)) {
u.unshift(i);
break
}
if (u[0] in n) o = u[0];
else {
for (i in n) {
if (!u[0] || e.converters[i + " " + u[0]]) {
o = i;
break
}
s || (s = i)
}
o = o || s
}
if (o) return o !== u[0] && u.unshift(o), n[o]
}
function G(e, t, n, r) {
var i, o, s, a, u, l = {},
c = e.dataTypes.slice();
if (c[1])
for (s in e.converters) l[s.toLowerCase()] = e.converters[s];
for (o = c.shift(); o;)
if (e.responseFields[o] && (n[e.responseFields[o]] = t), !u && r && e.dataFilter && (t = e.dataFilter(t, e.dataType)), u = o, o = c.shift())
if ("*" === o) o = u;
else if ("*" !== u && u !== o) {
if (s = l[u + " " + o] || l["* " + o], !s)
for (i in l)
if (a = i.split(" "), a[1] === o && (s = l[u + " " + a[0]] || l["* " + a[0]])) {
s === !0 ? s = l[i] : l[i] !== !0 && (o = a[0], c.unshift(a[1]));
break
}
if (s !== !0)
if (s && e["throws"]) t = s(t);
else try {
t = s(t)
} catch (f) {
return {
state: "parsererror",
error: s ? f : "No conversion from " + u + " to " + o
}
}
}
return {
state: "success",
data: t
}
}
function X(e, t, n, r) {
var i;
if (oe.isArray(t)) oe.each(t, function (t, i) {
n || Ht.test(e) ? r(e, i) : X(e + "[" + ("object" == typeof i && null != i ? t : "") + "]", i, n, r)
});
else if (n || "object" !== oe.type(t)) r(e, t);
else
for (i in t) X(e + "[" + i + "]", t[i], n, r)
}
function Q(e) {
return oe.isWindow(e) ? e : 9 === e.nodeType && e.defaultView
}
var U = [],
Y = e.document,
V = U.slice,
J = U.concat,
K = U.push,
Z = U.indexOf,
ee = {},
te = ee.toString,
ne = ee.hasOwnProperty,
re = {},
ie = "2.2.4",
oe = function (e, t) {
return new oe.fn.init(e, t)
},
se = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
ae = /^-ms-/,
ue = /-([\da-z])/gi,
le = function (e, t) {
return t.toUpperCase()
};
oe.fn = oe.prototype = {
jquery: ie,
constructor: oe,
selector: "",
length: 0,
toArray: function () {
return V.call(this)
},
get: function (e) {
return null != e ? e < 0 ? this[e + this.length] : this[e] : V.call(this)
},
pushStack: function (e) {
var t = oe.merge(this.constructor(), e);
return t.prevObject = this, t.context = this.context, t
},
each: function (e) {
return oe.each(this, e)
},
map: function (e) {
return this.pushStack(oe.map(this, function (t, n) {
return e.call(t, n, t)
}))
},
slice: function () {
return this.pushStack(V.apply(this, arguments))
},
first: function () {
return this.eq(0)
},
last: function () {
return this.eq(-1)
},
eq: function (e) {
var t = this.length,
n = +e + (e < 0 ? t : 0);
return this.pushStack(n >= 0 && n < t ? [this[n]] : [])
},
end: function () {
return this.prevObject || this.constructor()
},
push: K,
sort: U.sort,
splice: U.splice
}, oe.extend = oe.fn.extend = function () {
var e, t, n, r, i, o, s = arguments[0] || {},
a = 1,
u = arguments.length,
l = !1;
for ("boolean" == typeof s && (l = s, s = arguments[a] || {}, a++), "object" == typeof s || oe.isFunction(s) || (s = {}), a === u && (s = this, a--); a < u; a++)
if (null != (e = arguments[a]))
for (t in e) n = s[t], r = e[t], s !== r && (l && r && (oe.isPlainObject(r) || (i = oe.isArray(r))) ? (i ? (i = !1, o = n && oe.isArray(n) ? n : []) : o = n && oe.isPlainObject(n) ? n : {}, s[t] = oe.extend(l, o, r)) : void 0 !== r && (s[t] = r));
return s
}, oe.extend({
expando: "jQuery" + (ie + Math.random()).replace(/\D/g, ""),
isReady: !0,
error: function (e) {
throw new Error(e)
},
noop: function () {},
isFunction: function (e) {
return "function" === oe.type(e)
},
isArray: Array.isArray,
isWindow: function (e) {
return null != e && e === e.window
},
isNumeric: function (e) {
var t = e && e.toString();
return !oe.isArray(e) && t - parseFloat(t) + 1 >= 0
},
isPlainObject: function (e) {
var t;
if ("object" !== oe.type(e) || e.nodeType || oe.isWindow(e)) return !1;
if (e.constructor && !ne.call(e, "constructor") && !ne.call(e.constructor.prototype || {}, "isPrototypeOf")) return !1;
for (t in e);
return void 0 === t || ne.call(e, t)
},
isEmptyObject: function (e) {
var t;
for (t in e) return !1;
return !0
},
type: function (e) {
return null == e ? e + "" : "object" == typeof e || "function" == typeof e ? ee[te.call(e)] || "object" : typeof e
},
globalEval: function (e) {
var t, n = eval;
e = oe.trim(e), e && (1 === e.indexOf("use strict") ? (t = Y.createElement("script"), t.text = e, Y.head.appendChild(t).parentNode.removeChild(t)) : n(e))
},
camelCase: function (e) {
return e.replace(ae, "ms-").replace(ue, le)
},
nodeName: function (e, t) {
return e.nodeName && e.nodeName.toLowerCase() === t.toLowerCase()
},
each: function (e, t) {
var r, i = 0;
if (n(e))
for (r = e.length; i < r && t.call(e[i], i, e[i]) !== !1; i++);
else
for (i in e)
if (t.call(e[i], i, e[i]) === !1) break; return e
},
trim: function (e) {
return null == e ? "" : (e + "").replace(se, "")
},
makeArray: function (e, t) {
var r = t || [];
return null != e && (n(Object(e)) ? oe.merge(r, "string" == typeof e ? [e] : e) : K.call(r, e)), r
},
inArray: function (e, t, n) {
return null == t ? -1 : Z.call(t, e, n)
},
merge: function (e, t) {
for (var n = +t.length, r = 0, i = e.length; r < n; r++) e[i++] = t[r];
return e.length = i, e
},
grep: function (e, t, n) {
for (var r, i = [], o = 0, s = e.length, a = !n; o < s; o++) r = !t(e[o], o), r !== a && i.push(e[o]);
return i
},
map: function (e, t, r) {
var i, o, s = 0,
a = [];
if (n(e))
for (i = e.length; s < i; s++) o = t(e[s], s, r), null != o && a.push(o);
else
for (s in e) o = t(e[s], s, r), null != o && a.push(o);
return J.apply([], a)
},
guid: 1,
proxy: function (e, t) {
var n, r, i;
if ("string" == typeof t && (n = e[t], t = e, e = n), oe.isFunction(e)) return r = V.call(arguments, 2), i = function () {
return e.apply(t || this, r.concat(V.call(arguments)))
}, i.guid = e.guid = e.guid || oe.guid++, i
},
now: Date.now,
support: re
}), "function" == typeof Symbol && (oe.fn[Symbol.iterator] = U[Symbol.iterator]), oe.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "), function (e, t) {
ee["[object " + t + "]"] = t.toLowerCase()
});
var ce =
/*!
* Sizzle CSS Selector Engine v2.2.1
* http://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-10-17
*/
function (e) {
function t(e, t, n, r) {
var i, o, s, a, u, l, f, h, p = t && t.ownerDocument,
g = t ? t.nodeType : 9;
if (n = n || [], "string" != typeof e || !e || 1 !== g && 9 !== g && 11 !== g) return n;
if (!r && ((t ? t.ownerDocument || t : R) !== D && N(t), t = t || D, O)) {
if (11 !== g && (l = ve.exec(e)))
if (i = l[1]) {
if (9 === g) {
if (!(s = t.getElementById(i))) return n;
if (s.id === i) return n.push(s), n
} else if (p && (s = p.getElementById(i)) && P(t, s) && s.id === i) return n.push(s), n
} else {
if (l[2]) return K.apply(n, t.getElementsByTagName(e)), n;
if ((i = l[3]) && w.getElementsByClassName && t.getElementsByClassName) return K.apply(n, t.getElementsByClassName(i)), n
}
if (w.qsa && !G[e + " "] && (!q || !q.test(e))) {
if (1 !== g) p = t, h = e;
else if ("object" !== t.nodeName.toLowerCase()) {
for ((a = t.getAttribute("id")) ? a = a.replace(be, "\\$&") : t.setAttribute("id", a = F), f = k(e), o = f.length, u = de.test(a) ? "#" + a : "[id='" + a + "']"; o--;) f[o] = u + " " + d(f[o]);
h = f.join(","), p = ye.test(e) && c(t.parentNode) || t
}
if (h) try {
return K.apply(n, p.querySelectorAll(h)), n
} catch (m) {} finally {
a === F && t.removeAttribute("id")
}
}
}
return S(e.replace(ae, "$1"), t, n, r)
}
function n() {
function e(n, r) {
return t.push(n + " ") > $.cacheLength && delete e[t.shift()], e[n + " "] = r
}
var t = [];
return e
}
function r(e) {
return e[F] = !0, e
}
function i(e) {
var t = D.createElement("div");
try {
return !!e(t)
} catch (n) {
return !1
} finally {
t.parentNode && t.parentNode.removeChild(t), t = null
}
}
function o(e, t) {
for (var n = e.split("|"), r = n.length; r--;) $.attrHandle[n[r]] = t
}
function s(e, t) {
var n = t && e,
r = n && 1 === e.nodeType && 1 === t.nodeType && (~t.sourceIndex || Q) - (~e.sourceIndex || Q);
if (r) return r;
if (n)
for (; n = n.nextSibling;)
if (n === t) return -1;
return e ? 1 : -1
}
function a(e) {
return function (t) {
var n = t.nodeName.toLowerCase();
return "input" === n && t.type === e
}
}
function u(e) {
return function (t) {
var n = t.nodeName.toLowerCase();
return ("input" === n || "button" === n) && t.type === e
}
}
function l(e) {
return r(function (t) {
return t = +t, r(function (n, r) {
for (var i, o = e([], n.length, t), s = o.length; s--;) n[i = o[s]] && (n[i] = !(r[i] = n[i]))
})
})
}
function c(e) {
return e && "undefined" != typeof e.getElementsByTagName && e
}
function f() {}
function d(e) {
for (var t = 0, n = e.length, r = ""; t < n; t++) r += e[t].value;
return r
}
function h(e, t, n) {
var r = t.dir,
i = n && "parentNode" === r,
o = W++;
return t.first ? function (t, n, o) {
for (; t = t[r];)
if (1 === t.nodeType || i) return e(t, n, o)
} : function (t, n, s) {
var a, u, l, c = [z, o];
if (s) {
for (; t = t[r];)
if ((1 === t.nodeType || i) && e(t, n, s)) return !0
} else
for (; t = t[r];)
if (1 === t.nodeType || i) {
if (l = t[F] || (t[F] = {}), u = l[t.uniqueID] || (l[t.uniqueID] = {}), (a = u[r]) && a[0] === z && a[1] === o) return c[2] = a[2];
if (u[r] = c, c[2] = e(t, n, s)) return !0
}
}
}
function p(e) {
return e.length > 1 ? function (t, n, r) {
for (var i = e.length; i--;)
if (!e[i](t, n, r)) return !1;
return !0
} : e[0]
}
function g(e, n, r) {
for (var i = 0, o = n.length; i < o; i++) t(e, n[i], r);
return r
}
function m(e, t, n, r, i) {
for (var o, s = [], a = 0, u = e.length, l = null != t; a < u; a++)(o = e[a]) && (n && !n(o, r, i) || (s.push(o), l && t.push(a)));
return s
}
function v(e, t, n, i, o, s) {
return i && !i[F] && (i = v(i)), o && !o[F] && (o = v(o, s)), r(function (r, s, a, u) {
var l, c, f, d = [],
h = [],
p = s.length,
v = r || g(t || "*", a.nodeType ? [a] : a, []),
y = !e || !r && t ? v : m(v, d, e, a, u),
b = n ? o || (r ? e : p || i) ? [] : s : y;
if (n && n(y, b, a, u), i)
for (l = m(b, h), i(l, [], a, u), c = l.length; c--;)(f = l[c]) && (b[h[c]] = !(y[h[c]] = f));
if (r) {
if (o || e) {
if (o) {
for (l = [], c = b.length; c--;)(f = b[c]) && l.push(y[c] = f);
o(null, b = [], l, u)
}
for (c = b.length; c--;)(f = b[c]) && (l = o ? ee(r, f) : d[c]) > -1 && (r[l] = !(s[l] = f))
}
} else b = m(b === s ? b.splice(p, b.length) : b), o ? o(null, s, b, u) : K.apply(s, b)
})
}
function y(e) {
for (var t, n, r, i = e.length, o = $.relative[e[0].type], s = o || $.relative[" "], a = o ? 1 : 0, u = h(function (e) {
return e === t
}, s, !0), l = h(function (e) {
return ee(t, e) > -1
}, s, !0), c = [function (e, n, r) {
var i = !o && (r || n !== j) || ((t = n).nodeType ? u(e, n, r) : l(e, n, r));
return t = null, i
}]; a < i; a++)
if (n = $.relative[e[a].type]) c = [h(p(c), n)];
else {
if (n = $.filter[e[a].type].apply(null, e[a].matches), n[F]) {
for (r = ++a; r < i && !$.relative[e[r].type]; r++);
return v(a > 1 && p(c), a > 1 && d(e.slice(0, a - 1).concat({
value: " " === e[a - 2].type ? "*" : ""
})).replace(ae, "$1"), n, a < r && y(e.slice(a, r)), r < i && y(e = e.slice(r)), r < i && d(e))
}
c.push(n)
}
return p(c)
}
function b(e, n) {
var i = n.length > 0,
o = e.length > 0,
s = function (r, s, a, u, l) {
var c, f, d, h = 0,
p = "0",
g = r && [],
v = [],
y = j,
b = r || o && $.find.TAG("*", l),
x = z += null == y ? 1 : Math.random() || .1,
w = b.length;
for (l && (j = s === D || s || l); p !== w && null != (c = b[p]); p++) {
if (o && c) {
for (f = 0, s || c.ownerDocument === D || (N(c), a = !O); d = e[f++];)
if (d(c, s || D, a)) {
u.push(c);
break
}
l && (z = x)
}
i && ((c = !d && c) && h--, r && g.push(c))
}
if (h += p, i && p !== h) {
for (f = 0; d = n[f++];) d(g, v, s, a);
if (r) {
if (h > 0)
for (; p--;) g[p] || v[p] || (v[p] = V.call(u));
v = m(v)
}
K.apply(u, v), l && !r && v.length > 0 && h + n.length > 1 && t.uniqueSort(u)
}
return l && (z = x, j = y), g
};
return i ? r(s) : s
}
var x, w, $, C, T, k, E, S, j, M, H, N, D, A, O, q, I, L, P, F = "sizzle" + 1 * new Date,
R = e.document,
z = 0,
W = 0,
B = n(),
_ = n(),
G = n(),
X = function (e, t) {
return e === t && (H = !0), 0
},
Q = 1 << 31,
U = {}.hasOwnProperty,
Y = [],
V = Y.pop,
J = Y.push,
K = Y.push,
Z = Y.slice,
ee = function (e, t) {
for (var n = 0, r = e.length; n < r; n++)
if (e[n] === t) return n;
return -1
},
te = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
ne = "[\\x20\\t\\r\\n\\f]",
re = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
ie = "\\[" + ne + "*(" + re + ")(?:" + ne + "*([*^$|!~]?=)" + ne + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + re + "))|)" + ne + "*\\]",
oe = ":(" + re + ")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|" + ie + ")*)|.*)\\)|)",
se = new RegExp(ne + "+", "g"),
ae = new RegExp("^" + ne + "+|((?:^|[^\\\\])(?:\\\\.)*)" + ne + "+$", "g"),
ue = new RegExp("^" + ne + "*," + ne + "*"),
le = new RegExp("^" + ne + "*([>+~]|" + ne + ")" + ne + "*"),
ce = new RegExp("=" + ne + "*([^\\]'\"]*?)" + ne + "*\\]", "g"),
fe = new RegExp(oe),
de = new RegExp("^" + re + "$"),
he = {
ID: new RegExp("^#(" + re + ")"),
CLASS: new RegExp("^\\.(" + re + ")"),
TAG: new RegExp("^(" + re + "|[*])"),
ATTR: new RegExp("^" + ie),
PSEUDO: new RegExp("^" + oe),
CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + ne + "*(even|odd|(([+-]|)(\\d*)n|)" + ne + "*(?:([+-]|)" + ne + "*(\\d+)|))" + ne + "*\\)|)", "i"),
bool: new RegExp("^(?:" + te + ")$", "i"),
needsContext: new RegExp("^" + ne + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + ne + "*((?:-\\d)?\\d*)" + ne + "*\\)|)(?=[^-]|$)", "i")
},
pe = /^(?:input|select|textarea|button)$/i,
ge = /^h\d$/i,
me = /^[^{]+\{\s*\[native \w/,
ve = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
ye = /[+~]/,
be = /'|\\/g,
xe = new RegExp("\\\\([\\da-f]{1,6}" + ne + "?|(" + ne + ")|.)", "ig"),
we = function (e, t, n) {
var r = "0x" + t - 65536;
return r !== r || n ? t : r < 0 ? String.fromCharCode(r + 65536) : String.fromCharCode(r >> 10 | 55296, 1023 & r | 56320)
},
$e = function () {
N()
};
try {
K.apply(Y = Z.call(R.childNodes), R.childNodes), Y[R.childNodes.length].nodeType
} catch (Ce) {
K = {
apply: Y.length ? function (e, t) {
J.apply(e, Z.call(t))
} : function (e, t) {
for (var n = e.length, r = 0; e[n++] = t[r++];);
e.length = n - 1
}
}
}
w = t.support = {}, T = t.isXML = function (e) {
var t = e && (e.ownerDocument || e).documentElement;
return !!t && "HTML" !== t.nodeName
}, N = t.setDocument = function (e) {
var t, n, r = e ? e.ownerDocument || e : R;
return r !== D && 9 === r.nodeType && r.documentElement ? (D = r, A = D.documentElement, O = !T(D), (n = D.defaultView) && n.top !== n && (n.addEventListener ? n.addEventListener("unload", $e, !1) : n.attachEvent && n.attachEvent("onunload", $e)), w.attributes = i(function (e) {
return e.className = "i", !e.getAttribute("className")
}), w.getElementsByTagName = i(function (e) {
return e.appendChild(D.createComment("")), !e.getElementsByTagName("*").length
}), w.getElementsByClassName = me.test(D.getElementsByClassName), w.getById = i(function (e) {
return A.appendChild(e).id = F, !D.getElementsByName || !D.getElementsByName(F).length
}), w.getById ? ($.find.ID = function (e, t) {
if ("undefined" != typeof t.getElementById && O) {
var n = t.getElementById(e);
return n ? [n] : []
}
}, $.filter.ID = function (e) {
var t = e.replace(xe, we);
return function (e) {
return e.getAttribute("id") === t
}
}) : (delete $.find.ID, $.filter.ID = function (e) {
var t = e.replace(xe, we);
return function (e) {
var n = "undefined" != typeof e.getAttributeNode && e.getAttributeNode("id");
return n && n.value === t
}
}), $.find.TAG = w.getElementsByTagName ? function (e, t) {
return "undefined" != typeof t.getElementsByTagName ? t.getElementsByTagName(e) : w.qsa ? t.querySelectorAll(e) : void 0
} : function (e, t) {
var n, r = [],
i = 0,
o = t.getElementsByTagName(e);
if ("*" === e) {
for (; n = o[i++];) 1 === n.nodeType && r.push(n);
return r
}
return o
}, $.find.CLASS = w.getElementsByClassName && function (e, t) {
if ("undefined" != typeof t.getElementsByClassName && O) return t.getElementsByClassName(e)
}, I = [], q = [], (w.qsa = me.test(D.querySelectorAll)) && (i(function (e) {
A.appendChild(e).innerHTML = "<a id='" + F + "'></a><select id='" + F + "-\r\\' msallowcapture=''><option selected=''></option></select>", e.querySelectorAll("[msallowcapture^='']").length && q.push("[*^$]=" + ne + "*(?:''|\"\")"), e.querySelectorAll("[selected]").length || q.push("\\[" + ne + "*(?:value|" + te + ")"), e.querySelectorAll("[id~=" + F + "-]").length || q.push("~="), e.querySelectorAll(":checked").length || q.push(":checked"), e.querySelectorAll("a#" + F + "+*").length || q.push(".#.+[+~]")
}), i(function (e) {
var t = D.createElement("input");
t.setAttribute("type", "hidden"), e.appendChild(t).setAttribute("name", "D"), e.querySelectorAll("[name=d]").length && q.push("name" + ne + "*[*^$|!~]?="), e.querySelectorAll(":enabled").length || q.push(":enabled", ":disabled"), e.querySelectorAll("*,:x"), q.push(",.*:")
})), (w.matchesSelector = me.test(L = A.matches || A.webkitMatchesSelector || A.mozMatchesSelector || A.oMatchesSelector || A.msMatchesSelector)) && i(function (e) {
w.disconnectedMatch = L.call(e, "div"), L.call(e, "[s!='']:x"), I.push("!=", oe)
}), q = q.length && new RegExp(q.join("|")), I = I.length && new RegExp(I.join("|")), t = me.test(A.compareDocumentPosition), P = t || me.test(A.contains) ? function (e, t) {
var n = 9 === e.nodeType ? e.documentElement : e,
r = t && t.parentNode;
return e === r || !(!r || 1 !== r.nodeType || !(n.contains ? n.contains(r) : e.compareDocumentPosition && 16 & e.compareDocumentPosition(r)))
} : function (e, t) {
if (t)
for (; t = t.parentNode;)
if (t === e) return !0;
return !1
}, X = t ? function (e, t) {
if (e === t) return H = !0, 0;
var n = !e.compareDocumentPosition - !t.compareDocumentPosition;
return n ? n : (n = (e.ownerDocument || e) === (t.ownerDocument || t) ? e.compareDocumentPosition(t) : 1, 1 & n || !w.sortDetached && t.compareDocumentPosition(e) === n ? e === D || e.ownerDocument === R && P(R, e) ? -1 : t === D || t.ownerDocument === R && P(R, t) ? 1 : M ? ee(M, e) - ee(M, t) : 0 : 4 & n ? -1 : 1)
} : function (e, t) {
if (e === t) return H = !0, 0;
var n, r = 0,
i = e.parentNode,
o = t.parentNode,
a = [e],
u = [t];
if (!i || !o) return e === D ? -1 : t === D ? 1 : i ? -1 : o ? 1 : M ? ee(M, e) - ee(M, t) : 0;
if (i === o) return s(e, t);
for (n = e; n = n.parentNode;) a.unshift(n);
for (n = t; n = n.parentNode;) u.unshift(n);
for (; a[r] === u[r];) r++;
return r ? s(a[r], u[r]) : a[r] === R ? -1 : u[r] === R ? 1 : 0
}, D) : D
}, t.matches = function (e, n) {
return t(e, null, null, n)
}, t.matchesSelector = function (e, n) {
if ((e.ownerDocument || e) !== D && N(e), n = n.replace(ce, "='$1']"), w.matchesSelector && O && !G[n + " "] && (!I || !I.test(n)) && (!q || !q.test(n))) try {
var r = L.call(e, n);
if (r || w.disconnectedMatch || e.document && 11 !== e.document.nodeType) return r
} catch (i) {}
return t(n, D, null, [e]).length > 0
}, t.contains = function (e, t) {
return (e.ownerDocument || e) !== D && N(e), P(e, t)
}, t.attr = function (e, t) {
(e.ownerDocument || e) !== D && N(e);
var n = $.attrHandle[t.toLowerCase()],
r = n && U.call($.attrHandle, t.toLowerCase()) ? n(e, t, !O) : void 0;
return void 0 !== r ? r : w.attributes || !O ? e.getAttribute(t) : (r = e.getAttributeNode(t)) && r.specified ? r.value : null
}, t.error = function (e) {
throw new Error("Syntax error, unrecognized expression: " + e)
}, t.uniqueSort = function (e) {
var t, n = [],
r = 0,
i = 0;
if (H = !w.detectDuplicates, M = !w.sortStable && e.slice(0), e.sort(X), H) {
for (; t = e[i++];) t === e[i] && (r = n.push(i));
for (; r--;) e.splice(n[r], 1)
}
return M = null, e
}, C = t.getText = function (e) {
var t, n = "",
r = 0,
i = e.nodeType;
if (i) {
if (1 === i || 9 === i || 11 === i) {
if ("string" == typeof e.textContent) return e.textContent;
for (e = e.firstChild; e; e = e.nextSibling) n += C(e)
} else if (3 === i || 4 === i) return e.nodeValue
} else
for (; t = e[r++];) n += C(t);
return n
}, $ = t.selectors = {
cacheLength: 50,
createPseudo: r,
match: he,
attrHandle: {},
find: {},
relative: {
">": {
dir: "parentNode",
first: !0
},
" ": {
dir: "parentNode"
},
"+": {
dir: "previousSibling",
first: !0
},
"~": {
dir: "previousSibling"
}
},
preFilter: {
ATTR: function (e) {
return e[1] = e[1].replace(xe, we), e[3] = (e[3] || e[4] || e[5] || "").replace(xe, we), "~=" === e[2] && (e[3] = " " + e[3] + " "), e.slice(0, 4)
},
CHILD: function (e) {
return e[1] = e[1].toLowerCase(), "nth" === e[1].slice(0, 3) ? (e[3] || t.error(e[0]), e[4] = +(e[4] ? e[5] + (e[6] || 1) : 2 * ("even" === e[3] || "odd" === e[3])), e[5] = +(e[7] + e[8] || "odd" === e[3])) : e[3] && t.error(e[0]), e
},
PSEUDO: function (e) {
var t, n = !e[6] && e[2];
return he.CHILD.test(e[0]) ? null : (e[3] ? e[2] = e[4] || e[5] || "" : n && fe.test(n) && (t = k(n, !0)) && (t = n.indexOf(")", n.length - t) - n.length) && (e[0] = e[0].slice(0, t), e[2] = n.slice(0, t)), e.slice(0, 3))
}
},
filter: {
TAG: function (e) {
var t = e.replace(xe, we).toLowerCase();
return "*" === e ? function () {
return !0
} : function (e) {
return e.nodeName && e.nodeName.toLowerCase() === t
}
},
CLASS: function (e) {
var t = B[e + " "];
return t || (t = new RegExp("(^|" + ne + ")" + e + "(" + ne + "|$)")) && B(e, function (e) {
return t.test("string" == typeof e.className && e.className || "undefined" != typeof e.getAttribute && e.getAttribute("class") || "")
})
},
ATTR: function (e, n, r) {
return function (i) {
var o = t.attr(i, e);
return null == o ? "!=" === n : !n || (o += "", "=" === n ? o === r : "!=" === n ? o !== r : "^=" === n ? r && 0 === o.indexOf(r) : "*=" === n ? r && o.indexOf(r) > -1 : "$=" === n ? r && o.slice(-r.length) === r : "~=" === n ? (" " + o.replace(se, " ") + " ").indexOf(r) > -1 : "|=" === n && (o === r || o.slice(0, r.length + 1) === r + "-"))
}
},
CHILD: function (e, t, n, r, i) {
var o = "nth" !== e.slice(0, 3),
s = "last" !== e.slice(-4),
a = "of-type" === t;
return 1 === r && 0 === i ? function (e) {
return !!e.parentNode
} : function (t, n, u) {
var l, c, f, d, h, p, g = o !== s ? "nextSibling" : "previousSibling",
m = t.parentNode,
v = a && t.nodeName.toLowerCase(),
y = !u && !a,
b = !1;
if (m) {
if (o) {
for (; g;) {
for (d = t; d = d[g];)
if (a ? d.nodeName.toLowerCase() === v : 1 === d.nodeType) return !1;
p = g = "only" === e && !p && "nextSibling"
}
return !0
}
if (p = [s ? m.firstChild : m.lastChild], s && y) {
for (d = m, f = d[F] || (d[F] = {}), c = f[d.uniqueID] || (f[d.uniqueID] = {}), l = c[e] || [], h = l[0] === z && l[1], b = h && l[2], d = h && m.childNodes[h]; d = ++h && d && d[g] || (b = h = 0) || p.pop();)
if (1 === d.nodeType && ++b && d === t) {
c[e] = [z, h, b];
break
}
} else if (y && (d = t, f = d[F] || (d[F] = {}), c = f[d.uniqueID] || (f[d.uniqueID] = {}), l = c[e] || [], h = l[0] === z && l[1], b = h), b === !1)
for (;
(d = ++h && d && d[g] || (b = h = 0) || p.pop()) && ((a ? d.nodeName.toLowerCase() !== v : 1 !== d.nodeType) || !++b || (y && (f = d[F] || (d[F] = {}), c = f[d.uniqueID] || (f[d.uniqueID] = {}), c[e] = [z, b]), d !== t)););
return b -= i, b === r || b % r === 0 && b / r >= 0
}
}
},
PSEUDO: function (e, n) {
var i, o = $.pseudos[e] || $.setFilters[e.toLowerCase()] || t.error("unsupported pseudo: " + e);
return o[F] ? o(n) : o.length > 1 ? (i = [e, e, "", n], $.setFilters.hasOwnProperty(e.toLowerCase()) ? r(function (e, t) {
for (var r, i = o(e, n), s = i.length; s--;) r = ee(e, i[s]), e[r] = !(t[r] = i[s])
}) : function (e) {
return o(e, 0, i)
}) : o
}
},
pseudos: {
not: r(function (e) {
var t = [],
n = [],
i = E(e.replace(ae, "$1"));
return i[F] ? r(function (e, t, n, r) {
for (var o, s = i(e, null, r, []), a = e.length; a--;)(o = s[a]) && (e[a] = !(t[a] = o))
}) : function (e, r, o) {
return t[0] = e, i(t, null, o, n), t[0] = null, !n.pop()
}
}),
has: r(function (e) {
return function (n) {
return t(e, n).length > 0
}
}),
contains: r(function (e) {
return e = e.replace(xe, we),
function (t) {
return (t.textContent || t.innerText || C(t)).indexOf(e) > -1
}
}),
lang: r(function (e) {
return de.test(e || "") || t.error("unsupported lang: " + e), e = e.replace(xe, we).toLowerCase(),
function (t) {
var n;
do
if (n = O ? t.lang : t.getAttribute("xml:lang") || t.getAttribute("lang")) return n = n.toLowerCase(), n === e || 0 === n.indexOf(e + "-");
while ((t = t.parentNode) && 1 === t.nodeType);
return !1
}
}),
target: function (t) {
var n = e.location && e.location.hash;
return n && n.slice(1) === t.id
},
root: function (e) {
return e === A
},
focus: function (e) {
return e === D.activeElement && (!D.hasFocus || D.hasFocus()) && !!(e.type || e.href || ~e.tabIndex)
},
enabled: function (e) {
return e.disabled === !1
},
disabled: function (e) {
return e.disabled === !0
},
checked: function (e) {
var t = e.nodeName.toLowerCase();
return "input" === t && !!e.checked || "option" === t && !!e.selected
},
selected: function (e) {
return e.parentNode && e.parentNode.selectedIndex, e.selected === !0
},
empty: function (e) {
for (e = e.firstChild; e; e = e.nextSibling)
if (e.nodeType < 6) return !1;
return !0
},
parent: function (e) {
return !$.pseudos.empty(e)
},
header: function (e) {
return ge.test(e.nodeName)
},
input: function (e) {
return pe.test(e.nodeName)
},
button: function (e) {
var t = e.nodeName.toLowerCase();
return "input" === t && "button" === e.type || "button" === t
},
text: function (e) {
var t;
return "input" === e.nodeName.toLowerCase() && "text" === e.type && (null == (t = e.getAttribute("type")) || "text" === t.toLowerCase())
},
first: l(function () {
return [0]
}),
last: l(function (e, t) {
return [t - 1]
}),
eq: l(function (e, t, n) {
return [n < 0 ? n + t : n]
}),
even: l(function (e, t) {
for (var n = 0; n < t; n += 2) e.push(n);
return e
}),
odd: l(function (e, t) {
for (var n = 1; n < t; n += 2) e.push(n);
return e
}),
lt: l(function (e, t, n) {
for (var r = n < 0 ? n + t : n; --r >= 0;) e.push(r);
return e
}),
gt: l(function (e, t, n) {
for (var r = n < 0 ? n + t : n; ++r < t;) e.push(r);
return e
})
}
}, $.pseudos.nth = $.pseudos.eq;
for (x in {
radio: !0,
checkbox: !0,
file: !0,
password: !0,
image: !0
}) $.pseudos[x] = a(x);
for (x in {
submit: !0,
reset: !0
}) $.pseudos[x] = u(x);
return f.prototype = $.filters = $.pseudos, $.setFilters = new f, k = t.tokenize = function (e, n) {
var r, i, o, s, a, u, l, c = _[e + " "];
if (c) return n ? 0 : c.slice(0);
for (a = e, u = [], l = $.preFilter; a;) {
r && !(i = ue.exec(a)) || (i && (a = a.slice(i[0].length) || a), u.push(o = [])), r = !1, (i = le.exec(a)) && (r = i.shift(), o.push({
value: r,
type: i[0].replace(ae, " ")
}), a = a.slice(r.length));
for (s in $.filter) !(i = he[s].exec(a)) || l[s] && !(i = l[s](i)) || (r = i.shift(), o.push({
value: r,
type: s,
matches: i
}), a = a.slice(r.length));
if (!r) break
}
return n ? a.length : a ? t.error(e) : _(e, u).slice(0)
}, E = t.compile = function (e, t) {
var n, r = [],
i = [],
o = G[e + " "];
if (!o) {
for (t || (t = k(e)), n = t.length; n--;) o = y(t[n]), o[F] ? r.push(o) : i.push(o);
o = G(e, b(i, r)), o.selector = e
}
return o
}, S = t.select = function (e, t, n, r) {
var i, o, s, a, u, l = "function" == typeof e && e,
f = !r && k(e = l.selector || e);
if (n = n || [], 1 === f.length) {
if (o = f[0] = f[0].slice(0), o.length > 2 && "ID" === (s = o[0]).type && w.getById && 9 === t.nodeType && O && $.relative[o[1].type]) {
if (t = ($.find.ID(s.matches[0].replace(xe, we), t) || [])[0], !t) return n;
l && (t = t.parentNode), e = e.slice(o.shift().value.length)
}
for (i = he.needsContext.test(e) ? 0 : o.length; i-- && (s = o[i], !$.relative[a = s.type]);)
if ((u = $.find[a]) && (r = u(s.matches[0].replace(xe, we), ye.test(o[0].type) && c(t.parentNode) || t))) {
if (o.splice(i, 1), e = r.length && d(o), !e) return K.apply(n, r), n;
break
}
}
return (l || E(e, f))(r, t, !O, n, !t || ye.test(e) && c(t.parentNode) || t), n
}, w.sortStable = F.split("").sort(X).join("") === F, w.detectDuplicates = !!H, N(), w.sortDetached = i(function (e) {
return 1 & e.compareDocumentPosition(D.createElement("div"))
}), i(function (e) {
return e.innerHTML = "<a href='#'></a>", "#" === e.firstChild.getAttribute("href")
}) || o("type|href|height|width", function (e, t, n) {
if (!n) return e.getAttribute(t, "type" === t.toLowerCase() ? 1 : 2)
}), w.attributes && i(function (e) {
return e.innerHTML = "<input/>", e.firstChild.setAttribute("value", ""), "" === e.firstChild.getAttribute("value")
}) || o("value", function (e, t, n) {
if (!n && "input" === e.nodeName.toLowerCase()) return e.defaultValue
}), i(function (e) {
return null == e.getAttribute("disabled")
}) || o(te, function (e, t, n) {
var r;
if (!n) return e[t] === !0 ? t.toLowerCase() : (r = e.getAttributeNode(t)) && r.specified ? r.value : null
}), t
}(e);
oe.find = ce, oe.expr = ce.selectors, oe.expr[":"] = oe.expr.pseudos, oe.uniqueSort = oe.unique = ce.uniqueSort, oe.text = ce.getText, oe.isXMLDoc = ce.isXML, oe.contains = ce.contains;
var fe = function (e, t, n) {
for (var r = [], i = void 0 !== n;
(e = e[t]) && 9 !== e.nodeType;)
if (1 === e.nodeType) {
if (i && oe(e).is(n)) break;
r.push(e)
}
return r
},
de = function (e, t) {
for (var n = []; e; e = e.nextSibling) 1 === e.nodeType && e !== t && n.push(e);
return n
},
he = oe.expr.match.needsContext,
pe = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,
ge = /^.[^:#\[\.,]*$/;
oe.filter = function (e, t, n) {
var r = t[0];
return n && (e = ":not(" + e + ")"), 1 === t.length && 1 === r.nodeType ? oe.find.matchesSelector(r, e) ? [r] : [] : oe.find.matches(e, oe.grep(t, function (e) {
return 1 === e.nodeType
}))
}, oe.fn.extend({
find: function (e) {
var t, n = this.length,
r = [],
i = this;
if ("string" != typeof e) return this.pushStack(oe(e).filter(function () {
for (t = 0; t < n; t++)
if (oe.contains(i[t], this)) return !0
}));
for (t = 0; t < n; t++) oe.find(e, i[t], r);
return r = this.pushStack(n > 1 ? oe.unique(r) : r), r.selector = this.selector ? this.selector + " " + e : e, r
},
filter: function (e) {
return this.pushStack(r(this, e || [], !1))
},
not: function (e) {
return this.pushStack(r(this, e || [], !0))
},
is: function (e) {
return !!r(this, "string" == typeof e && he.test(e) ? oe(e) : e || [], !1).length
}
});
var me, ve = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
ye = oe.fn.init = function (e, t, n) {
var r, i;
if (!e) return this;
if (n = n || me, "string" == typeof e) {
if (r = "<" === e[0] && ">" === e[e.length - 1] && e.length >= 3 ? [null, e, null] : ve.exec(e), !r || !r[1] && t) return !t || t.jquery ? (t || n).find(e) : this.constructor(t).find(e);
if (r[1]) {
if (t = t instanceof oe ? t[0] : t, oe.merge(this, oe.parseHTML(r[1], t && t.nodeType ? t.ownerDocument || t : Y, !0)), pe.test(r[1]) && oe.isPlainObject(t))
for (r in t) oe.isFunction(this[r]) ? this[r](t[r]) : this.attr(r, t[r]);
return this
}
return i = Y.getElementById(r[2]), i && i.parentNode && (this.length = 1, this[0] = i), this.context = Y, this.selector = e, this
}
return e.nodeType ? (this.context = this[0] = e, this.length = 1, this) : oe.isFunction(e) ? void 0 !== n.ready ? n.ready(e) : e(oe) : (void 0 !== e.selector && (this.selector = e.selector, this.context = e.context), oe.makeArray(e, this))
};
ye.prototype = oe.fn, me = oe(Y);
var be = /^(?:parents|prev(?:Until|All))/,
xe = {
children: !0,
contents: !0,
next: !0,
prev: !0
};
oe.fn.extend({
has: function (e) {
var t = oe(e, this),
n = t.length;
return this.filter(function () {
for (var e = 0; e < n; e++)
if (oe.contains(this, t[e])) return !0
})
},
closest: function (e, t) {
for (var n, r = 0, i = this.length, o = [], s = he.test(e) || "string" != typeof e ? oe(e, t || this.context) : 0; r < i; r++)
for (n = this[r]; n && n !== t; n = n.parentNode)
if (n.nodeType < 11 && (s ? s.index(n) > -1 : 1 === n.nodeType && oe.find.matchesSelector(n, e))) {
o.push(n);
break
}
return this.pushStack(o.length > 1 ? oe.uniqueSort(o) : o)
},
index: function (e) {
return e ? "string" == typeof e ? Z.call(oe(e), this[0]) : Z.call(this, e.jquery ? e[0] : e) : this[0] && this[0].parentNode ? this.first().prevAll().length : -1
},
add: function (e, t) {
return this.pushStack(oe.uniqueSort(oe.merge(this.get(), oe(e, t))))
},
addBack: function (e) {
return this.add(null == e ? this.prevObject : this.prevObject.filter(e))
}
}), oe.each({
parent: function (e) {
var t = e.parentNode;
return t && 11 !== t.nodeType ? t : null
},
parents: function (e) {
return fe(e, "parentNode")
},
parentsUntil: function (e, t, n) {
return fe(e, "parentNode", n)
},
next: function (e) {
return i(e, "nextSibling")
},
prev: function (e) {
return i(e, "previousSibling")
},
nextAll: function (e) {
return fe(e, "nextSibling")
},
prevAll: function (e) {
return fe(e, "previousSibling")
},
nextUntil: function (e, t, n) {
return fe(e, "nextSibling", n)
},
prevUntil: function (e, t, n) {
return fe(e, "previousSibling", n)
},
siblings: function (e) {
return de((e.parentNode || {}).firstChild, e)
},
children: function (e) {
return de(e.firstChild)
},
contents: function (e) {
return e.contentDocument || oe.merge([], e.childNodes)
}
}, function (e, t) {
oe.fn[e] = function (n, r) {
var i = oe.map(this, t, n);
return "Until" !== e.slice(-5) && (r = n), r && "string" == typeof r && (i = oe.filter(r, i)), this.length > 1 && (xe[e] || oe.uniqueSort(i), be.test(e) && i.reverse()), this.pushStack(i)
}
});
var we = /\S+/g;
oe.Callbacks = function (e) {
e = "string" == typeof e ? o(e) : oe.extend({}, e);
var t, n, r, i, s = [],
a = [],
u = -1,
l = function () {
for (i = e.once, r = t = !0; a.length; u = -1)
for (n = a.shift(); ++u < s.length;) s[u].apply(n[0], n[1]) === !1 && e.stopOnFalse && (u = s.length, n = !1);
e.memory || (n = !1), t = !1, i && (s = n ? [] : "")
},
c = {
add: function () {
return s && (n && !t && (u = s.length - 1, a.push(n)), function r(t) {
oe.each(t, function (t, n) {
oe.isFunction(n) ? e.unique && c.has(n) || s.push(n) : n && n.length && "string" !== oe.type(n) && r(n)
})
}(arguments), n && !t && l()), this
},
remove: function () {
return oe.each(arguments, function (e, t) {
for (var n;
(n = oe.inArray(t, s, n)) > -1;) s.splice(n, 1), n <= u && u--
}), this
},
has: function (e) {
return e ? oe.inArray(e, s) > -1 : s.length > 0
},
empty: function () {
return s && (s = []), this
},
disable: function () {
return i = a = [], s = n = "", this
},
disabled: function () {
return !s
},
lock: function () {
return i = a = [], n || (s = n = ""), this
},
locked: function () {
return !!i
},
fireWith: function (e, n) {
return i || (n = n || [], n = [e, n.slice ? n.slice() : n], a.push(n), t || l()), this
},
fire: function () {
return c.fireWith(this, arguments), this
},
fired: function () {
return !!r
}
};
return c
}, oe.extend({
Deferred: function (e) {
var t = [
["resolve", "done", oe.Callbacks("once memory"), "resolved"],
["reject", "fail", oe.Callbacks("once memory"), "rejected"],
["notify", "progress", oe.Callbacks("memory")]
],
n = "pending",
r = {
state: function () {
return n
},
always: function () {
return i.done(arguments).fail(arguments), this
},
then: function () {
var e = arguments;
return oe.Deferred(function (n) {
oe.each(t, function (t, o) {
var s = oe.isFunction(e[t]) && e[t];
i[o[1]](function () {
var e = s && s.apply(this, arguments);
e && oe.isFunction(e.promise) ? e.promise().progress(n.notify).done(n.resolve).fail(n.reject) : n[o[0] + "With"](this === r ? n.promise() : this, s ? [e] : arguments)
})
}), e = null
}).promise()
},
promise: function (e) {
return null != e ? oe.extend(e, r) : r
}
},
i = {};
return r.pipe = r.then, oe.each(t, function (e, o) {
var s = o[2],
a = o[3];
r[o[1]] = s.add, a && s.add(function () {
n = a
}, t[1 ^ e][2].disable, t[2][2].lock), i[o[0]] = function () {
return i[o[0] + "With"](this === i ? r : this, arguments), this
}, i[o[0] + "With"] = s.fireWith
}), r.promise(i), e && e.call(i, i), i
},
when: function (e) {
var t, n, r, i = 0,
o = V.call(arguments),
s = o.length,
a = 1 !== s || e && oe.isFunction(e.promise) ? s : 0,
u = 1 === a ? e : oe.Deferred(),
l = function (e, n, r) {
return function (i) {
n[e] = this, r[e] = arguments.length > 1 ? V.call(arguments) : i, r === t ? u.notifyWith(n, r) : --a || u.resolveWith(n, r)
}
};
if (s > 1)
for (t = new Array(s), n = new Array(s), r = new Array(s); i < s; i++) o[i] && oe.isFunction(o[i].promise) ? o[i].promise().progress(l(i, n, t)).done(l(i, r, o)).fail(u.reject) : --a;
return a || u.resolveWith(r, o), u.promise()
}
});
var $e;
oe.fn.ready = function (e) {
return oe.ready.promise().done(e), this
}, oe.extend({
isReady: !1,
readyWait: 1,
holdReady: function (e) {
e ? oe.readyWait++ : oe.ready(!0)
},
ready: function (e) {
(e === !0 ? --oe.readyWait : oe.isReady) || (oe.isReady = !0, e !== !0 && --oe.readyWait > 0 || ($e.resolveWith(Y, [oe]), oe.fn.triggerHandler && (oe(Y).triggerHandler("ready"), oe(Y).off("ready"))))
}
}), oe.ready.promise = function (t) {
return $e || ($e = oe.Deferred(), "complete" === Y.readyState || "loading" !== Y.readyState && !Y.documentElement.doScroll ? e.setTimeout(oe.ready) : (Y.addEventListener("DOMContentLoaded", s), e.addEventListener("load", s))), $e.promise(t)
}, oe.ready.promise();
var Ce = function (e, t, n, r, i, o, s) {
var a = 0,
u = e.length,
l = null == n;
if ("object" === oe.type(n)) {
i = !0;
for (a in n) Ce(e, t, a, n[a], !0, o, s)
} else if (void 0 !== r && (i = !0, oe.isFunction(r) || (s = !0), l && (s ? (t.call(e, r), t = null) : (l = t, t = function (e, t, n) {
return l.call(oe(e), n)
})), t))
for (; a < u; a++) t(e[a], n, s ? r : r.call(e[a], a, t(e[a], n)));
return i ? e : l ? t.call(e) : u ? t(e[0], n) : o
},
Te = function (e) {
return 1 === e.nodeType || 9 === e.nodeType || !+e.nodeType
};
a.uid = 1, a.prototype = {
register: function (e, t) {
var n = t || {};
return e.nodeType ? e[this.expando] = n : Object.defineProperty(e, this.expando, {
value: n,
writable: !0,
configurable: !0
}), e[this.expando]
},
cache: function (e) {
if (!Te(e)) return {};
var t = e[this.expando];
return t || (t = {}, Te(e) && (e.nodeType ? e[this.expando] = t : Object.defineProperty(e, this.expando, {
value: t,
configurable: !0
}))), t
},
set: function (e, t, n) {
var r, i = this.cache(e);
if ("string" == typeof t) i[t] = n;
else
for (r in t) i[r] = t[r];
return i
},
get: function (e, t) {
return void 0 === t ? this.cache(e) : e[this.expando] && e[this.expando][t]
},
access: function (e, t, n) {
var r;
return void 0 === t || t && "string" == typeof t && void 0 === n ? (r = this.get(e, t), void 0 !== r ? r : this.get(e, oe.camelCase(t))) : (this.set(e, t, n), void 0 !== n ? n : t)
},
remove: function (e, t) {
var n, r, i, o = e[this.expando];
if (void 0 !== o) {
if (void 0 === t) this.register(e);
else {
oe.isArray(t) ? r = t.concat(t.map(oe.camelCase)) : (i = oe.camelCase(t), t in o ? r = [t, i] : (r = i, r = r in o ? [r] : r.match(we) || [])), n = r.length;
for (; n--;) delete o[r[n]]
}(void 0 === t || oe.isEmptyObject(o)) && (e.nodeType ? e[this.expando] = void 0 : delete e[this.expando])
}
},
hasData: function (e) {
var t = e[this.expando];
return void 0 !== t && !oe.isEmptyObject(t)
}
};
var ke = new a,
Ee = new a,
Se = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
je = /[A-Z]/g;
oe.extend({
hasData: function (e) {
return Ee.hasData(e) || ke.hasData(e)
},
data: function (e, t, n) {
return Ee.access(e, t, n)
},
removeData: function (e, t) {
Ee.remove(e, t)
},
_data: function (e, t, n) {
return ke.access(e, t, n)
},
_removeData: function (e, t) {
ke.remove(e, t)
}
}), oe.fn.extend({
data: function (e, t) {
var n, r, i, o = this[0],
s = o && o.attributes;
if (void 0 === e) {
if (this.length && (i = Ee.get(o), 1 === o.nodeType && !ke.get(o, "hasDataAttrs"))) {
for (n = s.length; n--;) s[n] && (r = s[n].name, 0 === r.indexOf("data-") && (r = oe.camelCase(r.slice(5)), u(o, r, i[r])));
ke.set(o, "hasDataAttrs", !0)
}
return i
}
return "object" == typeof e ? this.each(function () {
Ee.set(this, e)
}) : Ce(this, function (t) {
var n, r;
if (o && void 0 === t) {
if (n = Ee.get(o, e) || Ee.get(o, e.replace(je, "-$&").toLowerCase()), void 0 !== n) return n;
if (r = oe.camelCase(e), n = Ee.get(o, r), void 0 !== n) return n;
if (n = u(o, r, void 0), void 0 !== n) return n
} else r = oe.camelCase(e), this.each(function () {
var n = Ee.get(this, r);
Ee.set(this, r, t), e.indexOf("-") > -1 && void 0 !== n && Ee.set(this, e, t)
})
}, null, t, arguments.length > 1, null, !0)
},
removeData: function (e) {
return this.each(function () {
Ee.remove(this, e)
})
}
}), oe.extend({
queue: function (e, t, n) {
var r;
if (e) return t = (t || "fx") + "queue", r = ke.get(e, t), n && (!r || oe.isArray(n) ? r = ke.access(e, t, oe.makeArray(n)) : r.push(n)), r || []
},
dequeue: function (e, t) {
t = t || "fx";
var n = oe.queue(e, t),
r = n.length,
i = n.shift(),
o = oe._queueHooks(e, t),
s = function () {
oe.dequeue(e, t)
};
"inprogress" === i && (i = n.shift(), r--), i && ("fx" === t && n.unshift("inprogress"), delete o.stop, i.call(e, s, o)), !r && o && o.empty.fire()
},
_queueHooks: function (e, t) {
var n = t + "queueHooks";
return ke.get(e, n) || ke.access(e, n, {
empty: oe.Callbacks("once memory").add(function () {
ke.remove(e, [t + "queue", n])
})
})
}
}), oe.fn.extend({
queue: function (e, t) {
var n = 2;
return "string" != typeof e && (t = e, e = "fx", n--), arguments.length < n ? oe.queue(this[0], e) : void 0 === t ? this : this.each(function () {
var n = oe.queue(this, e, t);
oe._queueHooks(this, e), "fx" === e && "inprogress" !== n[0] && oe.dequeue(this, e)
})
},
dequeue: function (e) {
return this.each(function () {
oe.dequeue(this, e)
})
},
clearQueue: function (e) {
return this.queue(e || "fx", [])
},
promise: function (e, t) {
var n, r = 1,
i = oe.Deferred(),
o = this,
s = this.length,
a = function () {
--r || i.resolveWith(o, [o])
};
for ("string" != typeof e && (t = e, e = void 0), e = e || "fx"; s--;) n = ke.get(o[s], e + "queueHooks"), n && n.empty && (r++, n.empty.add(a));
return a(), i.promise(t)
}
});
var Me = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
He = new RegExp("^(?:([+-])=|)(" + Me + ")([a-z%]*)$", "i"),
Ne = ["Top", "Right", "Bottom", "Left"],
De = function (e, t) {
return e = t || e, "none" === oe.css(e, "display") || !oe.contains(e.ownerDocument, e)
},
Ae = /^(?:checkbox|radio)$/i,
Oe = /<([\w:-]+)/,
qe = /^$|\/(?:java|ecma)script/i,
Ie = {
option: [1, "<select multiple='multiple'>", "</select>"],
thead: [1, "<table>", "</table>"],
col: [2, "<table><colgroup>", "</colgroup></table>"],
tr: [2, "<table><tbody>", "</tbody></table>"],
td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
_default: [0, "", ""]
};
Ie.optgroup = Ie.option, Ie.tbody = Ie.tfoot = Ie.colgroup = Ie.caption = Ie.thead, Ie.th = Ie.td;
var Le = /<|&#?\w+;/;
! function () {
var e = Y.createDocumentFragment(),
t = e.appendChild(Y.createElement("div")),
n = Y.createElement("input");
n.setAttribute("type", "radio"), n.setAttribute("checked", "checked"), n.setAttribute("name", "t"), t.appendChild(n), re.checkClone = t.cloneNode(!0).cloneNode(!0).lastChild.checked, t.innerHTML = "<textarea>x</textarea>", re.noCloneChecked = !!t.cloneNode(!0).lastChild.defaultValue
}();
var Pe = /^key/,
Fe = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
Re = /^([^.]*)(?:\.(.+)|)/;
oe.event = {
global: {},
add: function (e, t, n, r, i) {
var o, s, a, u, l, c, f, d, h, p, g, m = ke.get(e);
if (m)
for (n.handler && (o = n, n = o.handler, i = o.selector), n.guid || (n.guid = oe.guid++), (u = m.events) || (u = m.events = {}), (s = m.handle) || (s = m.handle = function (t) {
return "undefined" != typeof oe && oe.event.triggered !== t.type ? oe.event.dispatch.apply(e, arguments) : void 0
}), t = (t || "").match(we) || [""], l = t.length; l--;) a = Re.exec(t[l]) || [], h = g = a[1], p = (a[2] || "").split(".").sort(), h && (f = oe.event.special[h] || {}, h = (i ? f.delegateType : f.bindType) || h, f = oe.event.special[h] || {}, c = oe.extend({
type: h,
origType: g,
data: r,
handler: n,
guid: n.guid,
selector: i,
needsContext: i && oe.expr.match.needsContext.test(i),
namespace: p.join(".")
}, o), (d = u[h]) || (d = u[h] = [], d.delegateCount = 0, f.setup && f.setup.call(e, r, p, s) !== !1 || e.addEventListener && e.addEventListener(h, s)), f.add && (f.add.call(e, c), c.handler.guid || (c.handler.guid = n.guid)), i ? d.splice(d.delegateCount++, 0, c) : d.push(c), oe.event.global[h] = !0)
},
remove: function (e, t, n, r, i) {
var o, s, a, u, l, c, f, d, h, p, g, m = ke.hasData(e) && ke.get(e);
if (m && (u = m.events)) {
for (t = (t || "").match(we) || [""], l = t.length; l--;)
if (a = Re.exec(t[l]) || [], h = g = a[1], p = (a[2] || "").split(".").sort(), h) {
for (f = oe.event.special[h] || {}, h = (r ? f.delegateType : f.bindType) || h, d = u[h] || [], a = a[2] && new RegExp("(^|\\.)" + p.join("\\.(?:.*\\.|)") + "(\\.|$)"), s = o = d.length; o--;) c = d[o], !i && g !== c.origType || n && n.guid !== c.guid || a && !a.test(c.namespace) || r && r !== c.selector && ("**" !== r || !c.selector) || (d.splice(o, 1),
c.selector && d.delegateCount--, f.remove && f.remove.call(e, c));
s && !d.length && (f.teardown && f.teardown.call(e, p, m.handle) !== !1 || oe.removeEvent(e, h, m.handle), delete u[h])
} else
for (h in u) oe.event.remove(e, h + t[l], n, r, !0);
oe.isEmptyObject(u) && ke.remove(e, "handle events")
}
},
dispatch: function (e) {
e = oe.event.fix(e);
var t, n, r, i, o, s = [],
a = V.call(arguments),
u = (ke.get(this, "events") || {})[e.type] || [],
l = oe.event.special[e.type] || {};
if (a[0] = e, e.delegateTarget = this, !l.preDispatch || l.preDispatch.call(this, e) !== !1) {
for (s = oe.event.handlers.call(this, e, u), t = 0;
(i = s[t++]) && !e.isPropagationStopped();)
for (e.currentTarget = i.elem, n = 0;
(o = i.handlers[n++]) && !e.isImmediatePropagationStopped();) e.rnamespace && !e.rnamespace.test(o.namespace) || (e.handleObj = o, e.data = o.data, r = ((oe.event.special[o.origType] || {}).handle || o.handler).apply(i.elem, a), void 0 !== r && (e.result = r) === !1 && (e.preventDefault(), e.stopPropagation()));
return l.postDispatch && l.postDispatch.call(this, e), e.result
}
},
handlers: function (e, t) {
var n, r, i, o, s = [],
a = t.delegateCount,
u = e.target;
if (a && u.nodeType && ("click" !== e.type || isNaN(e.button) || e.button < 1))
for (; u !== this; u = u.parentNode || this)
if (1 === u.nodeType && (u.disabled !== !0 || "click" !== e.type)) {
for (r = [], n = 0; n < a; n++) o = t[n], i = o.selector + " ", void 0 === r[i] && (r[i] = o.needsContext ? oe(i, this).index(u) > -1 : oe.find(i, this, null, [u]).length), r[i] && r.push(o);
r.length && s.push({
elem: u,
handlers: r
})
}
return a < t.length && s.push({
elem: this,
handlers: t.slice(a)
}), s
},
props: "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function (e, t) {
return null == e.which && (e.which = null != t.charCode ? t.charCode : t.keyCode), e
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function (e, t) {
var n, r, i, o = t.button;
return null == e.pageX && null != t.clientX && (n = e.target.ownerDocument || Y, r = n.documentElement, i = n.body, e.pageX = t.clientX + (r && r.scrollLeft || i && i.scrollLeft || 0) - (r && r.clientLeft || i && i.clientLeft || 0), e.pageY = t.clientY + (r && r.scrollTop || i && i.scrollTop || 0) - (r && r.clientTop || i && i.clientTop || 0)), e.which || void 0 === o || (e.which = 1 & o ? 1 : 2 & o ? 3 : 4 & o ? 2 : 0), e
}
},
fix: function (e) {
if (e[oe.expando]) return e;
var t, n, r, i = e.type,
o = e,
s = this.fixHooks[i];
for (s || (this.fixHooks[i] = s = Fe.test(i) ? this.mouseHooks : Pe.test(i) ? this.keyHooks : {}), r = s.props ? this.props.concat(s.props) : this.props, e = new oe.Event(o), t = r.length; t--;) n = r[t], e[n] = o[n];
return e.target || (e.target = Y), 3 === e.target.nodeType && (e.target = e.target.parentNode), s.filter ? s.filter(e, o) : e
},
special: {
load: {
noBubble: !0
},
focus: {
trigger: function () {
if (this !== g() && this.focus) return this.focus(), !1
},
delegateType: "focusin"
},
blur: {
trigger: function () {
if (this === g() && this.blur) return this.blur(), !1
},
delegateType: "focusout"
},
click: {
trigger: function () {
if ("checkbox" === this.type && this.click && oe.nodeName(this, "input")) return this.click(), !1
},
_default: function (e) {
return oe.nodeName(e.target, "a")
}
},
beforeunload: {
postDispatch: function (e) {
void 0 !== e.result && e.originalEvent && (e.originalEvent.returnValue = e.result)
}
}
}
}, oe.removeEvent = function (e, t, n) {
e.removeEventListener && e.removeEventListener(t, n)
}, oe.Event = function (e, t) {
return this instanceof oe.Event ? (e && e.type ? (this.originalEvent = e, this.type = e.type, this.isDefaultPrevented = e.defaultPrevented || void 0 === e.defaultPrevented && e.returnValue === !1 ? h : p) : this.type = e, t && oe.extend(this, t), this.timeStamp = e && e.timeStamp || oe.now(), void(this[oe.expando] = !0)) : new oe.Event(e, t)
}, oe.Event.prototype = {
constructor: oe.Event,
isDefaultPrevented: p,
isPropagationStopped: p,
isImmediatePropagationStopped: p,
isSimulated: !1,
preventDefault: function () {
var e = this.originalEvent;
this.isDefaultPrevented = h, e && !this.isSimulated && e.preventDefault()
},
stopPropagation: function () {
var e = this.originalEvent;
this.isPropagationStopped = h, e && !this.isSimulated && e.stopPropagation()
},
stopImmediatePropagation: function () {
var e = this.originalEvent;
this.isImmediatePropagationStopped = h, e && !this.isSimulated && e.stopImmediatePropagation(), this.stopPropagation()
}
}, oe.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function (e, t) {
oe.event.special[e] = {
delegateType: t,
bindType: t,
handle: function (e) {
var n, r = this,
i = e.relatedTarget,
o = e.handleObj;
return i && (i === r || oe.contains(r, i)) || (e.type = o.origType, n = o.handler.apply(this, arguments), e.type = t), n
}
}
}), oe.fn.extend({
on: function (e, t, n, r) {
return m(this, e, t, n, r)
},
one: function (e, t, n, r) {
return m(this, e, t, n, r, 1)
},
off: function (e, t, n) {
var r, i;
if (e && e.preventDefault && e.handleObj) return r = e.handleObj, oe(e.delegateTarget).off(r.namespace ? r.origType + "." + r.namespace : r.origType, r.selector, r.handler), this;
if ("object" == typeof e) {
for (i in e) this.off(i, t, e[i]);
return this
}
return t !== !1 && "function" != typeof t || (n = t, t = void 0), n === !1 && (n = p), this.each(function () {
oe.event.remove(this, e, n, t)
})
}
});
var ze = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,
We = /<script|<style|<link/i,
Be = /checked\s*(?:[^=]|=\s*.checked.)/i,
_e = /^true\/(.*)/,
Ge = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
oe.extend({
htmlPrefilter: function (e) {
return e.replace(ze, "<$1><$2>")
},
clone: function (e, t, n) {
var r, i, o, s, a = e.cloneNode(!0),
u = oe.contains(e.ownerDocument, e);
if (!(re.noCloneChecked || 1 !== e.nodeType && 11 !== e.nodeType || oe.isXMLDoc(e)))
for (s = c(a), o = c(e), r = 0, i = o.length; r < i; r++) w(o[r], s[r]);
if (t)
if (n)
for (o = o || c(e), s = s || c(a), r = 0, i = o.length; r < i; r++) x(o[r], s[r]);
else x(e, a);
return s = c(a, "script"), s.length > 0 && f(s, !u && c(e, "script")), a
},
cleanData: function (e) {
for (var t, n, r, i = oe.event.special, o = 0; void 0 !== (n = e[o]); o++)
if (Te(n)) {
if (t = n[ke.expando]) {
if (t.events)
for (r in t.events) i[r] ? oe.event.remove(n, r) : oe.removeEvent(n, r, t.handle);
n[ke.expando] = void 0
}
n[Ee.expando] && (n[Ee.expando] = void 0)
}
}
}), oe.fn.extend({
domManip: $,
detach: function (e) {
return C(this, e, !0)
},
remove: function (e) {
return C(this, e)
},
text: function (e) {
return Ce(this, function (e) {
return void 0 === e ? oe.text(this) : this.empty().each(function () {
1 !== this.nodeType && 11 !== this.nodeType && 9 !== this.nodeType || (this.textContent = e)
})
}, null, e, arguments.length)
},
append: function () {
return $(this, arguments, function (e) {
if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) {
var t = v(this, e);
t.appendChild(e)
}
})
},
prepend: function () {
return $(this, arguments, function (e) {
if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) {
var t = v(this, e);
t.insertBefore(e, t.firstChild)
}
})
},
before: function () {
return $(this, arguments, function (e) {
this.parentNode && this.parentNode.insertBefore(e, this)
})
},
after: function () {
return $(this, arguments, function (e) {
this.parentNode && this.parentNode.insertBefore(e, this.nextSibling)
})
},
empty: function () {
for (var e, t = 0; null != (e = this[t]); t++) 1 === e.nodeType && (oe.cleanData(c(e, !1)), e.textContent = "");
return this
},
clone: function (e, t) {
return e = null != e && e, t = null == t ? e : t, this.map(function () {
return oe.clone(this, e, t)
})
},
html: function (e) {
return Ce(this, function (e) {
var t = this[0] || {},
n = 0,
r = this.length;
if (void 0 === e && 1 === t.nodeType) return t.innerHTML;
if ("string" == typeof e && !We.test(e) && !Ie[(Oe.exec(e) || ["", ""])[1].toLowerCase()]) {
e = oe.htmlPrefilter(e);
try {
for (; n < r; n++) t = this[n] || {}, 1 === t.nodeType && (oe.cleanData(c(t, !1)), t.innerHTML = e);
t = 0
} catch (i) {}
}
t && this.empty().append(e)
}, null, e, arguments.length)
},
replaceWith: function () {
var e = [];
return $(this, arguments, function (t) {
var n = this.parentNode;
oe.inArray(this, e) < 0 && (oe.cleanData(c(this)), n && n.replaceChild(t, this))
}, e)
}
}), oe.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function (e, t) {
oe.fn[e] = function (e) {
for (var n, r = [], i = oe(e), o = i.length - 1, s = 0; s <= o; s++) n = s === o ? this : this.clone(!0), oe(i[s])[t](n), K.apply(r, n.get());
return this.pushStack(r)
}
});
var Xe, Qe = {
HTML: "block",
BODY: "block"
},
Ue = /^margin/,
Ye = new RegExp("^(" + Me + ")(?!px)[a-z%]+$", "i"),
Ve = function (t) {
var n = t.ownerDocument.defaultView;
return n && n.opener || (n = e), n.getComputedStyle(t)
},
Je = function (e, t, n, r) {
var i, o, s = {};
for (o in t) s[o] = e.style[o], e.style[o] = t[o];
i = n.apply(e, r || []);
for (o in t) e.style[o] = s[o];
return i
},
Ke = Y.documentElement;
! function () {
function t() {
a.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%", a.innerHTML = "", Ke.appendChild(s);
var t = e.getComputedStyle(a);
n = "1%" !== t.top, o = "2px" === t.marginLeft, r = "4px" === t.width, a.style.marginRight = "50%", i = "4px" === t.marginRight, Ke.removeChild(s)
}
var n, r, i, o, s = Y.createElement("div"),
a = Y.createElement("div");
a.style && (a.style.backgroundClip = "content-box", a.cloneNode(!0).style.backgroundClip = "", re.clearCloneStyle = "content-box" === a.style.backgroundClip, s.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute", s.appendChild(a), oe.extend(re, {
pixelPosition: function () {
return t(), n
},
boxSizingReliable: function () {
return null == r && t(), r
},
pixelMarginRight: function () {
return null == r && t(), i
},
reliableMarginLeft: function () {
return null == r && t(), o
},
reliableMarginRight: function () {
var t, n = a.appendChild(Y.createElement("div"));
return n.style.cssText = a.style.cssText = "-webkit-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0", n.style.marginRight = n.style.width = "0", a.style.width = "1px", Ke.appendChild(s), t = !parseFloat(e.getComputedStyle(n).marginRight), Ke.removeChild(s), a.removeChild(n), t
}
}))
}();
var Ze = /^(none|table(?!-c[ea]).+)/,
et = {
position: "absolute",
visibility: "hidden",
display: "block"
},
tt = {
letterSpacing: "0",
fontWeight: "400"
},
nt = ["Webkit", "O", "Moz", "ms"],
rt = Y.createElement("div").style;
oe.extend({
cssHooks: {
opacity: {
get: function (e, t) {
if (t) {
var n = E(e, "opacity");
return "" === n ? "1" : n
}
}
}
},
cssNumber: {
animationIterationCount: !0,
columnCount: !0,
fillOpacity: !0,
flexGrow: !0,
flexShrink: !0,
fontWeight: !0,
lineHeight: !0,
opacity: !0,
order: !0,
orphans: !0,
widows: !0,
zIndex: !0,
zoom: !0
},
cssProps: {
"float": "cssFloat"
},
style: function (e, t, n, r) {
if (e && 3 !== e.nodeType && 8 !== e.nodeType && e.style) {
var i, o, s, a = oe.camelCase(t),
u = e.style;
return t = oe.cssProps[a] || (oe.cssProps[a] = j(a) || a), s = oe.cssHooks[t] || oe.cssHooks[a], void 0 === n ? s && "get" in s && void 0 !== (i = s.get(e, !1, r)) ? i : u[t] : (o = typeof n, "string" === o && (i = He.exec(n)) && i[1] && (n = l(e, t, i), o = "number"), null != n && n === n && ("number" === o && (n += i && i[3] || (oe.cssNumber[a] ? "" : "px")), re.clearCloneStyle || "" !== n || 0 !== t.indexOf("background") || (u[t] = "inherit"), s && "set" in s && void 0 === (n = s.set(e, n, r)) || (u[t] = n)), void 0)
}
},
css: function (e, t, n, r) {
var i, o, s, a = oe.camelCase(t);
return t = oe.cssProps[a] || (oe.cssProps[a] = j(a) || a), s = oe.cssHooks[t] || oe.cssHooks[a], s && "get" in s && (i = s.get(e, !0, n)), void 0 === i && (i = E(e, t, r)), "normal" === i && t in tt && (i = tt[t]), "" === n || n ? (o = parseFloat(i), n === !0 || isFinite(o) ? o || 0 : i) : i
}
}), oe.each(["height", "width"], function (e, t) {
oe.cssHooks[t] = {
get: function (e, n, r) {
if (n) return Ze.test(oe.css(e, "display")) && 0 === e.offsetWidth ? Je(e, et, function () {
return N(e, t, r)
}) : N(e, t, r)
},
set: function (e, n, r) {
var i, o = r && Ve(e),
s = r && H(e, t, r, "border-box" === oe.css(e, "boxSizing", !1, o), o);
return s && (i = He.exec(n)) && "px" !== (i[3] || "px") && (e.style[t] = n, n = oe.css(e, t)), M(e, n, s)
}
}
}), oe.cssHooks.marginLeft = S(re.reliableMarginLeft, function (e, t) {
if (t) return (parseFloat(E(e, "marginLeft")) || e.getBoundingClientRect().left - Je(e, {
marginLeft: 0
}, function () {
return e.getBoundingClientRect().left
})) + "px"
}), oe.cssHooks.marginRight = S(re.reliableMarginRight, function (e, t) {
if (t) return Je(e, {
display: "inline-block"
}, E, [e, "marginRight"])
}), oe.each({
margin: "",
padding: "",
border: "Width"
}, function (e, t) {
oe.cssHooks[e + t] = {
expand: function (n) {
for (var r = 0, i = {}, o = "string" == typeof n ? n.split(" ") : [n]; r < 4; r++) i[e + Ne[r] + t] = o[r] || o[r - 2] || o[0];
return i
}
}, Ue.test(e) || (oe.cssHooks[e + t].set = M)
}), oe.fn.extend({
css: function (e, t) {
return Ce(this, function (e, t, n) {
var r, i, o = {},
s = 0;
if (oe.isArray(t)) {
for (r = Ve(e), i = t.length; s < i; s++) o[t[s]] = oe.css(e, t[s], !1, r);
return o
}
return void 0 !== n ? oe.style(e, t, n) : oe.css(e, t)
}, e, t, arguments.length > 1)
},
show: function () {
return D(this, !0)
},
hide: function () {
return D(this)
},
toggle: function (e) {
return "boolean" == typeof e ? e ? this.show() : this.hide() : this.each(function () {
De(this) ? oe(this).show() : oe(this).hide()
})
}
}), oe.Tween = A, A.prototype = {
constructor: A,
init: function (e, t, n, r, i, o) {
this.elem = e, this.prop = n, this.easing = i || oe.easing._default, this.options = t, this.start = this.now = this.cur(), this.end = r, this.unit = o || (oe.cssNumber[n] ? "" : "px")
},
cur: function () {
var e = A.propHooks[this.prop];
return e && e.get ? e.get(this) : A.propHooks._default.get(this)
},
run: function (e) {
var t, n = A.propHooks[this.prop];
return this.options.duration ? this.pos = t = oe.easing[this.easing](e, this.options.duration * e, 0, 1, this.options.duration) : this.pos = t = e, this.now = (this.end - this.start) * t + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), n && n.set ? n.set(this) : A.propHooks._default.set(this), this
}
}, A.prototype.init.prototype = A.prototype, A.propHooks = {
_default: {
get: function (e) {
var t;
return 1 !== e.elem.nodeType || null != e.elem[e.prop] && null == e.elem.style[e.prop] ? e.elem[e.prop] : (t = oe.css(e.elem, e.prop, ""), t && "auto" !== t ? t : 0)
},
set: function (e) {
oe.fx.step[e.prop] ? oe.fx.step[e.prop](e) : 1 !== e.elem.nodeType || null == e.elem.style[oe.cssProps[e.prop]] && !oe.cssHooks[e.prop] ? e.elem[e.prop] = e.now : oe.style(e.elem, e.prop, e.now + e.unit)
}
}
}, A.propHooks.scrollTop = A.propHooks.scrollLeft = {
set: function (e) {
e.elem.nodeType && e.elem.parentNode && (e.elem[e.prop] = e.now)
}
}, oe.easing = {
linear: function (e) {
return e
},
swing: function (e) {
return .5 - Math.cos(e * Math.PI) / 2
},
_default: "swing"
}, oe.fx = A.prototype.init, oe.fx.step = {};
var it, ot, st = /^(?:toggle|show|hide)$/,
at = /queueHooks$/;
oe.Animation = oe.extend(F, {
tweeners: {
"*": [function (e, t) {
var n = this.createTween(e, t);
return l(n.elem, e, He.exec(t), n), n
}]
},
tweener: function (e, t) {
oe.isFunction(e) ? (t = e, e = ["*"]) : e = e.match(we);
for (var n, r = 0, i = e.length; r < i; r++) n = e[r], F.tweeners[n] = F.tweeners[n] || [], F.tweeners[n].unshift(t)
},
prefilters: [L],
prefilter: function (e, t) {
t ? F.prefilters.unshift(e) : F.prefilters.push(e)
}
}), oe.speed = function (e, t, n) {
var r = e && "object" == typeof e ? oe.extend({}, e) : {
complete: n || !n && t || oe.isFunction(e) && e,
duration: e,
easing: n && t || t && !oe.isFunction(t) && t
};
return r.duration = oe.fx.off ? 0 : "number" == typeof r.duration ? r.duration : r.duration in oe.fx.speeds ? oe.fx.speeds[r.duration] : oe.fx.speeds._default, null != r.queue && r.queue !== !0 || (r.queue = "fx"), r.old = r.complete, r.complete = function () {
oe.isFunction(r.old) && r.old.call(this), r.queue && oe.dequeue(this, r.queue)
}, r
}, oe.fn.extend({
fadeTo: function (e, t, n, r) {
return this.filter(De).css("opacity", 0).show().end().animate({
opacity: t
}, e, n, r)
},
animate: function (e, t, n, r) {
var i = oe.isEmptyObject(e),
o = oe.speed(t, n, r),
s = function () {
var t = F(this, oe.extend({}, e), o);
(i || ke.get(this, "finish")) && t.stop(!0)
};
return s.finish = s, i || o.queue === !1 ? this.each(s) : this.queue(o.queue, s)
},
stop: function (e, t, n) {
var r = function (e) {
var t = e.stop;
delete e.stop, t(n)
};
return "string" != typeof e && (n = t, t = e, e = void 0), t && e !== !1 && this.queue(e || "fx", []), this.each(function () {
var t = !0,
i = null != e && e + "queueHooks",
o = oe.timers,
s = ke.get(this);
if (i) s[i] && s[i].stop && r(s[i]);
else
for (i in s) s[i] && s[i].stop && at.test(i) && r(s[i]);
for (i = o.length; i--;) o[i].elem !== this || null != e && o[i].queue !== e || (o[i].anim.stop(n), t = !1, o.splice(i, 1));
!t && n || oe.dequeue(this, e)
})
},
finish: function (e) {
return e !== !1 && (e = e || "fx"), this.each(function () {
var t, n = ke.get(this),
r = n[e + "queue"],
i = n[e + "queueHooks"],
o = oe.timers,
s = r ? r.length : 0;
for (n.finish = !0, oe.queue(this, e, []), i && i.stop && i.stop.call(this, !0), t = o.length; t--;) o[t].elem === this && o[t].queue === e && (o[t].anim.stop(!0), o.splice(t, 1));
for (t = 0; t < s; t++) r[t] && r[t].finish && r[t].finish.call(this);
delete n.finish
})
}
}), oe.each(["toggle", "show", "hide"], function (e, t) {
var n = oe.fn[t];
oe.fn[t] = function (e, r, i) {
return null == e || "boolean" == typeof e ? n.apply(this, arguments) : this.animate(q(t, !0), e, r, i)
}
}), oe.each({
slideDown: q("show"),
slideUp: q("hide"),
slideToggle: q("toggle"),
fadeIn: {
opacity: "show"
},
fadeOut: {
opacity: "hide"
},
fadeToggle: {
opacity: "toggle"
}
}, function (e, t) {
oe.fn[e] = function (e, n, r) {
return this.animate(t, e, n, r)
}
}), oe.timers = [], oe.fx.tick = function () {
var e, t = 0,
n = oe.timers;
for (it = oe.now(); t < n.length; t++) e = n[t], e() || n[t] !== e || n.splice(t--, 1);
n.length || oe.fx.stop(), it = void 0
}, oe.fx.timer = function (e) {
oe.timers.push(e), e() ? oe.fx.start() : oe.timers.pop()
}, oe.fx.interval = 13, oe.fx.start = function () {
ot || (ot = e.setInterval(oe.fx.tick, oe.fx.interval))
}, oe.fx.stop = function () {
e.clearInterval(ot), ot = null
}, oe.fx.speeds = {
slow: 600,
fast: 200,
_default: 400
}, oe.fn.delay = function (t, n) {
return t = oe.fx ? oe.fx.speeds[t] || t : t, n = n || "fx", this.queue(n, function (n, r) {
var i = e.setTimeout(n, t);
r.stop = function () {
e.clearTimeout(i)
}
})
},
function () {
var e = Y.createElement("input"),
t = Y.createElement("select"),
n = t.appendChild(Y.createElement("option"));
e.type = "checkbox", re.checkOn = "" !== e.value, re.optSelected = n.selected, t.disabled = !0, re.optDisabled = !n.disabled, e = Y.createElement("input"), e.value = "t", e.type = "radio", re.radioValue = "t" === e.value
}();
var ut, lt = oe.expr.attrHandle;
oe.fn.extend({
attr: function (e, t) {
return Ce(this, oe.attr, e, t, arguments.length > 1)
},
removeAttr: function (e) {
return this.each(function () {
oe.removeAttr(this, e)
})
}
}), oe.extend({
attr: function (e, t, n) {
var r, i, o = e.nodeType;
if (3 !== o && 8 !== o && 2 !== o) return "undefined" == typeof e.getAttribute ? oe.prop(e, t, n) : (1 === o && oe.isXMLDoc(e) || (t = t.toLowerCase(), i = oe.attrHooks[t] || (oe.expr.match.bool.test(t) ? ut : void 0)), void 0 !== n ? null === n ? void oe.removeAttr(e, t) : i && "set" in i && void 0 !== (r = i.set(e, n, t)) ? r : (e.setAttribute(t, n + ""), n) : i && "get" in i && null !== (r = i.get(e, t)) ? r : (r = oe.find.attr(e, t), null == r ? void 0 : r))
},
attrHooks: {
type: {
set: function (e, t) {
if (!re.radioValue && "radio" === t && oe.nodeName(e, "input")) {
var n = e.value;
return e.setAttribute("type", t), n && (e.value = n), t
}
}
}
},
removeAttr: function (e, t) {
var n, r, i = 0,
o = t && t.match(we);
if (o && 1 === e.nodeType)
for (; n = o[i++];) r = oe.propFix[n] || n, oe.expr.match.bool.test(n) && (e[r] = !1), e.removeAttribute(n)
}
}), ut = {
set: function (e, t, n) {
return t === !1 ? oe.removeAttr(e, n) : e.setAttribute(n, n), n
}
}, oe.each(oe.expr.match.bool.source.match(/\w+/g), function (e, t) {
var n = lt[t] || oe.find.attr;
lt[t] = function (e, t, r) {
var i, o;
return r || (o = lt[t], lt[t] = i, i = null != n(e, t, r) ? t.toLowerCase() : null, lt[t] = o), i
}
});
var ct = /^(?:input|select|textarea|button)$/i,
ft = /^(?:a|area)$/i;
oe.fn.extend({
prop: function (e, t) {
return Ce(this, oe.prop, e, t, arguments.length > 1)
},
removeProp: function (e) {
return this.each(function () {
delete this[oe.propFix[e] || e]
})
}
}), oe.extend({
prop: function (e, t, n) {
var r, i, o = e.nodeType;
if (3 !== o && 8 !== o && 2 !== o) return 1 === o && oe.isXMLDoc(e) || (t = oe.propFix[t] || t, i = oe.propHooks[t]), void 0 !== n ? i && "set" in i && void 0 !== (r = i.set(e, n, t)) ? r : e[t] = n : i && "get" in i && null !== (r = i.get(e, t)) ? r : e[t]
},
propHooks: {
tabIndex: {
get: function (e) {
var t = oe.find.attr(e, "tabindex");
return t ? parseInt(t, 10) : ct.test(e.nodeName) || ft.test(e.nodeName) && e.href ? 0 : -1
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
}), re.optSelected || (oe.propHooks.selected = {
get: function (e) {
var t = e.parentNode;
return t && t.parentNode && t.parentNode.selectedIndex, null
},
set: function (e) {
var t = e.parentNode;
t && (t.selectedIndex, t.parentNode && t.parentNode.selectedIndex)
}
}), oe.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function () {
oe.propFix[this.toLowerCase()] = this
});
var dt = /[\t\r\n\f]/g;
oe.fn.extend({
addClass: function (e) {
var t, n, r, i, o, s, a, u = 0;
if (oe.isFunction(e)) return this.each(function (t) {
oe(this).addClass(e.call(this, t, R(this)))
});
if ("string" == typeof e && e)
for (t = e.match(we) || []; n = this[u++];)
if (i = R(n), r = 1 === n.nodeType && (" " + i + " ").replace(dt, " ")) {
for (s = 0; o = t[s++];) r.indexOf(" " + o + " ") < 0 && (r += o + " ");
a = oe.trim(r), i !== a && n.setAttribute("class", a)
}
return this
},
removeClass: function (e) {
var t, n, r, i, o, s, a, u = 0;
if (oe.isFunction(e)) return this.each(function (t) {
oe(this).removeClass(e.call(this, t, R(this)))
});
if (!arguments.length) return this.attr("class", "");
if ("string" == typeof e && e)
for (t = e.match(we) || []; n = this[u++];)
if (i = R(n), r = 1 === n.nodeType && (" " + i + " ").replace(dt, " ")) {
for (s = 0; o = t[s++];)
for (; r.indexOf(" " + o + " ") > -1;) r = r.replace(" " + o + " ", " ");
a = oe.trim(r), i !== a && n.setAttribute("class", a)
}
return this
},
toggleClass: function (e, t) {
var n = typeof e;
return "boolean" == typeof t && "string" === n ? t ? this.addClass(e) : this.removeClass(e) : oe.isFunction(e) ? this.each(function (n) {
oe(this).toggleClass(e.call(this, n, R(this), t), t)
}) : this.each(function () {
var t, r, i, o;
if ("string" === n)
for (r = 0, i = oe(this), o = e.match(we) || []; t = o[r++];) i.hasClass(t) ? i.removeClass(t) : i.addClass(t);
else void 0 !== e && "boolean" !== n || (t = R(this), t && ke.set(this, "__className__", t), this.setAttribute && this.setAttribute("class", t || e === !1 ? "" : ke.get(this, "__className__") || ""))
})
},
hasClass: function (e) {
var t, n, r = 0;
for (t = " " + e + " "; n = this[r++];)
if (1 === n.nodeType && (" " + R(n) + " ").replace(dt, " ").indexOf(t) > -1) return !0;
return !1
}
});
var ht = /\r/g,
pt = /[\x20\t\r\n\f]+/g;
oe.fn.extend({
val: function (e) {
var t, n, r, i = this[0]; {
if (arguments.length) return r = oe.isFunction(e), this.each(function (n) {
var i;
1 === this.nodeType && (i = r ? e.call(this, n, oe(this).val()) : e, null == i ? i = "" : "number" == typeof i ? i += "" : oe.isArray(i) && (i = oe.map(i, function (e) {
return null == e ? "" : e + ""
})), t = oe.valHooks[this.type] || oe.valHooks[this.nodeName.toLowerCase()], t && "set" in t && void 0 !== t.set(this, i, "value") || (this.value = i))
});
if (i) return t = oe.valHooks[i.type] || oe.valHooks[i.nodeName.toLowerCase()], t && "get" in t && void 0 !== (n = t.get(i, "value")) ? n : (n = i.value, "string" == typeof n ? n.replace(ht, "") : null == n ? "" : n)
}
}
}), oe.extend({
valHooks: {
option: {
get: function (e) {
var t = oe.find.attr(e, "value");
return null != t ? t : oe.trim(oe.text(e)).replace(pt, " ")
}
},
select: {
get: function (e) {
for (var t, n, r = e.options, i = e.selectedIndex, o = "select-one" === e.type || i < 0, s = o ? null : [], a = o ? i + 1 : r.length, u = i < 0 ? a : o ? i : 0; u < a; u++)
if (n = r[u], (n.selected || u === i) && (re.optDisabled ? !n.disabled : null === n.getAttribute("disabled")) && (!n.parentNode.disabled || !oe.nodeName(n.parentNode, "optgroup"))) {
if (t = oe(n).val(), o) return t;
s.push(t)
}
return s
},
set: function (e, t) {
for (var n, r, i = e.options, o = oe.makeArray(t), s = i.length; s--;) r = i[s], (r.selected = oe.inArray(oe.valHooks.option.get(r), o) > -1) && (n = !0);
return n || (e.selectedIndex = -1), o
}
}
}
}), oe.each(["radio", "checkbox"], function () {
oe.valHooks[this] = {
set: function (e, t) {
if (oe.isArray(t)) return e.checked = oe.inArray(oe(e).val(), t) > -1
}
}, re.checkOn || (oe.valHooks[this].get = function (e) {
return null === e.getAttribute("value") ? "on" : e.value
})
});
var gt = /^(?:focusinfocus|focusoutblur)$/;
oe.extend(oe.event, {
trigger: function (t, n, r, i) {
var o, s, a, u, l, c, f, d = [r || Y],
h = ne.call(t, "type") ? t.type : t,
p = ne.call(t, "namespace") ? t.namespace.split(".") : [];
if (s = a = r = r || Y, 3 !== r.nodeType && 8 !== r.nodeType && !gt.test(h + oe.event.triggered) && (h.indexOf(".") > -1 && (p = h.split("."), h = p.shift(), p.sort()), l = h.indexOf(":") < 0 && "on" + h, t = t[oe.expando] ? t : new oe.Event(h, "object" == typeof t && t), t.isTrigger = i ? 2 : 3, t.namespace = p.join("."), t.rnamespace = t.namespace ? new RegExp("(^|\\.)" + p.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, t.result = void 0, t.target || (t.target = r), n = null == n ? [t] : oe.makeArray(n, [t]), f = oe.event.special[h] || {}, i || !f.trigger || f.trigger.apply(r, n) !== !1)) {
if (!i && !f.noBubble && !oe.isWindow(r)) {
for (u = f.delegateType || h, gt.test(u + h) || (s = s.parentNode); s; s = s.parentNode) d.push(s), a = s;
a === (r.ownerDocument || Y) && d.push(a.defaultView || a.parentWindow || e)
}
for (o = 0;
(s = d[o++]) && !t.isPropagationStopped();) t.type = o > 1 ? u : f.bindType || h, c = (ke.get(s, "events") || {})[t.type] && ke.get(s, "handle"), c && c.apply(s, n), c = l && s[l], c && c.apply && Te(s) && (t.result = c.apply(s, n), t.result === !1 && t.preventDefault());
return t.type = h, i || t.isDefaultPrevented() || f._default && f._default.apply(d.pop(), n) !== !1 || !Te(r) || l && oe.isFunction(r[h]) && !oe.isWindow(r) && (a = r[l], a && (r[l] = null), oe.event.triggered = h, r[h](), oe.event.triggered = void 0, a && (r[l] = a)), t.result
}
},
simulate: function (e, t, n) {
var r = oe.extend(new oe.Event, n, {
type: e,
isSimulated: !0
});
oe.event.trigger(r, null, t)
}
}), oe.fn.extend({
trigger: function (e, t) {
return this.each(function () {
oe.event.trigger(e, t, this)
})
},
triggerHandler: function (e, t) {
var n = this[0];
if (n) return oe.event.trigger(e, t, n, !0)
}
}), oe.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), function (e, t) {
oe.fn[t] = function (e, n) {
return arguments.length > 0 ? this.on(t, null, e, n) : this.trigger(t)
}
}), oe.fn.extend({
hover: function (e, t) {
return this.mouseenter(e).mouseleave(t || e)
}
}), re.focusin = "onfocusin" in e, re.focusin || oe.each({
focus: "focusin",
blur: "focusout"
}, function (e, t) {
var n = function (e) {
oe.event.simulate(t, e.target, oe.event.fix(e))
};
oe.event.special[t] = {
setup: function () {
var r = this.ownerDocument || this,
i = ke.access(r, t);
i || r.addEventListener(e, n, !0), ke.access(r, t, (i || 0) + 1)
},
teardown: function () {
var r = this.ownerDocument || this,
i = ke.access(r, t) - 1;
i ? ke.access(r, t, i) : (r.removeEventListener(e, n, !0), ke.remove(r, t))
}
}
});
var mt = e.location,
vt = oe.now(),
yt = /\?/;
oe.parseJSON = function (e) {
return JSON.parse(e + "")
}, oe.parseXML = function (t) {
var n;
if (!t || "string" != typeof t) return null;
try {
n = (new e.DOMParser).parseFromString(t, "text/xml")
} catch (r) {
n = void 0
}
return n && !n.getElementsByTagName("parsererror").length || oe.error("Invalid XML: " + t), n
};
var bt = /#.*$/,
xt = /([?&])_=[^&]*/,
wt = /^(.*?):[ \t]*([^\r\n]*)$/gm,
$t = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
Ct = /^(?:GET|HEAD)$/,
Tt = /^\/\//,
kt = {},
Et = {},
St = "*/".concat("*"),
jt = Y.createElement("a");
jt.href = mt.href, oe.extend({
active: 0,
lastModified: {},
etag: {},
ajaxSettings: {
url: mt.href,
type: "GET",
isLocal: $t.test(mt.protocol),
global: !0,
processData: !0,
async: !0,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
accepts: {
"*": St,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
converters: {
"* text": String,
"text html": !0,
"text json": oe.parseJSON,
"text xml": oe.parseXML
},
flatOptions: {
url: !0,
context: !0
}
},
ajaxSetup: function (e, t) {
return t ? B(B(e, oe.ajaxSettings), t) : B(oe.ajaxSettings, e)
},
ajaxPrefilter: z(kt),
ajaxTransport: z(Et),
ajax: function (t, n) {
function r(t, n, r, a) {
var l, f, y, b, w, C = n;
2 !== x && (x = 2, u && e.clearTimeout(u), i = void 0, s = a || "", $.readyState = t > 0 ? 4 : 0, l = t >= 200 && t < 300 || 304 === t, r && (b = _(d, $, r)), b = G(d, b, $, l), l ? (d.ifModified && (w = $.getResponseHeader("Last-Modified"), w && (oe.lastModified[o] = w), w = $.getResponseHeader("etag"), w && (oe.etag[o] = w)), 204 === t || "HEAD" === d.type ? C = "nocontent" : 304 === t ? C = "notmodified" : (C = b.state, f = b.data, y = b.error, l = !y)) : (y = C, !t && C || (C = "error", t < 0 && (t = 0))), $.status = t, $.statusText = (n || C) + "", l ? g.resolveWith(h, [f, C, $]) : g.rejectWith(h, [$, C, y]), $.statusCode(v), v = void 0, c && p.trigger(l ? "ajaxSuccess" : "ajaxError", [$, d, l ? f : y]), m.fireWith(h, [$, C]), c && (p.trigger("ajaxComplete", [$, d]), --oe.active || oe.event.trigger("ajaxStop")))
}
"object" == typeof t && (n = t, t = void 0), n = n || {};
var i, o, s, a, u, l, c, f, d = oe.ajaxSetup({}, n),
h = d.context || d,
p = d.context && (h.nodeType || h.jquery) ? oe(h) : oe.event,
g = oe.Deferred(),
m = oe.Callbacks("once memory"),
v = d.statusCode || {},
y = {},
b = {},
x = 0,
w = "canceled",
$ = {
readyState: 0,
getResponseHeader: function (e) {
var t;
if (2 === x) {
if (!a)
for (a = {}; t = wt.exec(s);) a[t[1].toLowerCase()] = t[2];
t = a[e.toLowerCase()]
}
return null == t ? null : t
},
getAllResponseHeaders: function () {
return 2 === x ? s : null
},
setRequestHeader: function (e, t) {
var n = e.toLowerCase();
return x || (e = b[n] = b[n] || e, y[e] = t), this
},
overrideMimeType: function (e) {
return x || (d.mimeType = e), this
},
statusCode: function (e) {
var t;
if (e)
if (x < 2)
for (t in e) v[t] = [v[t], e[t]];
else $.always(e[$.status]);
return this
},
abort: function (e) {
var t = e || w;
return i && i.abort(t), r(0, t), this
}
};
if (g.promise($).complete = m.add, $.success = $.done, $.error = $.fail, d.url = ((t || d.url || mt.href) + "").replace(bt, "").replace(Tt, mt.protocol + "//"), d.type = n.method || n.type || d.method || d.type, d.dataTypes = oe.trim(d.dataType || "*").toLowerCase().match(we) || [""], null == d.crossDomain) {
l = Y.createElement("a");
try {
l.href = d.url, l.href = l.href, d.crossDomain = jt.protocol + "//" + jt.host != l.protocol + "//" + l.host
} catch (C) {
d.crossDomain = !0
}
}
if (d.data && d.processData && "string" != typeof d.data && (d.data = oe.param(d.data, d.traditional)), W(kt, d, n, $), 2 === x) return $;
c = oe.event && d.global, c && 0 === oe.active++ && oe.event.trigger("ajaxStart"), d.type = d.type.toUpperCase(), d.hasContent = !Ct.test(d.type), o = d.url, d.hasContent || (d.data && (o = d.url += (yt.test(o) ? "&" : "?") + d.data, delete d.data), d.cache === !1 && (d.url = xt.test(o) ? o.replace(xt, "$1_=" + vt++) : o + (yt.test(o) ? "&" : "?") + "_=" + vt++)), d.ifModified && (oe.lastModified[o] && $.setRequestHeader("If-Modified-Since", oe.lastModified[o]), oe.etag[o] && $.setRequestHeader("If-None-Match", oe.etag[o])), (d.data && d.hasContent && d.contentType !== !1 || n.contentType) && $.setRequestHeader("Content-Type", d.contentType), $.setRequestHeader("Accept", d.dataTypes[0] && d.accepts[d.dataTypes[0]] ? d.accepts[d.dataTypes[0]] + ("*" !== d.dataTypes[0] ? ", " + St + "; q=0.01" : "") : d.accepts["*"]);
for (f in d.headers) $.setRequestHeader(f, d.headers[f]);
if (d.beforeSend && (d.beforeSend.call(h, $, d) === !1 || 2 === x)) return $.abort();
w = "abort";
for (f in {
success: 1,
error: 1,
complete: 1
}) $[f](d[f]);
if (i = W(Et, d, n, $)) {
if ($.readyState = 1, c && p.trigger("ajaxSend", [$, d]), 2 === x) return $;
d.async && d.timeout > 0 && (u = e.setTimeout(function () {
$.abort("timeout")
}, d.timeout));
try {
x = 1, i.send(y, r)
} catch (C) {
if (!(x < 2)) throw C;
r(-1, C)
}
} else r(-1, "No Transport");
return $
},
getJSON: function (e, t, n) {
return oe.get(e, t, n, "json")
},
getScript: function (e, t) {
return oe.get(e, void 0, t, "script")
}
}), oe.each(["get", "post"], function (e, t) {
oe[t] = function (e, n, r, i) {
return oe.isFunction(n) && (i = i || r, r = n, n = void 0), oe.ajax(oe.extend({
url: e,
type: t,
dataType: i,
data: n,
success: r
}, oe.isPlainObject(e) && e))
}
}), oe._evalUrl = function (e) {
return oe.ajax({
url: e,
type: "GET",
dataType: "script",
async: !1,
global: !1,
"throws": !0
})
}, oe.fn.extend({
wrapAll: function (e) {
var t;
return oe.isFunction(e) ? this.each(function (t) {
oe(this).wrapAll(e.call(this, t))
}) : (this[0] && (t = oe(e, this[0].ownerDocument).eq(0).clone(!0), this[0].parentNode && t.insertBefore(this[0]), t.map(function () {
for (var e = this; e.firstElementChild;) e = e.firstElementChild;
return e
}).append(this)), this)
},
wrapInner: function (e) {
return oe.isFunction(e) ? this.each(function (t) {
oe(this).wrapInner(e.call(this, t))
}) : this.each(function () {
var t = oe(this),
n = t.contents();
n.length ? n.wrapAll(e) : t.append(e)
})
},
wrap: function (e) {
var t = oe.isFunction(e);
return this.each(function (n) {
oe(this).wrapAll(t ? e.call(this, n) : e)
})
},
unwrap: function () {
return this.parent().each(function () {
oe.nodeName(this, "body") || oe(this).replaceWith(this.childNodes)
}).end()
}
}), oe.expr.filters.hidden = function (e) {
return !oe.expr.filters.visible(e)
}, oe.expr.filters.visible = function (e) {
return e.offsetWidth > 0 || e.offsetHeight > 0 || e.getClientRects().length > 0
};
var Mt = /%20/g,
Ht = /\[\]$/,
Nt = /\r?\n/g,
Dt = /^(?:submit|button|image|reset|file)$/i,
At = /^(?:input|select|textarea|keygen)/i;
oe.param = function (e, t) {
var n, r = [],
i = function (e, t) {
t = oe.isFunction(t) ? t() : null == t ? "" : t, r[r.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t)
};
if (void 0 === t && (t = oe.ajaxSettings && oe.ajaxSettings.traditional), oe.isArray(e) || e.jquery && !oe.isPlainObject(e)) oe.each(e, function () {
i(this.name, this.value)
});
else
for (n in e) X(n, e[n], t, i);
return r.join("&").replace(Mt, "+")
}, oe.fn.extend({
serialize: function () {
return oe.param(this.serializeArray())
},
serializeArray: function () {
return this.map(function () {
var e = oe.prop(this, "elements");
return e ? oe.makeArray(e) : this
}).filter(function () {
var e = this.type;
return this.name && !oe(this).is(":disabled") && At.test(this.nodeName) && !Dt.test(e) && (this.checked || !Ae.test(e))
}).map(function (e, t) {
var n = oe(this).val();
return null == n ? null : oe.isArray(n) ? oe.map(n, function (e) {
return {
name: t.name,
value: e.replace(Nt, "\r\n")
}
}) : {
name: t.name,
value: n.replace(Nt, "\r\n")
}
}).get()
}
}), oe.ajaxSettings.xhr = function () {
try {
return new e.XMLHttpRequest
} catch (t) {}
};
var Ot = {
0: 200,
1223: 204
},
qt = oe.ajaxSettings.xhr();
re.cors = !!qt && "withCredentials" in qt, re.ajax = qt = !!qt, oe.ajaxTransport(function (t) {
var n, r;
if (re.cors || qt && !t.crossDomain) return {
send: function (i, o) {
var s, a = t.xhr();
if (a.open(t.type, t.url, t.async, t.username, t.password), t.xhrFields)
for (s in t.xhrFields) a[s] = t.xhrFields[s];
t.mimeType && a.overrideMimeType && a.overrideMimeType(t.mimeType), t.crossDomain || i["X-Requested-With"] || (i["X-Requested-With"] = "XMLHttpRequest");
for (s in i) a.setRequestHeader(s, i[s]);
n = function (e) {
return function () {
n && (n = r = a.onload = a.onerror = a.onabort = a.onreadystatechange = null, "abort" === e ? a.abort() : "error" === e ? "number" != typeof a.status ? o(0, "error") : o(a.status, a.statusText) : o(Ot[a.status] || a.status, a.statusText, "text" !== (a.responseType || "text") || "string" != typeof a.responseText ? {
binary: a.response
} : {
text: a.responseText
}, a.getAllResponseHeaders()))
}
}, a.onload = n(), r = a.onerror = n("error"), void 0 !== a.onabort ? a.onabort = r : a.onreadystatechange = function () {
4 === a.readyState && e.setTimeout(function () {
n && r()
})
}, n = n("abort");
try {
a.send(t.hasContent && t.data || null)
} catch (u) {
if (n) throw u
}
},
abort: function () {
n && n()
}
}
}), oe.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function (e) {
return oe.globalEval(e), e
}
}
}), oe.ajaxPrefilter("script", function (e) {
void 0 === e.cache && (e.cache = !1), e.crossDomain && (e.type = "GET")
}), oe.ajaxTransport("script", function (e) {
if (e.crossDomain) {
var t, n;
return {
send: function (r, i) {
t = oe("<script>").prop({
charset: e.scriptCharset,
src: e.url
}).on("load error", n = function (e) {
t.remove(), n = null, e && i("error" === e.type ? 404 : 200, e.type)
}), Y.head.appendChild(t[0])
},
abort: function () {
n && n()
}
}
}
});
var It = [],
Lt = /(=)\?(?=&|$)|\?\?/;
oe.ajaxSetup({
jsonp: "callback",
jsonpCallback: function () {
var e = It.pop() || oe.expando + "_" + vt++;
return this[e] = !0, e
}
}), oe.ajaxPrefilter("json jsonp", function (t, n, r) {
var i, o, s, a = t.jsonp !== !1 && (Lt.test(t.url) ? "url" : "string" == typeof t.data && 0 === (t.contentType || "").indexOf("application/x-www-form-urlencoded") && Lt.test(t.data) && "data");
if (a || "jsonp" === t.dataTypes[0]) return i = t.jsonpCallback = oe.isFunction(t.jsonpCallback) ? t.jsonpCallback() : t.jsonpCallback, a ? t[a] = t[a].replace(Lt, "$1" + i) : t.jsonp !== !1 && (t.url += (yt.test(t.url) ? "&" : "?") + t.jsonp + "=" + i), t.converters["script json"] = function () {
return s || oe.error(i + " was not called"), s[0]
}, t.dataTypes[0] = "json", o = e[i], e[i] = function () {
s = arguments
}, r.always(function () {
void 0 === o ? oe(e).removeProp(i) : e[i] = o, t[i] && (t.jsonpCallback = n.jsonpCallback, It.push(i)), s && oe.isFunction(o) && o(s[0]), s = o = void 0
}), "script"
}), oe.parseHTML = function (e, t, n) {
if (!e || "string" != typeof e) return null;
"boolean" == typeof t && (n = t, t = !1), t = t || Y;
var r = pe.exec(e),
i = !n && [];
return r ? [t.createElement(r[1])] : (r = d([e], t, i), i && i.length && oe(i).remove(), oe.merge([], r.childNodes))
};
var Pt = oe.fn.load;
oe.fn.load = function (e, t, n) {
if ("string" != typeof e && Pt) return Pt.apply(this, arguments);
var r, i, o, s = this,
a = e.indexOf(" ");
return a > -1 && (r = oe.trim(e.slice(a)), e = e.slice(0, a)), oe.isFunction(t) ? (n = t, t = void 0) : t && "object" == typeof t && (i = "POST"), s.length > 0 && oe.ajax({
url: e,
type: i || "GET",
dataType: "html",
data: t
}).done(function (e) {
o = arguments, s.html(r ? oe("<div>").append(oe.parseHTML(e)).find(r) : e)
}).always(n && function (e, t) {
s.each(function () {
n.apply(this, o || [e.responseText, t, e])
})
}), this
}, oe.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function (e, t) {
oe.fn[t] = function (e) {
return this.on(t, e)
}
}), oe.expr.filters.animated = function (e) {
return oe.grep(oe.timers, function (t) {
return e === t.elem
}).length
}, oe.offset = {
setOffset: function (e, t, n) {
var r, i, o, s, a, u, l, c = oe.css(e, "position"),
f = oe(e),
d = {};
"static" === c && (e.style.position = "relative"), a = f.offset(), o = oe.css(e, "top"), u = oe.css(e, "left"), l = ("absolute" === c || "fixed" === c) && (o + u).indexOf("auto") > -1, l ? (r = f.position(), s = r.top, i = r.left) : (s = parseFloat(o) || 0, i = parseFloat(u) || 0), oe.isFunction(t) && (t = t.call(e, n, oe.extend({}, a))), null != t.top && (d.top = t.top - a.top + s), null != t.left && (d.left = t.left - a.left + i), "using" in t ? t.using.call(e, d) : f.css(d)
}
}, oe.fn.extend({
offset: function (e) {
if (arguments.length) return void 0 === e ? this : this.each(function (t) {
oe.offset.setOffset(this, e, t)
});
var t, n, r = this[0],
i = {
top: 0,
left: 0
},
o = r && r.ownerDocument;
if (o) return t = o.documentElement, oe.contains(t, r) ? (i = r.getBoundingClientRect(), n = Q(o), {
top: i.top + n.pageYOffset - t.clientTop,
left: i.left + n.pageXOffset - t.clientLeft
}) : i
},
position: function () {
if (this[0]) {
var e, t, n = this[0],
r = {
top: 0,
left: 0
};
return "fixed" === oe.css(n, "position") ? t = n.getBoundingClientRect() : (e = this.offsetParent(), t = this.offset(), oe.nodeName(e[0], "html") || (r = e.offset()), r.top += oe.css(e[0], "borderTopWidth", !0), r.left += oe.css(e[0], "borderLeftWidth", !0)), {
top: t.top - r.top - oe.css(n, "marginTop", !0),
left: t.left - r.left - oe.css(n, "marginLeft", !0)
}
}
},
offsetParent: function () {
return this.map(function () {
for (var e = this.offsetParent; e && "static" === oe.css(e, "position");) e = e.offsetParent;
return e || Ke
})
}
}), oe.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function (e, t) {
var n = "pageYOffset" === t;
oe.fn[e] = function (r) {
return Ce(this, function (e, r, i) {
var o = Q(e);
return void 0 === i ? o ? o[t] : e[r] : void(o ? o.scrollTo(n ? o.pageXOffset : i, n ? i : o.pageYOffset) : e[r] = i)
}, e, r, arguments.length)
}
}), oe.each(["top", "left"], function (e, t) {
oe.cssHooks[t] = S(re.pixelPosition, function (e, n) {
if (n) return n = E(e, t), Ye.test(n) ? oe(e).position()[t] + "px" : n
})
}), oe.each({
Height: "height",
Width: "width"
}, function (e, t) {
oe.each({
padding: "inner" + e,
content: t,
"": "outer" + e
}, function (n, r) {
oe.fn[r] = function (r, i) {
var o = arguments.length && (n || "boolean" != typeof r),
s = n || (r === !0 || i === !0 ? "margin" : "border");
return Ce(this, function (t, n, r) {
var i;
return oe.isWindow(t) ? t.document.documentElement["client" + e] : 9 === t.nodeType ? (i = t.documentElement, Math.max(t.body["scroll" + e], i["scroll" + e], t.body["offset" + e], i["offset" + e], i["client" + e])) : void 0 === r ? oe.css(t, n, s) : oe.style(t, n, r, s)
}, t, o ? r : void 0, o, null)
}
})
}), oe.fn.extend({
bind: function (e, t, n) {
return this.on(e, null, t, n)
},
unbind: function (e, t) {
return this.off(e, null, t)
},
delegate: function (e, t, n, r) {
return this.on(t, e, n, r)
},
undelegate: function (e, t, n) {
return 1 === arguments.length ? this.off(e, "**") : this.off(t, e || "**", n)
},
size: function () {
return this.length
}
}), oe.fn.andSelf = oe.fn.addBack, "function" == typeof define && define.amd && define("jquery", [], function () {
return oe
});
var Ft = e.jQuery,
Rt = e.$;
return oe.noConflict = function (t) {
return e.$ === oe && (e.$ = Rt), t && e.jQuery === oe && (e.jQuery = Ft), oe
}, t || (e.jQuery = e.$ = oe), oe
})
}, {}]
}, {}, [10]); | 3d82268c3fbf0a300c8a7911ecbd6bb226134ccd | [
"JavaScript"
] | 1 | JavaScript | MJCoderMJCoder/mr-design.jp | 868a036699de2cea7188cdf505860d960454e4b6 | fb259b42779d9e06893edb071329ba7f2ac63bf0 | |
refs/heads/master | <repo_name>Mark-Mulligan/ReactEmployeeManagementBackend<file_sep>/db/schema.sql
Drop Database IF exists company_db;
CREATE DATABASE company_db;
Use company_db;
CREATE TABLE departments (
id INT NOT NULL AUTO_INCREMENT PRIMARY Key,
name VARCHAR(30),
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW()
);
CREATE TABLE roles (
id INT NOT NULL AUTO_INCREMENT PRIMARY Key,
title VARCHAR(30),
salary DECIMAL,
department_id INT,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW(),
FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE CASCADE
);
CREATE TABLE employees (
id INT NOT NULL AUTO_INCREMENT PRIMARY Key,
first_name VARCHAR(30),
last_name VARCHAR(30),
role_id INT,
manager_id INT,
date_hired DATE,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW(),
FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE
);<file_sep>/db/seeds.sql
Use company_db;
INSERT INTO departments (name) VALUES
('Management'),
('Sales'),
('Finance'),
('R&D'),
('Human Resources');
INSERT INTO roles (title, salary, department_id) VALUES
('CEO', 500000, 1),
('Regional Manager', 150000, 1),
('Lead Salesperson', 90000, 2),
('Salesperson', 70000, 2),
('Lead Accountant', 100000, 3),
('Accountant', 75000, 3),
('Analyst', 85000, 4),
('HR Rep', 50000, 5);
INSERT INTO employees (first_name, last_name, role_id, manager_id, date_hired) VALUES
('David', 'Wallace', 1, null, '2010-01-01'),
('Michael', 'Scott', 2, 1, '2010-01-01'),
('Dwight', 'Schrute', 3, 2, '2010-03-20'),
('Jim', 'Halpert', 4, 3, '2010-05-10'),
('Stanley', 'Hudson', 4, 3, '2011-02-12'),
('Creed', 'Bratton', 7, 2, '2011-04-15'),
('Andy', 'Bernard', 3, 3, '2012-08-12'),
('Oscar', 'Martinez', 5, 2, '2013-10-09'),
('Angela', 'Martin', 6, 8, '2014-11-02'),
('Kevin', 'Malone', 6, 8, '2014-12-01'),
('Ryan', 'Howard', 7, 2, '2015-06-23'),
('Gabe', 'Lewis', 8, 2, '2015-09-07');<file_sep>/models/employee.js
const orm = require("../config/orm");
const employee = {
getTableData: (orderby, cb, errCb) => {
orm.getEmployeeTableData(
orderby,
(response) => cb(response),
(err) => errCb(err)
);
},
getBarChartData: (cb, errCb) => {
orm.getEmployeeBarChartData(
(response) => cb(response),
(err) => errCb(err)
);
},
getOne: (id, cb, errCb) => {
orm.getSingleEmployee(
id,
(response) => cb(response),
(err) => errCb(err)
);
},
getManagersForForm: (cb, errCb) => {
orm.simpleSelect(
`id, CONCAT(first_name, ' ', last_name) as manager`,
"employees",
(response) => cb(response),
(err) => errCb(err)
);
},
getManagersForEdit: (userWhereValue, cb, errCb) => {
orm.simpleSelectWithWhere(
`id, CONCAT(first_name, ' ', last_name) as manager`,
"employees",
"id",
"!=",
userWhereValue,
(response) => cb(response),
(err) => errCb(err)
);
},
create: (userValuesArr, cb, errCb) => {
orm.simpleInsert(
"employees",
["first_name", "last_name", "role_id", "manager_id"],
userValuesArr,
(response) => cb(response),
(err) => errCb(err)
);
},
update: (userValuesArr, employeeId, cb, errCb) => {
orm.simpleUpdate(
"employees",
["first_name", "last_name", "role_id", "manager_id"],
userValuesArr,
employeeId,
(response) => cb(response),
(err) => errCb(err)
);
},
deleteOne: (userWhereValue, cb, errCb) => {
orm.simpleDelete(
"employees",
"id",
"=",
userWhereValue,
(response) => cb(response),
(err) => errCb(err)
);
},
};
module.exports = employee;
<file_sep>/server.js
const express = require("express");
const cors = require('cors')
const PORT = process.env.PORT || 3001;
const app = express();
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Import routes and give the server access to them.
const employeeRoutes = require('./controllers/employeeController');
const roleRoutes = require('./controllers/roleController');
const departmentRoutes = require('./controllers/departmentController');
app.use(employeeRoutes);
app.use(roleRoutes);
app.use(departmentRoutes);
app.listen(PORT, function() {
console.log("App now listening at localhost:" + PORT);
});<file_sep>/models/role.js
const orm = require("../config/orm");
const role = {
getTableData: (cb, errCb) => {
orm.getRoleTableData(
(response) => cb(response),
(err) => errCb(err)
);
},
getOne: (roleId, cb, errCb) => {
orm.getSingleRole(
roleId,
(response) => cb(response),
(err) => errCb(err)
);
},
create: (userValuesArr, cb, errCb) => {
orm.simpleInsert(
"roles",
["title", "salary", "department_id"],
userValuesArr,
(response) => cb(response),
(err) => errCb(err)
);
},
update: (userValuesArr, roleId, cb, errCb) => {
orm.simpleUpdate(
"roles",
["title", "salary", "department_id"],
userValuesArr,
roleId,
(response) => cb(response),
(err) => errCb(err)
);
},
delete: (userWhereValue, cb, errCb) => {
orm.simpleDelete(
"roles",
"id",
"=",
userWhereValue,
(response) => cb(response),
(err) => errCb(err)
);
},
getBarChartData: (cb, errCb) => {
orm.getRoleBarChartData(
(response) => cb(response),
(err) => errCb(err)
);
},
};
module.exports = role;
<file_sep>/util/util.js
const util = {
createPlaceholders: (arr) => {
let placeholders = '';
for (let i = 0; i < arr.length; i++) {
if (i === 0 && arr.length === 1) {
placeholders += '?'
} else if (i === 0) {
placeholders += '?,'
} else if (i === arr.length - 1) {
placeholders += ' ?'
} else {
placeholders += ' ?,'
}
}
return placeholders;
}
}
module.exports = util;<file_sep>/db/queries.sql
SELECT *
FROM employees
INNER JOIN roles ON roles.id = employees.role_id
INNER JOIN departments ON departments.id = roles.department_id;
SELECT *
FROM employees
INNER JOIN roles ON roles.id = employees.role_id
Where department_id = 2;
SELECT departments.*, count(roles.department_id) as roles
from departments
left join roles
on (roles.department_id = departments.id)
group by
departments.id;
/* Gets number of employees in department */
SELECT departments.*, count(roles.department_id) as roles
from departments
left join roles
on (roles.department_id = departments.id)
left join employees
on (employees.role_id = roles.id)
group by
departments.id;
/* Returns department id, name, num employees, and utilization */
SELECT departments.id, departments.name,
count(roles.department_id) as employees,
count(distinct roles.id) as roles,
SUM(roles.salary) as departmentUtilization
from departments
join roles
on (roles.department_id = departments.id)
join employees
on (employees.role_id = roles.id)
group by
departments.id;
/* query for individual department */
SELECT departments.id, departments.name,
roles.title as roles, roles.salary as salary,
CONCAT(employees.first_name, ' ', employees.last_name) as employees
from departments
join roles
on (roles.department_id = departments.id)
join employees
on (employees.role_id = roles.id)
Where departments.id = 1;
/* Get Additional data for Role Table */
SELECT roles.id, roles.title, roles.salary,
departments.name, count(employees.id) as employees, sum(roles.salary) as roleUtilization
from roles left join employees on (roles.id = employees.role_id)
left join departments on (roles.department_id = departments.id)
group by roles.id;
/* Select invdividual role */
SELECT roles.id, roles.title, roles.salary,
departments.name, count(employees.id) as employees, sum(roles.salary) as roleUtilization
from roles left join employees on (roles.id = employees.role_id)
left join departments on (roles.department_id = departments.id)
group by roles.id having roles.id = 3;<file_sep>/controllers/roleController.js
const express = require("express");
//const { getTableData: getRoles } = require("../models/department");
const router = express.Router();
const role = require("../models/role");
router.get("/roles", (req, res) => {
role.getTableData(
(data) => res.json(data),
(err) => {
res.status(500);
res.json(err);
}
);
});
router.post("/roles", (req, res) => {
const { title, salary, departmentId } = req.body;
role.create([title, salary, departmentId], (data) => res.json(data),
(err) => {
res.status(500);
res.json(err);
});
});
router.get("/role/:id", (req, res) => {
const roleId = req.params.id;
role.getOne(
roleId,
(data) => res.json(data),
(err) => {
res.status(500);
res.json(err);
}
);
});
router.put("/role/:id", (req, res) => {
const roleId = req.params.id;
const { title, salary, departmentId } = req.body;
role.update(
[title, salary, departmentId],
roleId,
(data) => res.json(data),
(err) => {
res.status(500);
res.json(err);
}
);
});
router.delete("/role/:id", (req, res) => {
const roleId = req.params.id;
role.delete(
roleId,
(data) => res.json(data),
(err) => {
res.status(500);
res.json(err);
}
);
});
router.get("/api/roles/chartdata", (req, res) => {
role.getBarChartData(
(data) => res.json(data),
(err) => {
res.status(500);
res.json(err);
}
);
});
module.exports = router;
<file_sep>/models/department.js
const orm = require("../config/orm");
const department = {
getTableData: (cb, errCb) => {
orm.getDepartmentTableData(
(response) => cb(response),
(err) => errCb(err)
);
},
getOne: (departmentId, cb, errCb) => {
orm.getSingleDepartment(
departmentId,
(response) => cb(response),
(err) => errCb(err)
);
},
getNamesAndIds: (cb, errCb) => {
orm.simpleSelect(
`name, id`,
"departments",
(response) => cb(response),
(err) => errCb(err)
);
},
getRolesInDepartment: (departmentId, cb, errCb) => {
orm.simpleSelectWithWhere(
"title, id",
"roles",
"department_id",
"=",
departmentId,
(response) => cb(response),
(err) => errCb(err)
);
},
create: (valuesArr, cb, errCb) => {
orm.simpleInsert(
"departments",
["name"],
valuesArr,
(response) => cb(response),
(err) => errCb(err)
);
},
update: (userValuesArr, departmentId, cb, errCb) => {
orm.simpleUpdate(
"departments",
["name"],
userValuesArr,
departmentId,
(response) => cb(response),
(err) => errCb(err)
);
},
delete: (userWhereValue, cb, errCb) => {
orm.simpleDelete(
"departments",
"id",
"=",
userWhereValue,
(response) => cb(response),
(err) => errCb(err)
);
},
};
module.exports = department;
| d34e7086a9fe20279f6f1678743ef472d92247c7 | [
"JavaScript",
"SQL"
] | 9 | SQL | Mark-Mulligan/ReactEmployeeManagementBackend | bc8893a184f741b3c860f857a9bf6feee347e3a6 | b8c14429a96bcbd4d92eca6be8ad56070bb69e90 | |
refs/heads/master | <repo_name>Pierrik/GuitarZero<file_sep>/src/SelectMode.java
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.lang.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* Select Mode.
*
* @author <NAME>
* @version 2.0, March 2019.
*/
public class SelectMode extends JPanel {
/**
* Initialises the GUI classes for a carousel with menu options specific to Select Mode
*/
public SelectMode() throws NoSongsException {
ArrayList<JLabel> menuOptions = new ArrayList<>();
String cd = System.getProperty("user.dir");
String bundleDirPath = "../local_store/bundle_files/";
File[] song_folders = new File(bundleDirPath).listFiles();
if (song_folders == null || song_folders.length == 0){
System.out.println("No songs in local store.");
throw new NoSongsException("No songs in local store");
}
for (File song_folder : song_folders) {
File albumCover = new File("");
String songName;
if (!song_folder.getName().equals(".DS_Store")) {
songName = song_folder.getName();
File[] song_files = song_folder.listFiles();
for (File song_file : song_files) {
if (getExtension(song_file.getName()).equalsIgnoreCase("png")) {
albumCover = song_file;
}
}
JLabel label = new JLabel(new ImageIcon(albumCover.getPath()));
label.setText(songName);
menuOptions.add(label);
}
}
// Initialise the model, controller, view GUI classes
CarouselView view = new CarouselView( menuOptions);
CarouselModel model = new CarouselModel( view );
CarouselController controller = new CarouselController( model , Mode.SELECT);
try {
Thread.sleep(200);
} catch (InterruptedException e){
e.printStackTrace();
}
Thread controllerThread = new Thread(controller);
controllerThread.start();
this.add(view);
}
/**
* Gets the extension of a file
* @param fileName the name of the file to check
* @return the file extension
*/
private String getExtension (String fileName) {
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i + 1);
}
return extension;
}
/**
* Draws the highway background that the carousel will be placed on top of
* @param g
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // paint the background image and scale it to fill the entire space
Image highway = null;
try {
highway = ImageIO.read(new File("../assets/Done/Highway.bmp"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(highway, -7, 5, this);
}
}<file_sep>/src/TutorialModeModel.java
/**
* CarouselModel
*
* @author <NAME>
* @version 1.00, March 2019.
*/
public class TutorialModeModel {
TutorialModeView view;
public TutorialModeModel (TutorialModeView view) {
this.view = view;
}
/**
* Calls the rightMovement method in the tutorialView file causing icons to shift right
*/
public void right() {
view.rightMovement();
}
/**
* Calls the leftMovement method in the tutorialView file causing icons to shift left
*/
public void left() {
view.leftMovement();
}
}
<file_sep>/src/NoPictureException.java
/**
* NoPictureException.
* Can be thrown when no pictures are found in the local store directory.
*
* @author <NAME>
* @version 1.0, March 2019
*/
public class NoPictureException extends Exception {
public NoPictureException(String message){
super(message);
}
}<file_sep>/src/ModeChanger.java
/**
* Mode Changer.
*
* @author <NAME>
* @version 1.0, March 2019
*/
public class ModeChanger implements Runnable{
private Mode mode;
public ModeChanger(Mode mode){
this.mode = mode;
}
public void run() {
Run.changeMode(mode);
}
}
<file_sep>/server/MockClient.java
import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* MockClient.
*
* @author <NAME>
* @version 2.09, February 2019.
*/
public class MockClient {
private String host;
private int port;
private final static int BUFFER_SIZE = 4092;
MockClient(String host, int port){
this.host = host;
this.port = port;
}
/**
* Uploads the given bundle to the server.
*
* @param fileName: The filepath of the file to upload.
* @param method: Upload method (UPLOAD_BUNDLE or UPLOAD_PREVIEW).
*/
public void uploadFile(String fileName, String method){
try {
Socket sck = new Socket(this.host, this.port);
// Instantiating byte array of correct size to store file
File file = new File(fileName);
byte[] bytes = new byte[(int) file.length()];
// Streams for reading/writing the file
DataInputStream dataIn = new DataInputStream(new FileInputStream(file));
DataOutputStream dataOut = new DataOutputStream(sck.getOutputStream());
// Reading the file into the byte array
dataIn.readFully(bytes, 0, bytes.length);
// Writing the file to the socket output stream (from the byte array)
dataOut.writeUTF(method + "/" + fileName);
dataOut.writeLong(file.length());
dataOut.write(bytes, 0, bytes.length);
dataOut.flush();
// Cleaning up
sck.close();
} catch ( Exception exn ) {
System.out.println( exn ); System.exit( 1 );
}
}
/**
* Downloads the given file from the server, and unzips it in the corresponding directory.
*
* @param fileName: The filepath of the file to download.
* @param method: Download method (DOWNLOAD_BUNDLE or DOWNLOAD_PREVIEW).
*/
public void downloadFile(String fileName, String method){
try {
// Checking if local_store directory exists, and creates it if it doesn't yet
String bundleDir = "../local_store/bundle_files/";
String previewDir = "../local_store/preview_files/";
if (Files.notExists(Paths.get(bundleDir))) {
Files.createDirectories(Paths.get(bundleDir));
}
if (Files.notExists(Paths.get(previewDir))) {
Files.createDirectories(Paths.get(previewDir));
}
// Requesting to download the file
Socket sck = new Socket(this.host, this.port);
DataOutputStream dataOut = new DataOutputStream(sck.getOutputStream());
dataOut.writeUTF(method + "/" + fileName);
dataOut.flush();
// Attempting to receive the file
DataInputStream dataIn = new DataInputStream(sck.getInputStream());
BufferedOutputStream fileOut;
String zipPath;
if (method.equals("DOWNLOAD_BUNDLE")) {
zipPath = bundleDir + fileName;
}
else if (method.equals("DOWNLOAD_PREVIEW")) {
zipPath = previewDir + fileName;
}
else {
sck.close();
return;
}
File file = new File(zipPath);
fileOut = new BufferedOutputStream(new FileOutputStream(file));
int fileSize = (int)dataIn.readLong();
int n;
byte[] buf = new byte[BUFFER_SIZE];
while (fileSize > 0
&& (n = dataIn.read(buf, 0, (int) Math.min(buf.length, fileSize))) != -1) {
fileOut.write(buf, 0, n);
fileSize -= 1;
}
// Cleaning up
fileOut.close();
sck.close();
unzip(zipPath, "../local_store/bundle_files/");
} catch ( Exception exn ) {
System.out.println( exn ); System.exit( 1 );
}
}
/**
* Deletes specified file.
*
* @param filePath: File path of file to delete.
*/
public static void deleteFile(String filePath){
try {
Path path = Paths.get(filePath);
Files.delete(path);
} catch (IOException e){
e.printStackTrace();
}
}
/**
* Removes the parentheses and file extension from a bundle file name.
* e.g. "Song(bundle).zip" to "Song".
*
* @param bundle: Bundle file name.
* @return: Song name.
*/
public static String getSongBundle(String bundle){
return bundle.substring(0, bundle.length() - 12);
}
/**
* Removes the parentheses and file extension from a preview file name.
* e.g. "Song(preview).zip" to "Song".
*
* @param preview: Preview file name.
* @return: Song name.
*/
public static String getSongPreview(String preview){
return preview.substring(0, preview.length() - 13);
}
/**
* Unzips the contents of a specified .zip file to a specified destination directory, and
* deletes the original .zip file afterwards.
*
* @param zipFilePath: File path to zip file.
* @param destDir: Destination directory.
*/
public static void unzip(String zipFilePath, String destDir) {
// Create output directory if it doesn't exist
File dir = new File(destDir);
if(!dir.exists()) {
dir.mkdirs();
}
try {
// Unzipping and writing each entry to disk
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destDir + "/" + entry.getName();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] buf = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(buf)) != -1) {
bos.write(buf, 0, read);
}
bos.close();
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.closeEntry();
zipIn.close();
// Deleting the remaining zip file
deleteFile(zipFilePath);
}
catch (EOFException e){
// JVM bug (JVM-6519463) - So catch every time and do nothing with it (extraction still works)
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Requests a directory listing of the previews directory on the server.
*
* @return ArrayList: ArrayList of filenames in previews directory (songs available to buy).
*/
public ArrayList<String> listDirectory(){
try{
// Requesting the directory listing
Socket sck = new Socket(this.host, this.port);
DataOutputStream out = new DataOutputStream(sck.getOutputStream());
out.writeUTF("LIST_DIRECTORY");
out.flush();
// Attempting to receive the filenames and build arraylist
DataInputStream dataIn = new DataInputStream(sck.getInputStream());
ArrayList<String> songNames = new ArrayList<>();
String songName;
while (!(songName = dataIn.readUTF()).equals("END")){
songNames.add(songName);
}
// Cleaning up and returning arraylist of filenames
sck.close();
return songNames;
} catch ( Exception exn ) {
System.out.println(exn); return null;
}
}
}<file_sep>/src/StoreMode.java
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* StoreMode.
* @author <NAME>
* @author <NAME> (exception handling)
* @version 2.13, March 2019
*/
public class StoreMode extends JPanel {
// Server settings
private static final String HOST = "localhost";
private static final int PORT = 8888;
private final static int MODE_DELAY = 150;
private static final int POINT_0_0 = 0;
// Store settings
private static final String PREVIEWS = "../local_store/preview_files/";
public StoreMode() {
String songName = null;
String previewDir = null;
MockClient client = null;
try {
client = new MockClient(HOST, PORT);
}
catch(Exception e){
System.out.println("Enable to create MockClient. /STOREMODE");
GameUtils.changeModeOnNewThread(Mode.SLASH);
}
// Getting preview filenames of all available songs on the server
ArrayList<String> fileNames = client.listDirectory();
// Downloading and unzipping all previews, and giving each title/cover a JLabel
ArrayList<JLabel> menuOptions = new ArrayList<>();
for (String fileName : fileNames){
try {
// Downloading and unzipping preview (and deleting zip after)
client.downloadFile(fileName, "DOWNLOAD_PREVIEW");
songName = MockClient.getSongPreview(fileName);
previewDir = PREVIEWS + songName + "/";
MockClient.unzip(PREVIEWS + fileName, previewDir);
}
catch(Exception e){
System.out.println("Couldn't download files. /STOREMODE");
GameUtils.changeModeOnNewThread(Mode.SLASH);
}
// Reading in the cover image and song name, assigning to a JLabel and adding to ArrayList
File[] previewContents = new File(previewDir).listFiles();
try {
for (File cover : previewContents) {
JLabel label = new JLabel(new ImageIcon(previewDir + cover.getName()));
label.setText(songName);
menuOptions.add(label);
}
}
catch(Exception e){
System.out.println("Can't create JLabels in Carousel. /STOREMODE");
GameUtils.changeModeOnNewThread(Mode.SLASH);
}
}
CarouselController controller = null;
CarouselView view = null;
try {
// Initialise the model, controller, view GUI classes
view = new CarouselView(menuOptions);
view.displayCurrency();
CarouselModel model = new CarouselModel(view);
controller = new CarouselController(model, Mode.STORE);
}
catch(Exception e){
System.out.println("Unable to start MVC. /STOREMODE");
GameUtils.changeModeOnNewThread(Mode.SLASH);
}
try {
Thread controllerThread = new Thread(controller);
controllerThread.start();
}
catch(Exception e){
System.out.println("Enable to start Thread for controller. /STOREMODE");
GameUtils.changeModeOnNewThread(Mode.SLASH);
}
this.add(view);
//view.setVisible(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // paint the background image and scale it to fill the entire space
Image highway = null;
try {
highway = ImageIO.read(new File("../assets/Done/Highway.bmp"));
} catch (IOException e) {
System.out.println("Unable to load highway");
GameUtils.changeModeOnNewThread(Mode.SLASH);
}
g.drawImage(highway, -7, 5, this);
}
public void sleep(int millis){
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
System.out.println("Woken from sleep");
GameUtils.changeModeOnNewThread(Mode.SLASH);
}
}
}<file_sep>/src/NoSongsException.java
/**
* NoSongsException.
* Can be thrown when no songs are found in the local store directory.
*
* @author <NAME>
* @version 1.0, March 2019
*/
public class NoSongsException extends Exception {
public NoSongsException(String message){
super(message);
}
}<file_sep>/src/StoreManagerButton.java
public enum StoreManagerButton {
TITLE, COVER, SONG, SAVE;
}
<file_sep>/src/CarouselModel.java
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.swing.*;
/**
* CarouselModel
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @version 2.00, March 2019.
*/
public class CarouselModel {
CarouselView view;
File currencyFile;
private static int totalCurrency;
final static String BUNDLES = "../local_store/bundle_files/";
final static String HOST = "localhost";
final static int PORT = 8888;
final static int POP_UP_TIME = 3000;
final static int POP_UP_WIDTH = 260;
final static int POP_UP_HEIGHT = 160;
final static int POP_UP_Y = 50;
final static int POP_UP_X = 275;
JLabel popUp;
/**
* Skeleton constructor for later use
*/
public CarouselModel(CarouselView view) {
this.view = view;
// If the currency file can't be loaded, do not start the game
try {
this.currencyFile = Currency.findCurrencyFile();
} catch (Exception e) {
e.printStackTrace();
}
// If currency file cannot be read properly, do not start the game
try {
this.totalCurrency = Currency.loadCurrencyFile(this.currencyFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Calls the rightMovement method in the carouselView file causing icons to shift right
*/
public void right() {
view.rightMovement();
}
/**
* Calls the leftMovement method in the carouselView file causing icons to shift left
*/
public void left() {
view.leftMovement();
}
/**
* Returns a string from the chosenOption method in the carouselView file allowing a user to
* choose a menu option
*/
public String select() {
//System.out.println(view.chosenOption());
return view.chosenOption();
}
/**
* Downloads a song to local directory.
*/
public void buySong(String songName) {
String bundleName = songName + "(bundle).zip";
if (totalCurrency > 0 && !isInLocalDir(songName)) {
try {
updateCurrencyAndLocalStore(bundleName, songName);
} catch (Exception e) {
e.printStackTrace();
}
} else if (totalCurrency < 1 && isInLocalDir(songName)){
popUp("../assets/NoMoneyAndSongOwnedPopUp.jpg", POP_UP_TIME);
} else if (totalCurrency > 0 && isInLocalDir(songName)){
popUp("../assets/SongOwnedPopUp.jpg", POP_UP_TIME);
} else {
popUp("../assets/NoMoneyPopUp.jpg", POP_UP_TIME);
}
}
/**
* Updates currency and local store.
*/
public void updateCurrencyAndLocalStore(String bundleName, String songName) throws Exception {
totalCurrency --;
Currency.saveCurrencyFile(totalCurrency);
MockClient client = new MockClient(HOST, PORT);
client.downloadFile(bundleName, "DOWNLOAD_BUNDLE");
String bundlesDir = BUNDLES + songName + "/";
MockClient.unzip(BUNDLES + bundleName, bundlesDir);
}
/**
* Displays pop up messages.
*/
public void popUp(String pngPath, int time) {
popUp = new JLabel(new ImageIcon(pngPath));
popUp.setSize(POP_UP_WIDTH, POP_UP_HEIGHT);
popUp.setBounds(POP_UP_X, POP_UP_Y, POP_UP_WIDTH, POP_UP_HEIGHT);
this.view.add(popUp, 0);
this.view.repaint();
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.view.remove(popUp);
}
/**
* Checks if the song is already in the local directory.
*/
public static boolean isInLocalDir(String song) {
// checking if local_store directory exists
String bundleDir = "../local_store/bundle_files/";
if (Files.notExists(Paths.get(bundleDir))) {
return false;
} else {
File tmpDir = new File("../local_store/bundle_files/" + song);
if (tmpDir.exists())
return true;
else
return false;
}
}
}
<file_sep>/README.md
# GuitarZero
Instructions:
Server:
Put Server.java, Handler.java and InvalidSongException.java in one directory.
cd to this directory and enter the following commands -
javac Server.java
java Server
Store Manager Mode:
Put StoreManagerMain.java, StoreManagerController.java, StoreManagerModel.java, StoreManagerView.java, StoreManagerButton.java
cd to this directory and enter the following commands -
javac StoreManagerMain.java
java StoreManagerMain
GuitarZero:
Have ALL source files in one directory. Ensure the local_store directory is set up properly if intend on using Select mode, and ensure the
server is running if you intend on buying songs in Store mode. local_store/bundle_files/ is where bundles are stored, and
local_store/preview_files is where the store mode caching is stored.
cd to this directory and enter the following commands -
(Windows)
set CLASSPATH=jinput-2.0.9.jar;.
javac *.java
java Run
(Linux)
$ CLASSPATH=jinput-2.0.9.jar:.
$ export CLASSPATH
$ javac *.java
$ java Run
<file_sep>/src/Mode.java
public enum Mode {
SLASH, SELECT, STORE, PLAY, TUTORIAL, EXIT;
}
<file_sep>/src/PlayModeView.java
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.io.IOException;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.util.ArrayList;
/**
* PlayModeView
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @version 5.1, March 2019.
*/
public class PlayModeView extends JPanel{
ArrayList<Note> notes = new ArrayList<Note>();
private static int frame;
// Setup background animation values
private static int backgroundFrameCount = 1;
private static int backgroundFrameDelay = 100;
// Create BufferedImage array to store the background frames
static BufferedImage[] bg = new BufferedImage[backgroundFrameCount];
// Initialise JLabels to display notes and game values
private JLabel coverArtLabel;
private JLabel multiplierLabel;
private JLabel currencyLabel;
private JLabel scoreLabel;
private JLabel streakLabel;
private JLabel zeroPowerLabel;
private JLabel noteLabel;
private JLabel noteCollected;
private JLabel endStatisticsBackground;
private JLabel endStatisticsImg;
private JLabel endStatisticsTitle;
private JLabel endStatisticsScore;
private JLabel endStatisticsCurrency;
private JLabel endStatisticsNote;
private JLabel[] activeNotes = new JLabel[6];
private JLabel[] collectedNotes = new JLabel[6];
// Path to the background of the game
private static final String HIGHWAY_PATH = "../assets/Done/Highway.bmp";
// Dimensions for displaying the end statistics
private static final int END_STATISTICS_WIDTH = 400;
private static final int END_STATISTICS_HEIGHT = 400;
private static final int END_STATISTICS_X = 300;
private static final int END_STATISTICS_Y = 100;
private static final int END_STATISTIC_MARGIN = 20;
private static final int END_STATISTIC_TEXT_HEIGHT = 40;
// Dimensions for displaying the cover art
private static final int COVER_ART_WIDTH = 200;
private static final int COVER_ART_HEIGHT = 200;
private static final int COVER_ART_X = 50;
private static final int COVER_ART_Y = 28;
// Dimensions for displaying the score multiplier
private static final int MULTIPLIER_WIDTH = 100;
private static final int MULTIPLIER_HEIGHT = 100;
private static final int MULTIPLIER_X = 50;
private static final int MULTIPLIER_Y = 250;
// Dimensions for displaying the currency earned during the game
private static final int CURRENCY_WIDTH = 140;
private static final int CURRENCY_HEIGHT = 30;
private static final int CURRENCY_X = 200;
private static final int CURRENCY_Y = 437;
// Dimensions for displaying the zero power icon during zero power mode
private static final int ZERO_POWER_WIDTH = 174;
private static final int ZERO_POWER_HEIGHT = 192;
private static final int ZERO_POWER_X = 726;
private static final int ZERO_POWER_Y = 140;
// Dimensions for displaying the current score during the game
private static final int SCORE_X = 50;
private static final int SCORE_Y = 400;
private static final int SCORE_WIDTH = 200;
private static final int SCORE_HEIGHT = 100;
// Size of the text for the score label and the streak label
private static final int TEXT_SIZE = 32;
// Dimensions for displaying the current note streak
private static final int STREAK_WIDTH = 200;
private static final int STREAK_HEIGHT = 200;
private static final int STREAK_X = 440;
private static final int STREAK_Y = 28;
// Dimensions and asset paths for displaying the notes on the fretboard at the bottom of the highway
private static final int FRETBOARD_Y = 395;
private static final String FRETBOARD_WHITE = "../assets/Done/WhiteNoteToPlay.png";
private static final String FRETBOARD_BLACK = "../assets/Done/BlackNoteToPlay.png";
private static final String FRETBOARD_WHITE_COLLECTED = "../assets/Done/WhiteNoteCollected.png";
private static final String FRETBOARD_BLACK_COLLECTED = "../assets/Done/BlackNoteCollected.png";
private static final int FRETBOARD_NOTE_WIDTH = 100;
private static final int FRETBOARD_NOTE_HEIGHT = 100;
private static final int FRETBOARD_LEFT_X = 350;
private static final int FRETBOARD_MIDDLE_X = 450;
private static final int FRETBOARD_RIGHT_X = 550;
// Amount of note buttons on the guitar
private static final int TOTAL_NOTE_BUTTONS = 6;
// The y coordinate that causes a note to be removed from the screen if it falls past this point
private static final int DROP_NOTE_BOUND = 463;
public PlayModeView(){
frame = 0;
try{
for(int i = 0; i<backgroundFrameCount; i++){
bg[i] = ImageIO.read(new File(HIGHWAY_PATH));
}
}
catch(Exception e){
e.printStackTrace();
}
this.setLayout(null);
}
/**
* displayEndValues
* @param img The cover art of the current song
* @param songTitle The current songs name
* @param score The final score of the game
* @param currency The users currency total
*/
public void displayEndValues(File img, String songTitle, String score, String currency){
String[] segments = songTitle.split("/");
String idStr = segments[segments.length-1];
songTitle = idStr;
endStatisticsBackground = new JLabel(new ImageIcon("../assets/emptyBox.jpeg"));
endStatisticsBackground.setBounds(END_STATISTICS_X,END_STATISTICS_Y,END_STATISTICS_WIDTH,END_STATISTICS_HEIGHT);
//SONG NAME
endStatisticsTitle = new JLabel("Song: "+songTitle);
endStatisticsTitle.setBounds(END_STATISTICS_X + (END_STATISTICS_WIDTH/2) - (COVER_ART_WIDTH/2), END_STATISTICS_Y+COVER_ART_HEIGHT+(2*END_STATISTIC_MARGIN), COVER_ART_WIDTH, END_STATISTIC_TEXT_HEIGHT);
endStatisticsTitle.setForeground(Color.BLACK);
scoreLabel.setFont(new Font("Serif", Font.BOLD, TEXT_SIZE));
endStatisticsTitle.setVisible(true);
add(endStatisticsTitle);
//GAME SCORE
endStatisticsScore = new JLabel("Score: "+score);
endStatisticsScore.setBounds(END_STATISTICS_X + (END_STATISTICS_WIDTH/2) - (COVER_ART_WIDTH/2), END_STATISTICS_Y+COVER_ART_HEIGHT+(3*END_STATISTIC_MARGIN), COVER_ART_WIDTH, END_STATISTIC_TEXT_HEIGHT);
endStatisticsScore.setForeground(Color.BLACK);
scoreLabel.setFont(new Font("Serif", Font.BOLD, TEXT_SIZE));
endStatisticsScore.setVisible(true);
add(endStatisticsScore);
//TOTAL CURRENCY
endStatisticsCurrency = new JLabel("Currency: "+currency);
endStatisticsCurrency.setBounds(END_STATISTICS_X + (END_STATISTICS_WIDTH/2) - (COVER_ART_WIDTH/2), END_STATISTICS_Y+COVER_ART_HEIGHT+(4*END_STATISTIC_MARGIN), COVER_ART_WIDTH, END_STATISTIC_TEXT_HEIGHT);
endStatisticsCurrency.setForeground(Color.BLACK);
scoreLabel.setFont(new Font("Serif", Font.BOLD, TEXT_SIZE));
endStatisticsCurrency.setVisible(true);
add(endStatisticsCurrency);
//FOOT NOTE
endStatisticsNote = new JLabel("Exit Button (O) - Main Menu");
endStatisticsNote.setBounds(END_STATISTICS_X + (END_STATISTICS_WIDTH/2) - (COVER_ART_WIDTH/2), END_STATISTICS_Y+END_STATISTICS_HEIGHT-40, COVER_ART_WIDTH,40);
endStatisticsNote.setForeground(Color.BLACK);
scoreLabel.setFont(new Font("Serif", Font.BOLD, TEXT_SIZE));
endStatisticsNote.setVisible(true);
add(endStatisticsNote);
//COVER ART
endStatisticsImg = new JLabel(new ImageIcon(resizeImage(img, COVER_ART_WIDTH, COVER_ART_HEIGHT)));
endStatisticsImg.setBounds((int) (END_STATISTICS_X + (END_STATISTICS_WIDTH/2) - (COVER_ART_WIDTH/2)), END_STATISTICS_Y+50,COVER_ART_WIDTH,COVER_ART_HEIGHT);
add(endStatisticsImg);
add(endStatisticsBackground);
}
/**
* setCoverArtLabel
* Sets the cover art to be displayed on the screen during the game
* Resizes the image file to fit the size of the JLabel
* @param coverFile
*/
public void setCoverArtLabel(File coverFile) {
Image resizedImage = resizeImage(coverFile,COVER_ART_WIDTH,COVER_ART_HEIGHT);
coverArtLabel = new JLabel(new ImageIcon(resizedImage));
coverArtLabel.setBounds(COVER_ART_X, COVER_ART_Y, COVER_ART_WIDTH, COVER_ART_HEIGHT);
add(coverArtLabel);
}
/**
* Reads an image file and resizes it to desired dimensions
* @param file
* @param width
* @param height
* @return Resized Image as Image
*/
public Image resizeImage(File file, int width, int height){
Image image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_DEFAULT);
return resizedImage;
}
/**
* setMultiplierLabel
* Initialises the multiplier label to display the user's score multiplier
* Also used to set a blank multiplier label when the user loses their score multiplier
*/
public void setMultiplierLabel() {
multiplierLabel = new JLabel();
multiplierLabel.setBounds(MULTIPLIER_X, MULTIPLIER_Y, MULTIPLIER_WIDTH, MULTIPLIER_HEIGHT);
multiplierLabel.setVisible(false);
add(multiplierLabel);
}
/**
* changeMultiplier
* Called when the user gains a new score multiplier or loses their multiplier
* Changes the multiplier label displayed on the screen
* @param path the path of the multiplier asset to display
*/
public void changeMultiplierLabel(String path) {
multiplierLabel.setIcon(new ImageIcon(path));
multiplierLabel.setVisible(true);
}
/**
* setCurrencyLabel
* Initialises tbe JLabel to display the currency stars
*/
public void setCurrencyLabel() {
currencyLabel = new JLabel();
currencyLabel.setBounds(CURRENCY_X, CURRENCY_Y, CURRENCY_WIDTH, CURRENCY_HEIGHT);
currencyLabel.setVisible(false);
add(currencyLabel);
}
/**
* Change currency label
* Called when the user earns currency
* Updates the amount of stars displayed on the screen
* @param path the path to the asset corresponding to the amount of stars to be displayed
*/
public void changeCurrencyLabel(String path) {
currencyLabel.setIcon(new ImageIcon(path));
currencyLabel.setVisible(true);
}
/**
* setZeroPowerLabelInit
* Initialises the zero power JLabel
* @param path the path of the zero power image
*/
public void setZeroPowerLabelInit(String path) {
zeroPowerLabel = new JLabel(new ImageIcon(path));
zeroPowerLabel.setBounds(ZERO_POWER_X, ZERO_POWER_Y, ZERO_POWER_WIDTH, ZERO_POWER_HEIGHT);
}
/**
* setZeroPowerLabelVisible
* Shows the zero power icon on the screen when zero power mode is active
*/
public void setZeroPowerLabelVisible() {
zeroPowerLabel.setVisible(true);
add(zeroPowerLabel);
}
public void setZeroPowerLabelFalse() {
zeroPowerLabel.setVisible(false);
}
/**
* setScoreLabel
* Initialises the Jlabel to display the user's current score
* @param score
*/
public void setScoreLabel(Integer score) {
scoreLabel = new JLabel("Score: " + Integer.toString(score));
scoreLabel.setFont(new Font("Serif", Font.BOLD, TEXT_SIZE));
scoreLabel.setBounds(SCORE_X, SCORE_Y, SCORE_WIDTH, SCORE_HEIGHT);
scoreLabel.setForeground(Color.white);
scoreLabel.setVisible(true);
add(scoreLabel);
}
/**
* resetScoreLabel
* Sets the value of the score being displayed
* @param score the new score to be displayed
*/
public void resetScoreLabel(Integer score) {
scoreLabel.setText("Score: " + Integer.toString(score));
}
/**
* setStreakLabel
* Initialises the JLabel to display the user's note streak
*/
public void setStreakLabel() {
streakLabel = new JLabel("Streak: " + Integer.toString(0));
streakLabel.setFont(new Font("Serif", Font.BOLD, TEXT_SIZE));
streakLabel.setBounds(STREAK_X,STREAK_Y, STREAK_WIDTH, STREAK_HEIGHT);
streakLabel.setForeground(Color.white);
add(streakLabel);
}
/**
* resetStreakLabel
* Sets the value of the streak being displayed
* @param streak the new streak to display
*/
public void resetStreakLabel(Integer streak) {
streakLabel.setText("Streak: " + streak);
}
/**
* noteInit
* Initialises the notes to be shown on the fretboard when the user presses a note button
* Initialises the coloured note image for when the user collects a note
*/
public void noteInit() {
// WHITE1 - 0 in controller
noteLabel = new JLabel(new ImageIcon(FRETBOARD_WHITE));
noteLabel.setBounds(FRETBOARD_LEFT_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteLabel.setVisible(false);
activeNotes[0] = noteLabel;
noteCollected = new JLabel(new ImageIcon(FRETBOARD_WHITE_COLLECTED));
noteCollected.setBounds(FRETBOARD_LEFT_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteCollected.setVisible(false);
collectedNotes[0] = noteCollected;
//BLACK1 - 1 in controller
noteLabel = new JLabel(new ImageIcon(FRETBOARD_BLACK));
noteLabel.setBounds(FRETBOARD_LEFT_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteLabel.setVisible(false);
activeNotes[1] = noteLabel;
noteCollected = new JLabel(new ImageIcon(FRETBOARD_BLACK_COLLECTED));
noteCollected.setBounds(FRETBOARD_LEFT_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteCollected.setVisible(false);
collectedNotes[1] = noteCollected;
//BLACK2 - 2 in controller
noteLabel = new JLabel(new ImageIcon(FRETBOARD_BLACK));
noteLabel.setBounds(FRETBOARD_MIDDLE_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteLabel.setVisible(false);
activeNotes[2] = noteLabel;
noteCollected = new JLabel(new ImageIcon(FRETBOARD_BLACK_COLLECTED));
noteCollected.setBounds(FRETBOARD_MIDDLE_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteCollected.setVisible(false);
collectedNotes[2] = noteCollected;
//BLACK3 - 3 in controller
noteLabel = new JLabel(new ImageIcon(FRETBOARD_BLACK));
noteLabel.setBounds(FRETBOARD_RIGHT_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteLabel.setVisible(false);
activeNotes[3] = noteLabel;
noteCollected = new JLabel(new ImageIcon(FRETBOARD_BLACK_COLLECTED));
noteCollected.setBounds(FRETBOARD_RIGHT_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteCollected.setVisible(false);
collectedNotes[3] = noteCollected;
//WHITE2 - 4 in controller
noteLabel = new JLabel(new ImageIcon(FRETBOARD_WHITE));
noteLabel.setBounds(FRETBOARD_MIDDLE_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteLabel.setVisible(false);
activeNotes[4] = noteLabel;
noteCollected = new JLabel(new ImageIcon(FRETBOARD_WHITE_COLLECTED));
noteCollected.setBounds(FRETBOARD_MIDDLE_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteCollected.setVisible(false);
collectedNotes[4] = noteCollected;
//WHITE3 - 5 in controller
noteLabel = new JLabel(new ImageIcon(FRETBOARD_WHITE));
noteLabel.setBounds(FRETBOARD_RIGHT_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteLabel.setVisible(false);
activeNotes[5] = noteLabel;
noteCollected = new JLabel(new ImageIcon(FRETBOARD_WHITE_COLLECTED));
noteCollected.setBounds(FRETBOARD_RIGHT_X, FRETBOARD_Y, FRETBOARD_NOTE_WIDTH, FRETBOARD_NOTE_HEIGHT);
noteCollected.setVisible(false);
collectedNotes[5] = noteCollected;
for (int i = 0; i < TOTAL_NOTE_BUTTONS; i ++) {
add(activeNotes[i]);
add(collectedNotes[i]);
}
}
/**
* noteDisplay
* Displays a note on the fretboard when the user presses the button
* Note corresponds with the button pressed on the guitar
* @param display true if note should be displayed, false otherwise
* @param pressedButton the button pressed by the user
*/
public void noteDisplay(boolean display, int pressedButton) {
if (display) {
activeNotes[pressedButton].setVisible(true);
} else {
if(noteLabel != null) {
for (int i = 0; i < pressedButton; i++)
activeNotes[i].setVisible(false);
}
}
}
/**
* noteCollected
* Displays a coloured version of a note on the fretboard if a note has been collected
* Note displayed on the fretboard corresponds to the note collected
* @param display true if the collected note should be displayed, false otherwise
* @param pressedButton the button pressed by the user when collecting the note
*/
public void noteCollected(boolean display, int pressedButton) {
if (display) {
collectedNotes[pressedButton].setVisible(true);
} else {
if(noteCollected != null) {
for (int i = 0; i < pressedButton; i++)
collectedNotes[i].setVisible(false);
}
}
}
/**
* addNote
* @param note the note to be added to the highway, passed from the model
*/
public void addNote(Note note){
notes.add(note);
}
/**
* paintComponent
* Draws all necessary GUI elements on the JPanel
* Removes a note if it has passed a certain boundary
* @param g: The the graphics object associated with the JPanel
*/
@Override
public synchronized void paintComponent(Graphics g) {
super.paintComponent(g);
//Draw the background animation frame depending on the current frame/10%(number of frames in the animation)
g.drawImage(this.bg[((frame/this.backgroundFrameDelay)%this.backgroundFrameCount)], 0, 0, null);
int len = notes.size();
for(int i=len-1; i>-1; i--){
// Draw the note
notes.get(i).paintComponent(g);
// Remove from the notes ArrayList as no longer needed
if(notes.get(i).getY() > DROP_NOTE_BOUND || notes.get(i).collected)
notes.remove(i);
}
frame++;
}
}
<file_sep>/src/TutorialModeView.java
import javax.swing.*;
import java.util.ArrayList;
import javax.swing.JLabel;
/**
* TutorialModeView.
*
* @author <NAME>
* @version 1.01, March 2019.
*/
public class TutorialModeView extends JPanel {
private ArrayList<ImageIcon> pictureIcons;
JLabel currentPicture = null;
ArrayList<JLabel> pictureLabels = new ArrayList<JLabel>();
/**
* Alters the GUI by taking commands from a model class
*
* @param pictureIcons: A list of pictures to display graphically
*/
public TutorialModeView (ArrayList<ImageIcon> pictureIcons) {
this.pictureIcons = pictureIcons;
setBounds(0, 0, 1000, 500);
for (ImageIcon pictureIcon : pictureIcons) {
JLabel label = new JLabel(pictureIcon);
label.setBounds(50, 50, 400, 400);
add(label);
label.setVisible(false);
pictureLabels.add(label);
}
pictureLabels.get(0).setVisible(true);
currentPicture = pictureLabels.get(0);
setVisible(true);
}
/**
* Switches images to the left, replacing with next picture
*/
public void leftMovement() {
for (int i = 0; i < pictureLabels.size(); i++) {
if (pictureLabels.get(i) == currentPicture && i != 0) {
pictureLabels.get(i).setVisible(false);
pictureLabels.get(i-1).setVisible(true);
currentPicture = pictureLabels.get(i-1);
setVisible(true);
break;
} else if (pictureLabels.get(i) == currentPicture && i == 0){
break;
}
}
}
/**
* Switches images to the right, replacing with next picture
*/
public void rightMovement() {
for (int i = 0; i < pictureLabels.size(); i++) {
if (pictureLabels.get(i) == currentPicture && i != pictureLabels.size()-1) {
pictureLabels.get(i).setVisible(false);
pictureLabels.get(i + 1).setVisible(true);
currentPicture = pictureLabels.get(i + 1);
setVisible(true);
break;
} else if (pictureLabels.get(i) == currentPicture && i == pictureLabels.size()-1) {
break;
}
}
}
}
<file_sep>/src/StoreManagerView.java
import java.awt.*;
import javax.swing.*;
import java.io.*;
/**
* StoreManagerView.
*
* @author <NAME>
* @version 2.3, March 2019
*
*/
public class StoreManagerView extends JFrame {
static File titleFile = null;
static File coverArtFile = null;
static File musicFile = null;
static JTextField titleField = new JTextField(10);
static JTextField coverArtField = new JTextField(10);
static JTextField musicField = new JTextField(10);
private static final int STORE_WIDTH = 300;
private static final int STORE_HEIGHT = 200;
/**
* Sets up the JFrame.
* @param titleButton: Title browse controller
* @param coverArtButton: Cover browse controller
* @param songButton: Midi browse controller
* @param saveButton: Save button controller
*/
public StoreManagerView ( StoreManagerController titleButton,
StoreManagerController coverArtButton,
StoreManagerController songButton,
StoreManagerController saveButton) {
setTitle("Store Manager");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(STORE_WIDTH, STORE_HEIGHT);
// Creating components to populate the frame
JLabel titleLabel = new JLabel("Title: ");
JLabel coverArtLabel = new JLabel("Cover art:");
JLabel musicLabel = new JLabel("Music: ");
JButton titleBrowse = new JButton("Browse");
JButton coverArtBrowse = new JButton("Browse");
JButton musicBrowse = new JButton("Browse");
// Creating the three sub-top panels to the top panel
JPanel topPanel = new JPanel(new BorderLayout());
JPanel topFirstPanel = panelCreator(titleLabel, titleField, titleBrowse);
JPanel topSecondPanel = panelCreator(coverArtLabel, coverArtField, coverArtBrowse);
JPanel topThirdPanel = panelCreator(musicLabel, musicField, musicBrowse);
topPanel.add(BorderLayout.NORTH, topFirstPanel);
topPanel.add(BorderLayout.CENTER, topSecondPanel);
topPanel.add(BorderLayout.SOUTH, topThirdPanel);
// Creating the bottom panel and adding the 'save' button
JPanel bottomPanel = new JPanel();
JButton save = new JButton("Save");
bottomPanel.add(save);
// Adding the main top and bottom panels to the frame
getContentPane().add(BorderLayout.NORTH, topPanel);
getContentPane().add(BorderLayout.SOUTH, bottomPanel);
titleBrowse.addActionListener(titleButton);
coverArtBrowse.addActionListener(coverArtButton);
musicBrowse.addActionListener(songButton);
save.addActionListener(saveButton);
}
/**
* Creates a JPanel
* @param label: A JLabel to add to the JPanel
* @param textField: A JTextField to add to the JPanel
* @param button: A JButton to add to the JPanel
* @return The JPanel containing all the passed parameters
*/
public static JPanel panelCreator (JLabel label, JTextField textField, JButton button) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.LINE_START, label);
panel.add(BorderLayout.CENTER, textField);
panel.add(BorderLayout.LINE_END, button);
return panel;
}
public static void setTitleTitle (String filePath) { titleField.setText(filePath); }
public static void setCoverArtTitle (String filePath) { coverArtField.setText(filePath); }
public static void setMusicTitle (String filePath) { musicField.setText(filePath); }
}<file_sep>/src/Handler.java
import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Handler.
*
* @author <NAME>
* @version 1.17, March 2019.
*/
public class Handler implements Runnable {
private Socket sck;
final int BUFFER_SIZE = 4092;
Handler(Socket sck) {
this.sck = sck;
}
/**
* Downloads/uploads files to/from clients.
*/
public void run() {
try {
// Client socket streams
final DataInputStream dataIn = new DataInputStream(sck.getInputStream());
final DataOutputStream dataOut = new DataOutputStream(sck.getOutputStream());
// Parsing UTF - getting method
String header = dataIn.readUTF();
String[] headers = header.split("/");
String method = headers[0].toUpperCase();
char methodType = method.charAt(0);
// Getting file name (if uploading or downloading)
String fileName = "";
if (methodType == 'U' || methodType == 'D') {
fileName = headers[1];
}
// Processing request
if (methodType == 'U') {
long fileSize = dataIn.readLong();
processUpload(method, dataIn, fileName, fileSize);
} else if (methodType == 'D') {
processDownload(method, dataOut, fileName);
dataIn.close();
} else if (method.equals("LIST_DIRECTORY")) {
processListing(dataOut);
}
sck.close();
} catch (Exception exn) {
System.out.println(exn);
System.exit(1);
}
}
/**
* Processes an upload request (sending files from client to server).
*
* @param method: Method type. Either 'UPLOAD_BUNDLE' or 'UPLOAD_PREVIEW'.
* @param dataIn: DataInputStream to read from.
* @param fileName: Name of the file to upload.
* @param fileSize: Size of file to upload (bytes).
*/
public void processUpload(String method, DataInputStream dataIn, String fileName, long fileSize) {
// Building file path string
String filePath = "";
try {
filePath = getFilePath(method, fileName);
} catch (InvalidMethodException exn) {
System.out.println(exn);
System.exit(1);
}
// Processing the upload - synchronized to prevent 'connection abort: recv failed'
synchronized (this) {
try {
// Stream for file to be written to (local directory on server)
BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(filePath));
// Reading file in from dataIn and writing it to fileOut stream
int n;
byte[] buf = new byte[BUFFER_SIZE];
while (fileSize > 0
&& (n = dataIn.read(buf, 0, (int) Math.min(buf.length, fileSize))) != -1) {
fileOut.write(buf, 0, n);
fileSize -= 1;
}
// Cleaning up
fileOut.close();
} catch (Exception exn) {
System.out.println(exn);
System.exit(1);
}
}
}
/**
* Processes a download request (retrieving files from server to client).
*
* @param method: Download method. Either 'DOWNLOAD_BUNDLE' or 'DOWNLOAD_PREVIEW'.
* @param fileName: Name of file to download.
*/
public void processDownload(String method, DataOutputStream dataOut, String fileName) {
// Building file path string
String filePath = "";
try {
filePath = getFilePath(method, fileName);
} catch (InvalidMethodException exn) {
System.out.println(exn);
System.exit(1);
}
// Processing the download - synchronized to prevent 'connection abort: recv failed'
synchronized (this) {
try {
// Reading file into byte array
Path fileLocation = Paths.get(filePath);
byte[] data = Files.readAllBytes(fileLocation);
// Writing file from byte array to dataOut stream
dataOut.writeLong(data.length);
dataOut.write(data, 0, data.length);
dataOut.flush();
} catch (Exception exn) {
System.out.println(exn);
System.exit(1);
}
}
}
/**
* Builds (local) file path string from request method and file name.
*
* @param method: Request method (UPLOAD/DOWNLOAD + _BUNDLE/_PREVIEW)
* @param fileName: File name for request (name of file to be uploaded/downloaded to/from
* server).
* @throws InvalidMethodException: Thrown when provided method is invalid.
* @return: File path to requested file.
*/
public static String getFilePath(String method, String fileName) throws InvalidMethodException {
// Building file path string
String cd = System.getProperty("user.dir");
if (method.equals("DOWNLOAD_BUNDLE") || method.equals("UPLOAD_BUNDLE")) {
return cd + "/bundle_files/" + fileName;
} else if (method.equals("DOWNLOAD_PREVIEW") || method.equals("UPLOAD_PREVIEW")) {
return cd + "/preview_files/" + fileName;
} else {
throw new InvalidMethodException("Invalid method provided.");
}
}
/**
* Processes a listing request to the server.
*
* @param dataOut: DataOutputStream to write directory listings to.
*/
public void processListing(DataOutputStream dataOut) {
File previewDir = new File(System.getProperty("user.dir") + "/preview_files/");
String[] previews = previewDir.list();
synchronized (this) {
try {
// Writing song names to textOut
for (String preview : previews) {
dataOut.writeUTF(preview);
}
dataOut.writeUTF("END");
dataOut.flush();
// Cleaning up
sck.close();
} catch (Exception exn) {
System.out.println(exn);
System.exit(1);
}
}
}
} | 9775736ca333fb1aaf6d9d5fa81613810bee1b69 | [
"Markdown",
"Java"
] | 15 | Java | Pierrik/GuitarZero | 482d8302288200f65a70d7db0248dc1de3b314ea | 05c1f312e78732046d1084e09748782b7e3ec6e9 | |
refs/heads/gh-pages | <repo_name>Awaken3d/Connect4Updated<file_sep>/src/gameLogic.ts
//var h=6;//Rows
//var w=7;//Columns
//'use strict';
//angular.module('myApp',['ngTouch', 'ui.bootstrap', 'gameServices']).factory('gameLogic', function() {
module gameLogic {
var h=6;//Rows
var w=7;//Columns
export function isEqual(object1:any, object2:any) {
//console.log(JSON.stringify(object1));
//console.log(JSON.stringify(object2));
return angular.equals(object1, object2);
}
export function copyObject(object:any) {
return angular.copy(object);
}
/** Return the winner (either 'R' or 'B') or '' if there is no winner. */
export function getWinner(board:any) {
var count=0;
function p(y:any, x:any) {
return (y < 0 || x < 0 || y >= h || x >= w) ? 0 : board[y][x];
}
//loops through rows, columns, diagonals, etc
for (var y=0;y<h;y++){
for(var x=0;x<w;x++){
if(p(y,x)!==0 && p(y,x)!==''&& p(y,x)===p(y,x+1) && p(y,x)===p(y,x+2) && p(y,x)===p(y,x+3)){
return p(y,x);
}
}
}
for (var y=0;y<h;y++){
for(var x=0;x<w;x++){
if(p(y,x)!==0 &&p(y,x)!==''&& p(y,x)===p(y+1,x) && p(y,x)===p(y+2,x) && p(y,x)===p(y+3,x)){
return p(y,x);
}
}
}
for (var y=0;y<h;y++){
for(var x=0;x<w;x++){
for(var d=-1;d<=1;d+=2){
if(p(y,x)!==0&&p(y,x)!==''&& p(y,x)===p(y+1*d,x+1) && p(y,x)===p(y+2*d,x+2) && p(y,x)===p(y+3*d,x+3)) {
return p(y,x);
}
}
}
}
for (var y=0;y<h;y++){
for(var x=0;x<w;x++){
if(p(y,x)==='') {
return '';
}
}
}
}
export function isTie(board:any) {
var i:any, j:any;
for (i = 0; i < 5; i++) {
for (j = 0; j < 6; j++) {
if (board[i][j] === '') {
// If there is an empty cell then we do not have a tie.
return false;
}
}
}
// No empty cells --> tie!
return true;
}
export function getInitialBoard(){
return [['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','','']];
}
export function createComputerMove(board:any, turnIndexBeforeMove:any) {
var possibleMoves:any = [];
var i:any, j:any;
for (i = 0; i < 6; i++) {
for (j = 0; j <7 ; j++) {
try {
possibleMoves.push(createMove(board, i, j, turnIndexBeforeMove));
} catch (e) {
// The cell in that position was full.
}
}
}
var randomMove = possibleMoves[Math.floor(Math.random() * possibleMoves.length)];
return randomMove;
}
export function createMove(board:any, row:any, col:any, turnIndexBeforeMove:any) {
if (board === undefined) {
// Initially (at the beginning of the match), the board in state is undefined.
board = [['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','','']];
}
if (board[row][col] !== '') {
throw new Error("One can only make a move in an empty position!");
}
var count1=0;
for(var i=5;i>=0;i--){
if(board[i][col]===''){
count1++;
}
}
if(row!==count1-1){
throw new Error("One can only make a move in an correct position!");;
}
var boardAfterMove = copyObject(board);
boardAfterMove[row][col] = turnIndexBeforeMove === 0 ? 'R' : 'B';
var winner = getWinner(boardAfterMove);
var firstOperation:any;
if (winner !== '' || isTie(board)) {
// Game over.
firstOperation = {endMatch: {endMatchScores:
(winner === 'R' ? [1, 0] : (winner === 'B' ? [0, 1] : [0, 0]))}};
} else {
// Game continues. Now it's the opponent's turn (the turn switches from 0 to 1 and 1 to 0).
firstOperation = {setTurn: {turnIndex: 1 - turnIndexBeforeMove}};
}
return [firstOperation,
{set: {key: 'board', value: boardAfterMove}},
{set: {key: 'delta', value: {row: row, col: col}}}];
}
/** Returns an array of {stateBeforeMove, move, comment}. */
export function getExampleMoves(initialTurnIndex:any, initialState:any, arrayOfRowColComment:any) {
var exampleMoves:any = [];
var state = initialState;
var turnIndex = initialTurnIndex;
for (var i = 0; i < arrayOfRowColComment.length; i++) {
var rowColComment = arrayOfRowColComment[i];
var move = createMove(state.board, rowColComment.row, rowColComment.col, turnIndex);
exampleMoves.push({
stateBeforeMove: state,
turnIndexBeforeMove: turnIndex,
move: move,
comment: {en: rowColComment.comment}});
state = {board : move[1].set.value, delta: move[2].set.value};
turnIndex = 1 - turnIndex;
}
return exampleMoves;
}
export function getRiddles() {
return [
getExampleMoves(0,
{
board:
[['', '', '','','','',''],
['', '', '','','','',''],
['', '', 'B','','','',''],
['B', 'R', 'B','','','',''],
['B', 'B', 'R','','','',''],
['R', 'B', 'R','R','','','']],
delta: {row: 3, col: 0}
},
[
{row: 5, col: 3, comment: "Find the position for R where he could win in his next turn by having a diagonal "},
{row: 2, col: 2, comment: "B played here"},
{row: 2, col: 0, comment: "R wins by placing here having 4 diagonal elements ."}
]),
getExampleMoves(1,
{
board:
[['', '', '','','','',''],
['', '', '','','','',''],
['', '', 'B','','','',''],
['', 'R', 'B','','','',''],
['', 'R', 'B','','','',''],
['R', 'B', 'R','','','','']],
delta: {row: 4, col: 1}
},
[
{row: 2, col: 2, comment: "B places here to make a vertical 4"},
{row: 3, col: 1, comment: "R places to have 4 in a row in subsequent moves"},
{row: 1, col: 2, comment: "B wins by having 4 in a row!"}
])
];
}
export function getExampleGame() {
return getExampleMoves(0, {}, [
{row: 5, col: 4 , comment: "The classic opening is to put R in the middle"},
{row: 5, col: 3, comment: "Place B adjacent to R"},
{row: 5, col: 5, comment: "Place R next to original R"},
{row: 5, col: 2, comment: "Place B to adjacent to the first one"},
{row: 4, col: 5, comment: "Place R on top of 1 R"},
{row: 3, col: 3, comment: "Place R on top of yellow to prevent from reaching 4"},
{row: 4, col: 2, comment: "Place B on top of another B."},
{row: 3, col: 2, comment:"place R on top of that as well"},
{row: 5, col: 1,comment:"Place B here to create a 4 next time"},
{row: 5, col: 0,comment:"R blocks from B to create a 4"},
{row: 4, col: 1,comment:"Place B here to create a 4 next time "},
{row: 4, col: 0,comment:"R blocks this as well to prevent B to create a 4"},
{row: 3, col: 1,comment:"Place B here to create a vertical 4 next time"},
{row: 2, col: 1,comment:"R prevents it by placing R on top of B"},
{row: 3, col: 5,comment:"Place B on top of R here"},
{row: 4, col: 4,comment:"R places here"},
{row: 5, col: 6,comment:"Place B here"},
{row: 2, col: 1,comment:"R wins by creating a diagonal "},
]);
}
export function isMoveOk(params:any) {
var move = params.move;
var turnIndexBeforeMove = params.turnIndexBeforeMove;
var stateBeforeMove = params.stateBeforeMove;
try {
// Example move:
// [{setTurn: {turnIndex : 1},
// {set: {key: 'board', value: [['X', '', ''], ['', '', ''], ['', '', '']]}},
// {set: {key: 'delta', value: {row: 0, col: 0}}}]
var deltaValue = move[2].set.value;
var row = deltaValue.row;
var col = deltaValue.col;
var board = stateBeforeMove.board;
if (board === undefined) {
// Initially (at the beginning of the match), stateBeforeMove is {}.
board = [['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','',''],
['', '', '','','','','']];
}
// One can only make a move in an empty position
if (board[row][col] !== '') {
return false;
}
var count1=0;
for(var i=5;i>=0;i--){
if(board[i][col]===''){
count1++;
}
}
if(row!==count1-1){
return false;
}
var expectedMove = createMove(board, row, col, turnIndexBeforeMove);
if (!isEqual(move, expectedMove)) {
return false;
}
} catch (e) {
// if there are any exceptions then the move is illegal
return false;
}
return true;
}
}
angular.module('myApp',['ngTouch', 'ui.bootstrap', 'gameServices']).factory('gameLogic', function() {
return {
isMoveOk : gameLogic.isMoveOk,
getExampleGame : gameLogic.getExampleGame,
getRiddles : gameLogic.getRiddles,
getInitialBoard:gameLogic.getInitialBoard,
createMove :gameLogic.createMove,
createComputerMove :gameLogic.createComputerMove
};
});
<file_sep>/src/game.ts
/*angular.module('myApp')
.controller('Ctrl', ['$scope','$rootScope', '$log', '$timeout',
'gameLogic', function (
$scope:any, $rootScope:any, $log:any, $timeout:any,
gameLogic:any) {*/
module game{
//'use strict';
//resizeGameAreaService.setWidthToHeight(1.16667);
let gameArea: HTMLElement;
var rowsNum = 6;
var colsNum = 7;
//dragAndDropService.addDragListener("gameArea", handleDragEvent);
var draggingLines:any;
var horizontalDraggingLine:any;
var verticalDraggingLine:any;
//export var clickToDragPiece:HTMLElement = (<HTMLInputElement>document.getElementById("clickToDragPiece"));
export var clickToDragPiece:HTMLElement;
export function test(){
console.log("clicktodrag" + clickToDragPiece);
return "clicktodrag" + clickToDragPiece;
}
var canMakeMove = false;
//added new variables
var board:any = undefined;
var isYourTurn:any;
var turnIndex:number;
var delta:any;
export function init() {
resizeGameAreaService.setWidthToHeight(1.16667);
gameService.setGame({
gameDeveloperEmail: "<EMAIL>",
minNumberOfPlayers: 2,
maxNumberOfPlayers: 2,
// exampleGame: gameLogic.exampleGame(),
//riddles: gameLogic.riddles(),
isMoveOk: gameLogic.isMoveOk,
updateUI: updateUI
});
dragAndDropService.addDragListener("gameArea", handleDragEvent);
}
export function sendComputerMove(){
gameService.makeMove(
gameLogic.createComputerMove(board, turnIndex));
}
export function getIntegersTill(number:any) {
var res:any = [];
for (var i = 0; i < number; i++) {
res.push(i);
}
return res;
}
export function updateUI(params:any) {
// check if commented: $scope.jsonState = angular.toJson(params.stateAfterMove, true);
board = params.stateAfterMove.board;
delta = params.stateAfterMove.delta;
if (board === undefined) {
board = [
['', '', '', '', '', '', ''],
['', '', '', '', '', '', ''],
['', '', '', '', '', '', ''],
['', '', '', '', '', '', ''],
['', '', '', '', '', '', ''],
['', '', '', '', '', '', ''],
];
}
canMakeMove = params.turnIndexAfterMove >= 0 && // game is ongoing
params.yourPlayerIndex === params.turnIndexAfterMove; // it's my turn
isYourTurn = params.turnIndexAfterMove >= 0 && // game is ongoing
params.yourPlayerIndex === params.turnIndexAfterMove; //it's my turn
turnIndex = params.turnIndexAfterMove;
// Is it the computer's turn?
if (isYourTurn
&& params.playersInfo[params.yourPlayerIndex].playerId === '') {
isYourTurn = false;
$timeout(sendComputerMove, 1100);
}
}
updateUI({stateAfterMove: {}, turnIndexAfterMove: 0, yourPlayerIndex: -2});
export let cellClicked = function (row:any, col:any) {
//$log.info(["Clicked on cell:", row, col]);
if (!isYourTurn) {
return;
}
try {
var move = gameLogic.createMove(board, row, col, turnIndex);
isYourTurn = false; // to prevent making another move
gameService.makeMove(move);
} catch (e) {
//$log.info(["wrong move", row, col]);
return;
}
};
export let shouldSlowlyAppear = function (row:any, col:any) {
return delta !== undefined
&& delta.row === row && delta.col === col;
}
export let shouldShowImage = function (row:any, col:any) {
var cell = board[row][col];
return cell !== "";
};
export let rows = getIntegersTill(rowsNum);
export let cols = getIntegersTill(colsNum);
export let isWhite = function (row:any, col:any) {
if (board[row][col] === 'B')
{
return true;
}
else
{
return false;
}
}
export let isBlack = function (row:any, col:any) {
if (board[row][col] === 'R')
{
return true;
}
else
{
return false;
}
}
export let oddSum = function (row:any, col:any){
if ((row + col) % 2 !== 0)
{
return true;
}
else
{
return false;
}
}
export let evenSum = function (row:any, col:any){
if ((row + col) % 2 === 0)
{
return true;
}
else
{
return false;
}
}
export let getImageSrc = function (row:any, col:any) {
var cell = board[row][col];
return cell === "R" ? "img/red.png"
: cell === "B" ? "img/blue.png" : "";
};
export function handleDragEvent(type:any, clientX:any, clientY:any) {
//if not your turn, dont handle event
// if (!canMakeMove) {
// return;
// }
clickToDragPiece = document.getElementById("clickToDragPiece");
gameArea = document.getElementById("gameArea");
draggingLines = document.getElementById("draggingLines");
horizontalDraggingLine = document.getElementById("horizontalDraggingLine");
verticalDraggingLine = document.getElementById("verticalDraggingLine");
// Center point in gameArea
var x = clientX - gameArea.offsetLeft;
var y = clientY - gameArea.offsetTop;
// Is outside gameArea?
if (x < 0 || y < 0 || x >= gameArea.clientWidth || y >= gameArea.clientHeight) {
clickToDragPiece.style.display = "none";
draggingLines.style.display = "none";
return;
}
clickToDragPiece.style.display = "inline";
draggingLines.style.display = "inline";
// Inside gameArea. Let's find the containing square's row and col
var col = Math.floor(colsNum * x / gameArea.clientWidth);
var row = Math.floor(rowsNum * y / gameArea.clientHeight);
var centerXY = getSquareCenterXY(row, col);
verticalDraggingLine.setAttribute("x1", ""+centerXY.x);
verticalDraggingLine.setAttribute("x2", ""+centerXY.x);
horizontalDraggingLine.setAttribute("y1", ""+centerXY.y);
horizontalDraggingLine.setAttribute("y2", ""+centerXY.y);
var topLeft = getSquareTopLeft(row, col);
clickToDragPiece.style.left = topLeft.left + "px";
clickToDragPiece.style.top = topLeft.top + "px";
if (type === "touchend" || type === "touchcancel" || type === "touchleave" || type === "mouseup") {
// drag ended
clickToDragPiece.style.display = "none";
draggingLines.style.display = "none";
dragDone(row, col);
}
}
export function getSquareWidthHeight() {
return {
width: gameArea.clientWidth / colsNum,
height: gameArea.clientHeight / rowsNum
};
}
export function getSquareTopLeft(row:any, col:any) {
var size = getSquareWidthHeight();
return {top: row * size.height, left: col * size.width};
}
export function getSquareCenterXY(row:any, col:any) {
var size = getSquareWidthHeight();
return {
x: col * size.width + size.width / 2,
y: row * size.height + size.height / 2
};
}
export function dragDone(row:any, col:any) {
cellClicked(row, col);
$rootScope.$apply(function () {
//$log.info("Dragged to " + row + "x" + col);
});
}
export let getPreviewSrc = function () {
return turnIndex === 1 ? "img/blue.png" : "img/red.png";
};
}
//window.handleDragEvent = handleDragEvent;
angular.module('myApp')
.run(function() {
$rootScope['game'] = game;
/*gameService.setGame({
gameDeveloperEmail: "<EMAIL>",
minNumberOfPlayers: 2,
maxNumberOfPlayers: 2,
// exampleGame: gameLogic.exampleGame(),
//riddles: gameLogic.riddles(),
isMoveOk: gameLogic.isMoveOk,
updateUI: updateUI
});*/
translate.setLanguage('en',{
"RULES_OF_CONNECT4":"Rules of Connect4",
"RULES_SLIDE1":"Each player drops a disc of their color down a column. The disc can fall only on the lowest available spot in the column",
"RULES_SLIDE2":"The objective of the game is to connect four of one's own discs of the same color next to each other vertically, horizontally, or diagonally before your opponent",
"CLOSE":"Close"
});
game.init();
});
<file_sep>/coverage/Chrome 46.0.2490 (Mac OS X 10.10.5)/src/aiService.js.html
<!doctype html>
<html lang="en">
<head>
<title>Code coverage report for src/aiService.js</title>
<meta charset="utf-8">
<link rel="stylesheet" href="../prettify.css">
<link rel="stylesheet" href="../base.css">
<style type='text/css'>
div.coverage-summary .sorter {
background-image: url(../sort-arrow-sprite.png);
}
</style>
</head>
<body>
<div class="header high">
<h1>Code coverage report for <span class="entity">src/aiService.js</span></h1>
<h2>
Statements: <span class="metric">89.36% <small>(42 / 47)</small></span>
Branches: <span class="metric">80% <small>(8 / 10)</small></span>
Functions: <span class="metric">66.67% <small>(2 / 3)</small></span>
Lines: <span class="metric">89.36% <small>(42 / 47)</small></span>
Ignored: <span class="metric"><span class="ignore-none">none</span></span>
</h2>
<div class="path"><a href="../index.html">All files</a> » <a href="index.html">src/</a> » aiService.js</div>
</div>
<div class="body">
<pre><table class="coverage">
<tr><td class="line-count">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73</td><td class="line-coverage"><span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-no"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-no"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-no"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">2</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-no"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-no"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span></td><td class="text"><pre class="prettyprint lang-js">var aiService;
(function (aiService) {
function createComputerMove(board, playerIndex) {
console.log("ai has been summoned");
<span class="missing-if-branch" title="if path not taken" >I</span>if (board === undefined) {
<span class="cstat-no" title="statement not covered" > board = gameLogic.getInitialBoard();</span>
}
var pawn = 3;
var positions;
var result;
if (playerIndex === 0) {
var dogLocations = gameLogic.getDogPositions(board);
pawn = Math.floor(Math.random() * 3);
console.log(" dog selected to be moved " + (pawn));
while (dogLocations[pawn].row === 1 && dogLocations[pawn].col === 4) {
<span class="cstat-no" title="statement not covered" > pawn = Math.floor(Math.random() * 3);</span>
}
console.log(" dog selected to be move after check " + (pawn));
var dogRow = dogLocations[pawn].row;
var dogCol = dogLocations[pawn].col;
//setDogId(pawn+1);
positions = gameLogic.legalMovesDog[dogRow][dogCol];
//let m = positions[Math.floor(Math.random() * positions.length )];
var m;
while (result === undefined) {
console.log("mpika");
//while(m === undefined){
m = positions[Math.floor(Math.random() * positions.length)];
console.log(" move created by random " + m[0] + " " + m[1]);
//}
try {
result = gameLogic.createMove(board, { row: dogRow, col: dogCol }, { row: m[0], col: m[1] }, playerIndex);
}
catch (e) {
}
;
pawn = Math.floor(Math.random() * 3);
//console.log(" dog selected to be moved "+ (pawn));
while (dogLocations[pawn].row === 1 && <span class="branch-1 cbranch-no" title="branch not covered" >dogLocations[pawn].col === 4)</span> {
<span class="cstat-no" title="statement not covered" > pawn = Math.floor(Math.random() * 3);</span>
}
dogRow = dogLocations[pawn].row;
dogCol = dogLocations[pawn].col;
//setDogId(pawn+1);
positions = gameLogic.legalMovesDog[dogRow][dogCol];
}
return result;
}
else {
var bunnyPosition = gameLogic.getBunnyPosition(board);
positions = gameLogic.legalMovesBunny[bunnyPosition.row][bunnyPosition.col];
var y;
while (result === undefined) {
y = positions[Math.floor(Math.random() * positions.length)];
console.log(" move created by random " + y[0] + " " + y[1]);
try {
result = gameLogic.createMove(board, { row: bunnyPosition.row, col: bunnyPosition.col }, { row: y[0], col: y[1] }, playerIndex);
}
catch (e) {
<span class="cstat-no" title="statement not covered" > console.log(e);</span>
}
;
}
return result;
}
}
aiService.createComputerMove = createComputerMove;
<span class="fstat-no" title="function not covered" > function setDogId(id) {</span>
<span class="cstat-no" title="statement not covered" > aiService.dogId = id;</span>
}
aiService.setDogId = setDogId;
})(aiService || (aiService = {}));
</pre></td></tr>
</table></pre>
</div>
<div class="footer">
<div class="meta">Generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Tue Nov 24 2015 11:25:14 GMT-0500 (EST)</div>
</div>
<script src="../prettify.js"></script>
<script>
window.onload = function () {
if (typeof prettyPrint === 'function') {
prettyPrint();
}
};
</script>
<script src="../sorter.js"></script>
</body>
</html>
| 2e1f56efe1cddefd5b55ac57c9ed218bcc7cb734 | [
"TypeScript",
"HTML"
] | 3 | TypeScript | Awaken3d/Connect4Updated | 8f864760f7bf24461b376b0c02fc98f852567470 | 537ec7996a69b63799469fef6b5fff1ed74307d1 | |
refs/heads/main | <repo_name>Shriya1607/Netflix-Clone<file_sep>/src/Header.js
import React, { useEffect, useState } from "react";
import axios from "./axios";
import requests from "./requests";
import "./header.css";
function Header() {
const [Movie, setMovie] = useState([]);
useEffect(() => {
async function fetchData() {
const req = await axios.get(requests.fetchTrending);
setMovie(
req.data.results[
Math.floor(Math.random() * (req.data.results.length - 1))
]
);
return req;
}
fetchData();
}, []);
function truncateText(str, n) {
//truncate the text
return str?.length > n ? str.substr(0, n - 1) + "..." : str;
}
return (
<div
className="header"
style={{
backgroundImage: `url("https://image.tmdb.org/t/p/original/${Movie.backdrop_path}")`,
backgroundSize: "cover",
backgroundPosition: "center center",
}}
>
<div>
<h1 className="header_moviename">
{Movie.name || Movie.title || Movie.original_name}
</h1>
<h4 className="header_movieoverview">
{truncateText(Movie.overview, 150)}
</h4>
</div>
</div>
);
}
export default Header;
<file_sep>/src/App.js
import React from "react";
import "./App.css";
import Header from "./Header";
import MovieRow from "./MovieRow";
import Navbar from "./Navbar";
import requests from "./requests";
function App() {
return (
<div className="App">
<Navbar />
<Header/>
<MovieRow
title="NETFLIX ORIGINALS"
fetch_URL={requests.fetchNetflixOriginals}
/>
<MovieRow title="TRENDING" fetch_URL={requests.fetchTrending} />
<MovieRow title="TOP RATED" fetch_URL={requests.fetchTopRated} />
<MovieRow title="ACTION MOVIES" fetch_URL={requests.fetchActionMovies} />
<MovieRow title="COMEDY MOVIES" fetch_URL={requests.fetchComedyMovies} />
<MovieRow title="HORROR MOVIES" fetch_URL={requests.fetchHorrorMovies} />
<MovieRow
title="ROMANCE MOVIES"
fetch_URL={requests.fetchRomanceMovies}
/>
<MovieRow title="DOCUMENTARIES" fetch_URL={requests.fetchDocumentaries} />
</div>
);
}
export default App;
<file_sep>/src/MovieRow.js
import axios from "./axios";
import React, { useEffect, useState } from "react";
import "./movierow.css";
function MovieRow({ title, fetch_URL }) {
const url = "https://image.tmdb.org/t/p/original/";
const [Movies, setMovies] = useState([]);
useEffect(() => {
async function fetchData() {
const req = await axios.get(
fetch_URL
); /*fetching data from the url which is passed as a prop */
setMovies(req.data.results); /* assigning value to the movie array*/
return req;
}
fetchData();
}, [
fetch_URL /* whenever url changes the useEffect will run*/,
]); /* useEffect is a react hook, it is used to do something after every render(display)
[]-> if this is empty then use effect is called only once but if we write any variable then when the value of that variable changes then useState is called
asynch/await means the function will take its own time to run */
console.log(Movies);
return (
<div className="movierow">
<h2>{title}</h2>
<div className="movierow_thumbnail">
{Movies.map((mov) => {
return (
<img
key={mov.id}
src={`${url}${mov.poster_path}`}
alt={mov.name}
className="movierow_image"
/>
);
})}
</div>
</div>
);
}
export default MovieRow;
<file_sep>/src/Navbar.js
import React, { useEffect, useState } from "react";
import SearchIcon from "@material-ui/icons/Search";
import NotificationsActiveIcon from "@material-ui/icons/NotificationsActive";
import "./navbar.css";
import AccountBoxIcon from "@material-ui/icons/AccountBox";
import NotificationsIcon from "@material-ui/icons/Notifications";
function Navbar() {
const [show, handleShow] = useState(false);
useEffect(() => {
window.addEventListener("scroll", () => {
if (window.scrollY > 100) {
handleShow(true);
} else handleShow(false);
});
return () => {
window.removeEventListener("scroll");
};
}, []);
return (
// <div className={`navbar ${show && "nav_black"}`}>
// <div className="navbar_img">
// <img
// src={process.env.PUBLIC_URL + "/netflix-logo.png"}
// alt=""
// className="logo"
// />
// </div>
// <div className="navbar_middle">
// <p>Home</p>
// <p>TV shows</p>
// <p>Movies</p>
// <p>New & Popular</p>
// <p>My List</p>
// </div>
// <div className="navbar_right">
// <SearchIcon className="navbar_search" />
// <p>Kids</p>
// <NotificationsActiveIcon className="navbar_notification" />
// <AccountBoxIcon className="navbar_account" />
// </div>
// </div>
<div className={`nav ${show && "nav_black"}`}>
<div>
<img
src={process.env.PUBLIC_URL + "/netflix-logo.png"}
alt="Netflix Logo"
className="nav_logo"
/>
<div className="nav_links">
<p>Home</p>
<p>TV Shows</p>
<p>Movies</p>
<p>New & Popular</p>
<p>My List</p>
</div>
</div>
<div className="nav_links profile">
<SearchIcon style={{ marginRight: "1.25rem" }} />
<p>KIDS</p>
<NotificationsIcon className="navbar_notification" />
<img
className="nav_avatar"
src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRHg_t3WBJBy4SEC_9uU-gi71PNXXdInw5uRQ&usqp=CAU"
alt=""
/>
</div>
</div>
);
}
export default Navbar;
| 1c33d5ccdfcb4068a4b922bacadaf15b1eec8547 | [
"JavaScript"
] | 4 | JavaScript | Shriya1607/Netflix-Clone | e7815d67a00ab0d5702973cf3798274fcd7b7186 | e38ec33f50e35a0791ee88f3e7113a6a37cff25d | |
refs/heads/master | <repo_name>Nirlan-MTG/Curso-C-<file_sep>/Primeiro/Primeiro/Program.cs
using System;
using System.Globalization;
namespace Primeiro
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Entre com os dados do produto: ");
Console.Write("Nome: ");
string vNome = Console.ReadLine();
Console.Write("Preço: ");
double vPreco = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Produto p = new Produto(vNome, vPreco);
Console.WriteLine("Dados do produto: " + p);
Console.WriteLine();
Console.WriteLine("Digite a quantidade a ser adcionada ao estoque: ");
int qtd = int.Parse(Console.ReadLine());
p.AdicionarEstoque(qtd);
Console.WriteLine("Dados Atualizados: " + p);
Console.WriteLine();
Console.WriteLine("Digite a quantidade a ser removida do estoque: ");
qtd = int.Parse(Console.ReadLine());
p.RemoverEstoque(qtd);
Console.WriteLine("Dados Atualizados: " + p);
}
}
}
<file_sep>/ExemplosVetores/ExemplosVetores/Program.cs
using System;
using System.Globalization;
namespace ExemplosVetores
{
class Program
{
static void Main(string[] args)
{
Console.Write("Informe a quantidade: ");
int vQtd = int.Parse(Console.ReadLine());
Produto[] vVetor = new Produto[vQtd];
double vSoma = 0;
for (int i = 0; i < vQtd; i++)
{
string vNome = Console.ReadLine();
double vPreco = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
vVetor[i] = new Produto { Nome = vNome, Preco = vPreco };
vSoma += vVetor[i].Preco;
}
double vMedia = vSoma / vQtd;
Console.WriteLine("A media é: " + vMedia.ToString("F2", CultureInfo.InvariantCulture));
// exemplo do uso do foreach
string[] vVet = new string[] { "Maria", "Bob", "Alex" };
foreach(string obj in vVet)
{
Console.WriteLine(obj);
}
/* double[] vVetor = new double[vQtd];
double vSoma = 0;
for (int i = 0; i < vQtd; i++)
{
vVetor[i] = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
vSoma += vVetor[i];
}
double vMedia = vSoma / vQtd;
Console.Write("A media é: " + vMedia.ToString("F2", CultureInfo.InvariantCulture));
*/
}
}
}
<file_sep>/Listas/Listas/Program.cs
using System;
using System.Collections.Generic;
namespace Listas
{
class Program
{
static void Main(string[] args)
{
List<string> vLista = new List<string>();
vLista.Add("Maria");
vLista.Add("Alex");
vLista.Add("Bob");
vLista.Add("Ana");
vLista.Add("Gizelda");
vLista.Add("Poliana");
vLista.Add("Adriane");
vLista.Insert(2, "Marco");
foreach (string vObj in vLista)
{
Console.WriteLine(vObj);
}
Console.WriteLine("Qtd: " + vLista.Count);
string s1 = vLista.Find(x => x[0] == 'A');
Console.WriteLine("Primeiro que começa com letra A: " + s1);
s1 = vLista.FindLast(x => x[0] == 'M');
Console.WriteLine("Último que termina com a letra M: " + s1);
// Matriz
double[,] vMatriz = new double[2, 3]; // 2 linhas e 3 colunas
// teste github
Console.WriteLine("alteração para o github");
}
}
}
<file_sep>/Primeiro/Primeiro/Produto.cs
using System.Globalization;
namespace Primeiro
{
class Produto
{
private string vNome;
public double Preco { get; private set; }
public int Quantidade { get; private set; }
public Produto(string pNome, double pPreco, int pQuantidade)
{ // Construtor da classe
this.vNome = pNome;
this.Preco = pPreco;
this.Quantidade = pQuantidade;
}
public Produto(string pNome, double pPreco)
{ // Construtor da classe - sobrecarga
this.vNome = pNome;
this.Preco = pPreco;
this.Quantidade = 0;
}
// ------------------------------------------------------
public string Nome
{ // propertie
get { return this.vNome; }
set
{
if (value != null && value.Length > 2)
this.vNome = value;
}
}
// ------------------------------------------------------
public double ValorTotalEstoque()
{
return this.Preco * this.Quantidade;
}
public void AdicionarEstoque(int pQuantidade)
{
this.Quantidade = this.Quantidade + pQuantidade;
}
public void RemoverEstoque(int pQuantidade)
{
this.Quantidade = this.Quantidade - pQuantidade;
}
public override string ToString()
{
return vNome
+ ", $ "
+ this.Preco.ToString("F2", CultureInfo.InvariantCulture)
+ ", "
+ this.Quantidade
+ " unidades, Total: $ "
+ ValorTotalEstoque().ToString("F2", CultureInfo.InvariantCulture);
}
}
}
| 61cf5bd69c8aa82834085571b2a38af882e514e8 | [
"C#"
] | 4 | C# | Nirlan-MTG/Curso-C- | 431cb384c559254034036a280895c3a5b2a1e8f6 | 466089798b4255af34f577f3dbaa9f6a9985199b | |
refs/heads/master | <file_sep>using System;
using System.Diagnostics;
using Windows.Storage;
namespace workout7RT.Helpers
{
/// <summary>
/// Class responsible for managing application settings.
/// Cannot be static, because static classes couldn't possess constructors
/// </summary>
class SettingsManager
{
ApplicationDataContainer settingsManager;
// key names
const string currentStreakKeyName = "currentStreak";
const string recentDayOfWorkoutKeyName = "recentDayOfWorkout";
// default values
const int currentStreakDefaultValue = 0;
DateTimeOffset recentDayOfWorkoutDefaultValue = DateTime.Parse("2008-05-01T07:34:42-5:00"); // for sure?
/// <summary>
/// In the constructor class tries to fetch settings from application storage.
/// </summary>
public SettingsManager()
{
try
{
// get current settings of the application
settingsManager = ApplicationData.Current.LocalSettings;
}
catch (Exception e)
{
// if you can get current settings show toast
#if DEBUG
Debug.WriteLine("Exception while loading settings: " + e.ToString());
#endif
}
}
/// <summary>
/// Update application setting of given key. If setting does not exist - create one
/// </summary>
/// <param name="keyName">setting name (key)</param>
/// <param name="value">setting (value) of facultative type to save</param>
/// <returns>originally it shourd return true if the operation succeeds</returns>
private void AddOrUpdateValue(string keyName, Object value)
{
// bool valueChanged = false;
if (settingsManager != null)
{
if (settingsManager.Values.ContainsKey(keyName))
{
if (settingsManager.Values[keyName] != value)
{
settingsManager.Values[keyName] = value;
// valueChanged = true;
}
}
else
{
settingsManager.Values.Add(keyName, value);
// valueChanged = true;
}
}
// return valueChanged;
}
/// <summary>
/// Get the setting value from app settings. If the value does not exist - get default one
/// </summary>
/// <param name="keyName">setting name (key) to get</param>
/// <param name="defaultValue">default value of the setting</param>
private ValueType GetValueOrDefault<ValueType>(string keyName, ValueType defaultValue)
{
ValueType value;
// If key exists - retrieve the value
if (settingsManager.Values.ContainsKey(keyName))
{
value = (ValueType)settingsManager.Values[keyName];
}
else
{
value = defaultValue;
}
return value;
}
/// <summary>
/// Save the settings (obsolete in Windows Store app; in WP 7/8 - arbitrary)
/// </summary>
private void SaveSettings() {}
/// <summary>
/// Gets or sets current streak count
/// </summary>
public int CurrentStreakSetting
{
get
{
return GetValueOrDefault<int>(currentStreakKeyName, currentStreakDefaultValue);
}
set
{
AddOrUpdateValue(currentStreakKeyName, value);
// SaveSettings();
}
}
public DateTimeOffset RecentDayOfWorkout
{
get
{
return GetValueOrDefault<DateTimeOffset>(recentDayOfWorkoutKeyName, recentDayOfWorkoutDefaultValue);
}
set
{
AddOrUpdateValue(recentDayOfWorkoutKeyName, value);
// SaveSettings();
}
}
public bool FirstRun
{
get
{
return GetValueOrDefault<bool>("firstRun", true);
}
set
{
AddOrUpdateValue("firstRun", value);
}
}
}
}
<file_sep>using System;
using System.Diagnostics;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using workout7RT.Helpers;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace workout7RT
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
SettingsManager settings;
private const int TOTAL_EXERCISES = 12;
private TimeSpan timeSpan;
private DispatcherTimer dispatcherTimer;
private DateTime endTime;
private bool timerLocked; // simple method, but still does the job ;-)
private int exerciseIndex;
private readonly string[] exerciseNames;
private readonly string[] imageNames;
private readonly bool[] switchSides;
enum Activity
{
GettingReady,
Exercise,
Rest
};
private Activity currentActivity;
public MainPage()
{
this.InitializeComponent();
settings = new SettingsManager();
if (settings.FirstRun)
{
TileHelper.ShowToastNotification("The live tile will update once you finish your first workout.");
settings.FirstRun = false;
}
this.exerciseNames = new string[]{
"jumping jacks",
"wall-sit",
"push up",
"abdominal crunch",
"step up on chair",
"squat",
"triceps dip",
"plank",
"high knees running",
"lunge",
"push up and rotation",
"side plank",
""
};
this.switchSides = new bool[]
{
false,
false,
false,
false,
false,
false,
false,
false,
false,
true,
true,
true
};
this.imageNames = new string[] {
"exercise.jacks.png",
"exercise.wall-sit.png",
"exercise.push-up.png",
"exercise.crunch.png",
"exercise.step-up.png",
"exercise.squat.png",
"exercise.triceps-dip.png",
"exercise.plank.png",
"exercise.running.png",
"exercise.lunge.png",
"exercise.push-up-rotate.png",
"exercise.side-plank.png",
""
};
currentActivity = Activity.GettingReady;
// prepare dispatcher timer
if (this.dispatcherTimer == null)
{
this.dispatcherTimer = new DispatcherTimer();
this.dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
this.dispatcherTimer.Tick += new EventHandler<object>(dispatcherTimer_Tick);
}
nextExerciseLabel.Text = "\u2192 jumping jacks";
}
~MainPage()
{
this.dispatcherTimer = null;
// to do - zezwól na gaszenie ekranu
}
private void dispatcherTimer_Tick(object sender, object e)
{
TimeSpan tmps = (endTime - DateTime.Now);
timerLabel.Text = String.Format("00:{1:00}", tmps.Minutes, tmps.Seconds + 1);
if (this.currentActivity == Activity.Exercise)
{
if (tmps.Seconds + 1 != 30 && tmps.Seconds + 1 != 0)
tickEffect.Play();
if (this.switchSides[this.exerciseIndex] == true && tmps.Seconds == 15)
switchSidesEffect.Play();
}
if (tmps <= TimeSpan.Zero)
{
this.dispatcherTimer.Stop();
switch (this.currentActivity)
{
case Activity.GettingReady:
this.currentActivity = Activity.Exercise;
break;
case Activity.Exercise:
if (this.exerciseIndex < TOTAL_EXERCISES)
this.currentActivity = Activity.Rest;
break;
case Activity.Rest:
this.currentActivity = Activity.Exercise;
this.exerciseIndex++;
beepEffect.Play();
break;
}
if (this.exerciseIndex < TOTAL_EXERCISES)
this.NextActivity();
}
}
private void NextActivity()
{
if (this.dispatcherTimer != null)
{
switch (currentActivity)
{
/* In case of practitioner is getting ready to workout just
* set timespan to 5 seconds and label text.
*/
case Activity.GettingReady:
this.timeSpan = new TimeSpan(0, 0, 5);
currentExerciseLabel.Text = "get ready!";
currentExerciseImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/main.png", UriKind.Absolute));
nextExerciseLabel.Text = "\u2192 jumping jacks";
nextExerciseImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/exercise.jacks.png", UriKind.Absolute));
timerLabel.Text = "00:05";
beepEffect.Play();
break;
/* In case of activity is a workout set the timespan to 30 secs, label text
* and load image from Images/ folder.
*/
case Activity.Exercise:
this.timeSpan = new TimeSpan(0, 0, 30);
currentExerciseLabel.Text = exerciseNames[this.exerciseIndex];
nextExerciseLabel.Text = "\u2192 " + exerciseNames[exerciseIndex + 1];
currentExerciseImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/" + this.imageNames[this.exerciseIndex],
UriKind.Absolute));
nextExerciseImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/" + this.imageNames[this.exerciseIndex+1],
UriKind.Absolute));
timerLabel.Text = "00:30";
beepEffect.Play();
break;
/* In case of activity is a rest set the timespan to 10 secs
* and the label to combined "rest" word [...]
*/
case Activity.Rest:
if (this.exerciseIndex < TOTAL_EXERCISES - 1)
{
this.timeSpan = new TimeSpan(0, 0, 10);
currentExerciseLabel.Text = "rest";
currentExerciseImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/rest.png",
UriKind.Absolute));
timerLabel.Text = "00:10";
beepEffect.Play();
}
else Finish();
break;
}
/* set endTime to time after [timeSpan] seconds
*/
if (timerLocked == false)
{
this.endTime = DateTime.Now;
this.endTime = this.endTime.Add(timeSpan);
this.dispatcherTimer.Start();
}
}
}
private void Finish()
{
this.dispatcherTimer.Stop();
this.timerLocked = true;
timerLabel.Text = "Workout 7";
currentExerciseLabel.Text = "you've finished!";
currentExerciseImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Images/main.png", UriKind.Absolute));
nextExerciseLabel.Text="";
nextExerciseImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/fake_uri.png", UriKind.Absolute));
beepEffect.Play();
IncreaseCurrentStreak();
}
/// <summary>
/// Increases streak counter if there passed no more than 1 day.
/// </summary>
private void IncreaseCurrentStreak()
{
DateTimeOffset offset = new DateTimeOffset(DateTime.Today);
#if DEBUG
Debug.WriteLine("Days passed: {0}", (DateTime.Today - settings.RecentDayOfWorkout).TotalDays);
#endif
if ((DateTime.Today - settings.RecentDayOfWorkout.DateTime).TotalDays < 2.00)
{
#if DEBUG
Debug.WriteLine("Increasing streak");
#endif
settings.CurrentStreakSetting = settings.CurrentStreakSetting + 1;
}
else
{
#if DEBUG
Debug.WriteLine("Streak goes to 1");
#endif
settings.CurrentStreakSetting = 1;
}
settings.RecentDayOfWorkout = offset;
TileHelper.SetUpTiles(settings.CurrentStreakSetting);
}
protected override void OnNavigatedTo(NavigationEventArgs e) {}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.timerLocked = false;
#if DEBUG
exerciseIndex = 11;
#else
this.exerciseIndex = 0;
#endif
this.currentActivity = Activity.GettingReady;
this.NextActivity();
}
}
}
<file_sep>using Windows.UI.Notifications;
namespace workout7RT.Helpers
{
static class TileHelper
{//johny was here
static public void SetUpTiles(int streak)
{
// wide tile
var largeTile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideBlockAndText01);
largeTile.GetElementsByTagName("text")[0].InnerText = "Workout 7";
largeTile.GetElementsByTagName("text")[1].InnerText = "Your current streak is...";
largeTile.GetElementsByTagName("text")[4].InnerText = streak.ToString();
// medium tile
var mediumTile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareBlock);
mediumTile.GetElementsByTagName("text")[0].InnerText = streak.ToString();
mediumTile.GetElementsByTagName("text")[1].InnerText = "days in a row";
var node = largeTile.ImportNode(mediumTile.GetElementsByTagName("binding").Item(0), true);
largeTile.GetElementsByTagName("visual").Item(0).AppendChild(node);
var tileNotification = new TileNotification(largeTile); // { ExpirationTime = DateTimeOffset.UtcNow.AddSeconds(10) };
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
}
// TO DO
////static public void ShowToastNotification(int streak)
////{
//// // to do.
//// var xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
//// xml.GetElementsByTagName("text")[0].AppendChild(xml.CreateTextNode("Hello from toast!"));
//// ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(xml));
////}
static public void ShowToastNotification(string s)
{
var xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
xml.GetElementsByTagName("text")[0].AppendChild(xml.CreateTextNode(s));
ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(xml));
}
}
}
<file_sep>workout7rt
==========
Workout 7 app for Windows Store (port from WP7)
| 2462461b24ff0ee40bd0d8df0fa7bad1b0e42f88 | [
"Markdown",
"C#"
] | 4 | C# | kkoscielniak/workout7rt | 0904dcf80c7bb1fdb7847951feca98faedd68dfb | 571dd1ff81476148f22715e13c54cf1f3a236f20 | |
refs/heads/master | <file_sep>package main
import (
"context"
"fmt"
videoProto "fyoukuApi/micro/video/proto"
"github.com/micro/go-micro"
"github.com/micro/go-micro/registry"
"github.com/micro/go-plugins/registry/etcdv3"
)
func main() {
reg := etcdv3.NewRegistry(func(op *registry.Options) {
op.Addrs = []string{"http://127.0.0.1:2379"}
})
service := micro.NewService(
micro.Registry(reg),
)
service.Init()
video := videoProto.NewVideoService("go.micro.srv.fyoukuApi.video", service.Client())
rsp, err := video.ChannelAdvert(context.TODO(), &videoProto.RequestChannelAdvert{
ChannelId: "1",
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(rsp)
rspHot, _ := video.ChannelHotList(context.TODO(), &videoProto.RequestChannelHotList{
ChannelId: "1",
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(rspHot)
}
<file_sep>package redisClient
import (
"time"
"github.com/astaxie/beego"
"github.com/garyburd/redigo/redis"
)
//直接连接
func Connect() redis.Conn {
pool, _ := redis.Dial("tcp", beego.AppConfig.String("redisdb"))
return pool
}
//通过连接池
func PoolConnect() redis.Conn {
// 建立连接池
pool := &redis.Pool{
MaxIdle: 5000, //最大空闲连接数
MaxActive: 10000, //最大连接数
IdleTimeout: 180 * time.Second, //空闲连接超时时间
Wait: true, //超过最大连接数时,是等待还是报错
Dial: func() (redis.Conn, error) { //建立链接
c, err := redis.Dial("tcp", beego.AppConfig.String("redisdb"))
if err != nil {
return nil, err
}
// 选择db
//c.Do("SELECT", '')
return c, nil
},
}
return pool.Get()
}
<file_sep>package controllers
import (
"context"
userRpcProto "fyoukuApi/micro/user/proto"
"fyoukuApi/models"
"regexp"
"github.com/astaxie/beego"
)
// Operations about Users
type UserRpcController struct {
beego.Controller
}
//用户登录
// @router /login/do [*]
func (this *UserRpcController) LoginDo(ctx context.Context, req *userRpcProto.RequestLoginDo, res *userRpcProto.ResponseLoginDo) error {
var (
userLoginProto userRpcProto.LoginUser
isorno bool
uid int
name string
)
mobile := req.Mobile
password := req.Password
if mobile == "" {
res.Code = 4001
res.Msg = "手机号不能为空"
goto ERR
}
isorno, _ = regexp.MatchString(`^1(3|4|5|7|8)[0-9]\d{8}$`, mobile)
if !isorno {
res.Code = 4002
res.Msg = "手机号格式不正确"
goto ERR
}
if password == "" {
res.Code = 4003
res.Msg = "密码不能为空"
goto ERR
}
uid, name = models.IsMobileLogin(mobile, MD5V(password))
if uid != 0 {
userLoginProto.Uid = int64(uid)
userLoginProto.Username = name
res.Code = 0
res.Msg = "登录成功"
res.Items = &userLoginProto
res.Count = 1
return nil
} else {
res.Code = 4004
res.Msg = "手机号或密码不正确"
goto ERR
}
ERR:
res.Items = &userLoginProto
res.Count = 0
return nil
}
<file_sep># 微服务 服务发现(go version <= 1.14)
## 1.安装etcd(3.4.7)
地址:https://github.com/etcd-io/etcd/releases
下载后直接运行 目录下的etcd
## 安装go-micro
1. go get github.com/micro/go-micro
2. go get github.com/micro/protobuf/{proto,proto-gin-go}
2.go get github.com/micro/protoc-gen-micro/v2
3. go get go get github.com/micro/protoc-gin-micro
4.生成相关protobuf protoc -proto_path=xxx -go_out=xxx -micro_out=xxx xxx.proto
## 安装micro
1. go get 安装或二进制包安装(2.x)
2. go get github.com/micro/micro
3.export MICRO_REGISTRY=etcd
## 启动micro api
`micro api --address=0.0.0.0:8085 --handler=api`
## 启动micro web
`micro web`
## 启动所有服务
```shell script
micro api --address=0.0.0.0:8085 --handler=api
micro web
etcd
micro main
api main
```
<file_sep>package main
import (
"context"
"encoding/json"
user "fyoukuApi/micro/user/proto"
"log"
"strings"
"time"
"github.com/micro/go-micro"
api "github.com/micro/go-micro/api/proto"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/registry"
"github.com/micro/go-plugins/registry/etcdv3"
)
type User struct {
Client user.UserService
}
func (u *User) LoginDo(ctx context.Context, req *api.Request, rsp *api.Response) error {
log.Print("收到User.LoginDo API请求")
//接受参数
mobile, ok := req.Post["mobile"]
if !ok || len(mobile.Values) == 0 {
return errors.BadRequest("go.micro.api.fyoukuApi.user", "mobile为空")
}
password, ok := req.Post["password"]
if !ok || len(password.Values) == 0 {
return errors.BadRequest("go.micro.api.fyoukuApi.user", "password为空")
}
response, err := u.Client.LoginDo(ctx, &user.RequestLoginDo{
Mobile: strings.Join(mobile.Values, ""),
Password: strings.Join(password.Values, ""),
})
if err != nil {
return err
}
rsp.StatusCode = 200
b, _ := json.Marshal(map[string]interface{}{
"code": response.Code,
"msg": response.Msg,
"items": response.Items,
"count": response.Count,
})
rsp.Body = string(b)
return nil
}
func main() {
reg := etcdv3.NewRegistry(func(op *registry.Options) {
op.Addrs = []string{"http://127.0.0.1:2379"}
})
service := micro.NewService(
micro.Registry(reg),
micro.Name("go.micro.api.fyoukuApi.user"),
micro.RegisterTTL(time.Second*30),
micro.RegisterInterval(time.Second*10),
)
service.Init()
service.Server().Handle(
service.Server().NewHandler(
&User{Client: user.NewUserService("go.micro.srv.fyoukuApi.user", service.Client())},
),
)
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
<file_sep>package controllers
import (
"context"
videoRpcProto "fyoukuApi/micro/video/proto"
"fyoukuApi/models"
"strconv"
"github.com/astaxie/beego"
)
// Operations about Users
type VideoRpcController struct {
beego.Controller
}
func (this *VideoRpcController) ChannelAdvert(ctx context.Context, req *videoRpcProto.RequestChannelAdvert, res *videoRpcProto.ResponseChannelAdvert) error {
var (
channelAdvertDatas []*videoRpcProto.ChannelAdvertData
num int64
videos []models.Advert
err error
)
channelId, _ := strconv.Atoi(req.ChannelId)
if channelId == 0 {
res.Code = 4001
res.Msg = "必须指定频道"
goto ERR
}
num, videos, err = models.GetChannelAdvert(channelId)
if err == nil {
for _, v := range videos {
var channelAdvertData videoRpcProto.ChannelAdvertData
channelAdvertData.Id = int64(v.Id)
channelAdvertData.Title = v.Title
channelAdvertData.SubTitle = v.SubTitle
channelAdvertData.Img = v.Img
channelAdvertData.Url = v.Url
channelAdvertData.AddTime = v.AddTime
channelAdvertDatas = append(channelAdvertDatas, &channelAdvertData)
}
res.Code = 0
res.Msg = "success"
res.Items = channelAdvertDatas
res.Count = num
return nil
} else {
res.Code = 4004
res.Msg = "请求数据失败,请稍后重试~"
goto ERR
}
ERR:
res.Items = channelAdvertDatas
res.Count = 0
return nil
}
func (this *VideoRpcController) ChannelHotList(ctx context.Context, req *videoRpcProto.RequestChannelHotList, res *videoRpcProto.ResponseChannelHotList) error {
var (
channelHotListDatas []*videoRpcProto.ChannelHotListData
num int64
videos []models.VideoData
err error
)
channelId, _ := strconv.Atoi(req.ChannelId)
if channelId == 0 {
res.Code = 4001
res.Msg = "必须指定频道"
goto ERR
}
num, videos, err = models.GetChannelHotList(channelId)
if err == nil {
for _, v := range videos {
var channelHotListData videoRpcProto.ChannelHotListData
channelHotListData.Id = int64(v.Id)
channelHotListData.Title = v.Title
channelHotListData.SubTitle = v.SubTitle
channelHotListData.Img = v.Img
channelHotListData.Img1 = v.Img1
channelHotListData.IsEnd = int64(v.IsEnd)
channelHotListData.AddTime = v.AddTime
channelHotListData.EpisodesCount = int64(v.EpisodesCount)
channelHotListData.Comment = int64(v.Comment)
channelHotListDatas = append(channelHotListDatas, &channelHotListData)
}
res.Code = 0
res.Msg = "success"
res.Items = channelHotListDatas
res.Count = num
return nil
} else {
res.Code = 4004
res.Msg = "没有相关内容"
goto ERR
}
ERR:
res.Items = channelHotListDatas
res.Count = 0
return nil
}
<file_sep>package models
import (
"github.com/astaxie/beego/orm"
)
type Advert struct {
Id int
Title string
SubTitle string
AddTime int64
Img string
Url string
}
func init() {
orm.RegisterModel(new(Advert))
}
func GetChannelAdvert(channelId int) (int64, []Advert, error) {
o := orm.NewOrm()
var adverts []Advert
num, err := o.Raw("SELECT id, title, sub_title,img,add_time,url FROM advert WHERE status=1 AND channel_id=? ORDER BY sort DESC LIMIT 1", channelId).QueryRows(&adverts)
return num, adverts, err
}
<file_sep>package main
import (
"encoding/json"
"fmt"
"fyoukuApi/services/mq"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
func main() {
beego.LoadAppConfig("ini", "../../conf/app.conf")
defaultdb := beego.AppConfig.String("defaultdb")
orm.RegisterDriver("mysql", orm.DRMySQL)
orm.RegisterDataBase("default", "mysql", defaultdb, 30, 30)
mq.ConsumerDlx("fyouku.comment.count", "fyouku_comment_count", "fyouku.comment.count.dlx", "fyouku_comment_count_dlx", 10000, callback)
}
func callback(s string) {
type Data struct {
VideoId int
EpisodesId int
}
var data Data
err := json.Unmarshal([]byte(s), &data)
if err == nil {
o := orm.NewOrm()
//修改视频的总评论数
o.Raw("UPDATE video SET comment=comment+1 WHERE id=?", data.VideoId).Exec()
//修改视频剧集的评论数
o.Raw("UPDATE video_episodes SET comment=comment+1 WHERE id=?", data.EpisodesId).Exec()
//更新redis排行榜 - 通过MQ来实现
//创建一个简单模式的MQ
//把要传递的数据转换为json字符串
videoObj := map[string]int{
"VideoId": data.VideoId,
}
videoJson, _ := json.Marshal(videoObj)
mq.Publish("", "fyouku_top", string(videoJson))
}
fmt.Printf("msg is :%s\n", s)
}
<file_sep>package main
import (
"fmt"
"fyoukuApi/controllers"
"fyoukuApi/micro/user/proto"
_ "fyoukuApi/routers"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
"github.com/micro/go-micro"
"github.com/micro/go-micro/registry"
"github.com/micro/go-plugins/registry/etcdv3"
)
func main() {
beego.LoadAppConfig("ini", "../../conf/app.conf")
defaultdb := beego.AppConfig.String("defaultdb")
orm.RegisterDriver("mysql", orm.DRMySQL)
orm.RegisterDataBase("default", "mysql", defaultdb, 30, 30)
reg := etcdv3.NewRegistry(func(op *registry.Options) {
op.Addrs = []string{"http://127.0.0.1:2379"}
})
service := micro.NewService(
micro.Registry(reg),
micro.Name("go.micro.srv.fyoukuApi.user"),
micro.RegisterTTL(time.Second*30),
micro.RegisterInterval(time.Second*10),
)
service.Init()
proto.RegisterUserServiceHandler(service.Server(), new(controllers.UserRpcController))
if err := service.Run(); err != nil {
fmt.Println(err)
}
}
<file_sep>package main
import (
"context"
"encoding/json"
video "fyoukuApi/micro/video/proto"
"log"
"strings"
"time"
"github.com/micro/go-micro"
api "github.com/micro/go-micro/api/proto"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/registry"
"github.com/micro/go-plugins/registry/etcdv3"
)
type Video struct {
Client video.VideoService
}
func (v *Video) ChannelAdvert(ctx context.Context, req *api.Request, rsp *api.Response) error {
log.Print("收到Video.ChannelAdvert API请求")
//接受参数
channelId, ok := req.Get["channelId"]
if !ok || len(channelId.Values) == 0 {
return errors.BadRequest("go.micro.api.fyoukuApi.video", "channelId为空")
}
response, err := v.Client.ChannelAdvert(ctx, &video.RequestChannelAdvert{
ChannelId: strings.Join(channelId.Values, ""),
})
if err != nil {
return err
}
rsp.StatusCode = 200
b, _ := json.Marshal(map[string]interface{}{
"code": response.Code,
"msg": response.Msg,
"items": response.Items,
"count": response.Count,
})
rsp.Body = string(b)
return nil
}
func (v *Video) ChannelHotList(ctx context.Context, req *api.Request, rsp *api.Response) error {
log.Print("收到Video.ChannelHotList API请求")
//接受参数
channelId, ok := req.Get["channelId"]
if !ok || len(channelId.Values) == 0 {
return errors.BadRequest("go.micro.api.fyoukuApi.video", "channelId为空")
}
response, err := v.Client.ChannelHotList(ctx, &video.RequestChannelHotList{
ChannelId: strings.Join(channelId.Values, ""),
})
if err != nil {
return err
}
rsp.StatusCode = 200
b, _ := json.Marshal(map[string]interface{}{
"code": response.Code,
"msg": response.Msg,
"items": response.Items,
"count": response.Count,
})
rsp.Body = string(b)
return nil
}
func main() {
reg := etcdv3.NewRegistry(func(op *registry.Options) {
op.Addrs = []string{"http://127.0.0.1:2379"}
})
service := micro.NewService(
micro.Registry(reg),
micro.Name("go.micro.api.fyoukuApi.video"),
micro.RegisterTTL(time.Second*30),
micro.RegisterInterval(time.Second*10),
)
service.Init()
service.Server().Handle(
service.Server().NewHandler(
&Video{Client: video.NewVideoService("go.micro.srv.fyoukuApi.video", service.Client())},
),
)
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
<file_sep>package main
import (
"context"
"fmt"
userProto "fyoukuApi/micro/user/proto"
"github.com/micro/go-micro"
"github.com/micro/go-micro/registry"
"github.com/micro/go-plugins/registry/etcdv3"
)
func main() {
reg := etcdv3.NewRegistry(func(op *registry.Options) {
op.Addrs = []string{"http://127.0.0.1:2379"}
})
service := micro.NewService(
micro.Registry(reg),
)
service.Init()
user := userProto.NewUserService("go.micro.srv.fyoukuApi.user", service.Client())
rsp, err := user.LoginDo(context.TODO(), &userProto.RequestLoginDo{
Mobile: "18600001111",
Password: "<PASSWORD>",
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(rsp)
}
<file_sep>module fyoukuApi
go 1.15
require (
github.com/astaxie/beego v1.12.3
github.com/garyburd/redigo v1.6.2
github.com/go-sql-driver/mysql v1.5.0
github.com/golang/protobuf v1.4.2
github.com/gomodule/redigo v2.0.0+incompatible
github.com/gorilla/websocket v1.4.2
github.com/micro/go-micro v1.18.0
github.com/micro/go-plugins v1.5.1 // indirect
github.com/smartystreets/goconvey v1.6.4
github.com/streadway/amqp v1.0.0
)
<file_sep>package controllers
import (
"fyoukuApi/models"
"github.com/astaxie/beego"
)
type TopController struct {
beego.Controller
}
//根据频道获取排行榜
// @router /channel/top [*]
func (this *TopController) ChannelTop() {
//获取频道ID
channelId, _ := this.GetInt("channelId")
if channelId == 0 {
this.Data["json"] = ReturnError(4001, "必须指定频道")
this.ServeJSON()
}
num, videos, err := models.RedisGetChannelTop(channelId)
if err == nil {
this.Data["json"] = ReturnSuccess(0, "success", videos, num)
this.ServeJSON()
} else {
this.Data["json"] = ReturnError(4004, "没有相关内容")
this.ServeJSON()
}
}
//根据类型获取排行榜
// @router /type/top [*]
func (this *TopController) TypeTop() {
typeId, _ := this.GetInt("typeId")
if typeId == 0 {
this.Data["json"] = ReturnError(4001, "必须指定类型")
this.ServeJSON()
}
num, videos, err := models.RedisGetTypeTop(typeId)
if err == nil {
this.Data["json"] = ReturnSuccess(0, "success", videos, num)
this.ServeJSON()
} else {
this.Data["json"] = ReturnError(4004, "没有相关内容")
this.ServeJSON()
}
}
<file_sep>package controllers
import (
"fmt"
"fyoukuApi/models"
"github.com/astaxie/beego"
"regexp"
"strconv"
"strings"
)
// Operations about Users
type UserController struct {
beego.Controller
}
//用户注册功能
// @router /register/save [post]
func (this *UserController) SaveRegister() {
var (
mobile string
password string
err error
)
mobile = this.GetString("mobile")
password = this.GetString("password")
if mobile == "" {
this.Data["json"] = ReturnError(4001, "手机号不能为空")
this.ServeJSON()
}
isorno, _ := regexp.MatchString(`^1(3|4|5|7|8)[0-9]\d{8}$`, mobile)
if !isorno {
this.Data["json"] = ReturnError(4002, "手机号格式不正确")
this.ServeJSON()
}
if password == "" {
this.Data["json"] = ReturnError(4003, "密码不能为空")
this.ServeJSON()
}
//判断手机号是否已经注册
status := models.IsUserMobile(mobile)
if status {
this.Data["json"] = ReturnError(4005, "此手机号已经注册")
this.ServeJSON()
} else {
err = models.UserSave(mobile, MD5V(password))
if err == nil {
this.Data["json"] = ReturnSuccess(0, "注册成功", nil, 0)
this.ServeJSON()
} else {
this.Data["json"] = ReturnError(5000, err)
this.ServeJSON()
}
}
}
//用户登录
// @router /login/do [*]
func (this *UserController) LoginDo() {
mobile := this.GetString("mobile")
password := this.GetString("password")
if mobile == "" {
this.Data["json"] = ReturnError(4001, "手机号不能为空")
this.ServeJSON()
}
isorno, _ := regexp.MatchString(`^1(3|4|5|7|8)[0-9]\d{8}$`, mobile)
if !isorno {
this.Data["json"] = ReturnError(4002, "手机号格式不正确")
this.ServeJSON()
}
if password == "" {
this.Data["json"] = ReturnError(4003, "密码不能为空")
this.ServeJSON()
}
uid, name := models.IsMobileLogin(mobile, MD5V(password))
if uid != 0 {
this.Data["json"] = ReturnSuccess(0, "登录成功", map[string]interface{}{"uid": uid, "username": name}, 1)
this.ServeJSON()
} else {
this.Data["json"] = ReturnError(4004, "手机号或密码不正确")
this.ServeJSON()
}
}
//批量发送通知消息
// @router /send/message [*]
//func (this *UserController) SendMessageDo() {
// uids := this.GetString("uids")
// content := this.GetString("content")
//
// if uids == "" {
// this.Data["json"] = ReturnError(4001, "请填写接收人~")
// this.ServeJSON()
// }
// if content == "" {
// this.Data["json"] = ReturnError(4002, "请填写发送内容")
// this.ServeJSON()
// }
// messageId, err := models.SendMessageDo(content)
// if err == nil {
// uidConfig := strings.Split(uids, ",")
// for _, v := range uidConfig {
// userId, _ := strconv.Atoi(v)
// //models.SendMessageUser(userId, messageId)
// models.SendMessageUserMq(userId, messageId)
// }
// this.Data["json"] = ReturnSuccess(0, "发送成功~", "", 1)
// this.ServeJSON()
// } else {
// this.Data["json"] = ReturnError(5000, "发送失败,请联系客服~")
// this.ServeJSON()
// }
//}
type SendData struct {
UserId int
MessageId int64
}
//批量发送通知消息
// @router /send/message [*]
func (this *UserController) SendMessageDo() {
uids := this.GetString("uids")
content := this.GetString("content")
if uids == "" {
this.Data["json"] = ReturnError(4001, "请填写接收人~")
this.ServeJSON()
}
if content == "" {
this.Data["json"] = ReturnError(4002, "请填写发送内容")
this.ServeJSON()
}
messageId, err := models.SendMessageDo(content)
if err == nil {
uidConfig := strings.Split(uids, ",")
count := len(uidConfig)
sendChan := make(chan SendData, count)
closeChan := make(chan bool, count)
go func() {
var data SendData
for _, v := range uidConfig {
userId, _ := strconv.Atoi(v)
data.UserId = userId
data.MessageId = messageId
sendChan <- data
}
close(sendChan)
}()
for i := 0; i < 5; i++ {
go sendMessageFunc(sendChan, closeChan)
}
for i := 0; i < 5; i++ {
<-closeChan
}
close(closeChan)
this.Data["json"] = ReturnSuccess(0, "发送成功~", "", 1)
this.ServeJSON()
} else {
this.Data["json"] = ReturnError(5000, "发送失败,请联系客服~")
this.ServeJSON()
}
}
func sendMessageFunc(sendChan chan SendData, closeChan chan bool) {
for t := range sendChan {
fmt.Println(t)
models.SendMessageUserMq(t.UserId, t.MessageId)
}
closeChan <- true
}
| 691888d7be61b774ade7daedc9dc327fe1a29ef3 | [
"Markdown",
"Go Module",
"Go"
] | 14 | Go | azhuang321/fyoukuApi | 2e29d5ba74cee4854edddb954fe5b99fa9addfb4 | 42daa41afc8ffdf7ae8452e0b312b916252d7102 | |
refs/heads/master | <file_sep>#############################################################################################
#Record Linkage using RecordLinkage library
#Last modified 5/16/18
#Optimization Opportunities include:
#Index Method used for making record pairs for comparison:
# -Blocking v Sorted Neighbor
#feature(s) to use for Indexing
#Features to use for comparison
#Type of comparison to make (exact, string, other)
#Method to use for string comparisons (e.g., Jaro v Levenshtein v other)
#Thresholds to use for string comparisons (default is .85), which will vary from feature to feature
#computation for determining a match (currently using a simply summation of feature vectors)
#assignement of weights to feature vectors
##about the data being used##################################################################
#10K simulated dataset:
# 6K original recs
# 4K duplicated recs
# max_modification_per_field = 3
# max_modification_per_record = 3
# distribution = zipf
# modification_types = all
# family number = 0
#
#
#script used to create the training data: https://github.com/J535D165/FEBRL-fork-v0.4.2/blob/master/dsgen/generate2.py
###############################################################################################
#start imports
import random
import re
import sys
import time
import recordlinkage as rl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
#end imports###################################################################################
#global variables
training_data=r"C:\Users\Andrew\Desktop\RecordLinkage\TrainingData\infile_dob_abbr.csv"
features=pd.DataFrame()
matches=pd.DataFrame()
rec_num=[]
####read data, set index to rec_id
df=pd.read_csv(training_data,index_col=0,encoding = "ISO-8859-1")
df['rec_id']=df.index
###extract record number from rec_id for testing purposes
for item in df['rec_id']:
item=str(item)
item=re.search('rec-(.+?)-', item)
rec_num.append(item.group(1))
df["rec_num"]=rec_num
#####################################
#split data into training and test
train,test=train_test_split(df)
#Define matches
def ScoreRecords():
global features
global df
cols = df.columns.tolist()
cols = cols[-1:] + cols[:-1]
df=df[cols]
## create pairs
indexer = rl.SortedNeighbourhoodIndex(on='given_name',window=5)
pairs=indexer.index(train,test)
compare_cl = rl.Compare()
## methodology for scoring
compare_cl.exact('postcode', 'postcode',label='postcode')
compare_cl.string('surname', 'surname',method='jaro',threshold=.95,label='surname')
compare_cl.string('given_name', 'given_name',method='jaro', threshold=.95, label='name')
compare_cl.string('date_of_birth', 'date_of_birth',method='jaro', threshold=0.85,label='dob')
compare_cl.string('suburb', 'suburb',method='jaro',label='suburb',threshold=.85)
compare_cl.string('state', 'state',label='state',method='jaro', threshold=.85)
compare_cl.string('address_1', 'address_1', method='jaro',threshold=0.9,label='address_1')
compare_cl.exact('rec_num','rec_num',label='rec_num')
##compute feature vector
features = compare_cl.compute(pairs,train, test)
total_score=[]
features["Total_Score"]=features.sum(axis=1)
features.fillna(0)
y=[]
for row in features["Total_Score"]:
if row >=7:
y.append(1)
else:
y.append(0)
features["target"]=y
features.to_csv('feature_vectors.csv',sep=",",encoding='utf-8')
return (features)
ScoreRecords()
####################Known Matches#################################################################################################################
def knownMatches():
match=ScoreRecords()
known_match=np.sum(match['rec_num'])
return known_match
knownMatches()
###################Define Matches##################################################################################################################
def CreateMatches():
global features
matches = features[features.sum(axis=1) >6]
return matches
CreateMatches()
###############################################################Evaluation of Compare################################################################
###Join matchced records and print to file for analysis purposes
def JoinMatches():
global df
#split matches multi-index in columns to join to paired record values
matches=CreateMatches()
df_matches=pd.DataFrame(matches.index,columns=['record'])
dfm=pd.DataFrame(df_matches['record'].values.tolist())
dfm.columns=['record1','record2']
#join first record in matched pair
matched_records=pd.merge(dfm, df, left_on='record1',right_on='rec_id', how='inner')
#join second record in matched pair
matched_records=pd.merge(matched_records, df, left_on='record2',right_on='rec_id',how='inner')
#reorder columns to faciliate comparison and quality of matching
matched_records=matched_records[['record1','record2','rec_num_x','rec_num_y','surname_x', 'surname_y','given_name_x','given_name_y',
'date_of_birth_x','date_of_birth_y','address_1_x','address_1_y','state_x','state_y','suburb_x','suburb_y','postcode_x','postcode_y']]
matched_records.fillna(0)
#write matches to file
matched_records.to_csv('matched_records.csv',sep=",",encoding = "utf-8")
return (matched_records)
JoinMatches()
###identify incorrect matches and print to file for analysis purposes
def findFalsePos():
matched_records=JoinMatches()
matched_records_errors=matched_records
matched_records_errors=matched_records_errors.loc[matched_records['rec_num_x']!=matched_records['rec_num_y']]
matched_records_errors.dropna()
matched_records_errors.to_csv('false_pos_matches.csv',sep=",",encoding='utf-8')
false_positives=len(matched_records_errors)
return false_positives
findFalsePos()
###identify missed matches and print to file for analysis purposes
def missedMatches():
record_set=ScoreRecords()
##taking the record pairs that were not considered to be matches
missed_matches = record_set[record_set.sum(axis=1) <=6]
misses=np.sum(missed_matches['rec_num'])
return misses
missedMatches()
############################################################Classification#######################################################
###data prep###################################################
def prepData():
data=pd.read_csv('feature_vectors.csv',sep=",",encoding='utf-8')
del data["Total_Score"]
del data["rec_id"]
del data["rec_id.1"]
###calculate known matches, then delete for classification
del data['rec_num']
data.to_csv('feature_vectors_clean.csv',sep=",", encoding='utf-8')
return data
prepData()
####Evaluate vector scoring methodology###########################################################################################
known_matches=knownMatches()
missed_matches=missedMatches()
false_positives=findFalsePos()
pairs=ScoreRecords()
print "number of comparison pairs in index:",len(pairs)
print "number of matching pairs:",known_matches
print "number of missed matches:",missed_matches
print "number of false positives:",false_positives
#supervised#######################################################################################################
#unsupervised methods#############################################################################################
###k-means####################################################
data=prepData()
kmeans = rl.KMeansClassifier()
result_kmeans = kmeans.learn(data)
print 'number of predicted pairs using K-means clustering:',len(result_kmeans)
###ECM Maximization###########################################
ecm = rl.ECMClassifier()
result_ecm = ecm.learn((data > 0.8).astype(int))
print 'the number of predicted pairs using ECM Maximization:',len(result_ecm)
<file_sep>#############################################################################################
#Record Linkage using RecordLinkage library
#Last modified 5/8/18
#Optimization Opportunities include:
#Index Method used for making record pairs for comparison:
# -Blocking v Sorted Neighbor
#feature(s) to use for Indexing
#Features to use for comparison
#Type of comparison to make (exact, string, other)
#Method to use for string comparisons (e.g., Jaro v Levenshtein v other)
#Thresholds to use for string comparisons (default is .85), which will vary from feature to feature
#computation for determining a match (currently using a simply summation of feature vectors)
#assignement of weights to feature vectors
##about the data being used##################################################################
#10K simulated dataset:
# 6K original recs
# 4K duplicated recs
# max_modification_per_field = 3
# max_modification_per_record = 3
# distribution = zipf
# modification_types = all
# family number = 0
#
#
#script used to create the training data: https://github.com/J535D165/FEBRL-fork-v0.4.2/blob/master/dsgen/generate2.py
###############################################################################################
#start imports
import random
import re
import sys
import time
import recordlinkage as rl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from tpot import TPOTClassifier
#from sklearn.cluster import KMeans
#from sklearn import preprocessing
#from sklearn.linear_model import LogisticRegression
#from sklearn import model_selection
#from pandas.plotting import scatter_matrix
#from sklearn.utils import shuffle
#end imports###################################################################################
#global variables
training_data=r"C:\Users\Andrew\Desktop\RecordLinkage\TrainingData\infile_dob_abbr.csv"
features=pd.DataFrame()
matches=pd.DataFrame()
rec_num=[]
pipeline_optimizer = TPOTClassifier()
####read data, set index to rec_id and add target variable, 'y' column
df=pd.read_csv(training_data,index_col=0,encoding = "ISO-8859-1")
df['rec_id']=df.index
###extract record number from rec_id for testing purposes
for item in df['rec_id']:
item=str(item)
item=re.search('rec-(.+?)-', item)
rec_num.append(item.group(1))
df["rec_num"]=rec_num
#####################################
#split data into training and test
train,test=train_test_split(df, test_size=0.2)
#Define matches
def ScoreRecords():
global features
global df
cols = df.columns.tolist()
cols = cols[-1:] + cols[:-1]
df=df[cols]
##create pairs
x_train,y_train=train_test_split(train, test_size=0.5)
indexer = rl.SortedNeighbourhoodIndex(on='given_name',window=3)
pairs=indexer.index(x_train,y_train)
compare_cl = rl.Compare()
compare_cl.string('postcode', 'postcode', method='jaro', threshold=0.85,label='postcode')
compare_cl.string('surname', 'surname',method='jaro',threshold=.95,label='surname')
compare_cl.string('given_name', 'given_name',method='jaro', threshold=.95, label='name')
compare_cl.string('date_of_birth', 'date_of_birth',method='jaro', threshold=0.85,label='dob')
compare_cl.string('postcode', 'postcode', method='jaro', threshold=0.85,label='postcode')
compare_cl.string('suburb', 'suburb',method='jaro',label='suburb',threshold=.85)
compare_cl.string('state', 'state',label='state',method='jaro', threshold=.85)
compare_cl.string('address_1', 'address_1', method='jaro',threshold=0.9,label='address_1')
compare_cl.exact('rec_num','rec_num',label='rec_num')
##compute feature vector
features = compare_cl.compute(pairs,x_train, y_train)
total_score=[]
features["Total_Score"]=features.sum(axis=1)
##look at distribution of scores across record-pairs
plt.hist(features['Total_Score'],bins=8)
plt.title(r'Distribution of feature score totals for record pairs')
plt.show()
y=[]
for row in features["Total_Score"]:
if row >=6:
y.append(1)
else:
y.append(0)
features["y"]=y
###replace string in index columns with int
features.to_csv('feature_vectors.csv',sep=",",encoding='utf-8')
return (features)
ScoreRecords()
print "number of scored pairs:",len(features)
###############################################################Evaluation of Compare################################################################
###Join matchced records and print to file for analysis pusposes
def JoinMatches():
global df
#split matches multi-index in columns to join to paired record values
matches=ScoreRecords()
df_matches=pd.DataFrame(matches.index,columns=['record'])
dfm=pd.DataFrame(df_matches['record'].values.tolist())
dfm.columns=['record1','record2']
#join first record in matched pair
matched_records=pd.merge(dfm, df, left_on='record1',right_on='rec_id', how='inner')
#join second record in matched pair
matched_records=pd.merge(matched_records, df, left_on='record2',right_on='rec_id',how='inner')
#reorder columns to faciliate comparison and quality of matching
matched_records=matched_records[['rec_id_y','rec_id_x','record1','record2','surname_x', 'surname_y','given_name_x','given_name_y',
'date_of_birth_x','date_of_birth_y','address_1_x','address_1_y']]
#write matches to file
matched_records.to_csv('matched_records.csv',sep=",",encoding = "utf-8")
return (matched_records)
JoinMatches()
############################################################Classification#######################################################
###data prep###################################################
data=pd.read_csv('feature_vectors.csv',sep=",",encoding='utf-8')
del data["Total_Score"]
del data["rec_id"]
del data["rec_id.1"]
###calculate known matches, then delete for classification
known_match=tot_match=np.sum(data['rec_num'])
del data['rec_num']
#print data.head(10)
#unsupervised methods#############################################################################################
###k-means####################################################
print "number of matching pairs:",known_match
kmeans = rl.KMeansClassifier()
result_kmeans = kmeans.learn(data)
print 'number of predicted pairs using K-means clustering:',len(result_kmeans)
###ECM Maximization###########################################
ecm = rl.ECMClassifier()
result_ecm = ecm.learn((data > 0.8).astype(int))
print 'the number of predicted pairs using ECM Maximization:',len(result_ecm)
###get rid of annoying divide by zero runtime error
#####Logistic Regression#######################
#split training data into features and dependent variable, 'y'#
#matches=GoldenPairs()
#y=matches['y']
#x_train, y_train=train_test_split(matches,y,test_size=.5,random_state=42)
# Initialize the classifier
#logreg = LogisticRegression()
#logreg.fit(x_train, y_train)
#print ("Coefficients: ", logreg.coefficients)
#data.fillna(0)
##total true matches
#tot_match=np.sum(data['y'])
#print tot_match
####create golden_pairs
#golden_pairs=data[0:5000]
###create subset of known matches
#data.sort_values(['y'],inplace=True,ascending=False)
#matched_records=df.sample(2000)
#golden_matches_index = matched_records.index
#Train the classifier
#nb = rl.NaiveBayesClassifier()
#nb.learn(golden_pairs, golden_matches_index)
# Predict the match status for all record pairs
#result_nb = nb.predict(data)
#print len(result_nb) | 82a719910c8e170f324fc6f3d865e7b8df996df1 | [
"Python"
] | 2 | Python | amalinow1982/ZT-Data-Science | a3a2945bf2f23e10a32d962dc8c6480f907bbedb | 54d7c16f1f07ea99bc67eda6a8306378ef29232f | |
refs/heads/master | <file_sep>from csv import writer
import os
def extractContent(inString):
inString = inString.replace(' ',' ')
outArray = []
temp = ''
ignore = False
for i in range(len(inString)):
#print(i, inString[i])
if (inString[i] == '<'):
ignore = True
temp = temp.strip()
if (len(temp) > 0) :
if ('UTC' in temp or 'EST' in temp or 'CET' in temp):
pass
elif (('2001-08-' in temp) or ('2001-07-' in temp) or ('2001-09-' in temp)):
pass
elif ((':' in temp) or (')' in temp)):
pass
elif ( '(' in temp):
temp = temp.replace('(','')
if (len(temp)>0):
outArray.append(temp)
elif 'aet' in temp or 'a.e.t.' in temp:
if (len(outArray)>0):
outArray[-1]+=temp
else:
outArray.append('special'+temp+'special')
elif 'orfeited' in temp:
pass
elif not temp.isspace():
outArray.append(temp)
temp = ''
elif (inString[i] == '>'):
ignore = False
else:
if (ignore == False):
temp+=inString[i]
temp = temp.strip()
if (len(temp) > 0 and not temp.isspace()):
outArray.append(temp)
return outArray
def readFile(fname, mywriter):
infile = open(fname, encoding='utf8')
#outfile = open(fname[:-5]+'.out', 'w', newline='', encoding='utf-8')
#mywriter = writer(outfile, delimiter = ',')
matchInfo = []
getTokens = False
for line in infile:
#print(line)
line.rstrip()
if 'class="summary"' in line:
getTokens = True
tokenCount = 0
tokens = []
if getTokens == True:
#print(line)
if tokenCount < 4:
newTokens = extractContent(line)
tokens.extend(newTokens)
tokenCount += len(newTokens)
else:
mywriter.writerow(tokens)
getTokens = False
else:
continue
createSortedFile():
monthLookup = {
'January': 1,
'February': 2,
'March': 3,
'April': 4,
'May': 5,
'June': 6,
'July': 7,
'August': 8,
'September': 9,
'October': 10,
'November': 11,
'December': 12,
}
def driver(directory):
os.chdir(directory)
fnames = os.listdir('.')
outfile = open('CLHistory.log', 'w', newline='', encoding='utf-8')
mywriter = writer(outfile, delimiter = ',')
for fname in fnames:
if CLHistory not in fname:
readFile(fname,mywriter)
outfile.close()
| e2c1f594001edc785addda3b73e522aa2f88d2f1 | [
"Python"
] | 1 | Python | banjosupreme/SportsAnalytics | f8b582416bdaf0205f65516fce125da39bd38134 | 0f7a5396848f0f3d80ea1d3f3ec2370349dc0526 | |
refs/heads/master | <file_sep>opendj-utils
============
Small utilities for OpenDJ LDAP directory services (http://opendj.forgerock.org)
* schema-convert.py - Converts OpenLDAP .schema file to OpenDJ ldif format
* logstat.py - Compute statistics about LDAP operations from access logs
* opendj_patch4upgrade.sh - Patches an existing OpenDS or early OpenDJ instance to allow smooth upgrade afterwards
* dsmlQueryService.wsdl - DSML WSDL file to use with OpenDJ DSML Gateway
Additional utilities for OpenDJ can be found on [<NAME>'s GitHub space] (https://github.com/chrisridd/opendj-utils)
Note: these are my tools and in no way officially supported by ForgeRock.
<file_sep>#!/usr/bin/env python
# encoding: utf-8
"""
schema-convert.py
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (the "License"). You may not use this file except in compliance
# with the License.
#
# You can obtain a copy of the license at
# trunk/opends/resource/legal-notices/OpenDS.LICENSE
# or https://OpenDS.dev.java.net/OpenDS.LICENSE.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at
# trunk/opends/resource/legal-notices/OpenDS.LICENSE. If applicable,
# add the following below this CDDL HEADER, with the fields enclosed
# by brackets "[]" replaced with your own identifying information:
# Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2009 Sun Microsystems, Inc.
# Portions Copyright 2010-2012 ForgeRock Inc.
Created by <NAME> on 2009-01-28.
This program converts an OpenLDAP schema file to the OpenDS schema file format.
"""
import sys
import getopt
import re
import string
help_message = '''
Usage: schema-convert.py [options] <openldap-schema-file>
options:
\t -o output : specifies the output file, otherwise stdout is used
\t -v : verbose mode
'''
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def main(argv=None):
output = ""
seclineoid = 0
IDs = {}
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "ho:v", ["help", "output="])
except getopt.error, msg:
raise Usage(msg)
# option processing
for option, value in opts:
if option == "-v":
verbose = True
if option in ("-h", "--help"):
raise Usage(help_message)
if option in ("-o", "--output"):
output = value
except Usage, err:
print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
print >> sys.stderr, "\t for help use --help"
return 2
try:
infile = open(args[0], "r")
except Usage, err:
print >> sys.stderr, "Can't open file: " + str(err.msg)
if output != "":
try:
outfile = open(output, "w")
except Usage, err:
print >> sys.stderr, "Can't open output file: " + str(err.msg)
else:
outfile = sys.stdout
outfile.write("dn: cn=schema\n")
outfile.write("objectclass: top\n")
outfile.write("")
for i in infile:
newline = ""
if not i.strip():
continue
#if i.startswith("#"):
# continue
if re.match("objectidentifier", i, re.IGNORECASE):
# Need to fill in an array of identifiers
oid = i.split()
if not re.match ("[0-9.]+", oid[2]):
suboid = oid[2].split(':')
IDs[oid[1]] = IDs[suboid[0]] + "." + suboid[1]
else:
IDs[oid[1]] = oid[2]
continue
if seclineoid == 1:
subattr = i.split()
if not re.match("[0-9.]+", subattr[0]):
if re.match (".*:", subattr[0]):
# The OID is an name prefixed OID. Replace string with the OID
suboid = subattr[0].split(":")
repl = IDs[suboid[0]] + "." + suboid[1]
else:
# The OID is a name. Replace string with the OID
repl = IDs[subattr[0]]
newline = string.replace(i, subattr[0], repl, 1)
seclineoid = 0
if re.match("attributetype ", i, re.IGNORECASE):
newline = re.sub("attribute[tT]ype", "attributeTypes:", i)
# replace OID string with real OID if necessary
subattr = newline.split()
if len(subattr) < 3:
seclineoid = 1
else:
if not re.match("[0-9.]+", subattr[2]):
if re.match (".*:", subattr[2]):
# The OID is an name prefixed OID. Replace string with the OID
suboid = subattr[2].split(":")
repl = IDs[suboid[0]] + "." + suboid[1]
else:
# The OID is a name. Replace string with the OID
repl = IDs[subattr[2]]
newline = string.replace(newline, subattr[2], repl, 1)
if re.match("objectclass ", i, re.IGNORECASE):
newline = re.sub("object[cC]lass", "objectClasses:", i)
# replace OID String with real OID
subattr = newline.split()
if len(subattr) < 3:
seclineoid = 1
else:
if not re.match("[0-9.]+", subattr[2]):
if re.match (".*:", subattr[2]):
# The OID is an name prefixed OID. Replace string with the OID
suboid = subattr[2].split(":")
repl = IDs[suboid[0]] + "." + suboid[1]
else:
# The OID is a name. Replace string with the OID
repl = IDs[subattr[2]]
newline = string.replace(newline, subattr[2], repl, 1)
# Remove quoted syntax.
if re.search("SYNTAX\s'[\d.]+'", newline):
# Found a quoted syntax in an already updated line
newline = re.sub("SYNTAX '([\d.]+)'", "SYNTAX \g<1>", newline)
else:
if re.search("SYNTAX\s'[\d.]+'", i):
# Found a quoted syntax in the original line
newline = re.sub("SYNTAX '([\d.]+)'", "SYNTAX \g<1>", i)
# Remove quoted SUP
if re.search("SUP\s'[\w\-]+'", newline):
# Found a quoted sup in an already updated line
newline = re.sub("SUP '([\w\-]+)'", "SUP \g<1>", newline)
else:
if re.search("SUP\s'[\w\-]+'", i):
# Found a quoted sup in the original line
newline = re.sub("SUP '([\w\-]+)'", "SUP \g<1>", i)
# transform continuation lines with only 2 spaces
if re.match(" +|\t", i):
if newline != "":
newline = " " + newline.strip() + "\n"
else:
newline = " " + i.strip() + "\n"
if newline != "":
outfile.write(newline)
else:
outfile.write(i)
outfile.close()
if __name__ == "__main__":
sys.exit(main())
| 887b63d3df9ae238cf40a10d174fee513c64d324 | [
"Markdown",
"Python"
] | 2 | Markdown | mcdenbo/opendj-utils | 49da425181bb449e3ecb46e62522445f83ecd978 | 93f63075cf3bc6ac1d8b5bf655b9a63ea1e23d1f | |
refs/heads/master | <repo_name>animesiki/MEAN_Study<file_sep>/WebPortalDemo/routes/uploadFile.js
/**
* Created by JIANGWI on 5/22/2015.
*/
var fs = require('fs');
exports.uploadFile = function (req, res) {
var file = req.files.file;
var path = file.path;
var fileName = file.originalname;
fs.readFile(path, function (error, data) {
if (error) {
console.log(error);
}
res.send({'content': data, 'xsltName': fileName});
});
};<file_sep>/WebPortalDemo/routes/datasource.js
/**
* Created by williamjiang on 2015/5/6.
*/
var DataSourceModel = require('../models/DataSourceModel');
var DataSource = DataSourceModel.DataSource;
exports.createDS = function (req, res) {
var reqDataSource = req.body;
reqDataSource.create_time = Date.now();
if (req.body.channelType == 'FTPInbound') {
reqDataSource.channel = req.body.ftpInboundChannel;
reqDataSource.channel.channel_type='FTPInbound';
}
if (req.body.channelType == 'FTPOutbound') {
reqDataSource.channel = req.body.ftpOutboundChannel;
reqDataSource.channel.channel_type='FTPOutbound';
}
if (req.body.channelType == 'EmailInbound') {
reqDataSource.channel =req.body.emailInboundChannel;
reqDataSource.channel.channel_type='EmailInbound';
}
if (req.body.channelType == 'EmailOutbound') {
reqDataSource.channel = req.body.emailOutboundChannel;
reqDataSource.channel.channel_type='EmailOutbound';
}
DataSource.create(reqDataSource,function (err, docu) {
if (err) {
console.log(err);
} else {
console.log('datasource:' + docu);
res.json(docu);
}
});
};
exports.getAllDS = function (req, res) {
DataSource.find({},{'transformer.xslt':0},function (error, docs) {
if (error) {
console.log(error);
res.send(error);
}
if (docs) {
res.json(docs);
}
});
};
exports.getDSBySearchCon = function (req, res) {
console.log(req.query.app_name);
console.log(req.query.type);
var con = {
app_name: req.query.app_name
};
if (req.query.type) {
con.type = req.query.type
}
;
DataSource.find(con,{'transformer.xslt':0},function (error, docs) {
if (error) {
console.log(error);
res.send(error);
}
if (docs) {
console.log(docs);
res.json(docs);
}
});
};
exports.getDSById = function (req, res) {
var reqId = req.query.id;
console.log('reqId:' + reqId);
DataSource.find({'_id': reqId},{'transformer.xslt':0},function (error, doc) {
if (error) {
console.log(error);
res.send(error);
}
if (doc) {
console.log('getDSById:' + doc);
res.json(doc);
}
});
};
exports.removeDS = function (req, res) {
var id = req.body._id;
console.log("remove id:" + id);
DataSource.remove({_id: id}, function (err) {
if (err) {
console.log(err);
} else {
console.log("remove datasource success");
res.send("remove success");
}
});
};
exports.updateDS = function (req, res) {
var reqDataSource=req.body;
var id = req.body._id;
if (req.body.channelType == "FTPInbound") {
reqDataSource.channel=req.body.ftpInboundChannel;
reqDataSource.channel.channel_type='FTPInbound';
}
if (req.body.channelType == "FTPOutbound") {
reqDataSource.channel=req.body.ftpOutboundChannel;
reqDataSource.channel.channel_type='FTPOutbound';
}
if (req.body.channelType == "EmailInbound") {
reqDataSource.channel=req.body.emailInboundChannel;
reqDataSource.channel.channel_type='EmailInbound';
}
if (req.body.channelType == "EmailOutbound") {
reqDataSource.channel=req.body.emailOutboundChannel;
reqDataSource.channel.channel_type='EmailOutbound';
}
reqDataSource.update_time=Date.now();
DataSource.findByIdAndUpdate(id, {$set: reqDataSource}, function (err, doc) {
if (err) {
console.log(err);
} else {
console.log("update datasource success");
res.json(doc);
}
});
};
exports.getDataSourceCount = function (req, res) {
DataSource.count(function (err, count) {
if (err) {
console.log(err);
}
res.send({'count': count});
})
};
<file_sep>/WebPortalDemo/models/DataSourceModel.js
/**
* Created by williamjiang on 2015/5/6.
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var DataSourceSchema = new Schema({
app_name: {type: String,required:true},
owner_specific_key: {type: String},
type: {type: String},
is_inbound: {type: Boolean},
is_internal: {type: Boolean},
is_route: {type: Boolean},
create_time: {type: Date},
update_time: {type: Date},
adapter: {
adapter_type: {type: String},
with_col_header: {type: Boolean},
is_multi_sheets: {type: Boolean}
},
channel: {
host: {type: String},
user: {type: String},
pass: {type: String},
channel_type:{type:String},
read_pattern: {type: String},
write_pattern: {type: String},
dir_path: {type: String},
cron_expression: {type: String},
from: {type: String},
subject: {type: String},
send_to: {type: String},
subject_template: {type: String},
email_body_template: {type: String}
},
transformer: {
xslt_name: {type: String},
need_split: {type: Boolean},
split_num: {type: Number},
node_path: {type: String},
xslt: {type: Buffer}
}
}
);
var DataSource = mongoose.model('DataSource', DataSourceSchema);
// entity method,use in entity layer
//DataSourceSchema.methods.findSimilarTypes=function(cb){
// return DataSource.find({type:this.type},cb);
//};
////static method, use in model layer
//DataSource.methods.findDataSourceByKey=function(key,cb){
// this.find({owner_specific_key:key},cb);
//};
//virtual attribute
DataSourceSchema.virtual('code').get(function(){
return this.app_name+'/'+this.owner_specific_key;
});
DataSourceSchema.virtual('code').set(function(code){
var split=code.split('/');
this.app_name=split[0];
this.owner_specific_key=split[1];
});
exports.DataSource = DataSource;
<file_sep>/WebPortalDemo/app/app.js
/**
* Created by williamjiang on 2015/4/22.
*/
// Declare app level module which depends on views, and components
var reportApp = angular.module('webPortalApp', [
'ngRoute',
'webPortalApp.mainController',
'webPortalApp.dataSourceController',
'webPortalApp.services',
'webPortalApp.filters',
'webPortalApp.directives'
]);
reportApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'home'
})
.when('/DataSourceMgn', {
templateUrl: 'ds_manage.html',
controller: 'dataSourceMng'
})
.otherwise({
redirectTo: '/home'
});
}]);
<file_sep>/WebPortalDemo/routes/dmtpApp.js
/**
* Created by williamjiang on 2015/5/6.
*/
var AppModel = require('../models/AppModel');
var App = AppModel.App;
var Type = AppModel.Type;
exports.getAllApps = function (req, res) {
App.find(function (error, docs) {
if (error) {
console.log(error);
res.send(error);
}
if (docs) {
console.log(docs);
console.log(docs[0].types);
res.json(docs);
}
});
};
exports.getAppCount = function (req, res) {
App.count(function (err, count) {
if (err) {
console.log(err);
}
res.send({'count': count});
})
};<file_sep>/MeanLoginDemo/routes/user.js
/**
* Created by williamjiang on 2015/5/6.
*/
var path = require('path');
var UsersModel=require('../model/UsersModel');
var User=UsersModel.User;
exports.loginCheck=function(req,res){
console.log("request:"+req);
console.log("request body:"+req.body);
var name=req.body.name;
var password=req.body.password;
console.log(name);
User.findOne({name:name,password:password},function(error,doc){
if(error){
console.log(error);
res.send(error);
}
if(doc){
console.log(doc);
res.send({redirect: '/index',user:doc});
}
});
};
exports.allUser=function(req,res){
User.find({},{name:1,password:1,email:1,_id:1},function(err,result){
if(err){
console.log(err);
res.send(err);
}
console.log(result);
res.json(result);
});
};
exports.href=function(req,res){
var ident=req.body.ident;
console.log(ident);
if(ident=="signup"){
res.send({redirect:"/signup"});
}else{
res.send({redirect:"/login"});
}
};
exports.nameCheck=function(req,res){
console.log("request:"+req);
console.log("request body:"+req.body);
var name=req.body.name;
console.log(name);
User.findOne({name:name},function(error,doc){
if(error){
console.log(error);
res.send(error);
}
console.log(doc);
if(doc){
res.send({hint:"name exist"});
}else{
res.send({hint:"correct"});
}
});
};
exports.SignUp=function(req,res){
console.log("request:"+req);
console.log("request body:"+req.body);
var name=req.body.name;
var password=<PASSWORD>;
var email=req.body.email;
console.log(name);
User.create({name:name,password:<PASSWORD>,email:email},function(error,doc){
if(error){
console.log(error);
res.send(error);
}
if(doc){
console.log(doc);
res.send({hint:"Sign up success, pls login",redirect:"/login"});
}
});
};<file_sep>/WebPortalDemo/routes/routes.js
/**
* Created by williamjiang on 2015/5/6.
*/
var user = require('./user');
var datasource = require('./datasource');
var dmtpApp = require('./dmtpApp');
var upload = require('./uploadFile');
var download = require('./downloadFile');
module.exports = function (app) {
//app.get('/login',user.showLoginPage);
app.post('/loginCheck', user.loginCheck);
app.get('/logOut', user.logOut);
app.get('/getAllApps', dmtpApp.getAllApps);
app.get('/getAppCount', dmtpApp.getAppCount);
app.get('/getAllDS', datasource.getAllDS);
app.get('/searchDSByCon', datasource.getDSBySearchCon);
app.post('/createDS', datasource.createDS);
app.post('/updateDS', datasource.updateDS);
app.get('/getDSById', datasource.getDSById);
app.post('/removeDS', datasource.removeDS);
app.get('/getDataSourceCount', datasource.getDataSourceCount);
app.post('/uploadFile', upload.uploadFile);
app.get('/downloadFile', download.downloadFile);
}
<file_sep>/WebPortalDemo/models/UsersModel.js
/**
* Created by williamjiang on 2015/5/6.
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: {type: String},
password: {type: String},
email: {type: String},
age: {type: Number,min:18,max:70}
});
exports.User = mongoose.model('User', UserSchema);<file_sep>/WebPortalDemo/models/AppModel.js
/**
* Created by williamjiang on 2015/5/6.
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var AppSchema = new Schema({
name: {type: String, unique: true},
types: [String]
});
var App = mongoose.model('App', AppSchema);
exports.App = App;
<file_sep>/WebPortalDemo/routes/user.js
/**
* Created by williamjiang on 2015/5/6.
*/
var path = require('path');
var UsersModel = require('../models/UsersModel');
var User = UsersModel.User;
exports.showLoginPage = function (req, res) {
var html = path.normalize(__dirname + '/../app/login.html');
res.sendfile(html);
};
exports.loginCheck = function (req, res) {
console.log("request:" + req);
console.log("request body:" + req.body);
var name = req.body.name;
var password = req.body.password;
console.log(name);
User.findOne({name: name, password: <PASSWORD>}, function (error, doc) {
if (error) {
console.log(error);
res.send(error);
}
if (doc) {
console.log(doc);
req.session.user_id = doc._id;
res.json(doc);
}
});
};
exports.logOut = function (req, res) {
req.session.destroy(function (err) {
// cannot access session here
console.log("log out error" + err);
});
res.send('log out success');
};
<file_sep>/WebPortalDemo/server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var multer = require('multer');
var path = require('path');
var routes = require('./routes/routes');
var DMTPAPP = require('./models/AppModel');
var session = require('express-session');
var app = express();
var db = mongoose.connect('mongodb://localhost:27017/meandb');
db.connection.on("error", function (error) {
console.log("connect failed:" + error);
});
db.connection.on("open", function () {
console.log("connect success");
});
app.set('views', __dirname + '/app');
app.set('view engine', 'html');
app.use(express.static(require('path').join(__dirname, 'app')));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(multer());
app.engine('.html', require('ejs').__express);
// create application/json parser
var jsonParser = bodyParser.json();
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({extended: false});
//add session
app.use(session({
//genid: function(req) {
// return genuuid() // use UUIDs for session IDs
//},
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.use('/index', function (req, res, next) {
if (req.session.user_id) {
next();
} else {
res.redirect('/login');
}
});
routes(app);
//Definition model
var App = DMTPAPP.App;
var App1 = new App({
name: 'DCS',
types: ['LOK', 'IGH']
});
App1.types.push('CGO','RPL');
App1.save(function (error, doc) {
if (error) {
console.log("error :" + error);
} else {
console.log(doc);
}
});
app.get('/index', function (req, res) {
res.render('index');
});
app.get('/login', function (req, res) {
res.render('login');
});
var server = app.listen(8800, function () {
console.log('listening on port %d', server.address().port);
});
<file_sep>/WebPortalDemo/routes/downloadFile.js
/**
* Created by JIANGWI on 5/22/2015.
*/
var fs = require('fs');
var DataSourceModel = require('../models/DataSourceModel');
var DataSource = DataSourceModel.DataSource;
var path = require('path');
exports.downloadFile = function (req, res) {
var dataSourceId = req.query.id;
var dataSource;
//find datasource transformer and xslt
DataSource.findOne({_id: dataSourceId}, function (error, doc) {
if (error) {
console.log(error);
}
dataSource = doc;
var xsltBuffer =dataSource.transformer.xslt;
var xsltName =dataSource.transformer.xslt_name;
res.attachment(xsltName);
res.write(xsltBuffer);
res.end();
});
}; | 543bb7b6e22a31e1c1fab9263371fca0e6e4e615 | [
"JavaScript"
] | 12 | JavaScript | animesiki/MEAN_Study | f3d112811272542174b01c13b042d6ed3469b63f | 171f417b786de054fc9ebbe94497e86e55d18897 | |
refs/heads/master | <repo_name>nizulzaim/pcpart<file_sep>/packages/vue-component-dev-client/package.js
Package.describe({
name: 'akryum:vue-component-dev-client',
version: '0.2.11',
summary: 'Hot-reloading client for vue components',
git: 'https://github.com/Akryum/meteor-vue-component',
documentation: 'README.md',
debugOnly: true
});
Package.onUse(function(api) {
api.versionsFrom('1.3.3');
api.use('ecmascript');
api.use('reload');
api.use('autoupdate');
api.use('reactive-var');
api.mainModule('client/dev-client.js', 'client');
});
Npm.depends({
'socket.io-client': '1.4.6'
});
<file_sep>/imports/model/Guide.js
import {Class} from 'meteor/jagi:astronomy';
import {Meteor} from "meteor/meteor";
import {Product} from "./Product";
import {GuideLove} from "./GuideLove";
import {GuideComment} from "./GuideComment";
import {User} from "./User";
import {Manufacturer} from "./Manufacturer";
import {Images} from "./Images";
import {Seller} from "./Seller";
export const Guide = Class.create({
name: "Guide",
collection: new Mongo.Collection("guides"),
fields: {
title: {type: String},
author: {type: String, optional: true},
GeneralDescription: {type: String},
CpuAndCoolerDescription: {type: String, optional: true},
MotherboardDescription: {type: String, optional: true},
MemoryDescription: {type: String, optional: true},
StorageDescription: {type: String, optional: true},
VideocardDescription: {type: String, optional: true},
PSUDescription: {type: String, optional: true},
CaseDescription: {type: String, optional: true},
element: [String],
love: {
type: [String],
default: [],
optional : true,
},
randomSeed: {
type: Number,
optional: true,
}
},
behaviors: {
timestamp: {
hasCreatedField: true,
createdFieldName: 'createdAt',
hasUpdatedField: true,
updatedFieldName: 'updatedAt'
},
softremove: {
removedFieldName: 'removed',
hasRemovedAtField: true,
removedAtFieldName: 'removedAt'
}
},
helpers: {
products() {
return Product.find({_id: {$in: this.element}});
},
authorUser() {
return User.findOne(this.author);
},
image() {
let p = null;
if (this.products() && this.products().count() > 0) {
p = this.products();
let res = [];
p.forEach((item) => {
if (item.getImageLink()) res.push(item.getImageLink());
});
return res[0];
}
return "";
}
}
});
if (Meteor.isServer) {
Guide.extend({
meteorMethods: {
create(obj, element) {
let el = element.map((item)=> item.id);
obj.element = el;
obj.author = Meteor.userId();
this.set(obj, {merge: true, cast: true});
return this.save();
},
love() {
let indexOf = this.love.indexOf(Meteor.userId());
if (indexOf > -1) {
this.love.splice(indexOf,1);
} else {
this.love.push(Meteor.userId());
}
return this.save();
},
removeGuide() {
return this.softRemove();
}
},
events: {
afterInit(e) {
}
}
});
Meteor.publishComposite('guides', function(id) {
return {
find: function() {
if (id) {
return Guide.find(id);
}
return Guide.find();
},
children: [
{
find(guide) {
return Product.find({_id: {$in: guide.element}});
},
children:[
{
find: function(p) {
return Manufacturer.find(p.manufacturerId);
}
},
{
find: function(p) {
return Images.find(p.imageId).cursor;
}
},
{
find: function(p) {
return Seller.find({productId: p._id});
}
},
],
}, {
find(guide) {
return GuideLove.find({guideId: guide._id, userId: this.userId});
},
},
{
find(guide) {
return User.find(guide.author);
},
children:[
{
find(user) {
if (user.profile.imageId) {
return Images.find(user.profile.imageId).cursor;
}
return undefined;
}
}
],
},
]
};
});
Meteor.publishComposite('guideDetails', function(id) {
return {
find: function() {
if (id) {
return Guide.find(id);
}
return Guide.find();
},
children: [
{
find(guide) {
return Product.find({_id: {$in: guide.element}});
},
children:[
{
find: function(p) {
return Manufacturer.find(p.manufacturerId);
}
},
{
find: function(p) {
return Images.find(p.imageId).cursor;
}
},
{
find: function(p) {
return Seller.find({productId: p._id});
}
},
],
}, {
find(guide) {
return GuideLove.find({guideId: guide._id, userId: this.userId});
},
},
{
find(guide) {
return User.find(guide.author);
},
children:[
{
find(user) {
if (user.profile.imageId) {
return Images.find(user.profile.imageId).cursor;
}
return undefined;
}
}
],
},
{
find(guide) {
return GuideComment.find({guideId: guide._id});
},
children: [
{
find(gc) {
return User.find(gc.userId);
},
children:[
{
find(user) {
if (user.profile.imageId) {
return Images.find(user.profile.imageId).cursor;
}
return undefined;
}
}
],
}
]
}
]
};
});
}<file_sep>/imports/model/Product.js
import {
Class
} from 'meteor/jagi:astronomy';
import {
Meteor
} from "meteor/meteor";
import {Manufacturer} from "./Manufacturer";
import {Images} from "./Images";
import {Seller} from "./Seller";
export const Product = Class.create({
name: "Product",
typeField: 'type',
collection: new Mongo.Collection("products"),
fields: {
name: {type: String},
manufacturerId: String,
partNo: {type: String},
imageId: {type: String},
// model: Number,
},
behaviors: {
timestamp: {
hasCreatedField: true,
createdFieldName: 'createdAt',
hasUpdatedField: true,
updatedFieldName: 'updatedAt'
},
softremove: {
removedFieldName: 'removed',
hasRemovedAtField: true,
removedAtFieldName: 'removedAt'
}
},
helpers: {
manufacturer() {
return Manufacturer.findOne(this.manufacturerId);
},
getImageLink() {
let image = Images.findOne(this.imageId);
if (!image) {
return "";
}
return image._downloadRoute + "/images/" + image._id + "/original/" + image._id + "." + image.extension;
},
lowestPrice() {
let sellers = Seller.find({productId: this._id});
if (sellers && sellers.count() !== 0) {
let s = sellers.fetch();
s.sort((a, b) => {
return a.price - b.price;
})
return s[0].price;
}
return null;
}
}
});
export const Cpu = Product.inherit({
name: 'Cpu',
fields: {
dataWidth: Number,
socket: String,
operatingFrequency: String,
maxTurboFrequency: String,
cores: Number,
l1Cache: String,
l2Cache: String,
l3Cache: String,
lithography: Number,
thermalDesignPower: Number,
includeCpuCooler: Boolean,
hyperThreading: Boolean,
maximumSupportedMemory: Number,
integratedGraphics: String,
}
});
export const Cpucooler = Product.inherit({
name: 'Cpucooler',
fields: {
socket: String,
liquidCooled: Boolean,
bearingType: String,
minNoiseLevel: Number,
maxNoiseLevel: Number,
minFan: Number,
maxFan: Number,
height: Number,
},
helpers: {
noiseLevel() {
if (this.minNoiseLevel) {
return this.minNoiseLevel + " - " + this.maxNoiseLevel + " dB";
}
return this.maxNoiseLevel + " dB";
},
fanSpeed() {
if (this.minFan) {
return this.minFan + " - " + this.maxFan + " rpm";
}
return this.maxFan + " rpm";
}
}
});
export const Motherboard = Product.inherit({
name: 'Motherboard',
fields: {
formFactor: String,
socket: String,
chipset: String,
memorySlot: String,
memoryType: String,
maximumSupportedMemory: Number,
raidSupport: Boolean,
onboardVideo: Boolean,
crossFireSupport: Boolean,
sliSupport: String,
sata6gb: Number,
sataExpress: Number,
onboardEthernet: String,
onboardUsb3: Boolean,
}
});
export const Memory = Product.inherit({
name: 'Memory',
fields: {
memoryType: String,
speed: String,
size: String,
pricePerGb: Number,
casLatency: Number,
timing: String,
voltage: String,
heatSpreader: Boolean,
ecc: Boolean,
registered: Boolean,
color: String,
}
});
export const Storage = Product.inherit({
name: 'Storage',
fields: {
capacity: Number,
interface: String,
cache: String,
rpm: Number,
formFactor: String,
}
});
export const Gpu = Product.inherit({
name: 'Gpu',
fields: {
interface: String,
chipset: String,
memorySize: Number,
memoryType: String,
coreClock: Number,
boostClock: Number,
tdp: Number,
fan: Boolean,
sliSupport: Boolean,
crossFireSupport: Boolean,
sizeLength: Number,
dviDualLink: Number,
hdmi: Number,
vga: Number,
displayPort: Number,
}
});
export const Psu = Product.inherit({
name: 'Psu',
fields: {
psuType: String,
wattage: Number,
fans: Number,
modular: String,
output: String,
efficiencyCert: String,
pcieConnector: Number,
}
});
export const Case = Product.inherit({
name: 'Case',
fields: {
caseType: String,
color: String,
includePowerSupply: Boolean,
external35Bays: Number,
internal35Bays: Number,
internal25Bays: Number,
external25Bays: Number,
internal525Bays: Number,
external525Bays: Number,
motherboardCompatibility: String,
frontUsb3ports: Boolean,
maximumVideoCardLength: Number,
width: Number,
sizeLength: Number,
height: Number,
},
helpers: {
includePowerSupplyString() {
return this.includePowerSupply ? "Yes": "No";
},
dimensions() {
return this.width + "mm x " + this.sizeLength + "mm x " + this.height + "mm";
}
}
});
if (Meteor.isServer) {
Product.extend({
meteorMethods: {
create(general, specific) {
this.set(general, {
merge: true,
cast: true,
});
this.set(specific, {
merge: true,
cast: true,
});
return this.save();
},
update(profileObj) {
this.set({
profile: profileObj,
}, { merge: true });
console.log(this.save());
}
}
});
let children = [
{
find: function(p) {
return Manufacturer.find(p.manufacturerId);
}
},
{
find: function(p) {
return Images.find(p.imageId).cursor;
}
},
{
find: function(p) {
return Seller.find({productId: p._id});
}
},
];
Meteor.publishComposite('products', function(type ="", id="") {
return {
find: function() {
if (id) {
return Product.find(id);
}
if (type) {
return Product.find({type});
}
return Product.find();
},
children,
};
});
Meteor.publishComposite('productsByArrayOfID', function(arrayId) {
return {
find: function() {
return Product.find({_id: {$in: arrayId}});
},
children,
};
});
Meteor.publishComposite('productsSearch', function(type="", search = "",limit = 10) {
return {
find: function() {
if (search) {
return Product.find({type, name: {'$regex' : search, '$options' : 'i'}}, {limit});
}
return Product.find({type}, {limit});
},
children,
};
});
}<file_sep>/imports/model/Manufacturer.js
import {
Class
} from 'meteor/jagi:astronomy';
import {
Meteor
} from "meteor/meteor";
export const Manufacturer = Class.create({
name: "Manufacturer",
collection: new Mongo.Collection("manufacturers"),
fields: {
name: String,
},
behaviors: {
timestamp: {
hasCreatedField: true,
createdFieldName: 'createdAt',
hasUpdatedField: true,
updatedFieldName: 'updatedAt'
},
softremove: {
removedFieldName: 'removed',
hasRemovedAtField: true,
removedAtFieldName: 'removedAt'
}
},
});
if (Meteor.isServer) {
Manufacturer.extend({
meteorMethods: {
create(name) {
this.name = name;
return this.save();
},
}
});
Meteor.publishComposite('manufacturers', function(refresh = 0) {
return {
find: function() {
return Manufacturer.find();
},
};
});
if (!Manufacturer.findOne()) {
let m = new Manufacturer();
m.name = "Intel";
m.save();
m = new Manufacturer();
m.name = "AMD";
m.save();
m = new Manufacturer();
m.name = "Cooler Master";
m.save();
}
}<file_sep>/imports/model/Seller.js
import {
Class
} from 'meteor/jagi:astronomy';
import {
Meteor
} from "meteor/meteor";
export const Seller = Class.create({
name: "Seller",
collection: new Mongo.Collection("sellers"),
fields: {
userId: String,
productId: String,
link: String,
websiteType: Number,
price: Number,
},
behaviors: {
timestamp: {
hasCreatedField: true,
createdFieldName: 'createdAt',
hasUpdatedField: true,
updatedFieldName: 'updatedAt'
},
softremove: {
removedFieldName: 'removed',
hasRemovedAtField: true,
removedAtFieldName: 'removedAt'
}
},
helpers: {
websiteName() {
let res = "";
res = this.websiteType === 0? "Amazon": res;
res = this.websiteType === 1? "Lazada": res;
res = this.websiteType === 2? "Lelong": res;
res = this.websiteType === 3? "IP Mart": res;
return res;
}
}
});
if (Meteor.isServer) {
const possibleHostName = [
"amazon.com",
"lazada.com.my",
];
Seller.extend({
meteorMethods: {
create(obj) {
this.set(obj, {
merge: true,
cast: true,
});
let extractHostname = function (url) {
var hostname;
if (url.indexOf("://") > -1) {
hostname = url.split('/')[2];
}
else {
hostname = url.split('/')[0];
}
hostname = hostname.split(':')[0];
return hostname;
};
console.log(extractHostname(obj.link));
this.userId = Meteor.userId();
return this.save();
},
}
});
Meteor.publishComposite('sellers', function(productId = "") {
return {
find: function() {
return Seller.find({productId});
},
};
});
}<file_sep>/client/routes/index.routes.js
import {IndexNavigation, IndexToolbar} from "/imports/client/template";
import IndexPage from '/imports/client/views/public/Index.vue';
import Product from '/imports/client/views/public/Product.vue';
import ProductDetails from '/imports/client/views/public/ProductDetails.vue';
import ProductCompare from '/imports/client/views/public/ProductCompare.vue';
import Guide from '/imports/client/views/public/Guide.vue';
import Guides from '/imports/client/views/public/Guides.vue';
let routesParent = "";
export default [{
path: `${routesParent}/`,
name: "Index",
meta: { fixToolbar: true, pageTitle: "PC Part" },
components: {
default: IndexPage,
toolbar: IndexToolbar,
navigation: IndexNavigation,
}
},{
path: `${routesParent}/product/compare`,
name: "ProductCompare",
meta: { fixToolbar: true,depth: 1, pageTitle: "Product Comparison" },
components: {
default: ProductCompare,
toolbar: IndexToolbar,
navigation: IndexNavigation,
}
}, {
path: `${routesParent}/product/:type`,
name: "Products",
meta: { fixToolbar: true,depth: 1, pageTitle: "Parts" },
components: {
default: Product,
toolbar: IndexToolbar,
navigation: IndexNavigation,
}
}, {
path: `${routesParent}/product/details/:id`,
name: "ProductDetails",
meta: { fixToolbar: true,depth: 1, pageTitle: "Product Details" },
components: {
default: ProductDetails,
toolbar: IndexToolbar,
navigation: IndexNavigation,
}
},{
path: `${routesParent}/guides/:id`,
name: "Guide",
meta: { fixToolbar: true,depth: 1, pageTitle: "Guide" },
components: {
default: Guide,
toolbar: IndexToolbar,
navigation: IndexNavigation,
}
},{
path: `${routesParent}/guides/`,
name: "Guides",
meta: { fixToolbar: true,depth: 1, pageTitle: "Guides List" },
components: {
default: Guides,
toolbar: IndexToolbar,
navigation: IndexNavigation,
}
},];
<file_sep>/imports/client/template.js
export IndexToolbar from '/imports/client/views/templates/toolbar/IndexToolbar.vue';
export IndexNavigation from '/imports/client/views/templates/navigation/IndexNavigation.vue';<file_sep>/client/routes/admin.routes.js
import {IndexNavigation, IndexToolbar} from "/imports/client/template";
import ProductAdd from '/imports/client/views/public/dashboard/admin/ProductAdd.vue';
let routesParent = "/dashboard";
export default [{
path: `${routesParent}/product/add`,
name: "ProductAdd",
meta: { fixToolbar: true, depth: 1, pageTitle: "Add Product" },
components: {
default: ProductAdd,
toolbar: IndexToolbar,
navigation: IndexNavigation,
}
}, ];<file_sep>/imports/model/User.js
import {
Class
} from 'meteor/jagi:astronomy';
import {
Meteor
} from "meteor/meteor";
import {Images} from '/imports/model/Images.js';
export const UserProfile = Class.create({
name: 'UserProfile',
fields: {
firstname: String,
lastname: String,
email: String,
imageId: {type: String, optional: true},
userType: {
type: [Number],
default: [2],
},
}
});
export const User = Class.create({
name: "User",
collection: Meteor.users,
fields: {
username: String,
profile: UserProfile,
},
behaviors: {
timestamp: {
hasCreatedField: true,
createdFieldName: 'createdAt',
hasUpdatedField: true,
updatedFieldName: 'updatedAt'
},
softremove: {
removedFieldName: 'removed',
hasRemovedAtField: true,
removedAtFieldName: 'removedAt'
}
},
helpers: {
isAdmin() {
return this.profile.userType.indexOf(0) > -1;
},
isSaler() {
return this.profile.userType.indexOf(1) > -1;
},
isCustomer() {
return this.profile.userType.indexOf(2) > -1;
},
image() {
if(!this.profile.imageId) {
return null;
}
return Images.findOne(this.profile.imageId);
}
}
});
if (Meteor.isServer) {
User.extend({
meteorMethods: {
create(userObj, profileObj = {}) {
userObj.profile = profileObj;
Accounts.createUser(userObj);
},
update(username,profileObj) {
this.username = username;
this.set({
profile: profileObj,
}, { merge: true });
return this.save();
}
}
});
Meteor.publishComposite('loginUser', function(refresh = 0) {
return {
find: function() {
return User.find(this.userId);
},
children:[
{
find(user) {
if (user.profile.imageId) {
return Images.find(user.profile.imageId).cursor;
}
return undefined;
}
}
],
};
});
if (!User.findOne()) {
let user = new User();
user.create({
username: "admin",
password: "n",
}, {
firstname: "Admin",
lastname: "Account",
userType: [0],
email: "<EMAIL>",
});
}
}<file_sep>/packages/vue-component-dev-client/client/dev-client.js
import "./buffer";
import Vue from 'vue'
import { Reload } from 'meteor/reload'
import { Meteor } from 'meteor/meteor'
import { Tracker } from 'meteor/tracker'
import { Autoupdate } from 'meteor/autoupdate'
import { ReactiveVar } from 'meteor/reactive-var'
import VueHot1 from './vue-hot'
import VueHot2 from './vue2-hot'
let VueHotReloadApi
const vueVersion = parseInt(Vue.version.charAt(0))
console.log('[HMR] Vue', Vue.version)
if (vueVersion === 1) {
VueHotReloadApi = VueHot1
} else if (vueVersion === 2) {
VueHotReloadApi = VueHot2
}
Vue.use(VueHotReloadApi)
// Hot reload API
window.__vue_hot__ = VueHotReloadApi
// Records initialized before vue hot reload api
if (window.__vue_hot_pending__) {
for (let hash in window.__vue_hot_pending__) {
VueHotReloadApi.createRecord(hash, window.__vue_hot_pending__[hash])
}
}
// Reload override
var _suppressNextReload = false, _deferReload = 0
var _reload = Reload._reload
Reload._reload = function (options) {
// Disable original reload for autoupdate package
if (Reload._reload.caller.name !== '' && Reload._reload.caller.name !== 'checkNewVersionDocument') {
_reload(options)
}
}
// Custom reload method
function reload (options) {
console.log('[HMR] Reload request received')
if (_deferReload !== 0) {
setTimeout(_reload, _deferReload)
console.log(`[HMR] Client reload defered, will reload in ${_deferReload} ms`)
} else if (_suppressNextReload) {
console.log(`[HMR] Client version changed, you may need to reload the page`)
} else {
console.log(`[HMR] Reloading app...`)
_reload.call(Reload, options)
}
_suppressNextReload = false
_deferReload = 0
}
// Reimplement client version check from autoupdate package
var autoupdateVersion = __meteor_runtime_config__.autoupdateVersion || `unknown`
var ClientVersions = Autoupdate._ClientVersions
if (ClientVersions) {
function checkNewVersionDocument (doc) {
if (doc._id === 'version' && doc.version !== autoupdateVersion) {
reload()
}
}
ClientVersions.find().observe({
added: checkNewVersionDocument,
changed: checkNewVersionDocument,
})
} else {
console.log('[HMR] ClientVersions collection is not available, the app may full reload.')
}
// Hack https://github.com/socketio/socket.io-client/issues/961
import Response from 'meteor-node-stubs/node_modules/http-browserify/lib/response'
if (!Response.prototype.setEncoding) {
Response.prototype.setEncoding = function (encoding) {
// do nothing
}
}
Meteor.startup(function () {
// Dev client
let devUrl = __meteor_runtime_config__.VUE_DEV_SERVER_URL
console.log('[HMR] Dev client URL', devUrl)
// NOTE: Socket lib don't allow mix HTTP and HTTPS servers URLs on client!
let _socket = require('socket.io-client')(devUrl)
window.__dev_client__ = _socket
_socket.on('connect', function () {
console.log('[HMR] Dev client connected')
})
_socket.on('disconnect', function () {
console.log('[HMR] Dev client disconnected')
})
// JS
_socket.on('js', Meteor.bindEnvironment(function ({hash, js, template, path}) {
let args = ['vue']
let regResult
let error = null
while (regResult = jsImportsReg.exec(js)) {
args.push(regResult[2])
}
args.push(function (require, exports, module) {
try {
eval(js)
} catch (e) {
console.error(e)
error = e
}
})
let id = `${path + Math.round(new Date().getTime())}.js`
const files = id.split('/')
const fileObj = {}
let currentObj = fileObj
const indexMax = files.length - 1
files.forEach((file, index) => {
if (index === indexMax) {
currentObj[file] = args
} else {
currentObj = currentObj[file] = {}
}
})
let require = meteorInstall(fileObj)
let result = require('./' + id)
let needsReload = false
if (!error) {
console.log('[HMR] Reloading ' + path)
if (!result.default.render && !template) {
error = true
}
if (!error) {
try {
if (vueVersion === 1) {
needsReload = VueHotReloadApi.update(hash, result.default, template)
} else if (vueVersion === 2) {
needsReload = VueHotReloadApi.reload(hash, result.default, template)
}
} catch (e) {
console.error(e)
error = true
}
}
}
_suppressNextReload = !error && !needsReload
}))
// Template
_socket.on('render', function ({hash, template, path}) {
if (vueVersion === 2) {
console.log('[HMR] Rerendering ' + path)
let error = false
try {
var obj
eval(`obj = ${template};`)
// console.log(obj)
VueHotReloadApi.rerender(hash, obj)
} catch (e) {
error = true
}
_suppressNextReload = !error
}
})
// CSS
let _styleNodes = {}
_socket.on('css', function ({hash, css, path}) {
// console.log('css', hash, css.length);
let style = _styleNodes[hash]
if (!style) {
style = document.createElement('style')
style.setAttribute('data-v-source-file', path)
document.getElementsByTagName('head')[0].appendChild(style)
_styleNodes[hash] = style
}
style.textContent = css
})
// Locale
_socket.on('lang.updated', function ({lang, data}) {
Vue.locale(lang, data)
if (lang === Vue.config.lang) {
// Refresh
VueHotReloadApi.updateWatchers()
}
console.log(`[HMR] Updated locale ${lang}`)
_suppressNextReload = true
})
_socket.on('langs.updated', function ({langs}) {
_deferReload = 3000
})
// Message
_socket.on('message', function ({ type, message }) {
let func
if (type === 'error') {
func = console.error
} else if (type === 'warn') {
func = console.warn
} else {
func = console.log
}
func(`[HMR] ${message}`)
})
// Reg
const jsImportsReg = /module\.import\((['"])(.+?)\1/g
})
<file_sep>/imports/model/GuideComment.js
import {Class} from 'meteor/jagi:astronomy';
import {Meteor} from "meteor/meteor";
import {User} from "./User";
import {Images} from "./Images";
export const GuideComment = Class.create({
name: "GuideComment",
collection: new Mongo.Collection("guidecomments"),
fields: {
text: String,
guideId: String,
userId: String,
root: {
type: String,
optional: true,
default: 0,
}
},
behaviors: {
timestamp: {
hasCreatedField: true,
createdFieldName: 'createdAt',
hasUpdatedField: true,
updatedFieldName: 'updatedAt'
},
softremove: {
removedFieldName: 'removed',
hasRemovedAtField: true,
removedAtFieldName: 'removedAt'
}
},
helpers: {
user() {
return User.findOne(this.userId);
}
}
});
if (Meteor.isServer) {
GuideComment.extend({
meteorMethods: {
create(text, guideId) {
this.text = text;
this.guideId = guideId;
this.userId = Meteor.userId();
return this.save();
},
}
});
Meteor.publishComposite('guidecomments', function(id) {
return {
find: function() {
return GuideComment.find({guideId: id});
},
children: [
{
find(gc) {
return User.find(gc.userId);
},
children:[
{
find(user) {
if (user.profile.imageId) {
return Images.find(user.profile.imageId).cursor;
}
return undefined;
}
}
],
}
]
};
});
} | 808ff73412765919b918e3743d6158b1a8dc927b | [
"JavaScript"
] | 11 | JavaScript | nizulzaim/pcpart | 576505f0ffdc6c539185f7a9326d18ac82696ae7 | 0970aefd6947d9ae1c70f944b1433241b5038bd1 | |
refs/heads/main | <repo_name>prasanna815/Databasestoring<file_sep>/Databasestoring.py
from openpyxl import *
from tkinter import *
wb=load_workbook(r'C:/Users/91812/Desktop/data.xlsx')
sheet=wb.active
def excel():
sheet.column_dimensions['A'].width=30
sheet.column_dimensions['B'].width=30
sheet.column_dimensions['C'].width=50
sheet.cell(row=1,column=1).value="NAME"
sheet.cell(row=1,column=2).value="PHONE"
sheet.cell(row=1,column=3).value="EMAIL"
def clear():
name_field.delete(0,END)
phone_field.delete(0,END)
email_field.delete(0,END)
def insert():
if(name_field.get()=="" and phone_field.get()=="" and email_field.get()==""):
print("Please enter all fields")
else:
current_row=sheet.max_row
current_column=sheet.max_column
sheet.cell(row=current_row+1,column=1).value=name_field.get()
sheet.cell(row=current_row+1,column=2).value=phone_field.get()
sheet.cell(row=current_row+1,column=3).value=email_field.get()
wb.save(r'C:/Users/91812/Desktop/data.xlsx')
clear()
if __name__=="__main__":
root=Tk()
root.title("Register Here")
excel()
name=Label(root,text="Name")
name.grid(row=1,column=0)
phone=Label(root,text="Phone")
phone.grid(row=2,column=0)
email=Label(root,text="Email")
email.grid(row=3,column=0)
name_field=Entry(root)
name_field.grid(row=1,column=1,ipadx="100")
phone_field=Entry(root)
phone_field.grid(row=2,column=1,ipadx="100")
email_field=Entry(root)
email_field.grid(row=3,column=1,ipadx="100")
excel()
submit=Button(root,text="Submit",command=insert)
submit.grid(row=8,column=1)
root.mainloop()
| 26a21811dd8aa99337e7f34b144691bf64716fb3 | [
"Python"
] | 1 | Python | prasanna815/Databasestoring | dbdc1e36cb65998fdd29ffbcb32b3025c3d7618c | 50da41e6ba5df0525369ca6af5fa50304bcb06e3 | |
refs/heads/master | <file_sep>package com.philiproyer.audiobook.screens;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.philiproyer.audiobook.AudioBook;
import com.philiproyer.audiobook.tools.MetaData;
public class Player implements Screen {
private Stage stagePlayer;
private Table tablePlayer;
private Skin skinPlayer;
private Preferences prefs;
private MetaData meta;
private boolean pause;
private float volume;
private Music track;
private String path;
private String file;
public Player(String path) {
this.path = path; // Set the path that will be used for playing the requested file
this.track = Gdx.audio.newMusic(Gdx.files.internal(path)); // LibGDX music instance
this.file = this.path.substring(this.path.lastIndexOf("/") + 1).trim(); // Get the actual file name out of the path var
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stagePlayer.act(delta);
stagePlayer.draw();
}
@Override
public void resize(int width, int height) {
tablePlayer.invalidateHierarchy();
}
@Override
public void show() {
stagePlayer = new Stage();
Gdx.input.setInputProcessor(stagePlayer);
skinPlayer = new Skin(Gdx.files.internal("ui/menuSkin.json"), new TextureAtlas("ui/atlas.pack"));
tablePlayer = new Table(skinPlayer);
tablePlayer.setFillParent(true);
prefs = Gdx.app.getPreferences(AudioBook.TITLE); // Get the preferences
pause = true; // Default to pause
if(prefs.contains("volume")) { // Check if volume has been set previously
volume = prefs.getFloat("volume");
} else { // If not set the volume to something nice
volume = 0.7f;
prefs.putFloat("Volume", 0.7f);
prefs.flush();
}
meta = new MetaData(); // Instance of the TIKA metadata reader
meta.loadFile(this.path); // Load the current track and read the data
final TextButton play = new TextButton("Play", skinPlayer, "default");
play.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
play();
if(pause) {
play.setText("Play");
} else {
play.setText("Pause");
}
}
});
play.pad(5);
TextButton volumeUp = new TextButton("Volume +", skinPlayer, "default");
volumeUp.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
volumeUp();
}
});
volumeUp.pad(5);
TextButton volumeDown = new TextButton("Volume -", skinPlayer, "default");
volumeDown.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
volumeDown();
}
});
volumeDown.pad(5);
tablePlayer.add(new Label("AudioBook", skinPlayer, "big")).colspan(9).expandX().spaceBottom(100).row();
tablePlayer.add().uniformX().expandY().top().colspan(1);
tablePlayer.add(play).left().expandY().top().colspan(1);
tablePlayer.add().uniformX().expandY().top().colspan(7).row();
tablePlayer.add().uniformX().expandY().top().colspan(1);
tablePlayer.add(volumeUp).left().expandY().top().colspan(1);
tablePlayer.add().uniformX().expandY().top().colspan(7).row();
tablePlayer.add().uniformX().expandY().top().colspan(1);
tablePlayer.add(volumeDown).left().expandY().top().colspan(1);
tablePlayer.add().uniformX().expandY().top().colspan(7).row();
stagePlayer.addActor(tablePlayer);
}
@Override
public void hide() {
saveProgress();
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
System.out.println("The destroying is happening!");
}
// Volume buttons
private void volumeUp() {
if(this.volume < 1.0) {
this.volume += 0.05;
this.track.setVolume(volume);
System.out.println("Volume Increased " + volume);
}
}
private void volumeDown() {
if(this.volume > 0.0) {
this.volume -= 0.05;
this.track.setVolume(volume);
System.out.println("Volume Decreased " + volume);
}
}
private void play() {
if(!track.isPlaying()) {
this.pause = false;
this.track.setVolume(volume);
this.track.play();
if (Gdx.app.getType() == ApplicationType.Android) {
//this.track.setPosition(prefs.getFloat(this.file));
}
// Set location to last location
System.out.println("Play: " + this.track.getPosition());
} else {
this.pause = true;
this.track.pause();
saveProgress();
System.out.println("Pause: " + this.track.getPosition());
}
}
private void saveProgress() {
prefs.putFloat(this.file,this.track.getPosition()); // Store value of track in preferences
System.out.println("Progress saved for " + this.file);
}
}
<file_sep>app.version=1.0
app.id=com.philiproyer.audiobook.IOSLauncher
app.mainclass=com.philiproyer.audiobook.IOSLauncher
app.executable=IOSLauncher
app.build=1
app.name=Audiobook Player
<file_sep>An Open Source AudioBook Reader | f81fabe7df50ae35e180b47f02c481a2895723ab | [
"Markdown",
"Java",
"INI"
] | 3 | Java | littletinman/AudioBook | f8b0f8b54afd0d29b962c836b5b39a9b2f0c18b8 | 3536bdff6c6719a16e232528c52203e370c3bbd6 | |
refs/heads/master | <file_sep>import ChildSchema from "../models/schema/ChildSchema";
export const CreateChild = async (req, res) => {
try {
const { name, sex, father_name, mother_name, dob, district_id } = req.body;
const file = req.photoUrl;
let child = new ChildSchema({
name,
sex,
father_name,
mother_name,
dob,
district_id,
photo: file.url,
});
await child.save();
return res.status(200).json({
success: true,
status: 200,
data: child,
errors: [],
message: "Operation performed successfully",
});
} catch (error) {
console.log(error.message);
}
};
export const GetChildProfiles = async (req, res) => {
try {
let child = await ChildSchema.find().populate(
"district_id",
"district_name"
);
return res.status(200).json({
success: true,
status: 200,
data: child,
errors: [],
message: "Child Profile Details fetched successfully",
});
} catch (error) {
console.log(error.message);
}
};
<file_sep>import DistrictSchema from "../models/schema/DistrictSchema";
import StateSchema from "../models/schema/StateSchema";
export const CreateDistrict = async (req, res) => {
try {
const { district_name, state_name } = req.body;
let state = await StateSchema.findOne({ state_name: state_name });
if (!state) {
return res.status(400).json({
success: false,
status: 400,
data: {},
errors: [
{
value: state_name,
msg: "State is not exist",
param: "state Id",
location: "body",
},
],
});
}
let district = await DistrictSchema.findOne({
district_name: district_name,
});
if (district) {
return res.status(400).json({
success: false,
status: 400,
data: {},
errors: [
{
value: district_name,
msg: "District name already exist",
param: "district_name",
location: "body",
},
],
});
}
district = new DistrictSchema({
stateId: state._id,
district_name,
});
await district.save();
return res.status(200).json({
success: true,
status: 200,
data: {},
errors: [],
message: "Operation performed successfully",
});
} catch (error) {
console.log(error.message);
}
};
export const GetDistrict = async (req, res) => {
try {
const Id = req.query.state_id;
let district = await DistrictSchema.find(
{ stateId: Id },
{ _id: 1, district_name: 1 }
);
return res.status(200).json({
success: true,
status: 200,
data: district,
errors: [],
message: "District data fetched successfully",
});
} catch (error) {
console.log(error.message);
}
};
<file_sep>import { check, validationResult } from "express-validator";
export const validateRegister = [
check("name")
.not()
.isEmpty()
.withMessage("Name field cannot be empty")
.isAlphanumeric()
.withMessage("Name cannot contain special characters"),
check("email")
.not()
.isEmpty()
.withMessage("Email field cannot be empty")
.isEmail()
.withMessage("Not a valid email"),
check("password")
.not()
.isEmpty()
.withMessage("Password cannot be empty")
.isLength({ min: 8 })
.withMessage(
"Password must be 8<length, must contain 1 symbol, 1 uppercase, 1 lowercase and 1 number"
)
.matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d@$.!%*#?&]/)
.withMessage(
"Password must be 8<length, must contain 1 symbol, 1 uppercase, 1 lowercase and 1 number"
),
];
export const validateLogin = [
check("email")
.not()
.isEmpty()
.withMessage("Email cannot be empty")
.isEmail()
.withMessage("Not a valid email"),
check("password")
.not()
.isEmpty()
.withMessage("Password cannot be empty")
.isLength({ min: 8 })
.withMessage(
"Password must be 8<length, must contain 1 symbol, 1 uppercase, 1 lowercase and 1 number"
)
.matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d@$.!%*#?&]/)
.withMessage(
"Password must be 8<length, must contain 1 symbol, 1 uppercase, 1 lowercase and 1 number"
),
];
export const validateState = [
check("state_name")
.not()
.isEmpty()
.withMessage("State name field cannot be empty")
.isAlphanumeric()
.withMessage("State name cannot contain special characters"),
];
export const validateDistrict = [
check("state_name")
.not()
.isEmpty()
.withMessage("State name field cannot be empty")
.isAlphanumeric()
.withMessage("State name cannot contain special characters"),
check("district_name")
.not()
.isEmpty()
.withMessage("District name field cannot be empty")
.isAlphanumeric()
.withMessage("District name cannot contain special characters"),
];
export const validateChild = [
check("name").not().isEmpty().withMessage("Name field cannot be empty"),
check("father_name")
.not()
.isEmpty()
.withMessage("Father name field cannot be empty"),
check("mother_name")
.not()
.isEmpty()
.withMessage("Mother name field cannot be empty"),
check("dob").not().isEmpty().withMessage("DOB field cannot be empty"),
check("sex").not().isEmpty().withMessage("Sex field cannot be empty"),
check("district_id")
.not()
.isEmpty()
.withMessage("District Name field cannot be empty"),
];
export const isRequestValidate = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
success: false,
status: 400,
errors: errors.array(),
});
}
next();
};
<file_sep>import StateSchema from "../models/schema/StateSchema";
export const GetState = async (req, res) => {
try {
let state = await StateSchema.find();
return res.status(200).json({
success: true,
status: 200,
data: state,
errors: [],
message: "State data fetched successfully",
});
} catch (error) {
console.log(error.message);
}
};
export const CreateState = async (req, res) => {
try {
const { state_name } = req.body;
let state = await StateSchema.findOne({ state_name: state_name });
if (state) {
return res.status(400).json({
success: false,
status: 400,
data: {},
errors: [
{
value: state_name,
msg: "State name is already exist",
param: "state_name",
location: "body",
},
],
message: "State is already exist",
});
}
state = new StateSchema({
state_name,
});
await state.save();
return res.status(200).json({
success: true,
status: 200,
data: {},
errors: [],
message: "Operation performed successfully",
});
} catch (error) {
console.log(error.message);
}
};
<file_sep>const cloudinary = require("cloudinary").v2;
cloudinary.config({
cloud_name: process.env.Cloud_name,
api_key: process.env.api_key,
api_secret: process.env.api_secret,
});
const isFileValid = async (req, res, next) => {
try {
if (req.files) {
let isFile = req.files.photo;
let fileMimeType = isFile.mimetype.split("/")[1];
if (fileMimeType == "jpg" || fileMimeType == "png") {
await cloudinary.uploader.upload(isFile.tempFilePath, (err, res) => {
req.photoUrl = res;
});
next();
}
} else {
return res.status(400).json({
success: false,
status: 400,
data: {},
errors: [
{
value: "photo",
msg: "File extension must be PNG or JPG",
param: "file",
location: "file",
},
],
message: "Not a valid file extension",
});
}
} catch (error) {
console.log(error.message);
}
};
export default isFileValid;
<file_sep># Hi , This is <NAME>.
Backend Apis:
running command => npm run test
(Get) http://localhost:5001/health => for checking that server working or not
(Post) http://localhost:5001/api/register => for Register
(Post) http://localhost:5001/api/login => for Login
(Get) http://localhost:5001/api/logout => for Logout
(Get) http://localhost:5001/api/get_state => for Geting the State Data
(Post) http://localhost:5001/api/create/state => for Createing the State
(Post) http://localhost:5001/api/create/district => for Createing the District
(Get) http://localhost:5001/api/get_district => for Geting the District Data
(Get) http://localhost:5001/api/get_child_profile => for Geting the Child Profile Data
(Post) http://localhost:5001/api//create/child => for Creating a Child Data
FrontEnd Assignment:
running command => npm start
page 1 routes = http://localhost:3000 => for home page you can see the data table
page 2 routes = http://localhost:3000/chart => for Chart page you can see the chart or data
<file_sep>import mongoose from "mongoose";
const ChildSchema = mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true,
},
sex: {
type: String,
required: true,
trim: true,
},
dob: {
type: String,
required: true,
trim: true,
},
father_name: {
type: String,
required: true,
trim: true,
},
mother_name: {
type: String,
required: true,
trim: true,
},
district_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "district",
required: true,
},
photo: {
type: String,
required: true,
trim: true,
},
},
{ timestamps: true }
);
export default mongoose.model("child", ChildSchema);
<file_sep>import UserSchema from "../models/schema/UserSchema";
import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";
export const AuthRegister = async (req, res) => {
try {
const { name, email, password } = req.body;
let user = await UserSchema.find({ email: email });
if (user.length) {
return res.status(400).json({
success: false,
status: 400,
data: {},
errors: [
{
value: req.body.email,
msg: "User already exists.",
param: "email",
location: "body",
},
],
message: "Unable to create user",
});
}
const hashPassword = await bcrypt.hash(password, 10);
user = new UserSchema({
name,
email,
password: <PASSWORD>,
});
await user.save();
res.status(200).json({
success: true,
status: 200,
data: user,
errors: [],
message: "User Created Successfully",
});
} catch (error) {
console.log(error.message);
}
};
export const AuthLogin = async (req, res) => {
try {
const { email, password } = req.body;
let user = await UserSchema.findOne({ email: email });
if (!user) {
return res.status(400).json({
success: false,
status: 400,
data: {},
errors: [
{
value: req.body.email,
msg: "Invalid credentials",
param: "email",
location: "body",
},
],
message: "Invalid credentials",
});
}
const matchPassword = bcrypt.compareSync(password, user.password);
if (!matchPassword) {
return res.status(400).json({
success: false,
status: 400,
data: {},
errors: [
{
value: req.body.password,
msg: "Invalid credentials",
param: "password",
location: "body",
},
],
message: "Invalid credentials",
});
}
const logintoken = jwt.sign({ id: user._id }, process.env.jwt_secret, {
expiresIn: "1d",
});
req.session.logintoken = logintoken;
res.status(200).json({
success: true,
status: 200,
data: logintoken,
errors: [],
message: "Login successfully!",
});
} catch (error) {
console.log(error.message);
}
};
| a58cdd2c14e5c465c7d09350b757c04411087dec | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | rakesh-yadav-au13/assignments | bb451a4c4350fbb2f5a76422205d4dc49d6d9831 | ae57616c7af0f12dfd52375489ec7cd7f9c96205 | |
refs/heads/master | <file_sep># VCoinX
VCoinX - модификация для [VCoin](https://github.com/xTCry/VCoin), в которой вырезаны пожертвования и комиссии от платежей, и имеется несколько своих плюшек
# Установка
1) Для начала надо установить в систему [Node.JS версии 8 или выше](https://nodejs.org/) (установщик для **Windows** - [Node.js v10.15.3 LTS](https://nodejs.org/dist/v10.15.3/node-v10.15.3-x86.msi)), без этого бот просто не сможет работать
2) После скачивания и установки Node.JS, скачиваем самого бота нажав на [эту ссылку](https://github.com/cursedseal/VCoinX/releases/download/v1.3.11/VCoinX_v1.3.11.zip)
3) Распаковываем скачанный архив с файлами бота в *любую* папку и заходим в неё
4) Надо установить необходимые для бота файлы, для этого просто откройте файл `launch` формата `.bat` для Windows или `.sh` для Linux, дождитесь закрытия окна и переходите к следующему пункту
5) Теперь приступим к настройке аккаунта, инструкция ниже:
## Настройка с помощью логина и пароля
Открываем `userconfig.json` любым текстовым редактором, можно даже блокнотом
В поле `LOGIN` между кавычек вставляем номер телефона или email от страницы ВКонтакте, а в поле `PASSWORD` вставляем пароль, **после чего сохраняем файл**
## Настройка с помощью токена
Открываем `userconfig.json` любым текстовым редактором, можно даже блокнотом
В поле `VK_TOKEN` между кавычек вставляем [токен](#получение-токена), а о том, как [его](#получение-токена) получить, я расскажу чуть позднее
В принципе, нам достаточно одного токена, но если Вам интересны другие пункты, то пролистайте ниже
**! Не забываем сохранять файл после того как вписали в него нужные значения !**
Если у вас возникли какие-либо проблемы, то пишите **в группу ВКонтакте**, **на сервер в Discord** или попросите совета у *участников беседы*
[![Группа ВКонтакте](https://img.shields.io/badge/Группа-ВКонтакте-yellow.svg)](https://vk.com/vcoinx)
[![Беседа1 ВКонтакте](https://img.shields.io/badge/Беседа-ВКонтакте-yellow.svg)](https://vk.me/join/AJQ1d8Wp/g5Rju0b0CqwtSbh)
[![Беседа2 ВКонтакте](https://img.shields.io/badge/Беседа-ВКонтакте-yellow.svg)](https://vk.me/join/AJQ1d8fgFA9nDCK4vtZmN_96)
[![Беседа3 ВКонтакте](https://img.shields.io/badge/Беседа-ВКонтакте-yellow.svg)](https://vk.me/join/AJQ1d5SvLA/9NLWhykOAKrdM)
[![Сервер в Discord](https://img.shields.io/badge/Сервер-Discord-yellow.svg)](https://discord.gg/mpzttuu)
[![Telegram](https://img.shields.io/badge/Канал-Telegram-yellow.svg)](https://t.me/VCoinXru)
## Параметры конфига пользователя
| Параметр | Описание |
|-------------|---------------------------------------------------------|
| LOGIN | Номер телефона от аккаунта (для автополучения токена) |
| PASSWORD | Пароль от аккаунта (для автополучения токена) |
| VK_TOKEN | [Токен страницы пользователя](#получение-токена) |
| IFRAME_URL | Ссылка на приложение |
| GROUP_ID | Уникальный индефикатор сообщества (без минуса) |
> При указании токена, ссылку указывать не надо
### Настройка без использования аругументов
Можно избежать всякой возни с аргументами, ведь в обновлении `1.3.7` была введена настройка с помощью `botconfig.json` файла
### Использование аргументов
Можно избежать всей этой возни с настройками, если Вы разбираетесь в запуске файлов с аргументами, сейчас я перечислю все аргументы
* `-tforce` - принудительно использовать токен. (если в `userconfig.js` указан)
* `-url [URL]` - принудительно задать *URL*
* `-t [TOKEN]` - принудительно задать *VK TOKEN*
* `-flog` - использование продвинутых логов
* `-autobeep` - автоматическое проигрывание звука ошибки при ошибках. (по идее работает только на Windows)
* `-autobuy` - автоматическое приобретение улучшений
* `-autobuyitem` - указание улучшения для приобретения
* `-smartbuy` - умная авто-покупка улучшений
* `-setlimit` - установить лимит коинов / тик, до которого будет рабоать авто-закупка и умная покупка
* `-help` - вывод списка доступных команд
* `-tsum [SUM]` - автоматический перевод указанного количества коинов. (укажите больше 9000000 для перевода всей суммы)
* `-to [ID]` - указание страницы для автоматического перевода
* `-ti [SECS]` - указание интервала для автоматического перевода
* `-tperc [PERCENT]` - указать сумму для авто-перевода в процентах. (будет работать в приоритете над суммой)
* `-black` - отключение цветов в консоли
* `-noupdates` - отключение сообщений об обновлениях
* `-noautoupdates` - отключение автообновления
* `-hidejunk` - отключение сообщений про позицию в топе, количестве коинов и скорости
##### Загвоздки и подводные камни в аргументах
> Linux: Надо обратить внимание, что перед каждым символом `&` должен быть обратный слэш (`\&`)
> Windows: при принудительном использовании ссылки, её необходимо указать в кавычках
### Получение токена
[Перейдите по ссылке](https://vk.cc/9f4IXA), нажмите "Разрешить" и скопируйте часть адресной строки после access_token= и до &expires_in (85 символов)
### Получение расширенного токена
**Осторожно!** Если Вы передадите данный токен третьим лицам, то они могут **полностью** завладеть вашей страницей
Для получения расширенного токена, скопируйте ссылку ниже, замените обособленные двумя звездочками надписи на ваш логин и пароль соответственно, после чего перейдите по ссылке и скопируйте часть адресной строки от access_token= до &expires_in (85 символов)
`https://oauth.vk.com/token?grant_type=password&client_id=2274003&client_secret=<KEY>&username=**login**&password=**<PASSWORD>**`
## Список доступных команд для использования
- `help` - помощь
- `info` - отображение основной информации о боте
- `debug` - отображение расширенной информации о боте
- `run` - запустить
- `stop` - остановить
- `tran(sfer)` - перевод коинов. (только при запущенном процессе)
- `getuserscore` - получить информацию о количестве
- `autobeep` - автоматическое проигрывание звука ошибки при ошибках. (по идее работает только на Windows)
- `autobuy(ab)` - изменить статус работы авто-закупки
- `autobuyitem` - указать предмет для авто-закупки
- `smartbuy(sb)` - включить умную покупку
- `percentforsmartbuy(psb)` - установить процент от количества коинов, который будет выделяться на умную покупку
- `setlimit(sl)` - установить лимит коинов / тик, до которого будет рабоать авто-закупка и умная покупка
- `to` - указать ID пользователя для авто-перевода и автоматически его включить
- `ti` - указать интервал в секундах для авто-перевода
- `tsum` - указать сумму для авто-перевода. (укажите больше 9000000 для перевода всей суммы)
- `tperc` - указать сумму для авто-перевода в процентах. (будет работать в приоритете над суммой)
- `prices` - получить актуальный список цен
- `buy` - покупка. (только при запущенном процессе)
- `cursor` - приобрести улучшение `Курсор` в размере 1 единицы
- `cpu` - приобрести улучшение `Видеокарта` в размере 1 единицы
- `cpu_stack` - приобрести улучшение `Стойка видеокарт` в размере 1 единицы
- `computer` - приобрести улучшение `Суперкомпьютер` в размере 1 единицы
- `server_vk` - приобрести улучшение `Сервер ВКонтакте` в размере 1 единицы
- `quantum_pc` - приобрести улучшение `Квантовый компьютер` в размере 1 единицы
- `datacenter` - приобрести улучшение `Датацентр` в размере 1 единицы
- `bonus` - выдает случайное количество монет, можно использовать только один раз
## Автор(ы) бота
* [xTCry](https://github.com/xTCry) - разработчик оригинального VCoin
* [cursedseal](https://github.com/cursedseal) - разработчик модификации VCoinX
* [TemaSM](https://github.com/TemaSM) - разработчик модификации VCoinX
## Поддержать разработчиков
[![Донат разработчику оригинальной версии](https://img.shields.io/badge/Донат-VCoin-orange.svg)](https://qiwi.me/xtcry)
[![Донат разработчику VCoinX](https://img.shields.io/badge/Донат-VCoinX-orange.svg)](https://qiwi.me/vcoinx)
# Поддержавшие проект
* [Jeronyson](https://github.com/Jeronyson) - очень сильно помог при обновлении серверов, фиксы багов
## RoadMap
- [ ] Доработать README
- [ ] Реализовать бинарную версию `VCoinX` с поддержкой автообновления
- [ ] Переписать код, кардинально улучшив его
<file_sep>#! /bin/sh
if [ ! -d "./node_modules/auto-updater" ]; then
npm i --only=prod --no-audit --no-progress --loglevel=error
fi
if [ ! -f "./userconfig.json" ]; then
cp ./userconfig.example.json ./userconfig.json
fi
if [ ! -f "./botconfig.json" ]; then
cp ./botconfig.example.json ./botconfig.json
fi
node index.js
exit 0
| 2ba0988fa395355a825c21cfa87fde9865d317cf | [
"Markdown",
"Shell"
] | 2 | Markdown | hikinight/VCoinX | 172ca4426309e65c42d04e19ab46874aee1050e1 | e106469c878e8d67a95dec4264a0b462db1a8b2f | |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000000
void swap(int *var1, int *var2) {
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}
void choosePivot(int *array, int first, int last) {
int middle = (first + last) / 2;
if (array[first] < array[last]) {
if (array[first] < array[middle] && array[middle] < array[last]) {
swap(&array[first], &array[middle]);
}
}
else {
if (array[last] < array[middle] && array[middle] < array[first]) {
swap(&array[first], &array[middle]);
}
else {
swap(&array[first], &array[last]);
}
}
}
void partition(int *array, int first, int last, int *pivot) {
choosePivot(array, first, last);
*pivot = array[first];
int last_sort = first;
int unknown = first + 1;
for (; unknown <= last; unknown++) {
if (array[unknown] < *pivot) {
last_sort++;
swap(&array[unknown], &array[last_sort]);
}
}
swap(&array[first], &array[last_sort]);
*pivot = last_sort;
}
void quickSort(int *array, int first, int last) {
int pivot_index;
if (first < last) {
partition(array, first, last, &pivot_index);
quickSort(array, first, pivot_index - 1);
quickSort(array, pivot_index + 1, last);
}
}
void printArray(int *array, int size) {
int i = 0;
for (; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
void filltArray(int *array, int size) {
time_t t;
srand((unsigned)time(&t));
int i = 0;
for (; i < size; i++) {
array[i] = rand() % 65535;
}
}
int main() {
int array[SIZE] = {};
clock_t t1, t2;
filltArray(array, sizeof(array) / sizeof(int));
printf("Before sorting: \n");
//printArray(array, sizeof(array)/sizeof(int));
t1 = clock();
quickSort(array, 0, sizeof(array) / sizeof(int)-1);
t2 = clock();
printf("\nAfter sorting: \n");
//printArray(array, sizeof(array) / sizeof(int));
float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;
printf("Time taken = %f",diff);
// #include <sys/time.h>
// struct timeval stop, start;
// gettimeofday(&start, NULL);
// //do stuff
// gettimeofday(&stop, NULL);
// printf("took %lu\n", stop.tv_usec - start.tv_usec);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 100
void merge(int *array, int left, int right, int mid) {
int tempArray[SIZE] = {};
int pos = left;
int lpos = left;
int rpos = mid + 1;
while (lpos <= mid && rpos <= right) {
if (array[lpos] < array[rpos]) {
tempArray[pos++] = array[lpos++];
}
else {
tempArray[pos++] = array[rpos++];
}
}
while (lpos <= mid) {
tempArray[pos++] = array[lpos++];
}
while (rpos <= right) {
tempArray[pos++] = array[rpos++];
}
int i = left;
while (i <= right) {
array[i] = tempArray[i++];
}
}
void mergeSort(int *array, int left, int right) {
if (left < right) {
int mid = (left + right)/2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, right, mid);
}
}
void printArray(int *array, int size) {
int i = 0;
for (; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
void filltArray(int *array, int size) {
time_t t;
srand((unsigned)time(&t));
int i = 0;
for (; i < size; i++) {
array[i] = rand() % 100;
}
}
int main() {
int array[SIZE] = {};
filltArray(array, sizeof(array)/sizeof(int));
printf("Before sorting: \n");
printArray(array, sizeof(array)/sizeof(int));
mergeSort(array, 0, sizeof(array)/sizeof(int) - 1);
printf("\nAfter sorting: \n");
printArray(array, sizeof(array)/sizeof(int));
getchar();
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
typedef struct {
int last;
int size;
int *array;
} Heap;
void swap(int *, int *);
void printArray(int *, int);
void filltArray(int *, int);
Heap *heapCreate() {
Heap *heap = (Heap *)malloc(sizeof(Heap));
heap->last = 0;
heap->size = SIZE;
heap->array = (int *)malloc(sizeof(int) * heap->size);
return heap;
}
void heapDestroy(Heap *heap) {
free(heap->array);
heap = NULL;
}
void heapShiftUp(Heap *heap) {
int child = heap->last - 1;
int parent = (heap->last - 2) / 2;
while (heap->array[child] > heap->array[parent]) {
swap(&heap->array[child], &heap->array[parent]);
child = parent;
parent = (parent - 1) / 2;
}
}
int heapInsert(Heap *heap, int data) {
if (heap->last >= heap->size) {
printf("Heap is full\n");
return -1;
}
heap->array[heap->last++] = data;
if (heap->last >= 2) {
heapShiftUp(heap);
}
return 0;
}
Heap *heapify(int *array, int size) {
Heap *heap = heapCreate();
if (size > heap->size) {
printf("Array is larger than maximum heap size\n");
return NULL;
}
int i = 0;
for (; i < size; i++) {
heapInsert(heap, array[i]);
}
return heap;
}
void heapShiftDown(Heap *heap) {
int parent = 0;
int child = 2 * parent + 1;
while (heap->array[child] > heap->array[parent] && 2 * child + 1 < heap->size) {
swap(&heap->array[child], &heap->array[parent]);
parent = child;
child = 2 * child + 1;
}
}
int heapRemove(Heap *heap, int *data) {
if (heap->array <= 0) {
printf("Heap is empty\n");
return -1;
}
swap(&heap->array[0], &heap->array[heap->last - 1]);
*data = heap->array[heap->last - 1];
heap->array[heap->last - 1] = NULL;
heap->last--;
heapShiftDown(heap);
return 0;
}
void heapSort(int *array, int size) {
Heap *heap = heapify(array, size);
while (heap->last > 1) {
printf("Before: ");
printArray(heap->array, SIZE);
swap(&heap->array[heap->last - 1], &heap->array[0]);
heap->last--;
heapShiftDown(heap);
printf("After: ");
printArray(heap->array, SIZE);
}
*array = *heap->array;
}
int main() {
int array[SIZE] = { 8, 10, 15, 3, 30, 55, 2, 9, 41, 16 };
/*filltArray(array, sizeof(array)/sizeof(int));
printf("Before heapify: \n");
printArray(array, sizeof(array) / sizeof(int));
Heap* heap = heapify(array, sizeof(array) / sizeof(int));
printf("\nAfter heapify: \n");
printArray(heap->array, sizeof(array) / sizeof(int));*/
printf("Before sort: \n");
printArray(array, sizeof(array) / sizeof(int));
heapSort(array, sizeof(array) / sizeof(int));
printf("\nAfter sort: \n");
printArray(array, sizeof(array) / sizeof(int));
getchar();
return 0;
}
void swap(int *var1, int *var2) {
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}
void printArray(int *array, int size) {
int i = 0;
for (; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
void filltArray(int *array, int size) {
time_t t;
srand((unsigned)time(&t));
int i = 0;
for (; i < size; i++) {
array[i] = rand() % 100;
}
}
<file_sep># sort
heap, merge and quick sort in C
| cd0fa525b0afd427595e897eca1e5908742227f3 | [
"Markdown",
"C"
] | 4 | C | Nalaka1693/sort | d5c1cd41f5abd0942722bde6aff3845dcbdf31f7 | 8df42f1264d50aefbd7f9bdc5594c48ca933511f | |
refs/heads/master | <file_sep>import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-amenities',
templateUrl: './amenities.component.html',
styleUrls: ['./amenities.component.css']
})
export class AmenitiesComponent implements OnInit {
@Input() amenitie: string[];
splitElementeImage: string[];
amenitieImage: any = '';
constructor() { }
ngOnInit() {
this.amenitieImage = `${this.amenitie.toString()},`;
this.amenitieImage = this.amenitieImage.replace(/,/g, '.svg,');
this.splitElementeImage = this.amenitieImage.substring(0, this.amenitieImage.length - 1).split(',');
}
}
<file_sep># Almundo ui
Almundo-ui is an application developed in Angular adaptable to mobile devices, which allows to list and filter hotels.
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.6.5.
### Installation and requirements
- download and execute following step by step the instructions of the readme file the [Almundo-api](https://github.com/xiomarapulido/almundo-api.git) project that is the backend of the application.
- Clone this repository locally.
- Install the node modules with the command:
```sh
$ npm install
```
- Run the application with the command:
```sh
$ ng serve
```
- Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
<file_sep>export interface Hotel {
id: Number,
name: String,
stars: Array<Number>,
price: Number,
image: String,
amenities: {}
}<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HotelsComponent } from './components/hotels/hotels.component';
import { HeaderComponent } from './components/header/header.component';
import { FiltersComponent } from './components/filters/filters.component';
import { BodyComponent } from './components/body/body.component';
import { HotelsService } from './services/hotels.service';
import { HttpClientModule } from '@angular/common/http';
import { StarsRatingComponent } from './components/stars-rating/stars-rating.component';
import { AmenitiesComponent } from './components/amenities/amenities.component';
import { ViewHotelComponent } from './components/view-hotel/view-hotel.component';
import { CommunicationService } from './services/communications.service';
@NgModule({
declarations: [
AppComponent,
HotelsComponent,
HeaderComponent,
FiltersComponent,
BodyComponent,
StarsRatingComponent,
AmenitiesComponent,
ViewHotelComponent
],
imports: [
FormsModule,
BrowserModule,
HttpClientModule
],
providers: [
HotelsService,
CommunicationService
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { environment as ENV } from '../../environments/environment';
import { Hotel } from '../models/Hotel';
@Injectable()
export class HotelsService {
public servicesUrl = `${ENV.hotels_api}/hotel`;
constructor(private http: HttpClient) { }
public getHotelsFilter(name?: string, stars?: Array<number>, id?: string) {
let url = `${this.servicesUrl}?hotels=almundo`;
url += `${name ? `&name=${name}` : ''}`;
url += `${id ? `&id=${id}` : ''}`;
url += `${stars && stars.length ? `&stars=[${stars}]` : ''}`;
return this.http.get(url);
}
}
<file_sep>import { Component, OnInit, Input } from '@angular/core';
import { HotelsService } from '../../services/hotels.service';
import { Hotel } from '../../models/Hotel';
import { AfterViewInit } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
selector: 'app-view-hotel',
templateUrl: './view-hotel.component.html',
styleUrls: ['./view-hotel.component.css']
})
export class ViewHotelComponent implements OnInit, AfterViewInit {
@Input() id: string;
hotel: any;
constructor(private hotelsService: HotelsService) { }
ngOnInit() {
this.filterHotelsById();
}
ngAfterViewInit() {
document.getElementById('div-click-modal').click();
}
filterHotelsById() {
this.hotelsService.getHotelsFilter(null, [], this.id)
.subscribe((res) => {
const [hotel] = res['data'];
this.hotel = hotel;
});
}
}
<file_sep>import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, ComponentFactory } from '@angular/core';
import { HotelsService } from '../../services/hotels.service';
import { Hotel } from '../../models/Hotel';
import { CommunicationService } from '../../services/communications.service';
import { OnDestroy } from '@angular/core/src/metadata/lifecycle_hooks';
import { ViewHotelComponent } from '../view-hotel/view-hotel.component';
@Component({
selector: 'app-hotels',
templateUrl: './hotels.component.html',
entryComponents: [ViewHotelComponent]
})
export class HotelsComponent implements OnInit, OnDestroy {
@ViewChild('modalContainer', { read: ViewContainerRef }) modalContainer;
componentRef: ComponentRef<any>;
hotels: Array<Hotel>;
subscription: any;
constructor(private hotelsService: HotelsService,
private communicationService: CommunicationService,
private resolver: ComponentFactoryResolver) {
this.hotels = [];
}
ngOnInit() {
this.getHotels();
this.subscription = this.communicationService.$loadHotels.subscribe(({ id, name, stars }) => {
this.getHotels(name, stars, id);
});
}
ngOnDestroy(): void {
if (this.subscription)
this.subscription.unsubscribe();
}
viewHotel(id: string) {
this.modalContainer.clear();
const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(ViewHotelComponent);
this.componentRef = this.modalContainer.createComponent(factory);
this.componentRef.instance.id = id;
}
getHotels(name?, stars?, id?) {
this.hotelsService.getHotelsFilter(name, stars, id)
.subscribe((res) => { this.hotels = res['data']; });
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { HotelsService } from '../../services/hotels.service';
import { CommunicationService } from '../../services/communications.service';
@Component({
selector: 'app-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.css']
})
export class FiltersComponent implements OnInit {
public stars = {};
starsFilter: Array<number>;
indexArray: any;
nameHotel: string;
constructor(private hotelsService: HotelsService,
private communicationService: CommunicationService) {
this.starsFilter = [];
this.stars = {
one: false,
two: false,
three: false,
four: false,
five: false,
all: false
}
}
ngOnInit() {
}
public filterStarsHotels($event: any, stars: any) {
if (Array.isArray(stars) && $event) {
this.starsFilter = stars;
Object.keys(this.stars).map((key) => this.stars[key] = true)
} else if (Array.isArray(stars) && !$event) {
this.starsFilter = [];
Object.keys(this.stars).map((key) => this.stars[key] = false)
} else if ($event && !this.starsFilter.includes(stars)) {
this.starsFilter.push(stars);
} else {
this.stars['all'] = false;
this.starsFilter = this.starsFilter.filter(star => star !== stars)
}
this.filterHotels();
}
public filterHotels() {
this.communicationService.getHotelsWithParams(null, this.nameHotel, this.starsFilter)
}
}
<file_sep>import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-stars-rating',
templateUrl: './stars-rating.component.html',
styleUrls: ['./stars-rating.component.css']
})
export class StarsRatingComponent implements OnInit {
@Input() stars: number = 0;
public starsFixed: Array<number> = [1, 2, 3, 4, 5];
constructor() { }
ngOnInit() {
}
}
| d39cf503ef5fb116146fb20d0b4e6e3ff1362dfe | [
"Markdown",
"TypeScript"
] | 9 | TypeScript | xiomarapulido/almundo-ui | eec81ca3435113e873313cb7a102d650ffdc0819 | c021932189dc9b167a4fa0c10cffffd2b4ed093d | |
refs/heads/master | <repo_name>fahmifachreza/django_ctio_db<file_sep>/env_django_ctio_db/bin/django-admin.py
#!/Volumes/WORK/INDOSAT/DASHBOARD CTIO/django_ctio_db/env_django_ctio_db/bin/python3.7
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| f6ac924de464d16204e4c0d0c65b8e3a51e8b990 | [
"Python"
] | 1 | Python | fahmifachreza/django_ctio_db | d2cc1fe5020868baa0f8697f2b0cf5bfdd33650e | 2be3ca5e6f392dea21f3e6dbbda618b9b3e78a49 | |
refs/heads/master | <repo_name>paolord/cappu<file_sep>/test/cappu.test.js
'use strict';
const cli = require('../lib/cli');
const cappu = require('../lib/cappu');
describe('Integration', () => {
it('should trigger the callback when it is time to trigger growl and display results', (done) => {
const options = cli(['node', 'cappu', 'npm', 'run', 'test:docker']);
cappu(options, () => {
done(); // call done to emulate triggering growl
});
});
});<file_sep>/package.json
{
"name": "cappu",
"version": "0.1.3",
"description": "Trigger desktop notifications from JS testing frameworks",
"main": "index.js",
"scripts": {
"build": "node_modules/.bin/babel src --out-dir lib",
"pretest": "node_modules/.bin/babel src --out-dir lib",
"postinstall": "docker build -t test/cappu .",
"test": "NODE_ENV=test node_modules/.bin/_mocha --compilers js:babel-core/register --reporter spec --colors --timeout 60000 ./test/*.test.js",
"test:docker": "docker run -v $(pwd):/usr/src/app -w /usr/src/app test/cappu",
"test:demo": "NODE_ENV=test node_modules/.bin/_mocha --compilers js:babel-core/register --reporter spec --colors --timeout 10000 ./test/demo/test.js"
},
"bin": {
"cappu": "./bin/cappu.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/paolord/cappu.git"
},
"author": "<NAME> <<EMAIL>>",
"license": "MIT",
"bugs": {
"url": "https://github.com/paolord/cappu/issues"
},
"homepage": "https://github.com/paolord/cappu#readme",
"devDependencies": {
"babel-cli": "^6.16.0",
"babel-core": "^6.17.0",
"babel-preset-es2015": "^6.16.0",
"babel-preset-stage-0": "^6.16.0",
"chai": "^3.5.0",
"eslint": "^3.7.1",
"mocha": "^3.1.0"
},
"dependencies": {
"growl": "^1.9.2"
}
}
<file_sep>/test/demo/test.js
'use strict';
const expect = require('chai').expect;
describe('demo only', () => {
it('should pass', () => {
expect(1).to.eql(1);
});
});<file_sep>/lib/parser.js
'use strict';
var detected = false;
var code = 0;
/* mocha spec reporter */
var passing = void 0;
var failing = void 0;
var pending = void 0;
/* mocha tap reporter */
var pass = void 0;
var fail = void 0;
var tests = void 0;
function returnIfNotEmpty(list, index, d) {
if (typeof list === 'undefined' || list === null) {
return '';
} else if (index < list.length) {
if (typeof list[index] !== 'undefined' && list[index] !== null) {
return list[index];
}
}
if (typeof d !== 'undefined') {
return d;
}
return '';
}
module.exports = function (data, cb) {
if (!detected) {
if (data.indexOf('mocha') !== -1) {
var reporter = data.match(/(--reporter \w+)/i)[0] || '';
detected = true;
code = 0;
if (reporter.split(' ')[1] === 'spec') {
code = 0;
}
if (reporter.split(' ')[1] === 'tap') {
code = 1;
}
}
}
if (detected) {
/* code 0: mocha spec reporter */
if (code === 0) {
if (data.indexOf('passing') !== -1 || data.indexOf('failing') !== -1 || data.indexOf('pending') !== -1) {
passing = returnIfNotEmpty(data.match(/(\d+ passing)/i), 0);
failing = returnIfNotEmpty(data.match(/(\d+ failing)/i), 0);
pending = returnIfNotEmpty(data.match(/(\d+ pending)/i), 0);
cb([passing, failing, pending].join(' '));
}
}
/* code 1: mocha tap reporter */
if (code === 1) {
if (data.indexOf('# tests') !== -1 || data.indexOf('# pass') !== -1 || data.indexOf('# fail') !== -1) {
tests = returnIfNotEmpty(data.match(/(\# tests \d+)/i), 0, '# tests 0');
pass = returnIfNotEmpty(data.match(/(\# pass \d+)/i), 0, '# pass 0');
fail = returnIfNotEmpty(data.match(/(\# fail \d+)/i), 0, '# fail 0');
cb(['Test: ' + tests.split(' ')[2], 'Pass: ' + pass.split(' ')[2], 'Fail: ' + fail.split(' ')[2]].join(' '));
}
}
if (process.env.NODE_ENV === 'test') {
code = 0;
detected = false;
}
}
};<file_sep>/Dockerfile
FROM node:4.4.7-slim
ENTRYPOINT [ "npm", "run", "test:demo" ]<file_sep>/README.md
# cappu
Trigger desktop notifications from JS testing frameworks, based on growl.
[![Travis](https://img.shields.io/travis/paolord/cappu.svg)](https://travis-ci.org/paolord/cappu)
[![npm](https://img.shields.io/npm/v/cappu.svg?maxAge=2592000)](https://www.npmjs.com/package/cappu)
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/paolord/cappu/master/LICENSE)
Specially useful when tests are ran inside a docker container.
Works with the following testing frameworks and reporters:
* Mocha
* spec
* tap
## Installation
Follow instructions on [node-growl](https://github.com/tj/node-growl) and install it, then install cappu:
```
$ npm install -g cappu
```
## Example Use Case
Mocha tests are ran inside a docker container and you want to trigger notifications on the host OS.
test.js
```
const expect = require('chai').expect;
describe('demo only', () => {
it('should pass', () => {
expect(1).to.eql(1);
});
});
```
package.json
```
...
"scripts": {
"test": "docker build -t test/cappu-test . && docker run -d test/cappu-test",
"test:mocha": "mocha --reporter spec --colors ./test/demo/test.js"
}
...
```
Dockerfile
```
FROM node:4
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app/
RUN npm install
COPY . /usr/src/app
CMD [ "npm", "run", "test:mocha" ]
```
Run the test through the cappu command
```
$ cappu npm test
```
## Tests
Install docker before running:
```
$ npm test
```<file_sep>/test/parser.test.js
'use strict';
const expect = require('chai').expect;
const parser = require('../lib/parser');
describe('Parser', () => {
describe('#mocha', () => {
it('should detect the correct result from spec reporter', () => {
// emulate mocha stdout
const data = 'mocha --reporter spec ./test/*.unit.js\
25 passing (11s)\
2 pending';
parser(data, (results) => {
expect(results).to.eql('25 passing 2 pending');
});
});
it('should detect the correct result from tap reporter', () => {
// emulate mocha stdout
const data = 'mocha --reporter tap ./test/*.unit.js\
# tests 25\
# pass 25\
# fail 0';
parser(data, (results) => {
expect(results).to.eql('Test: 25 Pass: 25 Fail: 0');
});
});
});
});<file_sep>/src/cli.js
'use strict';
module.exports = function(argv) {
const cmd = argv[2];
const args = argv.splice(3, argv.length);
return {
cmd,
args,
};
};<file_sep>/src/cappu.js
'use strict';
const spawn = require('child_process').spawn;
const growl = require('growl');
const parser = require('./parser');
module.exports = (options, cb) => {
const main = options.cmd;
const args = options.args;
const logging = options.logging || true;
const cmd = spawn(main, args);
cmd.stdout.on('data', (out) => {
const data = `${out}`;
if (logging) {
console.log(data);
}
console.log(data);
parser(data, (results) => {
if (process.env.NODE_ENV !== 'test') {
growl(`Test Complete:\n${results}`);
} else {
cb();
}
});
});
// cmd.stderr.on('data', (out) => {
// // outputLines.push(data);
// });
cmd.on('close', (code) => {
console.log(`Exited with code ${code}`);
});
};<file_sep>/test/cli.test.js
'use strict';
const expect = require('chai').expect;
const cli = require('../lib/cli');
describe('CLI', () => {
it('should return the correct arguments', () => {
// include node command at the start because of #!/usr/bin/env node
const options = cli(['node', 'cappu', 'npm', 'test']);
expect(options).to.deep.eql({
cmd: 'npm',
args: ['test'],
});
});
});<file_sep>/src/index.js
'use strict';
const cappu = require('./cappu');
module.exports = cappu;<file_sep>/lib/cappu.js
'use strict';
var spawn = require('child_process').spawn;
var growl = require('growl');
var parser = require('./parser');
module.exports = function (options, cb) {
var main = options.cmd;
var args = options.args;
var logging = options.logging || true;
var cmd = spawn(main, args);
cmd.stdout.on('data', function (out) {
var data = '' + out;
if (logging) {
console.log(data);
}
console.log(data);
parser(data, function (results) {
if (process.env.NODE_ENV !== 'test') {
growl('Test Complete:\n' + results);
} else {
cb();
}
});
});
// cmd.stderr.on('data', (out) => {
// // outputLines.push(data);
// });
cmd.on('close', function (code) {
console.log('Exited with code ' + code);
});
};<file_sep>/src/parser.js
'use strict';
let detected = false;
let code = 0;
/* mocha spec reporter */
let passing;
let failing;
let pending;
/* mocha tap reporter */
let pass;
let fail;
let tests;
function returnIfNotEmpty(list, index, d) {
if (typeof list === 'undefined' || list === null) {
return '';
} else if (index < list.length) {
if (typeof list[index] !== 'undefined' && list[index] !== null) {
return list[index];
}
}
if (typeof d !== 'undefined') {
return d;
}
return '';
}
module.exports = (data, cb) => {
if (!detected) {
if (data.indexOf('mocha') !== -1) {
const reporter = data.match(/(--reporter \w+)/i)[0] || '';
detected = true;
code = 0;
if (reporter.split(' ')[1] === 'spec') {
code = 0;
}
if (reporter.split(' ')[1] === 'tap') {
code = 1;
}
}
}
if (detected) {
/* code 0: mocha spec reporter */
if (code === 0) {
if (data.indexOf('passing') !== -1 ||
data.indexOf('failing') !== -1 ||
data.indexOf('pending') !== -1) {
passing = returnIfNotEmpty(data.match(/(\d+ passing)/i), 0);
failing = returnIfNotEmpty(data.match(/(\d+ failing)/i), 0);
pending = returnIfNotEmpty(data.match(/(\d+ pending)/i), 0);
cb([
passing,
failing,
pending,
].join(' '));
}
}
/* code 1: mocha tap reporter */
if (code === 1) {
if (data.indexOf('# tests') !== -1 ||
data.indexOf('# pass') !== -1 ||
data.indexOf('# fail') !== -1) {
tests = returnIfNotEmpty(data.match(/(\# tests \d+)/i), 0, '# tests 0');
pass = returnIfNotEmpty(data.match(/(\# pass \d+)/i), 0, '# pass 0');
fail = returnIfNotEmpty(data.match(/(\# fail \d+)/i), 0, '# fail 0');
cb([
`Test: ${tests.split(' ')[2]}`,
`Pass: ${pass.split(' ')[2]}`,
`Fail: ${fail.split(' ')[2]}`,
].join(' '));
}
}
if (process.env.NODE_ENV === 'test') {
code = 0;
detected = false;
}
}
}; | 766272738270bbc617c0fc5f1784e46f8e2406a2 | [
"JavaScript",
"JSON",
"Dockerfile",
"Markdown"
] | 13 | JavaScript | paolord/cappu | 8ce684ab9643997cacde01b2b0361ac61f681896 | 56ba4508b19f7c9b972196dcbde88036f7523b25 | |
refs/heads/master | <repo_name>hudanursener/MedipolCodes<file_sep>/Python/EmpireXpOOP2o/Oyun.py
import Dunya
game = Dunya.dunya()
game.oyuncuSayisi = 3
game.oyuncuEkle()
game.ulkleriOlustur()
game.komsulariBelirle()
for o in game.oyuncular:
for u in o.ulkeleri:
o.bonusHesapla(u, 0, [])
for o in game.oyuncular:
print(o.renk, " ", o.askerHakki)
game.mainloop()
<file_sep>/IntTech/2019-2020-1/BirinciOgretim/Callback/teamviewerserverudp.js
const fs = require('fs');
var PORT = 3030;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening on ' + address.address + ':' + address.port);
});
server.on('message', function (message, remote) {
fs.writeFile("C:\\code\\MedipolCodes\\IntTech\\2019-2020-1\\BirinciOgretim\\Desktop\\app\\data\\content\\screen.jpg", message, "binary", function (err) {
if (err) {
return console.log(err);
}
});
});
server.bind(PORT, HOST); | 400c6b363204e38ed968f3212b75e52a9db130bb | [
"JavaScript",
"Python"
] | 2 | Python | hudanursener/MedipolCodes | 5d498dc320cd8e71ba233566570ab401330c8c1c | 1b03de54e924f3eb1d676fae33fcc96660de8c89 | |
refs/heads/master | <repo_name>chriniko13/eresearch-repositorer-service<file_sep>/src/main/java/com/eresearch/repositorer/test/ElsevierAuthorIntegrationTest.java
package com.eresearch.repositorer.test;
import com.eresearch.repositorer.connector.ElsevierAuthorConsumerConnector;
import com.eresearch.repositorer.dto.elsevierauthor.request.AuthorFinderDto;
import com.eresearch.repositorer.dto.elsevierauthor.request.AuthorNameDto;
import com.eresearch.repositorer.dto.elsevierauthor.response.AuthorFinderImmediateResultDto;
import com.eresearch.repositorer.dto.repositorer.request.RepositorerFindDto;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
public class ElsevierAuthorIntegrationTest {
@Autowired
private ElsevierAuthorConsumerConnector connector;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private ModelMapper modelMapper;
public void testIntegrationWithElsevierAuthor() throws RepositorerBusinessException, JsonProcessingException {
//we will test also how modelmapper behaves here...
RepositorerFindDto repositorerFindDto = RepositorerFindDto.builder()
.firstname("Anastasios")
.surname("Tsolakidis")
.build();
AuthorNameDto authorNameDto = modelMapper.map(repositorerFindDto, AuthorNameDto.class);
AuthorFinderDto authorFinderDto = new AuthorFinderDto(authorNameDto);
AuthorFinderImmediateResultDto authorImmediateResult =
connector.extractInfoFromElsevierAuthorWithRetries(authorFinderDto, UUID.randomUUID().toString());
String resultAsAString = objectMapper.writeValueAsString(authorImmediateResult);
System.out.println("[ELSEVIER AUTHOR INTEGRATION RESULT] == " + resultAsAString);
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/service/ErrorReportServiceImpl.java
package com.eresearch.repositorer.service;
import com.eresearch.repositorer.domain.error.ErrorReport;
import com.eresearch.repositorer.dto.repositorer.request.ErrorReportFilenameDto;
import com.eresearch.repositorer.dto.repositorer.request.ErrorReportSearchDto;
import com.eresearch.repositorer.dto.repositorer.response.ErrorReportDeleteOperationResultDto;
import com.eresearch.repositorer.dto.repositorer.response.ErrorReportDeleteOperationStatus;
import com.eresearch.repositorer.dto.repositorer.response.RandomEntriesResponseDto;
import com.eresearch.repositorer.dto.repositorer.response.RetrievedErrorReportDto;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.exception.error.RepositorerError;
import com.eresearch.repositorer.repository.ErrorReportRepository;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Clock;
import java.time.Instant;
import java.util.Collection;
import java.util.UUID;
@Log4j
@Service
public class ErrorReportServiceImpl implements ErrorReportService {
private static final String SAMPLE_ENTRIES_STORED_SUCCESSFULLY_TO_DB = "Sample entries stored successfully to db.";
@Autowired
private ErrorReportRepository errorReportRepository;
@Autowired
private Clock clock;
@Autowired
private RandomStringGeneratorService randomStringGeneratorService;
@Override
public Collection<RetrievedErrorReportDto> find(ErrorReportSearchDto errorReportSearchDto, boolean fullFetch) {
return errorReportRepository.find(fullFetch, errorReportSearchDto);
}
@Override
public Collection<RetrievedErrorReportDto> findAll(boolean fullFetch) {
return errorReportRepository.findAll(fullFetch);
}
@Override
public RandomEntriesResponseDto addRandomEntriesForTesting() {
for (int i = 1; i <= 20; i++) {
ErrorReport errorReport = ErrorReport.builder()
.crashedComponentName(randomStringGeneratorService.randomString(3000))
.createdAt(Instant.now(clock))
.errorStacktrace(randomStringGeneratorService.randomString(3000))
.exceptionToString(randomStringGeneratorService.randomString(3000))
.failedMessage(randomStringGeneratorService.randomString(3000))
.id(UUID.randomUUID().toString())
.repositorerError(RepositorerError.UNIDENTIFIED_ERROR)
.build();
errorReportRepository.store(errorReport);
}
return new RandomEntriesResponseDto(SAMPLE_ENTRIES_STORED_SUCCESSFULLY_TO_DB);
}
@Override
public ErrorReportDeleteOperationResultDto deleteAll() {
try {
boolean result = errorReportRepository.deleteAll();
return new ErrorReportDeleteOperationResultDto(result, ErrorReportDeleteOperationStatus.SUCCESS);
} catch (RepositorerBusinessException e) {
log.error("ErrorReportServiceImpl#deleteAll --- error occurred.", e);
final ErrorReportDeleteOperationStatus statusToReturn;
switch (e.getRepositorerError()) {
case REPOSITORY_IS_EMPTY:
statusToReturn = ErrorReportDeleteOperationStatus.REPOSITORY_IS_EMPTY;
break;
default: //Note: we should never go here....
statusToReturn = ErrorReportDeleteOperationStatus.APPLICATION_NOT_IN_CORRECT_STATE;
}
return new ErrorReportDeleteOperationResultDto(false, statusToReturn);
}
}
@Override
public ErrorReportDeleteOperationResultDto delete(ErrorReportFilenameDto errorReportFilenameDto) {
try {
String filename = errorReportFilenameDto.getFilename();
boolean deleteOperationResult = errorReportRepository.delete(filename);
return new ErrorReportDeleteOperationResultDto(deleteOperationResult, ErrorReportDeleteOperationStatus.SUCCESS);
} catch (RepositorerBusinessException e) {
log.error("ErrorReportServiceImpl#delete --- error occurred.", e);
final ErrorReportDeleteOperationStatus statusToReturn;
switch (e.getRepositorerError()) {
case RECORD_DOES_NOT_EXIST:
statusToReturn = ErrorReportDeleteOperationStatus.RECORD_DOES_NOT_EXIST;
break;
case NO_UNIQUE_RESULTS_EXIST_BASED_ON_PROVIDED_DISCRIMINATOR:
statusToReturn = ErrorReportDeleteOperationStatus.NO_UNIQUE_RESULTS_EXIST_BASED_ON_PROVIDED_DISCRIMINATOR;
break;
default: //Note: we should never go here....
statusToReturn = ErrorReportDeleteOperationStatus.APPLICATION_NOT_IN_CORRECT_STATE;
}
return new ErrorReportDeleteOperationResultDto(false, statusToReturn);
}
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/test/IntegrationTestsSuite.java
package com.eresearch.repositorer.test;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Log4j
@Component
public class IntegrationTestsSuite {
@Autowired
private AuthorMatcherIntegrationTest authorMatcherIntegrationTest;
@Autowired
private DblpConsumerIntegrationTest dblpConsumerIntegrationTest;
@Autowired
private ScienceDirectIntegrationTest scienceDirectIntegrationTest;
@Autowired
private ScopusIntegrationTest scopusIntegrationTest;
@Autowired
private ElsevierAuthorIntegrationTest elsevierAuthorIntegrationTest;
public void runSuite() {
//NOTE: add your scenarios or tests if needed...
try {
authorMatcherIntegrationTest.testIntegrationWithAuthorMatcher();
dblpConsumerIntegrationTest.testDblpConsumerIntegration();
scienceDirectIntegrationTest.testScienceDirectIntegration();
scopusIntegrationTest.testScopusIntegration();
elsevierAuthorIntegrationTest.testIntegrationWithElsevierAuthor();
} catch (JsonProcessingException e) {
log.error("IntegrationTestsSuite#runSuite --- error occurred.", e);
}
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/results/elsevierauthor/ElsevierAuthorResultsTransformer.java
package com.eresearch.repositorer.transformer.results.elsevierauthor;
import com.eresearch.repositorer.dto.elsevierauthor.response.*;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.exception.error.RepositorerError;
import com.eresearch.repositorer.transformer.dto.ElsevierAuthorResultsTransformerDto;
import com.eresearch.repositorer.transformer.results.ResultsTransformer;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Log4j
@Component
public class ElsevierAuthorResultsTransformer implements ResultsTransformer {
@Autowired
private ObjectMapper objectMapper;
@Override
public Message<?> transform(Message<?> message) {
try {
log.info("ElsevierAuthorResultsTransformer --> " + Thread.currentThread().getName());
final AuthorFinderQueueResultDto authorFinderQueueResultDto = deserializeMessage(message);
final List<String> elsevierAuthorIds = extractElsevierAuthorIds(authorFinderQueueResultDto);
final String transactionId = authorFinderQueueResultDto.getTransactionId();
return MessageBuilder
.withPayload(new ElsevierAuthorResultsTransformerDto(elsevierAuthorIds))
.setHeader(TRANSACTION_ID, transactionId)
.build();
} catch (IOException error) {
log.error("ElsevierAuthorResultsTransformer#deserializeMessage --- error occurred", error);
throw new RepositorerBusinessException(RepositorerError.COULD_NOT_DESERIALIZE_MESSAGE,
RepositorerError.COULD_NOT_DESERIALIZE_MESSAGE.getMessage(),
error,
this.getClass().getName());
}
}
private AuthorFinderQueueResultDto deserializeMessage(Message<?> message) throws IOException {
final String resultAsString = (String) message.getPayload();
return objectMapper.readValue(resultAsString, new TypeReference<AuthorFinderQueueResultDto>() {
});
}
private List<String> extractElsevierAuthorIds(AuthorFinderQueueResultDto authorFinderQueueResultDto) {
final List<String> elsevierAuthorIds = new ArrayList<>();
AuthorFinderResultsDto authorFinderResultsDto = authorFinderQueueResultDto.getAuthorFinderResultsDto();
if (!authorFinderResultsDto.getOperationResult()) {
throw new RepositorerBusinessException(RepositorerError.COULD_NOT_PERFORM_OPERATION,
RepositorerError.COULD_NOT_PERFORM_OPERATION.getMessage(),
this.getClass().getName());
}
for (AuthorSearchViewResultsDto authorSearchViewResultsDto : authorFinderResultsDto.getResults()) {
AuthorSearchViewDto authorSearchViewDto = authorSearchViewResultsDto.getAuthorSearchViewDto();
if (noResultsToProcess(authorSearchViewDto)) continue;
for (AuthorSearchViewEntry authorSearchViewEntry : authorSearchViewDto.getEntries()) {
//this will contain info such as: "dc:identifier": "AUTHOR_ID:23007591800"
String dcIdentifier = authorSearchViewEntry.getDcIdentifier();
final String elsevierAuthorId = dcIdentifier.split(":")[1];
elsevierAuthorIds.add(elsevierAuthorId);
}
}
return elsevierAuthorIds;
}
private boolean noResultsToProcess(AuthorSearchViewDto authorSearchViewDto) {
return "0".equals(authorSearchViewDto.getTotalResults())
&& "0".equals(authorSearchViewDto.getStartIndex())
&& "0".equals(authorSearchViewDto.getItemsPerPage())
&& authorSearchViewDto.getEntries() != null
&& authorSearchViewDto.getEntries().size() == 1
&& authorSearchViewDto.getEntries().iterator().next().getError().equals("Result set was empty");
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/dblp/response/generated/Dblp.java
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.02.27 at 11:20:24 PM EET
//
package com.eresearch.repositorer.dto.dblp.response.generated;
import lombok.Getter;
import lombok.Setter;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.List;
@Getter
@Setter
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "dblp")
public class Dblp {
@XmlAttribute(name = "mdate")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String mdate;
@XmlElement(name = "article", type = Article.class)
private List<Article> articles;
@XmlElement(name = "inproceedings", type = Inproceedings.class)
private List<Inproceedings> inproceedings;
@XmlElement(name = "proceedings", type = Proceedings.class)
private List<Proceedings> proceedings;
@XmlElement(name = "book", type = Book.class)
private List<Book> books;
@XmlElement(name = "incollection", type = Incollection.class)
private List<Incollection> incollections;
@XmlElement(name = "phdthesis", type = Phdthesis.class)
private List<Phdthesis> phdthesis;
@XmlElement(name = "mastersthesis", type = Mastersthesis.class)
private List<Mastersthesis> mastersthesis;
@XmlElement(name = "www", type = Www.class)
private List<Www> www;
@XmlElement(name = "person", type = Person.class)
private List<Person> persons;
@XmlElement(name = "data", type = Data.class)
private List<Data> data;
}
<file_sep>/src/main/java/com/eresearch/repositorer/validator/Validator.java
package com.eresearch.repositorer.validator;
import com.eresearch.repositorer.exception.data.RepositorerValidationException;
public interface Validator<T> {
void validate(T data) throws RepositorerValidationException;
}
<file_sep>/src/main/java/com/eresearch/repositorer/repository/NamesLookupRepository.java
package com.eresearch.repositorer.repository;
import com.eresearch.repositorer.domain.lookup.NameLookup;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface NamesLookupRepository extends MongoRepository<NameLookup, String> {
NameLookup findNamesLookupByTransactionIdEquals(String transactionId);
List<NameLookup> findAllByFirstnameEqualsAndInitialsEqualsAndSurnameEquals(String firstname, String initial, String surname);
}
<file_sep>/src/main/java/com/eresearch/repositorer/aggregator/release/ElsevierAuthorMessagesAwaitingReleaseStrategy.java
package com.eresearch.repositorer.aggregator.release;
import com.eresearch.repositorer.transformer.RepositorerFindDtoPopulator;
import org.springframework.integration.aggregator.ReleaseStrategy;
import org.springframework.integration.store.MessageGroup;
import org.springframework.stereotype.Component;
@Component
public class ElsevierAuthorMessagesAwaitingReleaseStrategy implements ReleaseStrategy {
private static final Integer OPERATIONS_PER_EXTERNAL_SYSTEM = RepositorerFindDtoPopulator.NO_OF_NAME_VARIANTS;
private static final Integer NO_OF_EXTERNAL_SYSTEMS = ExternalSystem
.values()
.length;
private enum ExternalSystem {
ELSEVIER_AUTHOR
}
@Override
public boolean canRelease(MessageGroup group) {
return group.size() == NO_OF_EXTERNAL_SYSTEMS * OPERATIONS_PER_EXTERNAL_SYSTEM;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/validator/RepositorerFindDtosValidator.java
package com.eresearch.repositorer.validator;
import com.eresearch.repositorer.dto.repositorer.request.RepositorerFindDto;
import com.eresearch.repositorer.dto.repositorer.request.RepositorerFindDtos;
import com.eresearch.repositorer.exception.data.RepositorerValidationException;
import com.eresearch.repositorer.exception.error.RepositorerError;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.stream.Stream;
/*
Note: Only initials could be empty or null.
*/
@Component
@Log4j
public class RepositorerFindDtosValidator implements Validator<RepositorerFindDtos> {
@Value("${no.records.to.process.threshold}")
private String noOfRecordsToProcessThreshold;
private int noOfRecordsToProcessThresholdInt;
@PostConstruct
public void init() {
noOfRecordsToProcessThresholdInt = Integer.parseInt(noOfRecordsToProcessThreshold);
}
@Override
public void validate(RepositorerFindDtos dtos) throws RepositorerValidationException {
// first validation...
if (dtos == null || dtos.getRepositorerFindDtos() == null || dtos.getRepositorerFindDtos().isEmpty()) {
log.error("RepositorerFindDtosValidator#validate --- error occurred (first validation) --- repositorerFindDtos = " + dtos);
throw new RepositorerValidationException(RepositorerError.INVALID_DATA_ERROR, RepositorerError.INVALID_DATA_ERROR.getMessage());
}
// second validation...
if (dtos.getRepositorerFindDtos().size() > noOfRecordsToProcessThresholdInt) {
log.error("RepositorerFindDtosValidator#validate --- error occurred (second validation) --- repositorerFindDtos = " + dtos);
throw new RepositorerValidationException(
RepositorerError.LIMIT_FOR_NUMBER_OF_TOTAL_RECORDS_TO_PROCESS_EXCEEDED,
RepositorerError.LIMIT_FOR_NUMBER_OF_TOTAL_RECORDS_TO_PROCESS_EXCEEDED.getMessage());
}
// third validation...
for (RepositorerFindDto repositorerFindDto : dtos.getRepositorerFindDtos()) {
boolean validationError = Stream
.of(repositorerFindDto.getFirstname(), repositorerFindDto.getSurname())
.anyMatch(d -> d == null || "".equals(d));
if (validationError) {
log.error("RepositorerFindDtosValidator#validate --- error occurred (third validation) --- repositorerFindDtos = " + dtos);
throw new RepositorerValidationException(RepositorerError.INVALID_DATA_ERROR, RepositorerError.INVALID_DATA_ERROR.getMessage());
}
}
}
}
<file_sep>/src/main/resources/application-dev.properties
# Note add you development properties here.<file_sep>/src/main/java/com/eresearch/repositorer/transformer/RecordsApplyUniquenessTransformer.java
package com.eresearch.repositorer.transformer;
import com.eresearch.repositorer.domain.record.Entry;
import com.eresearch.repositorer.domain.record.Record;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
@Log4j
@Component
public class RecordsApplyUniquenessTransformer {
private static final String TRANSACTION_ID = "Transaction-Id";
@Value("${apply.uniqueness.on.record.title}")
private String applyUniquenessOnRecordTitle;
public Message<?> transform(Message<?> message) {
log.info("RecordsApplyUniquenessTransformer --> " + Thread.currentThread().getName());
Record record = (Record) message.getPayload();
String transactionId = (String) message.getHeaders().get(TRANSACTION_ID);
if (Boolean.valueOf(applyUniquenessOnRecordTitle)) {
Collection<Entry> entries = record.getEntries();
if (entries != null && !entries.isEmpty()) {
Set<Entry> uniqueEntries = new LinkedHashSet<>(entries);
record.setEntries(uniqueEntries);
}
}
return MessageBuilder
.withPayload(record)
.setHeader(TRANSACTION_ID, transactionId)
.build();
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/repositorer/response/RetrievedNameLookupDtos.java
package com.eresearch.repositorer.dto.repositorer.response;
import com.eresearch.repositorer.domain.lookup.NameLookup;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Collection;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class RetrievedNameLookupDtos {
private Collection<NameLookup> nameLookups;
}
<file_sep>/src/main/java/com/eresearch/repositorer/service/NameLookupService.java
package com.eresearch.repositorer.service;
import com.eresearch.repositorer.domain.lookup.NameLookup;
import com.eresearch.repositorer.dto.repositorer.request.NameLookupSearchDto;
import com.eresearch.repositorer.dto.repositorer.response.NameLookupDeleteOperationResultDto;
import com.eresearch.repositorer.dto.repositorer.response.RandomEntriesResponseDto;
import java.util.Collection;
public interface NameLookupService {
NameLookup find(NameLookupSearchDto nameLookupSearchDto);
Collection<NameLookup> findAll();
RandomEntriesResponseDto addRandomEntriesForTesting();
NameLookupDeleteOperationResultDto deleteAll();
NameLookupDeleteOperationResultDto delete(NameLookupSearchDto nameLookupSearchDto);
}
<file_sep>/src/main/java/com/eresearch/repositorer/repository/RecordRepository.java
package com.eresearch.repositorer.repository;
import com.eresearch.repositorer.domain.record.Author;
import com.eresearch.repositorer.domain.record.Record;
import com.eresearch.repositorer.dto.repositorer.response.RetrievedRecordDto;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.exception.error.RepositorerError;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.ByteStreams;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Repository;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;
@Log4j
@Repository
public class RecordRepository implements EresearchRepositorerRepository<Record, RetrievedRecordDto, Author> {
private static final String FILENAME_PREFIX = "RECORD";
private static final String RECORD_TYPE = "RECORD";
private static final boolean APPLY_DISTINCTION_ON_SEARCH_RESULTS = true;
private static final String CONTENT_TYPE = "application/octet-stream";
private static final String NO_VALUE = "NoValue";
private static final String REGEX_FOR_ALL = ".*";
private final GridFsTemplate gridFsTemplate;
private final Clock clock;
private final Pattern findAllRecordsPattern;
private final ObjectMapper objectMapper;
@Autowired
public RecordRepository(GridFsTemplate gridFsTemplate, Clock clock, ObjectMapper objectMapper) {
this.gridFsTemplate = gridFsTemplate;
this.clock = clock;
this.objectMapper = objectMapper;
findAllRecordsPattern = Pattern.compile(REGEX_FOR_ALL);
}
@Override
public boolean deleteAll() {
// first perform all necessary validations....
List<GridFSDBFile> gridFSDBFiles = gridFsTemplate.find(Query.query(Criteria.where("filename").regex(FILENAME_PREFIX + findAllRecordsPattern)));
if (gridFSDBFiles.size() == 0) {
throw new RepositorerBusinessException(RepositorerError.REPOSITORY_IS_EMPTY,
RepositorerError.REPOSITORY_IS_EMPTY.getMessage());
}
// then perform delete operation...
gridFsTemplate.delete(Query.query(Criteria.where("filename").regex(FILENAME_PREFIX + findAllRecordsPattern)));
// and then perform all necessary validations again...
return findAll(false).size() == 0;
}
@Override
public boolean delete(String filename) {
// first perform all necessary validations....
List<GridFSDBFile> gridFSDBFiles = gridFsTemplate.find(Query.query(Criteria.where("filename").is(filename)));
if (gridFSDBFiles.size() > 1) {
throw new RepositorerBusinessException(RepositorerError.NO_UNIQUE_RESULTS_EXIST_BASED_ON_PROVIDED_DISCRIMINATOR,
RepositorerError.NO_UNIQUE_RESULTS_EXIST_BASED_ON_PROVIDED_DISCRIMINATOR.getMessage());
}
if (gridFSDBFiles.size() == 0) {
throw new RepositorerBusinessException(RepositorerError.RECORD_DOES_NOT_EXIST,
RepositorerError.RECORD_DOES_NOT_EXIST.getMessage());
}
// then perform delete operation...
gridFsTemplate.delete(Query.query(Criteria.where("filename").is(filename)));
// and then perform all necessary validations again...
gridFSDBFiles = gridFsTemplate.find(Query.query(Criteria.where("filename").is(filename)));
return gridFSDBFiles.size() == 0;
}
@Override
public Collection<RetrievedRecordDto> find(String filename, boolean fullFetch) {
final Collection<RetrievedRecordDto> retrievedRecordDtos = new ArrayList<>();
List<GridFSDBFile> gridFSDBFiles = gridFsTemplate.find(Query.query(Criteria.where("filename").is(filename)));
populateRetrievedRecordsWithResults(retrievedRecordDtos, gridFSDBFiles, fullFetch);
return retrievedRecordDtos;
}
@Override
public Collection<RetrievedRecordDto> find(boolean fullFetch, Author mainAuthorName) {
//------------- do main search --------------
final Collection<RetrievedRecordDto> retrievedRecordDtos = APPLY_DISTINCTION_ON_SEARCH_RESULTS ? new HashSet<>() : new ArrayList<>();
String filenameToSearchFor = createFilenameToSearchFor(mainAuthorName);
final List<GridFSDBFile> retrievedGridFSDBFilesFromMainSearch
= gridFsTemplate.find(Query.query(Criteria.where("filename").regex(filenameToSearchFor)));
populateRetrievedRecordsWithResults(retrievedRecordDtos, retrievedGridFSDBFilesFromMainSearch, fullFetch);
//--------- and then do additional search based on splitted metadata info ------------
List<GridFSDBFile> retrievedGridFSDBFilesFromNameVariantsSearch = gridFsTemplate.find(
Query.query(
Criteria.where("metadata.authorRecordName.firstname")
.regex(REGEX_FOR_ALL + mainAuthorName.getFirstname() + REGEX_FOR_ALL)
.and("metadata.authorRecordName.initials")
.regex(REGEX_FOR_ALL + mainAuthorName.getInitials() + REGEX_FOR_ALL)
.and("metadata.authorRecordName.lastname")
.regex(REGEX_FOR_ALL + mainAuthorName.getSurname() + REGEX_FOR_ALL)
.and("metadata.recordType")
.regex(RECORD_TYPE)
)
);
populateRetrievedRecordsWithResults(retrievedRecordDtos, retrievedGridFSDBFilesFromNameVariantsSearch, fullFetch);
return retrievedRecordDtos;
}
@Override
public Collection<RetrievedRecordDto> findAll(boolean fullFetch) {
final List<RetrievedRecordDto> retrievedRecordDtos = new ArrayList<>();
List<GridFSDBFile> gridFSDBFiles = gridFsTemplate.find(Query.query(Criteria.where("filename").regex(FILENAME_PREFIX + findAllRecordsPattern)));
populateRetrievedRecordsWithResults(retrievedRecordDtos, gridFSDBFiles, fullFetch);
return retrievedRecordDtos;
}
@Override
public void store(Record record) {
//first serialize record...
try {
byte[] bytes = objectMapper.writeValueAsBytes(record);
//then transform the serialized record into an input stream...
try (InputStream is = new ByteArrayInputStream(bytes)) {
//finally store the info...
String fileName = createFilename(record) + "#" + getStringifiedDate(record);
DBObject metaData = createMetadata(record);
gridFsTemplate.store(is, fileName, CONTENT_TYPE, metaData);
}
} catch (Exception error) {
log.error("RecordRepository#store --- error occurred.", error);
throw new RepositorerBusinessException(RepositorerError.COULD_NOT_SERIALIZE_OBJECT,
RepositorerError.COULD_NOT_SERIALIZE_OBJECT.getMessage(),
error,
this.getClass().getName());
}
}
private String createFilename(Record record) {
return FILENAME_PREFIX
+ normalizeInfo(record.getFirstname())
+ "_"
+ normalizeInfo(record.getInitials())
+ "_"
+ normalizeInfo(record.getLastname());
}
private DBObject createMetadata(Record record) {
DBObject metaData = new BasicDBObject();
DBObject authorRecordName = new BasicDBObject();
authorRecordName.put("firstname", record.getFirstname());
authorRecordName.put("initials", record.getInitials());
authorRecordName.put("lastname", record.getLastname());
metaData.put("authorRecordName", authorRecordName);
metaData.put("recordCreatedAt", getStringifiedDate(record));
metaData.put("recordType", RECORD_TYPE);
return metaData;
}
private String getStringifiedDate(Record record) {
return LocalDateTime.ofInstant(record.getCreatedAt(), clock.getZone()).toString();
}
private String normalizeInfo(String info) {
return Optional.ofNullable(info).filter(i -> !i.isEmpty()).orElse(NO_VALUE);
}
private String createFilenameToSearchFor(Author author) {
return FILENAME_PREFIX
+ normalizeInfo(author.getFirstname()) + REGEX_FOR_ALL
+ "_"
+ normalizeInfo(author.getInitials()) + REGEX_FOR_ALL
+ "_"
+ normalizeInfo(author.getSurname()) + REGEX_FOR_ALL;
}
private void populateRetrievedRecordsWithResults(Collection<RetrievedRecordDto> retrievedRecordDtos, List<GridFSDBFile> gridFSDBFiles, boolean fullFetch) {
for (GridFSDBFile gridFSDBFile : gridFSDBFiles) {
String filename = gridFSDBFile.getFilename();
RetrievedRecordDto retrievedRecordDto = new RetrievedRecordDto();
retrievedRecordDto.setFilename(filename);
if (fullFetch) {
Record record = deserializeStoredRecord(gridFSDBFile.getInputStream());
retrievedRecordDto.setRecord(record);
}
retrievedRecordDtos.add(retrievedRecordDto);
}
}
private Record deserializeStoredRecord(InputStream inputStream) {
try {
byte[] bytes = ByteStreams.toByteArray(inputStream);
return objectMapper.readValue(bytes, Record.class);
} catch (Exception error) {
log.error("RecordRepository#deserializeStoredRecord --- error occurred.", error);
throw new RepositorerBusinessException(RepositorerError.COULD_NOT_DESERIALIZE_OBJECT,
RepositorerError.COULD_NOT_DESERIALIZE_OBJECT.getMessage(),
error,
this.getClass().getName());
}
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/application/configuration/EventBusConfiguration.java
package com.eresearch.repositorer.application.configuration;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
public class EventBusConfiguration {
@Bean
public EventBus batchExtractorEventBus() {
ThreadPoolExecutor batchExtractorThreadPool = new ThreadPoolExecutor(
20, 80,
5000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(300, true),
new ThreadFactoryBuilder().setNameFormat("batch-extractor-thread-%d").build(),
new ThreadPoolExecutor.CallerRunsPolicy());
return new AsyncEventBus("batchExtractorBus", batchExtractorThreadPool);
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/application/configuration/AppConfiguration.java
package com.eresearch.repositorer.application.configuration;
import com.eresearch.repositorer.deserializer.InstantDeserializer;
import com.eresearch.repositorer.deserializer.LocalDateDeserializer;
import com.eresearch.repositorer.deserializer.LocalTimeDeserializer;
import com.eresearch.repositorer.serializer.InstantSerializer;
import com.eresearch.repositorer.serializer.LocalDateSerializer;
import com.eresearch.repositorer.serializer.LocalTimeSerializer;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.handler.ssl.SslContextBuilder;
import net.jodah.failsafe.RetryPolicy;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.Netty4ClientHttpRequestFactory;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLException;
import java.time.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
public class AppConfiguration {
@Bean
@Qualifier("basicRetryPolicyForConnectors")
public RetryPolicy basicRetryPolicyForConnectors() {
return new RetryPolicy()
.retryOn(RestClientException.class)
.withMaxRetries(10)
.withDelay(8, TimeUnit.SECONDS)
.withJitter(7, TimeUnit.SECONDS);
}
@Bean(destroyMethod = "shutdownNow")
@Qualifier("authorExtractionExecutor")
public ExecutorService authorExtractionExecutor() {
return new ThreadPoolExecutor(
20, 80,
5000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(300, true),
new ThreadFactoryBuilder().setNameFormat("author-extraction-thread-%d").build(),
new ThreadPoolExecutor.CallerRunsPolicy());
}
@Bean(destroyMethod = "shutdownNow")
@Qualifier("authorEntriesMatchingExecutor")
public ExecutorService authorEntriesMatchingExecutor() {
return new ThreadPoolExecutor(
20, 80,
5000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(300, true),
new ThreadFactoryBuilder().setNameFormat("author-entries-matching-thread-%d").build(),
new ThreadPoolExecutor.CallerRunsPolicy());
}
@Bean(destroyMethod = "shutdownNow")
@Qualifier("dblpEntriesProcessorsExecutor")
public ExecutorService dblpEntriesProcessorsExecutor() {
return new ThreadPoolExecutor(
20, 80,
5000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(300, true),
new ThreadFactoryBuilder().setNameFormat("dblp-entries-processing-thread-%d").build(),
new ThreadPoolExecutor.CallerRunsPolicy());
}
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(Instant.class, new InstantSerializer());
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer());
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
javaTimeModule.addDeserializer(Instant.class, new InstantDeserializer());
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer());
objectMapper.registerModule(javaTimeModule);
objectMapper.findAndRegisterModules();
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); //for elsevier api.
return objectMapper;
}
@Bean
@Qualifier("repositorerRestTemplate")
public RestTemplate restTemplate() throws SSLException {
Netty4ClientHttpRequestFactory nettyFactory = new Netty4ClientHttpRequestFactory();
nettyFactory.setSslContext(SslContextBuilder.forClient().build());
return new RestTemplate(nettyFactory);
}
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
@Value("${service.zone.id}")
private ZoneId zoneId;
@Bean
public Clock clock() {
return Clock.system(zoneId);
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/service/RandomStringGeneratorService.java
package com.eresearch.repositorer.service;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
@Service
public class RandomStringGeneratorService {
private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static SecureRandom rnd = new SecureRandom();
public String randomString(int len) {
final StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
sb.append(AB.charAt(rnd.nextInt(AB.length())));
}
return sb.toString();
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/results/dblp/processor/DblpDataProcessorBasic.java
package com.eresearch.repositorer.transformer.results.dblp.processor;
import com.eresearch.repositorer.domain.record.Entry;
import com.eresearch.repositorer.dto.dblp.response.DblpAuthor;
import com.eresearch.repositorer.dto.dblp.response.generated.Data;
import com.eresearch.repositorer.dto.dblp.response.generated.Dblp;
import com.eresearch.repositorer.transformer.results.dblp.processor.common.EntryCreator;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.LinkedList;
import java.util.List;
@Component
public class DblpDataProcessorBasic implements DblpProcessor {
private final EntryCreator entryCreator;
@Autowired
public DblpDataProcessorBasic(EntryCreator entryCreator) {
this.entryCreator = entryCreator;
}
@Override
public void doProcessing(List<Entry> entries, Dblp dblp, DblpAuthor dblpAuthor) throws JsonProcessingException {
List<Data> data = dblp.getData();
if (data != null && !data.isEmpty()) {
final List<Entry> collectedEntries = new LinkedList<>();
for (Data datum : data) {
entryCreator.create(dblpAuthor, collectedEntries, datum);
}
entries.addAll(collectedEntries);
}
}
@Override
public boolean allowProcessing() {
return false;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/scopus/response/ScopusConsumerResultsDto.java
package com.eresearch.repositorer.dto.scopus.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ScopusConsumerResultsDto {
@JsonProperty("search-results")
private ScopusConsumerSearchViewDto scopusConsumerSearchViewDto;
}
<file_sep>/src/main/java/com/eresearch/repositorer/service/RecordServiceImpl.java
package com.eresearch.repositorer.service;
import com.eresearch.repositorer.domain.record.Author;
import com.eresearch.repositorer.dto.repositorer.request.RecordFilenameDto;
import com.eresearch.repositorer.dto.repositorer.request.RecordSearchDto;
import com.eresearch.repositorer.dto.repositorer.response.RecordDeleteOperationResultDto;
import com.eresearch.repositorer.dto.repositorer.response.RecordDeleteOperationStatus;
import com.eresearch.repositorer.dto.repositorer.response.RecordSearchResultDto;
import com.eresearch.repositorer.dto.repositorer.response.RetrievedRecordDto;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.repository.RecordRepository;
import lombok.extern.log4j.Log4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Log4j
public class RecordServiceImpl implements RecordService {
private final RecordRepository recordRepository;
private final ModelMapper modelMapper;
@Autowired
public RecordServiceImpl(RecordRepository recordRepository, ModelMapper modelMapper) {
this.recordRepository = recordRepository;
this.modelMapper = modelMapper;
}
@Override
public RecordSearchResultDto find(RecordSearchDto recordSearchDto, boolean fullFetch) {
Author author = modelMapper.map(recordSearchDto, Author.class);
Collection<RetrievedRecordDto> retrievedRecordDtos = recordRepository.find(fullFetch, author);
return new RecordSearchResultDto(retrievedRecordDtos);
}
@Override
public RecordSearchResultDto findAll(boolean fullFetch) {
Collection<RetrievedRecordDto> retrievedRecordDtos = recordRepository.findAll(fullFetch);
List<RetrievedRecordDto> fromEarliestToLatestRecordDtos = retrievedRecordDtos
.stream()
.sorted(earliestToLatestRecordsComparator())
.collect(Collectors.toList());
return new RecordSearchResultDto(fromEarliestToLatestRecordDtos);
}
@Override
public RecordDeleteOperationResultDto deleteAll() {
try {
boolean result = recordRepository.deleteAll();
return new RecordDeleteOperationResultDto(result, RecordDeleteOperationStatus.SUCCESS);
} catch (RepositorerBusinessException e) {
final RecordDeleteOperationStatus statusToReturn;
switch (e.getRepositorerError()) {
case REPOSITORY_IS_EMPTY:
statusToReturn = RecordDeleteOperationStatus.REPOSITORY_IS_EMPTY;
break;
default: //Note: we should never go here....
statusToReturn = RecordDeleteOperationStatus.APPLICATION_NOT_IN_CORRECT_STATE;
}
return new RecordDeleteOperationResultDto(false, statusToReturn);
}
}
@Override
public RecordDeleteOperationResultDto delete(RecordFilenameDto recordFilenameDto) {
try {
String filename = recordFilenameDto.getFilename();
boolean deleteOperationResult = recordRepository.delete(filename);
return new RecordDeleteOperationResultDto(deleteOperationResult, RecordDeleteOperationStatus.SUCCESS);
} catch (RepositorerBusinessException e) {
final RecordDeleteOperationStatus statusToReturn;
switch (e.getRepositorerError()) {
case RECORD_DOES_NOT_EXIST:
statusToReturn = RecordDeleteOperationStatus.RECORD_DOES_NOT_EXIST;
break;
case NO_UNIQUE_RESULTS_EXIST_BASED_ON_PROVIDED_DISCRIMINATOR:
statusToReturn = RecordDeleteOperationStatus.NO_UNIQUE_RESULTS_EXIST_BASED_ON_PROVIDED_DISCRIMINATOR;
break;
default: //Note: we should never go here....
statusToReturn = RecordDeleteOperationStatus.APPLICATION_NOT_IN_CORRECT_STATE;
}
return new RecordDeleteOperationResultDto(false, statusToReturn);
}
}
@Override
public RecordSearchResultDto find(RecordFilenameDto recordFilenameDto, boolean fullFetch) {
Collection<RetrievedRecordDto> dtos = recordRepository.find(recordFilenameDto.getFilename(), fullFetch);
return new RecordSearchResultDto(dtos);
}
private Comparator<RetrievedRecordDto> earliestToLatestRecordsComparator() {
return (o1, o2) -> {
//Note: filename contains info such as: Errikos_NoValue_Ventouras#2017-08-28T01:07:10.590
String createdAtStr_o1 = o1.getFilename().split("#")[1];
LocalDateTime localDateTime_o1 = LocalDateTime.parse(createdAtStr_o1);
String createdAtStr_o2 = o2.getFilename().split("#")[1];
LocalDateTime localDateTime_o2 = LocalDateTime.parse(createdAtStr_o2);
return localDateTime_o1.compareTo(localDateTime_o2);
};
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/gateway/AuthorExtractor.java
package com.eresearch.repositorer.gateway;
import com.eresearch.repositorer.dto.repositorer.request.RepositorerFindDto;
import org.springframework.integration.annotation.Gateway;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import java.util.concurrent.Future;
public interface AuthorExtractor {
@Gateway
Future<Void> extract(@Payload RepositorerFindDto repositorerFindDto,
@Header("Transaction-Id") String transactionId);
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/elsevierauthor/response/AuthorSearchViewAffiliationCurrent.java
package com.eresearch.repositorer.dto.elsevierauthor.response;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AuthorSearchViewAffiliationCurrent {
@JsonProperty("affiliation-url")
private String url;
@JsonProperty("affiliation-id")
private String id;
@JsonProperty("affiliation-name")
private String name;
@JsonProperty("affiliation-city")
private String city;
@JsonProperty("affiliation-country")
private String country;
public AuthorSearchViewAffiliationCurrent() {
}
public AuthorSearchViewAffiliationCurrent(String url, String id, String name, String city, String country) {
this.url = url;
this.id = id;
this.name = name;
this.city = city;
this.country = country;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
<file_sep>/docker-compose.yml
version: '3.3'
services:
#### INFRASTRUCTURE ####
activemq:
image: webcenter/activemq:latest
ports:
- 8161:8161
- 61616:61616
- 61613:61613
environment:
ACTIVEMQ_NAME: amq
ACTIVEMQ_REMOVE_DEFAULT_ACCOUNT: 'True'
ACTIVEMQ_ADMIN_LOGIN: admin
ACTIVEMQ_ADMIN_PASSWORD: <PASSWORD>
volumes:
- /container_data/activemq/data:/data/activemq
- /container_data/activemq/log:/var/log/activemq
mongo:
image: mongo
ports:
- "27017:27017"
volumes:
- data-volume:/data/db
#### PLATFORM SERVICES ####
eresearch-scidir-consumer:
image: chriniko/eresearch-scidir-consumer:1.0
depends_on:
- activemq
ports:
- 8080:8080
eresearch-scopus-consumer:
image: chriniko/eresearch-scopus-consumer:1.0
depends_on:
- activemq
ports:
- 8082:8082
eresearch-dblp-consumer:
image: chriniko/eresearch-dblp-consumer:1.0
depends_on:
- activemq
ports:
- 8884:8884
eresearch-author-finder:
image: chriniko/eresearch-author-finder:1.0
depends_on:
- activemq
ports:
- 8083:8083
eresearch-author-matcher:
image: chriniko/eresearch-author-matcher:1.0
ports:
- 8881:8881
volumes:
data-volume:
my-db:
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/results/scopus/ElsevierScopusResultsTransformer.java
package com.eresearch.repositorer.transformer.results.scopus;
import com.eresearch.repositorer.domain.record.Author;
import com.eresearch.repositorer.domain.record.Entry;
import com.eresearch.repositorer.domain.record.metadata.MetadataLabelsHolder;
import com.eresearch.repositorer.domain.record.metadata.Source;
import com.eresearch.repositorer.dto.scopus.response.*;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.exception.error.RepositorerError;
import com.eresearch.repositorer.transformer.dto.TransformedEntriesDto;
import com.eresearch.repositorer.transformer.results.ResultsTransformer;
import com.eresearch.repositorer.transformer.results.metadata.ProcessMetadataPredicate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
@Log4j
@Component
public class ElsevierScopusResultsTransformer implements ResultsTransformer {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private ProcessMetadataPredicate processMetadataPredicate;
@Override
public Message<?> transform(Message<?> message) {
log.info("ElsevierScopusResultsTransformer --> " + Thread.currentThread().getName());
final String transactionId;
try {
final ScopusFinderQueueResultDto scopusFinderQueueResultDto = deserializeMessage(message);
final List<Entry> transformedEntries = doProcessing(scopusFinderQueueResultDto);
transactionId = scopusFinderQueueResultDto.getTransactionId();
return MessageBuilder
.withPayload(new TransformedEntriesDto(transformedEntries))
.setHeader(TRANSACTION_ID, transactionId)
.build();
} catch (IOException error) {
log.error("ElsevierScopusResultsTransformer#transform --- error occurred, error message: " + error.toString(), error);
throw new RepositorerBusinessException(RepositorerError.COULD_NOT_DESERIALIZE_MESSAGE,
RepositorerError.COULD_NOT_DESERIALIZE_MESSAGE.getMessage(),
error,
this.getClass().getName());
}
}
private ScopusFinderQueueResultDto deserializeMessage(Message<?> message) throws IOException {
final String resultAsString = (String) message.getPayload();
return objectMapper.readValue(resultAsString, new TypeReference<ScopusFinderQueueResultDto>() {
});
}
private List<Entry> doProcessing(ScopusFinderQueueResultDto scopusFinderQueueResultDto) throws JsonProcessingException {
final List<Entry> transformedEntries = new ArrayList<>();
ElsevierScopusConsumerResultsDto elsevierScopusConsumerResultsDto = scopusFinderQueueResultDto.getScopusConsumerResultsDto();
if (!elsevierScopusConsumerResultsDto.getOperationResult()) {
throw new RepositorerBusinessException(RepositorerError.COULD_NOT_PERFORM_OPERATION,
RepositorerError.COULD_NOT_PERFORM_OPERATION.getMessage(),
this.getClass().getName());
}
for (ScopusConsumerResultsDto scopusConsumerResultsDto : elsevierScopusConsumerResultsDto.getResults()) {
ScopusConsumerSearchViewDto scopusConsumerSearchViewDto = scopusConsumerResultsDto.getScopusConsumerSearchViewDto();
if (noResultsToProcess(scopusConsumerSearchViewDto)) continue;
for (ScopusSearchViewEntry entry : scopusConsumerSearchViewDto.getEntries()) {
Entry entryToSave = createEntry(entry);
transformedEntries.add(entryToSave);
}
}
return transformedEntries;
}
private boolean noResultsToProcess(ScopusConsumerSearchViewDto scopusConsumerSearchViewDto) {
return "0".equals(scopusConsumerSearchViewDto.getTotalResults())
&& "0".equals(scopusConsumerSearchViewDto.getStartIndex())
&& "0".equals(scopusConsumerSearchViewDto.getItemsPerPage())
&& scopusConsumerSearchViewDto.getEntries() != null
&& scopusConsumerSearchViewDto.getEntries().size() == 1
&& scopusConsumerSearchViewDto.getEntries().iterator().next().getError().equals("Result set was empty");
}
private Entry createEntry(ScopusSearchViewEntry entry) throws JsonProcessingException {
final Map<String, String> metadata;
if (processMetadataPredicate.doMetadataProcessing()) {
metadata = metadataPopulation(entry);
} else {
metadata = null;
}
String dcTitle = entry.getDcTitle();
Set<Author> entryAuthors = new LinkedHashSet<>();
Collection<ScopusSearchAuthor> authors = entry.getAuthors();
if (authors != null && !authors.isEmpty()) {
entryAuthors = authors
.stream()
.map(author -> new Author(author.getGivenName(), author.getInitials(), author.getSurname()))
.collect(LinkedHashSet::new, Set::add, Set::addAll);
}
return Entry
.builder()
.title(dcTitle)
.authors(entryAuthors)
.metadata(metadata)
.build();
}
private Map<String, String> metadataPopulation(ScopusSearchViewEntry entry) throws JsonProcessingException {
Map<String, String> metadata = new LinkedHashMap<>();
metadata.put(MetadataLabelsHolder.SOURCE.getLabelName(),
Source.ELSEVIER_SCOPUS.getSourceName());
Collection<ScopusSearchViewLink> links = entry.getLinks();
if (links != null && !links.isEmpty()) {
List<String> linksAsHrefs = links
.stream()
.map(ScopusSearchViewLink::getHref)
.filter(Objects::nonNull)
.collect(Collectors.toList());
String linksAsHrefsString = objectMapper.writeValueAsString(linksAsHrefs);
metadata.put(MetadataLabelsHolder.ScopusLabels.LINKS.getLabelName(),
linksAsHrefsString);
} else {
metadata.put(MetadataLabelsHolder.ScopusLabels.LINKS.getLabelName(),
null);
}
String prismUrl = entry.getPrismUrl();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_URL.getLabelName(),
prismUrl);
String dcIdentifier = entry.getDcIdentifier();
metadata.put(MetadataLabelsHolder.ScopusLabels.DC_IDENTIFIER.getLabelName(),
dcIdentifier);
String eid = entry.getEid();
metadata.put(MetadataLabelsHolder.ScopusLabels.EID.getLabelName(),
eid);
String dcTitle = entry.getDcTitle();
metadata.put(MetadataLabelsHolder.ScopusLabels.DC_TITLE.getLabelName(),
dcTitle);
String prismAggregationType = entry.getPrismAggregationType();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_AGGREGATION_TYPE.getLabelName(),
prismAggregationType);
String citedByCount = entry.getCitedByCount();
metadata.put(MetadataLabelsHolder.ScopusLabels.CITED_BY_COUNT.getLabelName(),
citedByCount);
String prismPublicationName = entry.getPrismPublicationName();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_PUBLICATION_NAME.getLabelName(),
prismPublicationName);
List<ScopusSearchPrismIsbn> prismIsbns = entry.getPrismIsbns();
if (prismIsbns != null && !prismIsbns.isEmpty()) {
String prismIsbnsAsString = objectMapper.writeValueAsString(prismIsbns);
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_ISBNS.getLabelName(), prismIsbnsAsString);
} else {
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_ISBNS.getLabelName(), null);
}
String prismIssn = entry.getPrismIssn();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_ISSN.getLabelName(),
prismIssn);
String prismEissn = entry.getPrismEissn();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_EISSN.getLabelName(),
prismEissn);
String prismVolume = entry.getPrismVolume();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_VOLUME.getLabelName(),
prismVolume);
String prismIssueIdentifier = entry.getPrismIssueIdentifier();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_ISSUE_IDENTIFIER.getLabelName(),
prismIssueIdentifier);
String prismPageRange = entry.getPrismPageRange();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_PAGE_RANGE.getLabelName(),
prismPageRange);
String prismCoverDate = entry.getPrismCoverDate();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_COVER_DATE.getLabelName(),
prismCoverDate);
String prismCoverDisplayDate = entry.getPrismCoverDisplayDate();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_COVER_DISPLAY_DATE.getLabelName(),
prismCoverDisplayDate);
String prismDoi = entry.getPrismDoi();
metadata.put(MetadataLabelsHolder.ScopusLabels.PRISM_DOI.getLabelName(),
prismDoi);
String pii = entry.getPii();
metadata.put(MetadataLabelsHolder.ScopusLabels.PII.getLabelName(),
pii);
String pubmedId = entry.getPubmedId();
metadata.put(MetadataLabelsHolder.ScopusLabels.PUBMED_ID.getLabelName(),
pubmedId);
String orcId = entry.getOrcId();
metadata.put(MetadataLabelsHolder.ScopusLabels.ORC_ID.getLabelName(),
orcId);
String dcCreator = entry.getDcCreator();
metadata.put(MetadataLabelsHolder.ScopusLabels.DC_CREATOR.getLabelName(),
dcCreator);
Collection<ScopusSearchAffiliation> affiliations = entry.getAffiliations();
if (affiliations != null && !affiliations.isEmpty()) {
String affiliationsAsString = objectMapper.writeValueAsString(affiliations);
metadata.put(MetadataLabelsHolder.ScopusLabels.AFFILIATIONS.getLabelName(),
affiliationsAsString);
} else {
metadata.put(MetadataLabelsHolder.ScopusLabels.AFFILIATIONS.getLabelName(),
null);
}
Collection<ScopusSearchAuthor> authors = entry.getAuthors();
if (authors != null && !authors.isEmpty()) {
String authorsAsString = objectMapper.writeValueAsString(authors);
metadata.put(MetadataLabelsHolder.ScopusLabels.AUTHORS.getLabelName(),
authorsAsString);
} else {
metadata.put(MetadataLabelsHolder.ScopusLabels.AUTHORS.getLabelName(),
null);
}
ScopusSearchAuthorCount authorCount = entry.getAuthorCount();
if (authorCount != null && authorCount.getAuthorCount() != null) {
metadata.put(MetadataLabelsHolder.ScopusLabels.AUTHOR_COUNT.getLabelName(),
authorCount.getAuthorCount());
} else {
metadata.put(MetadataLabelsHolder.ScopusLabels.AUTHOR_COUNT.getLabelName(),
null);
}
String dcDescription = entry.getDcDescription();
metadata.put(MetadataLabelsHolder.ScopusLabels.DC_DESCRIPTION.getLabelName(),
dcDescription);
String authorKeywords = entry.getAuthorKeywords();
metadata.put(MetadataLabelsHolder.ScopusLabels.AUTHOR_KEYWORDS.getLabelName(),
authorKeywords);
String articleNumber = entry.getArticleNumber();
metadata.put(MetadataLabelsHolder.ScopusLabels.ARTICLE_NUMBER.getLabelName(),
articleNumber);
String subtype = entry.getSubtype();
metadata.put(MetadataLabelsHolder.ScopusLabels.SUBTYPE.getLabelName(),
subtype);
String subtypeDescription = entry.getSubtypeDescription();
metadata.put(MetadataLabelsHolder.ScopusLabels.SUBTYPE_DESCRIPTION.getLabelName(),
subtypeDescription);
String sourceId = entry.getSourceId();
metadata.put(MetadataLabelsHolder.ScopusLabels.SOURCE_ID.getLabelName(),
sourceId);
String fundingAgencyAcronym = entry.getFundingAgencyAcronym();
metadata.put(MetadataLabelsHolder.ScopusLabels.FUNDING_AGENCY_ACRONYM.getLabelName(),
fundingAgencyAcronym);
String fundingAgencyIdentification = entry.getFundingAgencyIdentification();
metadata.put(MetadataLabelsHolder.ScopusLabels.FUNDING_AGENCY_IDENTIFICATION.getLabelName(),
fundingAgencyIdentification);
String fundingAgencyName = entry.getFundingAgencyName();
metadata.put(MetadataLabelsHolder.ScopusLabels.FUNDING_AGENCY_NAME.getLabelName(),
fundingAgencyName);
String message = entry.getMessage();
metadata.put(MetadataLabelsHolder.ScopusLabels.MESSAGE.getLabelName(),
message);
String openAccess = entry.getOpenAccess();
metadata.put(MetadataLabelsHolder.ScopusLabels.OPEN_ACCESS.getLabelName(), openAccess);
String openAccessFlag = entry.getOpenAccessFlag();
metadata.put(MetadataLabelsHolder.ScopusLabels.OPEN_ACCESS_FLAG.getLabelName(), openAccessFlag);
return metadata;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/test/ScopusIntegrationTest.java
package com.eresearch.repositorer.test;
import com.eresearch.repositorer.connector.ElsevierScopusConsumerConnector;
import com.eresearch.repositorer.dto.scopus.request.ElsevierScopusConsumerDto;
import com.eresearch.repositorer.dto.scopus.response.ScopusFinderImmediateResultDto;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
public class ScopusIntegrationTest {
@Autowired
private ElsevierScopusConsumerConnector connector;
@Autowired
private ObjectMapper objectMapper;
public void testScopusIntegration() throws RepositorerBusinessException, JsonProcessingException {
ScopusFinderImmediateResultDto scopusImmediateResult = connector.extractInfoFromScopusWithRetries(
ElsevierScopusConsumerDto.builder().scopusAuthorIdentifierNumber("23007591800").build(),
UUID.randomUUID().toString());
String resultAsAString = objectMapper.writeValueAsString(scopusImmediateResult);
System.out.println("[SCOPUS INTEGRATION RESULT] == " + resultAsAString);
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/service/DiscardedMessageService.java
package com.eresearch.repositorer.service;
import com.eresearch.repositorer.dto.repositorer.request.DiscardedMessageSearchDto;
import com.eresearch.repositorer.dto.repositorer.request.DiscaredMessageFilenameDto;
import com.eresearch.repositorer.dto.repositorer.response.DiscardedMessageDeleteOperationResultDto;
import com.eresearch.repositorer.dto.repositorer.response.RandomEntriesResponseDto;
import com.eresearch.repositorer.dto.repositorer.response.RetrievedDiscardedMessageDto;
import java.util.Collection;
public interface DiscardedMessageService {
Collection<RetrievedDiscardedMessageDto> find(DiscardedMessageSearchDto discardedMessageSearchDto, boolean fullFetch);
Collection<RetrievedDiscardedMessageDto> findAll(boolean fullFetch);
DiscardedMessageDeleteOperationResultDto deleteAll();
DiscardedMessageDeleteOperationResultDto delete(DiscaredMessageFilenameDto discaredMessageFilenameDto);
RandomEntriesResponseDto addRandomEntriesForTesting();
}
<file_sep>/src/main/java/com/eresearch/repositorer/domain/externalsystem/DynamicExternalSystemMessagesAwaiting.java
package com.eresearch.repositorer.domain.externalsystem;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.Instant;
/**
* This domain class holds external system integration info, such as for how many messages aggregator should wait (release strategy) etc.
*/
@Getter
@Setter
@Document(collection = "dynamic-external-systems-messages-awaiting")
public class DynamicExternalSystemMessagesAwaiting {
@Id
private String id;
private String transactionId;
private String externalSystemName;
private Integer noOfMessagesAwaiting;
private Instant createdAt;
public DynamicExternalSystemMessagesAwaiting(String transactionId, String externalSystemName, Integer noOfMessagesAwaiting, Instant createdAt) {
this.transactionId = transactionId;
this.externalSystemName = externalSystemName;
this.noOfMessagesAwaiting = noOfMessagesAwaiting;
this.createdAt = createdAt;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/results/dblp/processor/common/CommonDblpSource.java
package com.eresearch.repositorer.transformer.results.dblp.processor.common;
import com.eresearch.repositorer.dto.dblp.response.generated.*;
import com.eresearch.repositorer.dto.dblp.response.generated.Number;
import java.util.List;
public interface CommonDblpSource {
String getKey();
String getMdate();
String getPubltype();
String getReviewid();
String getRating();
String getCdate();
List<Author> getAuthors();
List<Editor> getEditors();
List<Title> getTitles();
List<Booktitle> getBooktitles();
List<Pages> getPages();
List<Year> getYears();
List<Address> getAddresses();
List<Journal> getJournals();
List<Volume> getVolumes();
List<Number> getNumbers();
List<Month> getMonths();
List<Url> getUrls();
List<Ee> getEes();
List<Cdrom> getCdroms();
List<Cite> getCites();
List<Publisher> getPublishers();
List<Note> getNotes();
List<Crossref> getCrossrefs();
List<Isbn> getIsbns();
List<Series> getSeries();
List<School> getSchools();
List<Chapter> getChapters();
List<Publnr> getPublnrs();
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/results/dblp/processor/common/ObjectAcceptor.java
package com.eresearch.repositorer.transformer.results.dblp.processor.common;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.exception.error.RepositorerError;
public interface ObjectAcceptor {
static CommonDblpSource isAcceptedObject(Object o) {
if (o instanceof CommonDblpSource) {
return (CommonDblpSource) o;
}
throw new RepositorerBusinessException(RepositorerError.APPLICATION_NOT_IN_CORRECT_STATE,
RepositorerError.APPLICATION_NOT_IN_CORRECT_STATE.getMessage(),
ObjectAcceptor.class.getName());
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/sciencedirect/response/SciDirImmediateResultDto.java
package com.eresearch.repositorer.dto.sciencedirect.response;
import lombok.*;
@Getter
@Setter
@AllArgsConstructor
@ToString
@NoArgsConstructor
public class SciDirImmediateResultDto {
private String message;
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/elsevierauthor/response/AuthorFinderImmediateResultDto.java
package com.eresearch.repositorer.dto.elsevierauthor.response;
import lombok.ToString;
@ToString
public class AuthorFinderImmediateResultDto {
private String message;
public AuthorFinderImmediateResultDto(String message) {
this.message = message;
}
public AuthorFinderImmediateResultDto() {
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/sciencedirect/response/ScienceDirectSearchViewEntry.java
package com.eresearch.repositorer.dto.sciencedirect.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import java.util.Collection;
@EqualsAndHashCode(of = {"dcIdentifier", "dcTitle"})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ScienceDirectSearchViewEntry {
@JsonProperty("@force-array")
private String forceArray;
@JsonProperty("error")
private String error;
@JsonProperty("@_fa")
private String fa;
@JsonProperty("load-date")
private String loadDate;
@JsonProperty("link")
private Collection<ScienceDirectSearchViewLink> links;
@JsonProperty("prism:url")
private String prismUrl;
@JsonProperty("dc:identifier")
private String dcIdentifier;
@JsonProperty("openaccess")
private String openAccess;
@JsonProperty("openaccessFlag")
private String openAccessFlag;
@JsonProperty("dc:title")
private String dcTitle;
@JsonProperty("prism:publicationName")
private String prismPublicationName;
@JsonProperty("prism:isbn")
private String prismIsbn;
@JsonProperty("prism:issn")
private String prismIssn;
@JsonProperty("prism:volume")
private String prismVolume;
@JsonProperty("prism:issueIdentifier")
private String prismIssueIdentifier;
@JsonProperty("prism:issueName")
private String prismIssueName;
@JsonProperty("prism:edition")
private String prismEdition;
@JsonProperty("prism:startingPage")
private String prismStartingPage;
@JsonProperty("prism:endingPage")
private String prismEndingPage;
@JsonProperty("prism:coverDate")
private String prismCoverDate;
@JsonProperty("prism:coverDisplayDate")
private String coverDisplayDate;
@JsonProperty("dc:creator")
private String dcCreator;
@JsonProperty("authors")
private ScienceDirectSearchViewEntryAuthors authors;
@JsonProperty("prism:doi")
private String prismDoi;
@JsonProperty("pii")
private String pii;
@JsonProperty("pubType")
private String pubType;
@JsonProperty("prism:teaser")
private String prismTeaser;
@JsonProperty("dc:description")
private String dcDescription;
@JsonProperty("authkeywords")
private String authKeywords;
@JsonProperty("prism:aggregationType")
private String prismAggregationType;
@JsonProperty("prism:copyright")
private String prismCopyright;
@JsonProperty("scopus-id")
private String scopusId;
@JsonProperty("eid")
private String eid;
@JsonProperty("scopus-eid")
private String scopusEid;
@JsonProperty("pubmed-id")
private String pubmedId;
@JsonProperty("openaccessArticle")
private String openAccessArticle;
@JsonProperty("openArchiveArticle")
private String openArchiveArticle;
@JsonProperty("openaccessUserLicense")
private String openAccessUserLicense;
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/scopus/request/ElsevierScopusConsumerDto.java
package com.eresearch.repositorer.dto.scopus.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class ElsevierScopusConsumerDto {
@JsonProperty("au-id")
private String scopusAuthorIdentifierNumber;
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/repositorer/request/RepositorerFindDtos.java
package com.eresearch.repositorer.dto.repositorer.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import java.util.List;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class RepositorerFindDtos {
@JsonProperty("names")
private List<RepositorerFindDto> repositorerFindDtos;
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/sciencedirect/response/ScienceDirectSearchViewEntryAuthor.java
package com.eresearch.repositorer.dto.sciencedirect.response;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class ScienceDirectSearchViewEntryAuthor {
@JsonProperty("$")
private String name;
/*
Note, in order to handle the following case:
1)
"authors": {
"author": "<NAME>"
}
2)
"authors": {
"author": [
{
"$": "<NAME>"
},
{
"$": "<NAME>"
},
{
"$": "<NAME>"
}
]
}
*/
@JsonCreator
public ScienceDirectSearchViewEntryAuthor(String input) {
if (input.contains("$")) {
String s = input.split(":")[1];
this.setName(s);
} else {
this.setName(input);
}
}
}
<file_sep>/init.sql
CREATE DATABASE IF NOT EXISTS scidir_consumer;
CREATE DATABASE IF NOT EXISTS scopus_consumer;
CREATE DATABASE IF NOT EXISTS dblp_consumer;
CREATE DATABASE IF NOT EXISTS author_matcher;
CREATE DATABASE IF NOT EXISTS author_finder_consumer;
<file_sep>/src/main/java/com/eresearch/repositorer/application/event/listener/BaseApplicationEventListener.java
package com.eresearch.repositorer.application.event.listener;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import lombok.extern.log4j.Log4j;
/**
* This is a basic application listener which logs all application events which
* take place. It is more used for investigation & logging purposes.
*
* Listens for every produced event.
*
* @author chriniko
*
*/
@Log4j
public class BaseApplicationEventListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
// Note: enrich this functionality based on your needs...
log.info("#### > " + event.getClass().getCanonicalName());
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/activator/externalsystem/ScienceDirectConsumptionActivator.java
package com.eresearch.repositorer.activator.externalsystem;
import com.eresearch.repositorer.connector.ScienceDirectConsumerConnector;
import com.eresearch.repositorer.dto.repositorer.request.RepositorerFindDto;
import com.eresearch.repositorer.dto.sciencedirect.request.ElsevierScienceDirectConsumerDto;
import com.eresearch.repositorer.dto.sciencedirect.response.SciDirImmediateResultDto;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.transformer.dto.RepositorerFindDtos;
import lombok.extern.log4j.Log4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
@Log4j
@Component
public class ScienceDirectConsumptionActivator implements ConsumptionActivator {
@Autowired
private ScienceDirectConsumerConnector scienceDirectConsumerConnector;
@Autowired
private ModelMapper modelMapper;
@Override
public void send(final Message<?> message) {
try {
log.info("ScienceDirectConsumptionActivator --> " + Thread.currentThread().getName());
final RepositorerFindDtos repositorerFindDtos = (RepositorerFindDtos) message.getPayload();
final String transactionId = (String) message.getHeaders().get(TRANSACTION_ID);
for (RepositorerFindDto repositorerFindDto : repositorerFindDtos.getDtos()) {
final ElsevierScienceDirectConsumerDto scienceDirectConsumerDto
= modelMapper.map(repositorerFindDto, ElsevierScienceDirectConsumerDto.class);
final SciDirImmediateResultDto immediateResult
= scienceDirectConsumerConnector.extractInfoFromScienceDirectWithRetries(scienceDirectConsumerDto, transactionId);
log.info("ScienceDirectConsumptionEventSender#send --- immediateResult = " + immediateResult);
}
} catch (RepositorerBusinessException e) {
log.error("ScienceDirectConsumptionEventSender#send --- error occurred.", e);
throw e;
}
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/dblp/response/DblpAuthor.java
package com.eresearch.repositorer.dto.dblp.response;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
import java.util.Objects;
@EqualsAndHashCode(of = {"authorName", "urlpt"})
@Getter
@Setter
@XmlAccessorType(XmlAccessType.FIELD)
public class DblpAuthor {
@XmlValue
private String authorName;
@XmlAttribute(name = "urlpt")
private String urlpt;
public DblpAuthor(String value) {
String[] splittedInfo = value.split("#");
authorName = splittedInfo[0].split("=")[1];
urlpt = splittedInfo[1].split("=")[1];
}
@Override
public String toString() {
return "authorName=" + authorName + "#urlpt=" + urlpt;
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.eresearch.repositorer</groupId>
<artifactId>eresearch-repositorer</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>eresearch-repositorer</name>
<description>This is the eresearch repositorer service.</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<skipUTs>false</skipUTs>
<skipITs>false</skipITs>
</properties>
<dependencies>
<!-- Start of Spring Dependencies -->
<dependency> <!-- is used -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency> <!-- is used -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- start of declaring dependencies for undertow server -->
<dependency> <!-- is used -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-core</artifactId>
<version>1.4.12.Final</version>
</dependency>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-servlet</artifactId>
<version>1.4.12.Final</version>
</dependency>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-websockets-jsr</artifactId>
<version>1.4.12.Final</version>
</dependency>
<!-- end of declaring dependencies for undertow server -->
<dependency> <!-- is used -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency> <!-- is used (in future) -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency> <!-- is used -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency> <!-- is used -->
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-jms</artifactId>
</dependency>
<dependency> <!-- is used -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- End of Spring Dependencies -->
<!-- Start of different dependencies -->
<!-- Start: in order to use spock framework -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>1.1-groovy-2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.athaydes</groupId>
<artifactId>spock-reports</artifactId>
<version>1.3.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.7.5</version>
</dependency>
<!-- End: in order to use spock framework -->
<dependency> <!-- is used -->
<groupId>javax.jms</groupId>
<artifactId>javax.jms-api</artifactId>
<version>2.0.1</version>
<scope>compile</scope>
</dependency>
<dependency> <!-- is used -->
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-broker</artifactId>
<version>5.14.3</version>
<scope>compile</scope>
</dependency>
<dependency> <!-- is used -->
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency> <!-- is used -->
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.7.Final</version>
</dependency>
<dependency> <!-- is used -->
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency> <!-- is used -->
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>0.7.5</version>
</dependency>
<dependency> <!-- is used -->
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
</dependency>
<dependency> <!-- is used -->
<groupId>net.jodah</groupId>
<artifactId>failsafe</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.22.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>3.1.6</version>
<scope>test</scope>
</dependency>
<!-- End of different dependencies -->
</dependencies>
<build>
<plugins>
<!-- Boot Maven Plugin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>boot</classifier>
</configuration>
</plugin>
<!-- Groovy Maven Plugin -->
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<goals>
<goal>addTestSources</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Maven Compiler Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- Maven Surefire Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<skipTests>${skipUTs}</skipTests>
<includes>
<include>**/*Test.java</include>
<include>**/*Spec.java</include>
</includes>
</configuration>
</plugin>
<!-- Failsafe Plugin -->
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.21.0</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<skipTests>${skipITs}</skipTests>
<!-- Sets the VM argument line used when unit tests are run. -->
<!--<argLine>${failsafeArgLine}</argLine>-->
<includes>
<include>**/*IT</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<!-- Start in order to create html test reports for spock framework -->
<repositories>
<repository>
<id>jcenter</id>
<name>JCenter Repo</name>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
</project>
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/dto/ElsevierAuthorResultsTransformerDto.java
package com.eresearch.repositorer.transformer.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Collection;
@Setter
@Getter
@AllArgsConstructor
@ToString
public class ElsevierAuthorResultsTransformerDto {
private Collection<String> elsevierAuthorIds;
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/elsevierauthor/response/AuthorSearchViewLink.java
package com.eresearch.repositorer.dto.elsevierauthor.response;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AuthorSearchViewLink {
@JsonProperty("@_fa")
private String fa;
@JsonProperty("@href")
private String href;
@JsonProperty("@ref")
private String ref;
@JsonProperty("@type")
private String type;
public AuthorSearchViewLink() {
}
public AuthorSearchViewLink(String fa, String href, String ref, String type) {
this.fa = fa;
this.href = href;
this.ref = ref;
this.type = type;
}
public String getFa() {
return fa;
}
public void setFa(String fa) {
this.fa = fa;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/event/BatchExtractorWakeUpEvent.java
package com.eresearch.repositorer.event;
import lombok.*;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class BatchExtractorWakeUpEvent {
private boolean continueWork;
}
<file_sep>/src/main/java/com/eresearch/repositorer/connector/DblpConsumerConnector.java
package com.eresearch.repositorer.connector;
import com.eresearch.repositorer.dto.dblp.request.DblpConsumerDto;
import com.eresearch.repositorer.dto.dblp.response.DblpImmediateResultDto;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.exception.error.RepositorerError;
import lombok.extern.log4j.Log4j;
import net.jodah.failsafe.Failsafe;
import net.jodah.failsafe.RetryPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Log4j
@Component
public class DblpConsumerConnector implements Connector {
private static final String TRANSACTION_ID = "Transaction-Id";
@Value("${dblp.consumer.url}")
private String dblpConsumerUrl;
@Autowired
@Qualifier("repositorerRestTemplate")
private RestTemplate restTemplate;
@Autowired
@Qualifier("basicRetryPolicyForConnectors")
private RetryPolicy basicRetryPolicyForConnectors;
private DblpImmediateResultDto extractInfoFromDblp(DblpConsumerDto dblpConsumerDto, String transactionId) {
final String url = dblpConsumerUrl;
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(TRANSACTION_ID, transactionId);
final HttpEntity<DblpConsumerDto> httpEntity = new HttpEntity<>(dblpConsumerDto, httpHeaders);
final ResponseEntity<DblpImmediateResultDto> responseEntity = restTemplate.exchange(
url,
HttpMethod.POST,
httpEntity,
DblpImmediateResultDto.class);
return responseEntity.getBody();
}
public DblpImmediateResultDto extractInfoFromDblpWithRetries(DblpConsumerDto dblpConsumerDto, String transactionId) {
return Failsafe
.with(basicRetryPolicyForConnectors)
.withFallback(() -> {
throw new RepositorerBusinessException(RepositorerError.CONNECTOR_CONNECTION_ERROR,
RepositorerError.CONNECTOR_CONNECTION_ERROR.getMessage(),
this.getClass().getName());
})
.onSuccess(s -> log.info("DblpConsumerConnector#extractInfoFromDblpWithRetries, completed successfully!"))
.onFailure(error -> log.error("DblpConsumerConnector#extractInfoFromDblpWithRetries, failed!"))
.onAbort(error -> log.error("DblpConsumerConnector#extractInfoFromDblpWithRetries, aborted!"))
.get((context) -> {
long startTime = context.getStartTime().toMillis();
long elapsedTime = context.getElapsedTime().toMillis();
int executions = context.getExecutions();
String message = String.format("DblpConsumerConnector#extractInfoFromDblpWithRetries, retrying...with params: " +
"[executions=%s, startTime(ms)=%s, elapsedTime(ms)=%s, dblpConsumerDto=%s, transactionId=%s]", executions, startTime, elapsedTime, dblpConsumerDto, transactionId);
log.warn(message);
return extractInfoFromDblp(dblpConsumerDto, transactionId);
});
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/application/event/listener/ApplicationReadyEventListener.java
package com.eresearch.repositorer.application.event.listener;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import lombok.extern.log4j.Log4j;
/**
* This listener listens for the event which is produced when the application is
* ready.
*
* @author chriniko
*
*/
@Log4j
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// Note: add functionality according to your needs...
log.info("~~~Application is Ready~~~");
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/results/metadata/ProcessMetadataPredicate.java
package com.eresearch.repositorer.transformer.results.metadata;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ProcessMetadataPredicate {
@Value("${collect.metadata.info}")
private String doMetadataProcessing;
public boolean doMetadataProcessing() {
return Boolean.valueOf(doMetadataProcessing);
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/AuthorEntriesMatchingTransformer.java
package com.eresearch.repositorer.transformer;
import com.eresearch.repositorer.connector.AuthorMatcherConnector;
import com.eresearch.repositorer.domain.record.Author;
import com.eresearch.repositorer.domain.record.Entry;
import com.eresearch.repositorer.domain.record.Record;
import com.eresearch.repositorer.dto.authormatcher.request.AuthorComparisonDto;
import com.eresearch.repositorer.dto.authormatcher.request.AuthorNameDto;
import com.eresearch.repositorer.dto.authormatcher.response.AuthorMatcherResultsDto;
import com.eresearch.repositorer.dto.authormatcher.response.StringMetricAlgorithm;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.service.CaptureRequestResponseService;
import com.eresearch.repositorer.transformer.dto.NameDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import lombok.extern.log4j.Log4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
@Log4j
@Component
public class AuthorEntriesMatchingTransformer {
private static final String TRANSACTION_ID = "Transaction-Id";
@Value("${author.entries.matching.string.metric.algorithm}")
private String stringMetricAlgorithmToUse;
private StringMetricAlgorithm stringMetricAlgorithmToUseEnum;
@Value("${author.entries.matching.success.threshold}")
private String successThreshold;
private double successThresholdDouble;
@Value("${apply.record.entries.filtering.with.author.matching}")
private String applyRecordEntriesFilteringWithAuthorMatching;
@Value("${author.entries.matching.multithread.approach}")
private String isMultithreadApproach;
@Value("${capture-service.enabled}")
private boolean captureServiceEnabled;
@Autowired
private CaptureRequestResponseService captureRequestResponseService;
@Autowired
@Qualifier("authorEntriesMatchingExecutor")
private ExecutorService authorEntriesMatchingExecutor;
@Autowired
private ModelMapper modelMapper;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private AuthorMatcherConnector authorMatcherConnector;
@Value("${author.entries.matching.size.splitting.threshold}")
private String authorEntriesMatchingSizeSplitting;
private Integer authorEntriesMatchingSizeSplittingInteger;
@Value("${author.entries.matching.splitting.list.size}")
private String authorEntriesMatchingSplittingListSize;
private Integer authorEntriesMatchingSplittingListSizeInteger;
@PostConstruct
public void init() {
successThresholdDouble = Double.valueOf(successThreshold);
stringMetricAlgorithmToUseEnum = StringMetricAlgorithm.valueOf(stringMetricAlgorithmToUse);
authorEntriesMatchingSizeSplittingInteger = Integer.valueOf(authorEntriesMatchingSizeSplitting);
authorEntriesMatchingSplittingListSizeInteger = Integer.valueOf(authorEntriesMatchingSplittingListSize);
}
public Message<?> transform(Message<?> message) {
log.info("AuthorEntriesMatchingTransformer --> " + Thread.currentThread().getName());
Record record = (Record) message.getPayload();
String transactionId = (String) message.getHeaders().get(TRANSACTION_ID);
if (Boolean.valueOf(applyRecordEntriesFilteringWithAuthorMatching)) {
doAuthorMatching(record);
}
return MessageBuilder
.withPayload(record)
.setHeader(TRANSACTION_ID, transactionId)
.build();
}
private void doAuthorMatching(Record record) {
final List<NameDto> nameDtosToCompareAgainst = getNameDtos(record);
if (record.getEntries() == null || record.getEntries().isEmpty()) {
return;
}
Collection<Entry> entries = record.getEntries();
final Collection<Entry> filteredEntries = getEntriesListToPopulate();
if (Boolean.valueOf(isMultithreadApproach) && entries.size() >= authorEntriesMatchingSizeSplittingInteger) {
List<List<Entry>> splittedEntries = Lists.partition(new ArrayList<>(entries), authorEntriesMatchingSplittingListSizeInteger);
List<CompletableFuture<Void>> workers = splittedEntries
.stream()
.map(splittedEntry -> CompletableFuture.runAsync(
() -> singleThreadApproach(splittedEntry, nameDtosToCompareAgainst, filteredEntries),
authorEntriesMatchingExecutor
)
)
.collect(Collectors.toList());
workers.forEach(CompletableFuture::join);
} else {
singleThreadApproach(entries, nameDtosToCompareAgainst, filteredEntries);
}
record.setEntries(filteredEntries);
}
private Collection<Entry> getEntriesListToPopulate() {
return Boolean.valueOf(isMultithreadApproach) ? Collections.synchronizedList(new LinkedList<>()) : new LinkedList<>();
}
private void singleThreadApproach(Collection<Entry> entries, List<NameDto> nameDtosToCompareAgainst, Collection<Entry> filteredEntries) {
boolean keepEntry;
for (Entry entry : entries) {
Set<Author> entryAuthors = entry.getAuthors();
if (entryAuthors == null || entryAuthors.isEmpty()) {
continue;
}
keepEntry = false;
for (NameDto nameDtoToCompareAgainst : nameDtosToCompareAgainst) {
for (Author author : entryAuthors) {
keepEntry = compare(keepEntry, nameDtoToCompareAgainst, author);
}
}
if (keepEntry) {
filteredEntries.add(entry);
}
}
}
private List<NameDto> getNameDtos(Record record) {
final List<NameDto> nameDtosToCompareAgainst = new LinkedList<>();
nameDtosToCompareAgainst.add(new NameDto(record.getFirstname(), record.getInitials(), record.getLastname()));
if (record.getNameVariants() != null && !record.getNameVariants().isEmpty()) {
nameDtosToCompareAgainst.addAll(record
.getNameVariants()
.stream()
.map(nameVariant -> modelMapper.map(nameVariant, NameDto.class))
.collect(Collectors.toCollection(LinkedList::new)));
}
return nameDtosToCompareAgainst;
}
private boolean compare(boolean keepEntry,
NameDto nameDtoToCompareAgainst /* Note: entry's author */,
Author author) {
AuthorComparisonDto authorComparisonDto = new AuthorComparisonDto(
modelMapper.map(nameDtoToCompareAgainst, AuthorNameDto.class),
modelMapper.map(author, AuthorNameDto.class)
);
try {
AuthorMatcherResultsDto authorMatcherResultsDto
= authorMatcherConnector.performAuthorMatchingWithRetries(authorComparisonDto);
if (captureServiceEnabled) {
try {
String filename = String.join("_",
Optional.ofNullable(author.getFirstname()).orElse("!"),
Optional.ofNullable(author.getInitials()).orElse("!"),
Optional.ofNullable(author.getSurname()).orElse("!"),
"$",
Optional.ofNullable(nameDtoToCompareAgainst.getFirstname()).orElse("!"),
Optional.ofNullable(nameDtoToCompareAgainst.getInitials()).orElse("!"),
Optional.ofNullable(nameDtoToCompareAgainst.getSurname()).orElse("!")
);
String requestContents = objectMapper.writeValueAsString(authorComparisonDto);
captureRequestResponseService.log(filename + "_REQUEST", requestContents, "json");
String responseContents = objectMapper.writeValueAsString(authorMatcherResultsDto);
captureRequestResponseService.log(filename + "_RESPONSE", responseContents, "json");
} catch (JsonProcessingException error) {
log.error("error occurred during serialization of contents to sent them to capture service", error);
}
}
Double comparisonResultFloor = authorMatcherResultsDto
.getResults()
.get(stringMetricAlgorithmToUseEnum)
.getComparisonResultFloor();
if (comparisonResultFloor >= successThresholdDouble) {
keepEntry = true;
}
} catch (RepositorerBusinessException e) {
log.error("AuthorEntriesMatchingTransformer#transform --- error occurred.", e);
keepEntry = true; //Note: if also retries failed and we are here, we keep it and move on.
}
return keepEntry;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/repositorer/request/RecordSearchDto.java
package com.eresearch.repositorer.dto.repositorer.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class RecordSearchDto {
@JsonProperty("firstname")
private String firstname;
@JsonProperty("initials")
private String initials;
@JsonProperty("surname")
private String surname;
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/results/dblp/processor/DblpInproceedingsProcessorBasic.java
package com.eresearch.repositorer.transformer.results.dblp.processor;
import com.eresearch.repositorer.domain.record.Entry;
import com.eresearch.repositorer.dto.dblp.response.DblpAuthor;
import com.eresearch.repositorer.dto.dblp.response.generated.Dblp;
import com.eresearch.repositorer.dto.dblp.response.generated.Inproceedings;
import com.eresearch.repositorer.transformer.results.dblp.processor.common.EntryCreator;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.LinkedList;
import java.util.List;
@Component
public class DblpInproceedingsProcessorBasic implements DblpProcessor {
private final EntryCreator entryCreator;
@Autowired
public DblpInproceedingsProcessorBasic(EntryCreator entryCreator) {
this.entryCreator = entryCreator;
}
@Override
public void doProcessing(List<Entry> entries, Dblp dblp, DblpAuthor dblpAuthor) throws JsonProcessingException {
List<Inproceedings> inproceedings = dblp.getInproceedings();
if (inproceedings != null && !inproceedings.isEmpty()) {
final List<Entry> collectedEntries = new LinkedList<>();
for (Inproceedings inproceeding : inproceedings) {
entryCreator.create(dblpAuthor, collectedEntries, inproceeding);
}
entries.addAll(collectedEntries);
}
}
@Override
public boolean allowProcessing() {
return true;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/domain/retry/RetryEntry.java
package com.eresearch.repositorer.domain.retry;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.Instant;
/**
* This domain class holds info for failed author extraction attempt(s), in order to perform retries on this/them.
*/
@Getter
@Setter
@NoArgsConstructor
@ToString(of = {"firstname", "initials", "surname", "createdAt"})
@Document(collection = "retry-entries")
public class RetryEntry implements Comparable<RetryEntry> {
@Id
private String id;
private String firstname;
private String initials;
private String surname;
private Instant createdAt;
public RetryEntry(String firstname, String initials, String surname, Instant createdAt) {
this.firstname = firstname;
this.initials = initials;
this.surname = surname;
this.createdAt = createdAt;
}
@Override
public int compareTo(RetryEntry other) {
return this.getCreatedAt().compareTo(other.getCreatedAt());
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/application/event/listener/ApplicationEnvironmentPreparedEventListener.java
package com.eresearch.repositorer.application.event.listener;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import lombok.extern.log4j.Log4j;
/**
* This listener listens for the event which is produced when the environment is
* known.
*
* @author chriniko
*
*/
@Log4j
public class ApplicationEnvironmentPreparedEventListener
implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
// NOTE: add functionality according to your needs...
log.info("~~~Application Environment Initialized(known)~~~");
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/authormatcher/request/AuthorComparisonDto.java
package com.eresearch.repositorer.dto.authormatcher.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
public class AuthorComparisonDto {
@JsonProperty("first-author-name")
private AuthorNameDto firstAuthorName;
@JsonProperty("second-author-name")
private AuthorNameDto secondAuthorName;
}
<file_sep>/src/main/java/com/eresearch/repositorer/connector/AuthorMatcherConnector.java
package com.eresearch.repositorer.connector;
import com.eresearch.repositorer.dto.authormatcher.request.AuthorComparisonDto;
import com.eresearch.repositorer.dto.authormatcher.response.AuthorMatcherResultsDto;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.exception.error.RepositorerError;
import lombok.extern.log4j.Log4j;
import net.jodah.failsafe.Failsafe;
import net.jodah.failsafe.RetryPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
@Log4j
@Component
public class AuthorMatcherConnector implements Connector {
@Value("${author.matcher.url}")
private String authorMatcherUrl;
@Autowired
@Qualifier("repositorerRestTemplate")
private RestTemplate restTemplate;
@Autowired
@Qualifier("basicRetryPolicyForConnectors")
private RetryPolicy basicRetryPolicyForConnectors;
private AuthorMatcherResultsDto performAuthorMatching(AuthorComparisonDto authorComparisonDto) {
final String url = authorMatcherUrl;
final RequestEntity<AuthorComparisonDto> requestEntity = new RequestEntity<>(
authorComparisonDto,
HttpMethod.POST,
URI.create(url));
final ResponseEntity<AuthorMatcherResultsDto> responseEntity = restTemplate.exchange(
requestEntity,
AuthorMatcherResultsDto.class);
return responseEntity.getBody();
}
public AuthorMatcherResultsDto performAuthorMatchingWithRetries(AuthorComparisonDto authorComparisonDto) {
return Failsafe
.with(basicRetryPolicyForConnectors)
.withFallback(() -> {
throw new RepositorerBusinessException(RepositorerError.CONNECTOR_CONNECTION_ERROR,
RepositorerError.CONNECTOR_CONNECTION_ERROR.getMessage(),
this.getClass().getName());
})
.onSuccess(s -> log.info("AuthorMatcherConnector#performAuthorMatchingWithRetries, completed successfully!"))
.onFailure(error -> log.error("AuthorMatcherConnector#performAuthorMatchingWithRetries, failed!"))
.onAbort(error -> log.error("AuthorMatcherConnector#performAuthorMatchingWithRetries, aborted!"))
.get((context) -> {
long startTime = context.getStartTime().toMillis();
long elapsedTime = context.getElapsedTime().toMillis();
int executions = context.getExecutions();
String message = String.format("AuthorMatcherConnector#performAuthorMatchingWithRetries, retrying...with params: " +
"[executions=%s, startTime(ms)=%s, elapsedTime(ms)=%s, authorComparisonDto=%s]", executions, startTime, elapsedTime, authorComparisonDto);
log.warn(message);
return performAuthorMatching(authorComparisonDto);
});
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/exception/business/RepositorerBusinessException.java
package com.eresearch.repositorer.exception.business;
import com.eresearch.repositorer.exception.error.RepositorerError;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class RepositorerBusinessException extends RuntimeException {
private final RepositorerError repositorerError;
private final String crashedComponentName;
public RepositorerBusinessException(RepositorerError repositorerError, String message, Throwable cause, String crashedComponentName) {
super(message, cause);
this.repositorerError = repositorerError;
this.crashedComponentName = crashedComponentName;
}
public RepositorerBusinessException(RepositorerError repositorerError, String message, String crashedComponentName) {
super(message);
this.repositorerError = repositorerError;
this.crashedComponentName = crashedComponentName;
}
public RepositorerBusinessException(RepositorerError repositorerError, String message) {
this(repositorerError, message, null);
}
public RepositorerError getRepositorerError() {
return repositorerError;
}
public String getCrashedComponentName() {
return crashedComponentName;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/error/scheduler/RecoveryEntryCreatorScheduler.java
package com.eresearch.repositorer.error.scheduler;
import com.eresearch.repositorer.domain.lookup.NameLookup;
import com.eresearch.repositorer.domain.lookup.NameLookupStatus;
import com.eresearch.repositorer.domain.retry.RetryEntry;
import com.eresearch.repositorer.repository.DynamicExternalSystemMessagesAwaitingRepository;
import com.eresearch.repositorer.repository.NamesLookupRepository;
import com.eresearch.repositorer.repository.RetryEntryRepository;
import com.google.common.collect.Sets;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Component
@Log4j
public class RecoveryEntryCreatorScheduler {
@Autowired
private NamesLookupRepository namesLookupRepository;
@Autowired
private DynamicExternalSystemMessagesAwaitingRepository externalSystemMessagesAwaitingRepository;
@Autowired
private RetryEntryRepository retryEntryRepository;
@Autowired
private Clock clock;
@Value("${healer.scheduler.enabled}")
private String isHealerSchedulerEnabled;
@Value("${entry.creator.scheduler.minutes.waiting.before.recovery.mode}")
private String minutesWaitingBeforeEnterInRecoverModeForDbConsistencyStr;
private long minutesWaitingBeforeEnterInRecoverModeForDbConsistency;
private Set<NameLookupStatus> nameLookupStatusesToNotProcess;
@PostConstruct
public void init() {
minutesWaitingBeforeEnterInRecoverModeForDbConsistency = Long.parseLong(minutesWaitingBeforeEnterInRecoverModeForDbConsistencyStr);
nameLookupStatusesToNotProcess = Sets.newHashSet(NameLookupStatus.COMPLETED, NameLookupStatus.TIMED_OUT);
}
/*
NOTE:
crone expression => second, minute, hour, day of month, month, day(s) of week
ADDITIONAL NOTES:
1) (*) means match any
2) * / X means 'every X'
3) ? ("no specific value") - useful when you need to specify something in one
of the two fields in which the character is allowed,
but not the other. For example, if I want my trigger to fire on a particular day
of the month (say, the 10th), but don't care what day of the week that happens to be,
I would put "10" in the day-of-month field, and "?" in the day-of-week field.
+-------------------- second (0 - 59)
| +----------------- minute (0 - 59)
| | +-------------- hour (0 - 23)
| | | +----------- day of month (1 - 31)
| | | | +-------- month (1 - 12)
| | | | | +----- day of week (0 - 6) (Sunday=0 or 7)
| | | | | | +-- year [optional]
| | | | | | |
* * * * * * * command to be executed
*/
@Scheduled(cron = "0 0/5 * * * *") //every five minutes.
public void doWork() {
List<NameLookup> nameLookups = namesLookupRepository.findAll();
if (nameLookups == null || nameLookups.isEmpty()) {
return;
}
//keep records which are only in PENDING status....
nameLookups = getNameLookupsWithPendingStatus(nameLookups);
log.info("RecoveryEntryCreatorScheduler#doWork --- fired, nameLookups = [" + nameLookups + "]");
final HashSet<NameLookup> uniqueNameLookups = Sets.newHashSet(nameLookups);
for (NameLookup uniqueNameLookup : uniqueNameLookups) {
Instant createdAt = uniqueNameLookup.getCreatedAt();
ZonedDateTime zonedCreatedAt = ZonedDateTime.ofInstant(createdAt, clock.getZone());
ZonedDateTime now = ZonedDateTime.now(clock);
final long minutesPassed = Duration.between(zonedCreatedAt.toInstant(), now.toInstant()).toMinutes();
final boolean shouldEnterIntoRecoverModeForDbConsistency = minutesPassed >= minutesWaitingBeforeEnterInRecoverModeForDbConsistency;
if (shouldEnterIntoRecoverModeForDbConsistency) {
recoverModeForDbConsistency(uniqueNameLookup, minutesPassed);
}
}
}
private List<NameLookup> getNameLookupsWithPendingStatus(List<NameLookup> nameLookups) {
return nameLookups
.stream()
.filter(nameLookup -> !nameLookupStatusesToNotProcess.contains(nameLookup.getNameLookupStatus()))
.collect(Collectors.toList());
}
private void recoverModeForDbConsistency(NameLookup uniqueNameLookup, long minutesPassed) {
//Note: in order to be sure and also remove duplicated entries...
String firstname = uniqueNameLookup.getFirstname();
String initials = uniqueNameLookup.getInitials();
String surname = uniqueNameLookup.getSurname();
final List<NameLookup> nameLookupsToRemove = namesLookupRepository.findAllByFirstnameEqualsAndInitialsEqualsAndSurnameEquals(
firstname,
initials,
surname);
for (NameLookup nameLookupToRemove : nameLookupsToRemove) {
String txId = nameLookupToRemove.getTransactionId();
//Note: update collection if needed -> names-lookup
NameLookup fetchedNameLookupToUpdate = namesLookupRepository.findNamesLookupByTransactionIdEquals(txId);
if (fetchedNameLookupToUpdate.getNameLookupStatus() == NameLookupStatus.PENDING) {
fetchedNameLookupToUpdate.setNameLookupStatus(NameLookupStatus.TIMED_OUT);
namesLookupRepository.save(fetchedNameLookupToUpdate);
}
//Note: clean collection -> dynamic-external-systems-messages-awaiting
externalSystemMessagesAwaitingRepository.deleteByTransactionIdEquals(txId);
}
//Note: create a new entry (if selected via properties), so another scheduler (healer) retries extraction process again in the future.
boolean recordNotExists = retryEntryRepository.findRetryEntryByFirstnameEqualsAndInitialsEqualsAndSurnameEquals(firstname, initials, surname) == null;
if (recordNotExists && Boolean.valueOf(isHealerSchedulerEnabled)) {
log.info("RecoveryScheduler#doRecovery --- going to create a recovery entry, nameLookup = [ " + uniqueNameLookup + "], minutesPassed = [" + minutesPassed + "]");
retryEntryRepository.insert(new RetryEntry(firstname, initials, surname, Instant.now(clock)));
}
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/repositorer/request/ErrorReportSearchDto.java
package com.eresearch.repositorer.dto.repositorer.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDate;
import java.time.LocalTime;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ErrorReportSearchDto {
@JsonProperty("date")
private LocalDate date;
@JsonProperty("time")
private LocalTime time;
}
<file_sep>/src/main/java/com/eresearch/repositorer/resource/NameLookupResource.java
package com.eresearch.repositorer.resource;
import com.eresearch.repositorer.dto.repositorer.request.NameLookupSearchDto;
import com.eresearch.repositorer.dto.repositorer.response.NameLookupDeleteOperationResultDto;
import com.eresearch.repositorer.dto.repositorer.response.RandomEntriesResponseDto;
import com.eresearch.repositorer.dto.repositorer.response.RetrievedNameLookupDtos;
import com.eresearch.repositorer.exception.data.RepositorerValidationException;
import org.springframework.http.ResponseEntity;
public interface NameLookupResource {
ResponseEntity<RetrievedNameLookupDtos> find(NameLookupSearchDto nameLookupSearchDto) throws RepositorerValidationException;
ResponseEntity<RetrievedNameLookupDtos> findAll();
ResponseEntity<RandomEntriesResponseDto> addRandomEntriesForTesting();
ResponseEntity<NameLookupDeleteOperationResultDto> deleteAll();
ResponseEntity<NameLookupDeleteOperationResultDto> delete(NameLookupSearchDto nameLookupSearchDto) throws RepositorerValidationException;
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/dblp/response/generated/Incollection.java
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.02.27 at 11:20:24 PM EET
//
package com.eresearch.repositorer.dto.dblp.response.generated;
import com.eresearch.repositorer.transformer.results.dblp.processor.common.CommonDblpSource;
import lombok.Getter;
import lombok.Setter;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.List;
@Getter
@Setter
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "incollection")
public class Incollection implements CommonDblpSource {
@XmlAttribute(name = "key", required = true)
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String key;
@XmlAttribute(name = "mdate")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String mdate;
@XmlAttribute(name = "publtype")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String publtype;
@XmlAttribute(name = "cdate")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String cdate;
@XmlElement(name = "author", type = Author.class)
private List<Author> authors;
@XmlElement(name = "editor", type = Editor.class)
private List<Editor> editors;
@XmlElement(name = "title", type = Title.class)
private List<Title> titles;
@XmlElement(name = "booktitle", type = Booktitle.class)
private List<Booktitle> booktitles;
@XmlElement(name = "pages", type = Pages.class)
private List<Pages> pages;
@XmlElement(name = "year", type = Year.class)
private List<Year> years;
@XmlElement(name = "address", type = Address.class)
private List<Address> addresses;
@XmlElement(name = "journal", type = Journal.class)
private List<Journal> journals;
@XmlElement(name = "volume", type = Volume.class)
private List<Volume> volumes;
@XmlElement(name = "number", type = Number.class)
private List<Number> numbers;
@XmlElement(name = "month", type = Month.class)
private List<Month> months;
@XmlElement(name = "url", type = Url.class)
private List<Url> urls;
@XmlElement(name = "ee", type = Ee.class)
private List<Ee> ees;
@XmlElement(name = "cdrom", type = Cdrom.class)
private List<Cdrom> cdroms;
@XmlElement(name = "cite", type = Cite.class)
private List<Cite> cites;
@XmlElement(name = "publisher", type = Publisher.class)
private List<Publisher> publishers;
@XmlElement(name = "note", type = Note.class)
private List<Note> notes;
@XmlElement(name = "crossref", type = Crossref.class)
private List<Crossref> crossrefs;
@XmlElement(name = "isbn", type = Isbn.class)
private List<Isbn> isbns;
@XmlElement(name = "series", type = Series.class)
private List<Series> series;
@XmlElement(name = "school", type = School.class)
private List<School> schools;
@XmlElement(name = "chapter", type = Chapter.class)
private List<Chapter> chapters;
@XmlElement(name = "publnr", type = Publnr.class)
private List<Publnr> publnrs;
@Override
public String getReviewid() {
throw new UnsupportedOperationException("not containing reviewId");
}
@Override
public String getRating() {
throw new UnsupportedOperationException("not containing rating");
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/notes.txt
-------------
--- NOTES ---
-------------
1) In order to see jacoco reports, when you have the target/jacoco.exec generated, then run the following maven goal: jacoco:report.
Then go to target/site/jacoco/index.html where you can see the results.<file_sep>/src/main/java/com/eresearch/repositorer/dto/repositorer/response/RandomEntriesResponseDto.java
package com.eresearch.repositorer.dto.repositorer.response;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class RandomEntriesResponseDto {
private String result;
}
<file_sep>/src/main/java/com/eresearch/repositorer/aggregator/correlation/TransactionIdCorrelationStrategy.java
package com.eresearch.repositorer.aggregator.correlation;
import org.springframework.integration.aggregator.CorrelationStrategy;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
@Component
public class TransactionIdCorrelationStrategy implements CorrelationStrategy {
private static final String TRANSACTION_ID = "Transaction-Id";
@Override
public Object getCorrelationKey(Message<?> message) {
return message.getHeaders().get(TRANSACTION_ID);
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/elsevierauthor/response/AuthorSearchViewEntry.java
package com.eresearch.repositorer.dto.elsevierauthor.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.EqualsAndHashCode;
import java.util.Collection;
import java.util.Objects;
@EqualsAndHashCode(of = {"dcIdentifier"})
public class AuthorSearchViewEntry {
@JsonProperty("@force-array")
private String forceArray;
@JsonProperty("error")
private String error;
@JsonProperty("@_fa")
private String fa;
@JsonProperty("link")
private Collection<AuthorSearchViewLink> links;
@JsonProperty("prism:url")
private String prismUrl;
@JsonProperty("dc:identifier")
private String dcIdentifier;
@JsonProperty("eid")
private String eid;
@JsonProperty("orcid")
private String orcId;
@JsonProperty("preferred-name")
private AuthorSearchViewPreferredName preferredName;
@JsonProperty("name-variant")
private Collection<AuthorSearchViewNameVariant> nameVariants;
@JsonProperty("document-count")
private String documentCount;
@JsonProperty("subject-area")
private Collection<AuthorSearchViewSubjectArea> subjectAreas;
@JsonProperty("affiliation-current")
private AuthorSearchViewAffiliationCurrent affiliationCurrent;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
AuthorSearchViewEntry that = (AuthorSearchViewEntry) o;
return Objects.equals(dcIdentifier, that.dcIdentifier);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), dcIdentifier);
}
public AuthorSearchViewEntry() {
}
public AuthorSearchViewEntry(String forceArray, String error, String fa, Collection<AuthorSearchViewLink> links, String prismUrl, String dcIdentifier, String eid, String orcId, AuthorSearchViewPreferredName preferredName, Collection<AuthorSearchViewNameVariant> nameVariants, String documentCount, Collection<AuthorSearchViewSubjectArea> subjectAreas, AuthorSearchViewAffiliationCurrent affiliationCurrent) {
this.forceArray = forceArray;
this.error = error;
this.fa = fa;
this.links = links;
this.prismUrl = prismUrl;
this.dcIdentifier = dcIdentifier;
this.eid = eid;
this.orcId = orcId;
this.preferredName = preferredName;
this.nameVariants = nameVariants;
this.documentCount = documentCount;
this.subjectAreas = subjectAreas;
this.affiliationCurrent = affiliationCurrent;
}
public String getForceArray() {
return forceArray;
}
public void setForceArray(String forceArray) {
this.forceArray = forceArray;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getFa() {
return fa;
}
public void setFa(String fa) {
this.fa = fa;
}
public Collection<AuthorSearchViewLink> getLinks() {
return links;
}
public void setLinks(Collection<AuthorSearchViewLink> links) {
this.links = links;
}
public String getPrismUrl() {
return prismUrl;
}
public void setPrismUrl(String prismUrl) {
this.prismUrl = prismUrl;
}
public String getDcIdentifier() {
return dcIdentifier;
}
public void setDcIdentifier(String dcIdentifier) {
this.dcIdentifier = dcIdentifier;
}
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getOrcId() {
return orcId;
}
public void setOrcId(String orcId) {
this.orcId = orcId;
}
public AuthorSearchViewPreferredName getPreferredName() {
return preferredName;
}
public void setPreferredName(AuthorSearchViewPreferredName preferredName) {
this.preferredName = preferredName;
}
public Collection<AuthorSearchViewNameVariant> getNameVariants() {
return nameVariants;
}
public void setNameVariants(Collection<AuthorSearchViewNameVariant> nameVariants) {
this.nameVariants = nameVariants;
}
public String getDocumentCount() {
return documentCount;
}
public void setDocumentCount(String documentCount) {
this.documentCount = documentCount;
}
public Collection<AuthorSearchViewSubjectArea> getSubjectAreas() {
return subjectAreas;
}
public void setSubjectAreas(Collection<AuthorSearchViewSubjectArea> subjectAreas) {
this.subjectAreas = subjectAreas;
}
public AuthorSearchViewAffiliationCurrent getAffiliationCurrent() {
return affiliationCurrent;
}
public void setAffiliationCurrent(AuthorSearchViewAffiliationCurrent affiliationCurrent) {
this.affiliationCurrent = affiliationCurrent;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/domain/lookup/NameLookup.java
package com.eresearch.repositorer.domain.lookup;
import com.eresearch.repositorer.deserializer.InstantDeserializer;
import com.eresearch.repositorer.domain.common.NameVariant;
import com.eresearch.repositorer.serializer.InstantSerializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.Instant;
import java.util.Collection;
/**
* This domain class holds the binding between author name to perform extraction and transaction id.
*/
@NoArgsConstructor
@Getter
@Setter
@ToString(of = {"firstname", "initials", "surname"})
@EqualsAndHashCode(of = {"firstname", "initials", "surname"})
@Document(collection = "names-lookup")
public class NameLookup {
@Id
private String id;
private String transactionId;
private String firstname;
private String initials;
private String surname;
private Collection<NameVariant> nameVariants;
private NameLookupStatus nameLookupStatus;
@JsonDeserialize(using = InstantDeserializer.class)
@JsonSerialize(using = InstantSerializer.class)
private Instant createdAt;
public NameLookup(String transactionId,
String firstname,
String initials,
String surname,
Collection<NameVariant> nameVariants,
NameLookupStatus nameLookupStatus,
Instant createdAt) {
this.transactionId = transactionId;
this.firstname = firstname;
this.initials = initials;
this.surname = surname;
this.nameVariants = nameVariants;
this.nameLookupStatus = nameLookupStatus;
this.createdAt = createdAt;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/error/handler/ErrorHandler.java
package com.eresearch.repositorer.error.handler;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.repository.ErrorReportRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.stereotype.Component;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.Clock;
@Component
public abstract class ErrorHandler {
final ErrorReportRepository errorReportRepository;
final Clock clock;
@Autowired
public ErrorHandler(ErrorReportRepository errorReportRepository, Clock clock) {
this.errorReportRepository = errorReportRepository;
this.clock = clock;
}
public abstract boolean canHandleIt(MessageHandlingException messageHandlingException);
public abstract void handle(MessageHandlingException messageHandlingException);
String getErrorStacktrace(Throwable businessException) {
StringWriter sw = new StringWriter();
businessException.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/service/RepositorerExtractorImpl.java
package com.eresearch.repositorer.service;
import com.eresearch.repositorer.dto.repositorer.request.RepositorerFindDto;
import com.eresearch.repositorer.dto.repositorer.request.RepositorerFindDtos;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.exception.error.RepositorerError;
import com.eresearch.repositorer.extractor.BatchExtractor;
import com.eresearch.repositorer.gateway.AuthorExtractor;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Log4j
@Service
public class RepositorerExtractorImpl implements RepositorerExtractor {
@Autowired
private TransactionId transactionId;
@Autowired
private AuthorExtractor authorExtractor;
@Autowired
private BatchExtractor batchExtractor;
@Override
public void extractAuthorInfo(final RepositorerFindDto dto, String transactionId) {
log.info("RepositorerExtractorImpl --> " + Thread.currentThread().getName());
final String txId = transactionId == null ? this.transactionId.getTransactionId() : transactionId;
authorExtractor.extract(dto, txId);
log.info("RepositorerExtractorImpl#extractAuthorInfo --- fired, with parameters: dto = "
+ dto
+ ", txId = "
+ txId);
}
@Override
public void extractAuthorInfo(RepositorerFindDtos dtos) {
// investigate if too many extraction processes are still active, if yes respond accordingly....
if (!batchExtractor.canAcceptIncomingExtraction()) {
throw new RepositorerBusinessException(RepositorerError.TOO_MANY_EXTRACTION_PROCESSES_ACTIVE,
RepositorerError.TOO_MANY_EXTRACTION_PROCESSES_ACTIVE.getMessage());
}
batchExtractor.handleExtraction(dtos);
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/results/dblp/processor/DblpProcessor.java
package com.eresearch.repositorer.transformer.results.dblp.processor;
import com.eresearch.repositorer.domain.record.Entry;
import com.eresearch.repositorer.dto.dblp.response.DblpAuthor;
import com.eresearch.repositorer.dto.dblp.response.generated.Dblp;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
public interface DblpProcessor {
void doProcessing(List<Entry> entries, Dblp dblp, DblpAuthor dblpAuthor) throws JsonProcessingException;
boolean allowProcessing();
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/authormatcher/response/StringMetricResultDto.java
package com.eresearch.repositorer.dto.authormatcher.response;
import com.fasterxml.jackson.annotation.JsonProperty;
public class StringMetricResultDto {
@JsonProperty("comparison-result")
private Double comparisonResult;
@JsonProperty("comparison-result-floor")
private Double comparisonResultFloor;
@JsonProperty("comparison-result-ceil")
private Double comparisonResultCeil;
public StringMetricResultDto() {
}
public StringMetricResultDto(Double comparisonResult, Double comparisonResultFloor, Double comparisonResultCeil) {
this.comparisonResult = comparisonResult;
this.comparisonResultFloor = comparisonResultFloor;
this.comparisonResultCeil = comparisonResultCeil;
}
public Double getComparisonResult() {
return comparisonResult;
}
public void setComparisonResult(Double comparisonResult) {
this.comparisonResult = comparisonResult;
}
public Double getComparisonResultFloor() {
return comparisonResultFloor;
}
public void setComparisonResultFloor(Double comparisonResultFloor) {
this.comparisonResultFloor = comparisonResultFloor;
}
public Double getComparisonResultCeil() {
return comparisonResultCeil;
}
public void setComparisonResultCeil(Double comparisonResultCeil) {
this.comparisonResultCeil = comparisonResultCeil;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/dto/RepositorerFindDtos.java
package com.eresearch.repositorer.transformer.dto;
import com.eresearch.repositorer.dto.repositorer.request.RepositorerFindDto;
import java.util.Collection;
public class RepositorerFindDtos {
private Collection<RepositorerFindDto> dtos;
public RepositorerFindDtos(Collection<RepositorerFindDto> dtos) {
this.dtos = dtos;
}
public RepositorerFindDtos() {
}
public Collection<RepositorerFindDto> getDtos() {
return dtos;
}
public void setDtos(Collection<RepositorerFindDto> dtos) {
this.dtos = dtos;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/application/actuator/health/EresearchRepositorerHealthCheck.java
package com.eresearch.repositorer.application.actuator.health;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Log4j
@Component
public class EresearchRepositorerHealthCheck extends AbstractHealthIndicator {
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private MongoTemplate mongoTemplate;
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
this.performBasicHealthChecks();
Optional<Exception> ex = this.specificHealthCheck();
if (ex.isPresent()) {
builder.down(ex.get());
} else {
builder.up();
}
}
private void performBasicHealthChecks() {
//check disk...
DiskSpaceHealthIndicatorProperties diskSpaceHealthIndicatorProperties
= new DiskSpaceHealthIndicatorProperties();
diskSpaceHealthIndicatorProperties.setThreshold(10737418240L); /*10 GB*/
new DiskSpaceHealthIndicator(diskSpaceHealthIndicatorProperties);
//check datasource...
new MongoHealthIndicator(mongoTemplate);
//check jms (active mq) is up...
new JmsHealthIndicator(jmsTemplate.getConnectionFactory());
}
private Optional<Exception> specificHealthCheck() {
//Note: add more thing to test for health if needed.
return Optional.empty();
}
}
<file_sep>/README.md
# ERESEARCH REPOSITORER SERVICE #
### Description
This is the backbone service of eresearch repository platform.
It integrates with external systems, collects --> aggregates based on a correlation id --> transforms and stores them
in a document based database which in our case is MongoDB.
This service integrates with the following external systems:
* [eresearch-author-matcher](https://github.com/chriniko13/eresearch-author-matcher)
* [eresearch-dblp-consumer](https://github.com/chriniko13/eresearch-dblp-consumer)
* [eresearch-scidir-consumer](https://github.com/chriniko13/eresearch-sciencedirect-consumer)
* [eresearch-author-finder](https://github.com/chriniko13/eresearch-author-finder)
* [eresearch-scopus-consumer](https://github.com/chriniko13/eresearch-scopus-consumer)
It consists of two workflows in order to collect and store the data.
* `repositorer-first-step-workflow.xml`
![first](first_workflow.jpg)
* `repositorer-second-step-workflow.xml`
![second](second_workflow.jpg)
Also it handles errors with the following workflows:
* `repositorer-error-handling-aggregators-workflow.xml`
* `repositorer-error-handling-workflow.xml`
### Convenient UI (Admin Portal) in order to run repositorer operations
* [eresearch-repositorer-admin-portal](https://github.com/chriniko13/eresearch-repositorer-admin-portal)
### External Dependencies needed in order to run service (Other services && Infrastructure)
* Dependencies
* Infrastructure
* MongoDB
* ActiveMQ
* Platform Services (Build docker images for the following services (detailed info on how to build docker image can be found on README.md
of each one of the following described services))
* [eresearch-author-matcher](https://github.com/chriniko13/eresearch-author-matcher)
* [eresearch-dblp-consumer](https://github.com/chriniko13/eresearch-dblp-consumer)
* [eresearch-scidir-consumer](https://github.com/chriniko13/eresearch-sciencedirect-consumer)
* [eresearch-author-finder](https://github.com/chriniko13/eresearch-author-finder)
* [eresearch-scopus-consumer](https://github.com/chriniko13/eresearch-scopus-consumer)
* How to init dependencies
* Execute: `docker-compose up`
* Execute: `docker-compose down`
### Unit Tests (written in Groovy with Spock Framework)
* Execute: `mvn clean test`
### Integration Tests (run docker-compose first, [eresearch-author-matcher](https://github.com/chriniko13/eresearch-author-matcher) is the only needed from platform's services, all the others are mocked with WireMock)
* Execute: `mvn clean verify`
### Create Docker Image
* Execute: `mvn clean install -DskipUTs=true -DskipITs=true`
* Execute: `docker build -t chriniko/eresearch-repositorer:1.0 .` in order to build docker image
* Fast: `mvn clean install -DskipUTs=true -DskipITs=true && docker build -t chriniko/eresearch-repositorer:1.0 .`
### How to run service (not dockerized)
1. Execute: `docker-compose up`
2. Execute: `mvn clean install -DskipUTs=true -DskipITs=true`
3. Execute: `java -Dspring.profiles.active=dev -jar target/eresearch-repositorer-1.0-boot.jar`
4. (Optional) Start: [eresearch-repositorer-admin-portal](https://github.com/chriniko13/eresearch-repositorer-admin-portal) with: `mvn tomcat7:run`
5. (Optional) To shutdown: `docker-compose down`
### Example Request for Author Extraction
* Hitting with HTTP POST the endpoint: `http://localhost:8889/repositorer/extract`
```json
{
"firstname":"Anastasios",
"initials":"",
"surname":"Tsolakidis"
}
```
### Example Response from Author Exctration
```json
{
"message": "Extraction fired."
}
```
#### After Extraction, we hit MongoDB in order to see the contents of the just fired extraction (Records Resource)
* Hitting with HTTP GET the endpoint: `http://localhost:8889/repositorer/records/find-all`
```json
{
"retrievedRecordDtos": [
{
"filename": "RECORDAnastasios_NoValue_Tsolakidis#2019-04-18T20:25:14.619"
}
]
}
```
* Hitting with HTTP GET the endpoint: `http://localhost:8889/repositorer/records/find-all?full-fetch=true`
```json
{
"retrievedRecordDtos": [
{
"filename": "RECORDAnastasios_NoValue_Tsolakidis#2019-04-18T20:25:14.619",
"record": {
"id": "e9943aff-5810-474c-b9cf-5e0e6223ca6c",
"transactionId": "f414a76c-0edb-4da6-b45b-e7c7d5bf6c6a",
"firstname": "Anastasios",
"initials": "",
"lastname": "Tsolakidis",
"nameVariants": [
{
"firstname": "A.",
"initials": "",
"surname": "Tsolakidis"
},
{
"firstname": "A",
"initials": "",
"surname": "Tsolakidis"
}
],
"createdAt": "2019-04-18T17:25:14.619Z",
"entries": [
{
"title": "AcademIS: an ontology for representing academic activity and collaborations within HEIs.",
"authors": [
{
"firstname": "Evangelia",
"initials": null,
"surname": "Triperina"
},
{
"firstname": "Cleo",
"initials": null,
"surname": "Sgouropoulou"
},
{
"firstname": "Anastasios",
"initials": null,
"surname": "Tsolakidis"
}
],
"metadata": {
"Source": "DBLP",
"Dblp Author": "{\"authorName\":\"<NAME>\",\"urlpt\":\"t/Tsolakidis:Anastasios\"}",
"Key": "conf/pci/TriperinaST13",
"Mdate": "2018-11-06",
"Publtype": null,
"Cdate": null,
"Authors": "[\"<NAME>\",\"<NAME>\",\"<NAME>\"]",
"Editors": null,
"Titles": "[\"AcademIS: an ontology for representing academic activity and collaborations within HEIs.\"]",
"Booktitles": "[\"Panhellenic Conference on Informatics\"]",
"Pages": "[\"264-271\"]",
"Years": "[\"2013\"]",
"Addresses": null,
"Journals": null,
"Volumes": null,
"Numbers": null,
"Months": null,
"Urls": "[\"db/conf/pci/pci2013.html#TriperinaST13\"]",
"Ees": "[\"https://doi.org/10.1145/2491845.2491884\"]",
"Cd roms": null,
"Cites": null,
"Publishers": null,
"Notes": null,
"Crossrefs": "[\"conf/pci/2013\"]",
"Isbns": null,
"Series": null,
"Schools": null,
"Chapters": null,
"Publnrs": null
}
},
{
"title": "PP-297. Factors that can affect birth type 10<ce:hsp sp=0.25></ce:hsp>years study",
"authors": [
{
"firstname": "Dimitrios",
"initials": null,
"surname": "Papadimitriou"
},
{
"firstname": "Athanasios",
"initials": null,
"surname": "Tsolakidis"
},
{
"firstname": "Hacer",
"initials": null,
"surname": "Hasan"
},
{
"firstname": "Anna",
"initials": null,
"surname": "Pantazi"
},
{
"firstname": "Eleni",
"initials": null,
"surname": "Karanikolaou"
}
],
"metadata": {
"Source": "Science Direct",
"Links": "[\"https://api.elsevier.com/content/article/pii/S0378378210005906\",\"https://www.sciencedirect.com/science/article/pii/S0378378210005906?dgcid=api_sd_search-api-endpoint\"]",
"Load Date": "2010-11-06T00:00:00Z",
"Prism Url": "https://api.elsevier.com/content/article/pii/S0378378210005906",
"Dc Identifier": "DOI:10.1016/j.earlhumdev.2010.09.353",
"Open Access": "false",
"Open Access Flag": null,
"Dc Title": "PP-297. Factors that can affect birth type 10<ce:hsp sp=0.25></ce:hsp>years study",
"Prism Publication Name": "Early Human Development",
"Prism Isbn": null,
"Prism Issn": null,
"Prism Volume": "86",
"Prism Issue Identifier": null,
"Prism Issue Name": null,
"Prism Edition": null,
"Prism Starting Page": "s134",
"Prism Ending Page": "s135",
"Prism Cover Date": "2010-11-30",
"Prism Cover Display Date": null,
"Dc Creator": "<NAME>",
"Authors": "[{\"$\":\"<NAME>\"},{\"$\":\"<NAME>\"},{\"$\":\"<NAME>\"},{\"$\":\"<NAME>\"},{\"$\":\"<NAME>\"}]",
"Prism Doi": "10.1016/j.earlhumdev.2010.09.353",
"Pii": "S0378378210005906",
"Pubtype": null,
"Prism Teaser": null,
"Dc Description": null,
"Author Keywords": null,
"Prism Aggregation Type": null,
"Prism Copyright": null,
"Scopus Id": null,
"Eid": null,
"Scopus Eid": null,
"Pubmed Id": null,
"Open Access Article": null,
"Open Archive Article": null,
"Open Access User License": null
}
},
.....
```
* Hitting with HTTP POST the endpoint: `http://localhost:8889/repositorer/records/find-by-filename?full-fetch=true`
* Payload:
```json
{
"filename":"RECORDGrammati_NoValue_Pantziou#2019-04-18T21:44:50.218"
}
```
* Result:
```json
{
"retrievedRecordDtos": [
{
"filename": "RECORDGrammati_NoValue_Pantziou#2019-04-18T21:44:50.218",
"record": {
"id": "7df75fa8-b063-439f-bbf4-714909a346a5",
"transactionId": "bd09a46a-9108-4102-8ef4-689ab53714a1",
"firstname": "Grammati",
"initials": "",
"lastname": "Pantziou",
"nameVariants": [
{
"firstname": "G.",
"initials": "",
"surname": "Pantziou"
},
{
"firstname": "G",
"initials": "",
"surname": "Pantziou"
}
],
"createdAt": "2019-04-18T18:44:50.218Z",
"entries": [
{
"title": "Clustering in mobile ad hoc networks through neighborhood stability-based mobility prediction",
"authors": [
{
"firstname": "Charalampos",
"initials": null,
"surname": "Konstantopoulos"
},
{
"firstname": "Grammati",
"initials": null,
"surname": "Pantziou"
},
{
"firstname": "Damianos",
"initials": null,
"surname": "Gavalas"
}
],
"metadata": {
"Source": "Science Direct",
"Links": "[\"https://api.elsevier.com/content/article/pii/S1389128608000923\",\"https://www.sciencedirect.com/science/article/pii/S1389128608000923?dgcid=api_sd_search-api-endpoint\"]",
"Load Date": "2008-03-16T00:00:00Z",
"Prism Url": "https://api.elsevier.com/content/article/pii/S1389128608000923",
"Dc Identifier": "DOI:10.1016/j.comnet.2008.01.018",
"Open Access": "false",
"Open Access Flag": null,
"Dc Title": "Clustering in mobile ad hoc networks through neighborhood stability-based mobility prediction",
"Prism Publication Name": "Computer Networks",
"Prism Isbn": null,
"Prism Issn": null,
"Prism Volume": "52",
"Prism Issue Identifier": null,
"Prism Issue Name": null,
"Prism Edition": null,
"Prism Starting Page": "1797",
"Prism Ending Page": "1824",
"Prism Cover Date": "2008-06-26",
"Prism Cover Display Date": null,
"Dc Creator": "<NAME>",
"Authors": "[{\"$\":\"<NAME>\"},{\"$\":\"<NAME>\"},{\"$\":\"<NAME>\"}]",
"Prism Doi": "10.1016/j.comnet.2008.01.018",
"Pii": "S1389128608000923",
"Pubtype": null,
"Prism Teaser": null,
"Dc Description": null,
"Author Keywords": null,
"Prism Aggregation Type": null,
"Prism Copyright": null,
"Scopus Id": null,
"Eid": null,
"Scopus Eid": null,
"Pubmed Id": null,
"Open Access Article": null,
"Open Archive Article": null,
"Open Access User License": null
}
},
{
"title": "Chapter 13: Design and management of vehicle-sharing systems: a survey of algorithmic approaches",
"authors": [
{
"firstname": "G.",
"initials": null,
"surname": "Pantziou"
},
{
"firstname": "C.",
"initials": null,
"surname": "Konstantopoulos"
},
{
"firstname": "D.",
"initials": null,
"surname": "Gavalas"
}
],
"metadata": {
"Source": "Science Direct",
"Links": "[\"https://api.elsevier.com/content/article/pii/B9780128034545000134\",\"https://www.sciencedirect.com/science/article/pii/B9780128034545000134?dgcid=api_sd_search-api-endpoint\"]",
"Load Date": "2016-06-17T00:00:00Z",
"Prism Url": "https://api.elsevier.com/content/article/pii/B9780128034545000134",
"Dc Identifier": "DOI:10.1016/B978-0-12-803454-5.00013-4",
"Open Access": "false",
"Open Access Flag": null,
"Dc Title": "Chapter 13: Design and management of vehicle-sharing systems: a survey of algorithmic approaches",
"Prism Publication Name": "Smart Cities and Homes",
"Prism Isbn": null,
"Prism Issn": null,
"Prism Volume": null,
"Prism Issue Identifier": null,
"Prism Issue Name": null,
"Prism Edition": null,
"Prism Starting Page": "261",
"Prism Ending Page": "289",
"Prism Cover Date": "2016-12-31",
"Prism Cover Display Date": null,
"Dc Creator": "<NAME>",
"Authors": "[{\"$\":\"<NAME>\"},{\"$\":\"<NAME>\"},{\"$\":\"<NAME>\"}]",
"Prism Doi": "10.1016/B978-0-12-803454-5.00013-4",
"Pii": "B9780128034545000134",
"Pubtype": null,
"Prism Teaser": null,
"Dc Description": null,
"Author Keywords": null,
"Prism Aggregation Type": null,
"Prism Copyright": null,
"Scopus Id": null,
"Eid": null,
"Scopus Eid": null,
"Pubmed Id": null,
"Open Access Article": null,
"Open Archive Article": null,
"Open Access User License": null
}
},
.....
```
### Error Report Sample
* Hitting with HTTP GET the endpoint: `http://localhost:8889/repositorer/error-reports/find-all?full-fetch=true`
```json
{
"retrievedErrorReportDtos": [
{
"filename": "ERROR_REPORT2019-04-18T15:38:34.281Z",
"errorReport": {
"id": "5cb04b8e-445e-4b9b-990d-2bd883d6387f",
"createdAt": "2019-04-18T15:38:34.281Z",
"exceptionToString": "com.eresearch.repositorer.exception.business.RepositorerBusinessException: Could not deserialize message.",
"repositorerError": "COULD_NOT_DESERIALIZE_MESSAGE",
"crashedComponentName": "com.eresearch.repositorer.transformer.results.sciencedirect.ScienceDirectResultsTransformer",
"errorStacktrace": "com.eresearch.repositorer.exception.business.RepositorerBusinessException: Could not deserialize message.\n\tat com.eresearch.repositorer.transformer.results.sciencedirect.ScienceDirectResultsTransformer.transform(ScienceDirectResultsTransformer.java:60)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.inv
...
```
### Name Lookup Sample
* Hitting with HTTP GET the endpoint: `http://localhost:8889/repositorer/name-lookups/find-all`
```json
{
"nameLookups": [
{
"id": "5cb8b2e21cf6f43290dba9fe",
"transactionId": "f414a76c-0edb-4da6-b45b-e7c7d5bf6c6a",
"firstname": "Anastasios",
"initials": "",
"surname": "Tsolakidis",
"nameVariants": [
{
"firstname": "A.",
"initials": "",
"surname": "Tsolakidis"
},
{
"firstname": "A",
"initials": "",
"surname": "Tsolakidis"
}
],
"nameLookupStatus": "COMPLETED",
"createdAt": "2019-04-18T17:24:50.865Z"
}
]
}
```
### Discarded Message Sample
TODO
<file_sep>/src/main/java/com/eresearch/repositorer/connector/ScienceDirectConsumerConnector.java
package com.eresearch.repositorer.connector;
import com.eresearch.repositorer.dto.sciencedirect.request.ElsevierScienceDirectConsumerDto;
import com.eresearch.repositorer.dto.sciencedirect.response.SciDirImmediateResultDto;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.eresearch.repositorer.exception.error.RepositorerError;
import lombok.extern.log4j.Log4j;
import net.jodah.failsafe.Failsafe;
import net.jodah.failsafe.RetryPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Log4j
@Component
public class ScienceDirectConsumerConnector implements Connector {
private static final String TRANSACTION_ID = "Transaction-Id";
@Value("${sciencedirect.consumer.url}")
private String scienceDirectConsumerUrl;
@Autowired
@Qualifier("repositorerRestTemplate")
private RestTemplate restTemplate;
@Autowired
@Qualifier("basicRetryPolicyForConnectors")
private RetryPolicy basicRetryPolicyForConnectors;
private SciDirImmediateResultDto extractInfoFromScienceDirect(ElsevierScienceDirectConsumerDto elsevierScienceDirectConsumerDto, String transactionId) {
final String url = scienceDirectConsumerUrl;
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(TRANSACTION_ID, transactionId);
final HttpEntity<ElsevierScienceDirectConsumerDto> httpEntity
= new HttpEntity<>(elsevierScienceDirectConsumerDto, httpHeaders);
final ResponseEntity<SciDirImmediateResultDto> responseEntity = restTemplate.exchange(
url,
HttpMethod.POST,
httpEntity,
SciDirImmediateResultDto.class);
return responseEntity.getBody();
}
public SciDirImmediateResultDto extractInfoFromScienceDirectWithRetries(ElsevierScienceDirectConsumerDto elsevierScienceDirectConsumerDto, String transactionId) {
return Failsafe
.with(basicRetryPolicyForConnectors)
.withFallback(() -> {
throw new RepositorerBusinessException(RepositorerError.CONNECTOR_CONNECTION_ERROR,
RepositorerError.CONNECTOR_CONNECTION_ERROR.getMessage(),
this.getClass().getName());
})
.onSuccess(s -> log.info("ScienceDirectConsumerConnector#extractInfoFromScienceDirectWithRetries, completed successfully!"))
.onFailure(error -> log.error("ScienceDirectConsumerConnector#extractInfoFromScienceDirectWithRetries, failed!"))
.onAbort(error -> log.error("ScienceDirectConsumerConnector#extractInfoFromScienceDirectWithRetries, aborted!"))
.get((context) -> {
long startTime = context.getStartTime().toMillis();
long elapsedTime = context.getElapsedTime().toMillis();
int executions = context.getExecutions();
String message = String.format("ScienceDirectConsumerConnector#extractInfoFromScienceDirectWithRetries, retrying...with params: " +
"[executions=%s, startTime(ms)=%s, elapsedTime(ms)=%s, elsevierScienceDirectConsumerDto=%s, transactionId=%s]", executions, startTime, elapsedTime, elsevierScienceDirectConsumerDto, transactionId);
log.warn(message);
return extractInfoFromScienceDirect(elsevierScienceDirectConsumerDto, transactionId);
});
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/elsevierauthor/response/AuthorSearchViewPreferredName.java
package com.eresearch.repositorer.dto.elsevierauthor.response;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AuthorSearchViewPreferredName {
@JsonProperty("surname")
private String surname;
@JsonProperty("given-name")
private String givenName;
@JsonProperty("initials")
private String initials;
public AuthorSearchViewPreferredName(String surname, String givenName, String initials) {
this.surname = surname;
this.givenName = givenName;
this.initials = initials;
}
public AuthorSearchViewPreferredName() {
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getInitials() {
return initials;
}
public void setInitials(String initials) {
this.initials = initials;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/elsevierauthor/response/AuthorSearchViewSubjectArea.java
package com.eresearch.repositorer.dto.elsevierauthor.response;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AuthorSearchViewSubjectArea {
@JsonProperty("@abbrev")
private String abbrev;
@JsonProperty("@frequency")
private String frequency;
@JsonProperty("$")
private String subjectArea;
public AuthorSearchViewSubjectArea() {
}
public AuthorSearchViewSubjectArea(String abbrev, String frequency, String subjectArea) {
this.abbrev = abbrev;
this.frequency = frequency;
this.subjectArea = subjectArea;
}
public String getAbbrev() {
return abbrev;
}
public void setAbbrev(String abbrev) {
this.abbrev = abbrev;
}
public String getFrequency() {
return frequency;
}
public void setFrequency(String frequency) {
this.frequency = frequency;
}
public String getSubjectArea() {
return subjectArea;
}
public void setSubjectArea(String subjectArea) {
this.subjectArea = subjectArea;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/test/README.txt
Remove this code, when service is fully functional.
Thanks!
<NAME>.<file_sep>/src/main/java/com/eresearch/repositorer/resource/ErrorReportResourceImpl.java
package com.eresearch.repositorer.resource;
import com.eresearch.repositorer.dto.repositorer.request.ErrorReportFilenameDto;
import com.eresearch.repositorer.dto.repositorer.request.ErrorReportSearchDto;
import com.eresearch.repositorer.dto.repositorer.response.ErrorReportDeleteOperationResultDto;
import com.eresearch.repositorer.dto.repositorer.response.RandomEntriesResponseDto;
import com.eresearch.repositorer.dto.repositorer.response.RetrievedErrorReportDtos;
import com.eresearch.repositorer.exception.data.RepositorerValidationException;
import com.eresearch.repositorer.service.ErrorReportService;
import com.eresearch.repositorer.validator.Validator;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
@Log4j
@RestController
@RequestMapping("/repositorer/error-reports")
public class ErrorReportResourceImpl implements ErrorReportResource {
private static final String DEV_PROFILE_NOT_ACTIVE_MESSAGE = "Method could not be executed, because dev profile is not active.";
@Autowired
private Environment environment;
@Autowired
private ErrorReportService errorReportService;
@Autowired
private Validator<ErrorReportSearchDto> errorReportSearchDtoValidator;
@Autowired
private Validator<ErrorReportFilenameDto> errorReportFilenameDtoValidator;
@RequestMapping(method = RequestMethod.POST, path = "/find", consumes = {
MediaType.APPLICATION_JSON_UTF8_VALUE}, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
@Override
public @ResponseBody
ResponseEntity<RetrievedErrorReportDtos> find(@RequestBody ErrorReportSearchDto errorReportSearchDto,
@RequestParam(name = "full-fetch", defaultValue = "false") boolean fullFetch) throws RepositorerValidationException {
try {
errorReportSearchDtoValidator.validate(errorReportSearchDto);
return ResponseEntity.ok(new RetrievedErrorReportDtos(errorReportService.find(errorReportSearchDto, fullFetch)));
} catch (RepositorerValidationException e) {
log.error("ErrorReportResourceImpl#find(ErrorReportSearchDto) --- error occurred.", e);
throw e;
}
}
@RequestMapping(method = RequestMethod.GET, path = "/find-all", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
@Override
public @ResponseBody
ResponseEntity<RetrievedErrorReportDtos> findAll(@RequestParam(name = "full-fetch", defaultValue = "false") boolean fullFetch) {
return ResponseEntity.ok(new RetrievedErrorReportDtos(errorReportService.findAll(fullFetch)));
}
@RequestMapping(method = RequestMethod.GET, path = "/add-random-entries", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
@Override
public @ResponseBody
ResponseEntity<RandomEntriesResponseDto> addRandomEntriesForTesting() {
boolean isDevProfileActive = Arrays.stream(environment.getActiveProfiles()).anyMatch(activeProfile -> activeProfile.equals("dev"));
if (!isDevProfileActive) {
return ResponseEntity.ok(new RandomEntriesResponseDto(DEV_PROFILE_NOT_ACTIVE_MESSAGE));
}
return ResponseEntity.ok(errorReportService.addRandomEntriesForTesting());
}
@RequestMapping(method = RequestMethod.DELETE, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
@Override
public @ResponseBody
ResponseEntity<ErrorReportDeleteOperationResultDto> deleteAll() {
ErrorReportDeleteOperationResultDto result = errorReportService.deleteAll();
return ResponseEntity.ok(result);
}
@RequestMapping(method = RequestMethod.DELETE,
consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE},
produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
@Override
public @ResponseBody
ResponseEntity<ErrorReportDeleteOperationResultDto> delete(@RequestBody ErrorReportFilenameDto errorReportFilenameDto)
throws RepositorerValidationException {
try {
errorReportFilenameDtoValidator.validate(errorReportFilenameDto);
final ErrorReportDeleteOperationResultDto result = errorReportService.delete(errorReportFilenameDto);
return ResponseEntity.ok(result);
} catch (RepositorerValidationException e) {
log.error("ErrorReportResourceImpl#delete(ErrorReportFilenameDto) --- error occurred.", e);
throw e;
}
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/resource/RepositorerResource.java
package com.eresearch.repositorer.resource;
import com.eresearch.repositorer.dto.repositorer.request.RepositorerFindDto;
import com.eresearch.repositorer.dto.repositorer.request.RepositorerFindDtos;
import com.eresearch.repositorer.dto.repositorer.response.RepositorerImmediateResultDto;
import com.eresearch.repositorer.exception.data.RepositorerValidationException;
import org.springframework.http.ResponseEntity;
public interface RepositorerResource {
ResponseEntity<RepositorerImmediateResultDto> extractAuthorInfo(RepositorerFindDto dto, String transactionId)
throws RepositorerValidationException;
ResponseEntity<RepositorerImmediateResultDto> extractAuthorInfo(RepositorerFindDtos dto)
throws RepositorerValidationException;
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/scopus/response/ScopusSearchAffiliation.java
package com.eresearch.repositorer.dto.scopus.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Collection;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ScopusSearchAffiliation {
@JsonProperty("@_fa")
private String fa;
@JsonProperty("affilname")
private String affiliationName;
@JsonProperty("affiliation-city")
private String affiliationCity;
@JsonProperty("affiliation-country")
private String affiliationCountry;
@JsonProperty("afid")
private String affiliationId;
@JsonProperty("affiliation-url")
private String affiliationUrl;
@JsonProperty("name-variant")
private Collection<ScopusSearchAffiliationNameVariant> affiliationNameVariant;
}
<file_sep>/src/main/java/com/eresearch/repositorer/test/AuthorMatcherIntegrationTest.java
package com.eresearch.repositorer.test;
import com.eresearch.repositorer.connector.AuthorMatcherConnector;
import com.eresearch.repositorer.dto.authormatcher.request.AuthorComparisonDto;
import com.eresearch.repositorer.dto.authormatcher.request.AuthorNameDto;
import com.eresearch.repositorer.dto.authormatcher.response.AuthorMatcherResultsDto;
import com.eresearch.repositorer.exception.business.RepositorerBusinessException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AuthorMatcherIntegrationTest {
@Autowired
private AuthorMatcherConnector authorMatcherConnector;
@Autowired
private ObjectMapper objectMapper;
public void testIntegrationWithAuthorMatcher() throws RepositorerBusinessException, JsonProcessingException {
AuthorComparisonDto authorComparisonDto = AuthorComparisonDto.builder()
.firstAuthorName(AuthorNameDto.builder()
.firstName("Nikolaos")
.surname("Christidis")
.build())
.secondAuthorName(AuthorNameDto.builder()
.firstName("N.")
.surname("Christidis")
.build())
.build();
AuthorMatcherResultsDto authorMatcherResultsDto = authorMatcherConnector.performAuthorMatchingWithRetries(authorComparisonDto);
String resultAsAString = objectMapper.writeValueAsString(authorMatcherResultsDto);
System.out.println("[AUTHOR MATCHER INTEGRATION RESULT] == " + resultAsAString);
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/connector/Connector.java
package com.eresearch.repositorer.connector;
/**
* This is used as a marker interface.
* Every class which implements it, means that access external systems (third-parties).
*/
public interface Connector {
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/repositorer/response/RetrievedErrorReportDto.java
package com.eresearch.repositorer.dto.repositorer.response;
import com.eresearch.repositorer.domain.error.ErrorReport;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString(of = {"filename"})
@EqualsAndHashCode(of = {"filename"})
@JsonInclude(value = JsonInclude.Include.NON_NULL) //in order to not include null error report.
public class RetrievedErrorReportDto {
private String filename;
private ErrorReport errorReport;
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/scopus/response/ScopusSearchViewLink.java
package com.eresearch.repositorer.dto.scopus.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ScopusSearchViewLink {
@JsonProperty("@_fa")
private String fa;
@JsonProperty("@href")
private String href;
@JsonProperty("@ref")
private String ref;
@JsonProperty("@type")
private String type;
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/elsevierauthor/request/AuthorFinderDto.java
package com.eresearch.repositorer.dto.elsevierauthor.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.ToString;
@Builder
@ToString
public class AuthorFinderDto {
@JsonProperty("author-name")
private AuthorNameDto authorName;
public AuthorFinderDto() {
}
public AuthorFinderDto(AuthorNameDto authorName) {
this.authorName = authorName;
}
public AuthorNameDto getAuthorName() {
return authorName;
}
public void setAuthorName(AuthorNameDto authorName) {
this.authorName = authorName;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/dblp/response/generated/Person.java
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.02.27 at 11:20:24 PM EET
//
package com.eresearch.repositorer.dto.dblp.response.generated;
import lombok.Getter;
import lombok.Setter;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.List;
@Getter
@Setter
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "person")
public class Person {
@XmlAttribute(name = "key", required = true)
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String key;
@XmlAttribute(name = "mdate")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String mdate;
@XmlAttribute(name = "cdate")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String cdate;
@XmlElement(name = "author", type = Author.class)
private List<Author> authors;
@XmlElement(name = "note", type = Note.class)
private List<Note> notes;
@XmlElement(name = "url", type = Url.class)
private List<Url> urls;
@XmlElement(name = "cite", type = Cite.class)
private List<Cite> cites;
@XmlElement(name = "crossref", type = Crossref.class)
private List<Crossref> crossrefs;
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/results/dblp/processor/DblpIncollectionsProcessorBasic.java
package com.eresearch.repositorer.transformer.results.dblp.processor;
import com.eresearch.repositorer.domain.record.Entry;
import com.eresearch.repositorer.dto.dblp.response.DblpAuthor;
import com.eresearch.repositorer.dto.dblp.response.generated.Dblp;
import com.eresearch.repositorer.dto.dblp.response.generated.Incollection;
import com.eresearch.repositorer.transformer.results.dblp.processor.common.EntryCreator;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.LinkedList;
import java.util.List;
@Component
public class DblpIncollectionsProcessorBasic implements DblpProcessor {
private final EntryCreator entryCreator;
@Autowired
public DblpIncollectionsProcessorBasic(EntryCreator entryCreator) {
this.entryCreator = entryCreator;
}
@Override
public void doProcessing(List<Entry> entries, Dblp dblp, DblpAuthor dblpAuthor) throws JsonProcessingException {
List<Incollection> incollections = dblp.getIncollections();
if (incollections != null && !incollections.isEmpty()) {
final List<Entry> collectedEntries = new LinkedList<>();
for (Incollection incollection : incollections) {
entryCreator.create(dblpAuthor, collectedEntries, incollection);
}
entries.addAll(collectedEntries);
}
}
@Override
public boolean allowProcessing() {
return true;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/transformer/results/dblp/processor/authors/AuthorsExtractor.java
package com.eresearch.repositorer.transformer.results.dblp.processor.authors;
import com.eresearch.repositorer.domain.record.Author;
import com.eresearch.repositorer.transformer.results.dblp.processor.common.CommonDblpSource;
import com.eresearch.repositorer.transformer.results.dblp.processor.common.ObjectAcceptor;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public interface AuthorsExtractor {
default Set<Author> extractAuthors(Object source) {
CommonDblpSource commonDblpSource = ObjectAcceptor.isAcceptedObject(source);
Set<com.eresearch.repositorer.domain.record.Author> entryAuthors
= new LinkedHashSet<>();
List<com.eresearch.repositorer.dto.dblp.response.generated.Author> authors = commonDblpSource.getAuthors();
if (authors != null && !authors.isEmpty()) {
for (com.eresearch.repositorer.dto.dblp.response.generated.Author author : authors) {
String authorFullName = author.getValue();
String[] splittedAuthorFullName = authorFullName.split(" ");
if (splittedAuthorFullName.length == 2) {
entryAuthors.add(new com.eresearch.repositorer.domain.record.Author(
splittedAuthorFullName[0],
null,
splittedAuthorFullName[1]));
} else if (splittedAuthorFullName.length == 3) {
entryAuthors.add(new com.eresearch.repositorer.domain.record.Author(
splittedAuthorFullName[0],
splittedAuthorFullName[1],
splittedAuthorFullName[2]));
} else {
entryAuthors.add(new com.eresearch.repositorer.domain.record.Author(
null,
null,
authorFullName));
}
}
}
return entryAuthors;
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/dto/scopus/response/ScopusSearchViewEntry.java
package com.eresearch.repositorer.dto.scopus.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import java.util.Collection;
import java.util.List;
@EqualsAndHashCode(of = {"dcIdentifier", "dcTitle"})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ScopusSearchViewEntry {
@JsonProperty("@force-array")
private String forceArray;
@JsonProperty("error")
private String error;
@JsonProperty("@_fa")
private String fa;
@JsonProperty("link")
private Collection<ScopusSearchViewLink> links;
@JsonProperty("prism:url")
private String prismUrl;
@JsonProperty("dc:identifier")
private String dcIdentifier;
@JsonProperty("eid")
private String eid;
@JsonProperty("dc:title")
private String dcTitle;
@JsonProperty("prism:aggregationType")
private String prismAggregationType;
@JsonProperty("citedby-count")
private String citedByCount;
@JsonProperty("prism:publicationName")
private String prismPublicationName;
@JsonProperty("prism:isbn")
private List<ScopusSearchPrismIsbn> prismIsbns;
@JsonProperty("prism:issn")
private String prismIssn;
@JsonProperty("prism:eIssn")
private String prismEissn;
@JsonProperty("prism:volume")
private String prismVolume;
@JsonProperty("prism:issueIdentifier")
private String prismIssueIdentifier;
@JsonProperty("prism:pageRange")
private String prismPageRange;
@JsonProperty("prism:coverDate")
private String prismCoverDate;
@JsonProperty("prism:coverDisplayDate")
private String prismCoverDisplayDate;
@JsonProperty("prism:doi")
private String prismDoi;
@JsonProperty("pii")
private String pii;
@JsonProperty("pubmed-id")
private String pubmedId;
@JsonProperty("orcid")
private String orcId;
@JsonProperty("dc:creator")
private String dcCreator;
@JsonProperty("affiliation")
private Collection<ScopusSearchAffiliation> affiliations;
@JsonProperty("author")
private Collection<ScopusSearchAuthor> authors;
@JsonProperty("author-count")
private ScopusSearchAuthorCount authorCount;
@JsonProperty("dc:description")
private String dcDescription;
@JsonProperty("authkeywords")
private String authorKeywords;
@JsonProperty("article-number")
private String articleNumber;
@JsonProperty("subtype")
private String subtype;
@JsonProperty("subtypeDescription")
private String subtypeDescription;
@JsonProperty("source-id")
private String sourceId;
@JsonProperty("fund-acr")
private String fundingAgencyAcronym;
@JsonProperty("fund-no")
private String fundingAgencyIdentification;
@JsonProperty("fund-sponsor")
private String fundingAgencyName;
@JsonProperty("message")
private String message;
@JsonProperty("openaccess")
private String openAccess;
@JsonProperty("openaccessFlag")
private String openAccessFlag;
}
<file_sep>/src/main/java/com/eresearch/repositorer/validator/ErrorReportFilenameDtoValidator.java
package com.eresearch.repositorer.validator;
import com.eresearch.repositorer.dto.repositorer.request.ErrorReportFilenameDto;
import com.eresearch.repositorer.exception.data.RepositorerValidationException;
import com.eresearch.repositorer.exception.error.RepositorerError;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Component;
@Component
@Log4j
public class ErrorReportFilenameDtoValidator implements Validator<ErrorReportFilenameDto> {
@Override
public void validate(ErrorReportFilenameDto data) throws RepositorerValidationException {
if (data.getFilename() == null
|| data.getFilename().isEmpty()) {
log.error("ErrorReportFilenameDtoValidator#validate --- error occurred (first validation) --- errorReportFilenameDto = " + data);
throw new RepositorerValidationException(RepositorerError.INVALID_DATA_ERROR, RepositorerError.INVALID_DATA_ERROR.getMessage());
}
}
}
<file_sep>/src/main/java/com/eresearch/repositorer/domain/error/ErrorReport.java
package com.eresearch.repositorer.domain.error;
import com.eresearch.repositorer.deserializer.InstantDeserializer;
import com.eresearch.repositorer.exception.error.RepositorerError;
import com.eresearch.repositorer.serializer.InstantSerializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.*;
import java.io.Serializable;
import java.time.Instant;
/**
* This domain class holds info about error(s) raised-produced in our service.
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ErrorReport implements Serializable {
private String id;
@JsonDeserialize(using = InstantDeserializer.class)
@JsonSerialize(using = InstantSerializer.class)
private Instant createdAt;
private String exceptionToString;
private RepositorerError repositorerError;
private String crashedComponentName;
private String errorStacktrace;
private String failedMessage;
}
| b3e338b835dfb66f85a361fa45ce66db96386508 | [
"SQL",
"YAML",
"Markdown",
"Maven POM",
"INI",
"Java",
"Text"
] | 88 | Java | chriniko13/eresearch-repositorer-service | c6dff3863d07d082a33c902a35244f806021d89f | 1d7ad1fcebcea476fbc27f89d956f32db00c229a | |
refs/heads/master | <file_sep>local socket = require "clientsocket"
local skynet = require "skynet"
local NORET = {}
server = server or {}
function server.onclose(errmsg)
print(string.format("%s lost connect,errmsg:%s",server.fd,errmsg))
socket.close(server.fd)
server.fd = nil
-- cann't use call
skynet.send(server.client,"lua","cmd","exit")
skynet.exit()
end
function server.unpack_package(text)
local size = #text
if size < 2 then
return nil,text
end
local s = text:byte(1) * 256 + text:byte(2)
if size < s + 2 then
return nil,text
end
return text:sub(3,s+2),text:sub(s+3)
end
function server.recv_package()
if not server.fd then
return nil
end
local result
result,server.last = server.unpack_package(server.last)
if result then
return result
end
local isok,r = pcall(socket.recv,server.fd)
if not isok then
server.onclose(r)
return nil
end
--print("server.recv_package",server.fd,r)
if not r then
return nil
end
if r == "" then
server.onclose()
return nil
end
result,server.last = server.unpack_package(server.last .. r)
return result
end
function server.sendpackage(pack)
if not server.fd then
return
end
local size = #pack
assert(size <= 65535)
local package = string.char(math.floor(size/256))..
string.char(size%256) ..
pack
socket.send(server.fd,package)
return NORET
end
function server.send_request(protoname,cmd,request,session)
local str = server.request(protoname .. "_" .. cmd,request,session)
server.sendpackage(str)
return NORET
end
function server.init(conf)
local sprotoloader = require "sprotoloader"
server.host = sprotoloader.load(1):host "package"
server.request = server.host:attach(sprotoloader.load(2))
server.client = assert(conf.client)
server.last = ""
local fd = assert(socket.connect(conf.ip,conf.port))
server.fd = fd
end
-- server -> client
function server.dispatch_package()
skynet.timeout(100,server.dispatch_package)
while true do
local v = server.recv_package()
if not v then
break
end
local typ,cmd,request,response = server.host:dispatch(v)
if typ == "REQUEST" then
local result = skynet.call(server.client,"lua","data",typ,cmd,request)
if response then
local result = response(result)
server.sendpackage(result)
end
else
assert(typ=="RESPONSE")
local session = cmd
local response = request
skynet.send(server.client,"lua","data",typ,session,response)
end
end
end
local command = {
send_request = server.send_request,
sendpackage = server.sendpackage,
}
function command.start(conf)
conf.ip = conf.ip or "127.0.0.1"
conf.port = conf.port or 8001
server.init(conf)
server.dispatch_package()
return NORET
end
function command.exit()
skynet.exit()
return NORET
end
-- client -> server
function server.dispatch(session,source,cmd,...)
local func = command[cmd]
local isok,result = pcall(func,...)
if isok then
if result ~= NORET then
skynet.ret(skynet.pack(result))
end
else
skynet.error(result)
end
end
skynet.start(function (conf)
skynet.dispatch("lua",server.dispatch)
end)
<file_sep>local skynet = require "skynet"
robert = robert or {}
robert.server = nil -- init in proto#command.start
function moveto(pos)
sendpackage(robert.server,"scene","move",{
dstpos=pos,
time = os.time(),
})
end
function enterscene(sceneid,pos)
sendpackage(robert.server,"scene","enter",{
sceneid = sceneid,
pos = pos,
})
end
function stop()
sendpackage(robert.server,"scene","stop",{})
end
function setpos(pos)
sendpackage(robert.server,"scene","setpos",{
pos = pos,
})
end
local ALL_POS = {
{x=1,y=1,dir=1},
{x=2,y=2,dir=1},
{x=3,y=3,dir=1},
{x=4,y=4,dir=1},
{x=5,y=5,dir=1},
{x=6,y=6,dir=1},
{x=7,y=7,dir=1},
{x=8,y=8,dir=1},
{x=9,y=9,dir=1},
{x=10,y=10,dir=1},
{x=11,y=11,dir=1},
{x=12,y=12,dir=1},
{x=13,y=13,dir=1},
{x=14,y=14,dir=1},
{x=15,y=15,dir=1},
{x=16,y=16,dir=1},
}
function randompos()
local i = math.random(#ALL_POS)
return ALL_POS[i]
end
local ALL_SCENEID = {1,2,3,4,5,6}
function randomsceneid()
local i = math.random(#ALL_SCENEID)
return ALL_SCENEID[i]
end
function ishit(num,limit)
return math.random(1,limit) <= num
end
local allcmd = {
moveto = 5,
stop = 4,
setpos = 90,
enterscene = 1,
}
function robert.run(server)
if not robert.server then
print "Server close"
return
end
local interval = 300 -- 1s
skynet.timeout(interval,robert.run)
local cmd = choosekey(allcmd)
--print("cmd:",cmd)
if cmd == "moveto" then
local pos = randompos()
moveto(pos)
elseif cmd == "stop" then
stop()
elseif cmd == "setpos" then
local pos = randompos()
setpos(pos)
elseif cmd == "enterscene" then
local sceneid = randomsceneid()
local pos = randompos()
enterscene(sceneid,pos)
end
end
return robert
<file_sep>local skynet = require "skynet"
skynet.start(function ()
skynet.uniqueservice("script/service/protoloader")
skynet.newservice("debug_console",6666)
local num = tonumber(skynet.getenv("num"))
local startpid = tonumber(skynet.getenv("startpid"))
if num and startpid then
skynet.newservice("script/service/robertd",num,startpid)
end
end)
<file_sep>local skynet = require "skynet"
local num,startpid = ...
num=tonumber(num) or 1
startpid=tonumber(startpid) or 1000001
skynet.start(function ()
local ip = skynet.getenv("ip") or "127.0.0.1"
local port = skynet.getenv("port") or 8001
port = tonumber(port)
for i = 0,num-1 do
local pid = startpid + i
--print("pid:",pid)
local client = skynet.newservice("script/service/client")
local server = skynet.newservice("script/service/server")
skynet.send(server,"lua","start",{
ip = ip,
port = port,
client = client,
})
skynet.send(client,"lua","cmd","start",server,pid)
end
skynet.exit()
end)
<file_sep>local sprotoloader = require "sprotoloader"
local proto = require "script.proto.proto"
local skynet = require "skynet"
local sprotoparser = require "sprotoparser"
skynet.start(function ()
--proto.dump()
local bin_c2s = sprotoparser.parse(proto.c2s)
local bin_s2c = sprotoparser.parse(proto.s2c)
sprotoloader.save(bin_s2c,1)
sprotoloader.save(bin_c2s,2)
-- don't call skynet.exit() , because sproto.core may unload and the global slot become invalid
end)
<file_sep>local skynet = require "skynet"
require "script.proto.init"
require "script.base.init"
require "script.errcode"
require "script.robert"
skynet.start(function ()
skynet.dispatch("lua",proto.dispatch)
end)
<file_sep>local skynet = require "skynet"
proto = proto or {}
local function onrequest(server,cmd,request)
pprintf("%d onrequest:%s\n",proto.pid,{
server = server,
cmd = cmd,
request = request,
})
end
local function onresponse(server,session,response)
pprintf("%d onresponse:%s\n",proto.pid,{
server = server,
session = session,
response = response,
})
local ses = assert(proto.sessions[session],"error session id:%s" .. tostring(session))
proto.sessions[session] = nil
local callback = ses.onresponse
if callback then
callback(server,ses.request,response)
end
end
local NORET = {} -- 返回NORET表示无须回复对方,调用者用send方式调用
local command = {}
function command.start(server,pid)
proto.init(server,pid)
local login = require "script.login"
local account = string.format("#%d",pid)
local passwd = "1"
print("login",server,account,passwd)
robert.server = server
login(server,account,passwd,robert.run)
return NORET
end
function command.exit()
robert.server = nil
proto.server = nil
skynet.exit()
return NORET
end
function proto.dispatch(session,source,cmd,typ,...)
if cmd == "data" then
if typ == "REQUEST" then
local ok,result = pcall(onrequest,source,...)
if ok then
skynet.ret(skynet.pack(result))
else
skynet.error(result)
end
else
assert(typ == "RESPONSE")
onresponse(source,...)
end
elseif cmd == "cmd" then
local func = command[typ]
local isok,result = pcall(func,...)
if isok then
if result ~= NORET then
skynet.ret(skynet.pack(result))
end
else
skynet.error(result)
end
end
end
function proto.sendpackage(server,protoname,cmd,request,onresponse)
local package = {
protoname = protoname,
cmd = cmd,
request = request,
onresponse = onresponse,
}
pprintf("%d sendpackage %s",proto.pid,package)
proto.session = proto.session + 1
proto.sessions[proto.session] = package
skynet.send(server,"lua","send_request",protoname,cmd,request,proto.session)
end
function proto.init(server,pid)
proto.server = server
proto.pid = pid
proto.session = 0
proto.sessions = {}
end
return proto
<file_sep>unpack = unpack or table.unpack
function pretty_tostring(obj,indent)
if type(obj) ~= "table" then
return tostring(obj)
end
local cache = {}
table.insert(cache,"{")
indent = indent + 4
for k,v in pairs(obj) do
if type(k) == "number" then
table.insert(cache,string.rep(" ",indent) .. string.format("[%d]=%s,",k,pretty_tostring(v,indent)))
else
local str = string.rep(" ",indent) .. string.format("%s=%s,",pretty_tostring(k,indent),pretty_tostring(v,indent))
table.insert(cache,str)
end
end
indent = indent - 4
table.insert(cache,string.rep(" ",indent) .. "}")
return table.concat(cache,"\n")
end
function pretty_format(fmt,...)
--local args = {...} --无法处理nil值参数
local args = table.pack(...)
local len = math.max(#args,args.n or 0)
for i = 1, len do
if type(args[i]) == "table" then
args[i] = pretty_tostring(args[i],0)
elseif type(args[i]) ~= "number" then
args[i] = tostring(args[i])
end
end
return string.format(fmt,unpack(args))
end
function pprintf(fmt,...)
local skynet = require "skynet"
local mode = skynet.getenv("mode")
if mode ~= "debug" then
return
end
print(pretty_format(fmt,...))
end
function choosekey(dct)
local sum = 0
for _,ratio in pairs(dct) do
sum = sum + ratio
end
local hit = math.random(1,sum)
local limit = 0
for key,ratio in pairs(dct) do
limit = limit + ratio
if hit <= limit then
return key
end
end
return nil
end
-- package
function sendpackage(server,protoname,cmd,request,onresponse)
require "script.proto.init"
proto.sendpackage(server,protoname,cmd,request,onresponse)
end
| 2ca9c8a0ea218cc43110b8c35c9f5f2adaf37498 | [
"Lua"
] | 8 | Lua | sundream/robert | ff67b11e227e73e5beea90fa2374339ccc157db6 | fcf31b7ce96943bd22f19dd39da4f71fc7b84d99 | |
refs/heads/master | <file_sep>window.onload = function () {
var canvas=document.getElementById("canvas");
var clearButton = document.getElementById("clear");
var context=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var isBeingDragged = false;
var startCoords ;
var endCoords ;
var context = canvas.getContext("2d");
var coordinates = [];
var flag = false;
var TriIndex = 0;
var randomColor ;
var changeDistance = {
x: 0,
y: 0
};
//coordinates wrt to the canvas
function getCoordinates(canvas, event) {
var bounds = canvas.getBoundingClientRect();
return {
x: event.clientX - bounds.left,
y: event.clientY - bounds.top
};
}
function drawTriangle(mode, x1, y1, x2, y2) {
var distance = calculateLineDistance(x1, y1, x2, y2);
var height = 1.414 * (distance) * mode;
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x1 + distance / 2, y1 + height);
context.lineTo(x1 - distance / 2, y1 + height);
context.moveTo(x1, y1);
context.fillStyle = randomColor;
context.fill();
context.stroke();
// coordinates.push([[start.x, start.y], [start.x + distance / 2, start.y + height * 1.25], [start.x - distance / 2, start.y + height * 1.25]]);
coordinates.push([[x1, y1], [x1 + distance / 2, y1 + height * 1.25], [x1 - distance / 2, y1 + height * 1.25], [context.fillStyle], [distance]]);
console.log(coordinates);
}
//select a random fill color
function selectColor() {
var r = Math.round(Math.random( )*256);
var g = Math.round(Math.random( )*256);
var b = Math.round(Math.random( )*256);
return 'rgb( ' + r + ',' + g + ',' + b + ')';
}
function calculateLineDistance(x1, y1, x2, y2) {
return Math.round(Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)));
}
function findArea(x1, y1, x2, y2, x3, y3) {
return Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
}
function insideTriangle(pos) {
flag = true;
coordinates.forEach(function (position) {
var Area = findArea(position[0][0], position[0][1], position[1][0], position[1][1], position[2][0], position[2][1]);
var Area1 = findArea(position[0][0], position[0][1], pos.x, pos.y, position[2][0], position[2][1]);
var Area2 = findArea(position[0][0], position[0][1], position[1][0], position[1][1], pos.x, pos.y);
var Area3 = findArea(pos.x, pos.y, position[1][0], position[1][1], position[2][0], position[2][1]);
if (Math.round(Area) === Math.round(Area1 + Area2 + Area3)) {
TriIndex = coordinates.indexOf(position);
flag = false;
return true;
}
});
return flag;
}
function reDrawTriangles(x1, y1, distance, color) {
var height = 1.414 * (distance);
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x1 + distance / 2, y1 + height);
context.lineTo(x1 - distance / 2, y1 + height);
context.moveTo(x1, y1);
context.fillStyle = color;
context.fill();
context.stroke();
}
function doDragTranslation(newx, newy) {
var newPos = coordinates[TriIndex];
var differenceX = newx - newPos[0][0] + changeDistance.x;
var differenceY = newy - newPos[0][1] + changeDistance.y;
newPos[0][0] += differenceX;
newPos[0][1] += differenceY;
newPos[1][0] += differenceX;
newPos[1][1] += differenceY;
newPos[2][0] += differenceX;
newPos[2][1] += differenceY;
coordinates.splice(TriIndex, 0, newPos);
clearCanvas();
coordinates.forEach(function (position) {
reDrawTriangles(position[0][0], position[0][1], position[4], position[3]);
});
}
//delete on double click
canvas.addEventListener('dblclick', function (event) {
var pos = getCoordinates(canvas, event);
coordinates.forEach(function (position) {
var Area = findArea(position[0][0], position[0][1], position[1][0], position[1][1], position[2][0], position[2][1]);
var Area1 = findArea(position[0][0], position[0][1], pos.x, pos.y, position[2][0], position[2][1]);
var Area2 = findArea(position[0][0], position[0][1], position[1][0], position[1][1], pos.x, pos.y);
var Area3 = findArea(pos.x, pos.y, position[1][0], position[1][1], position[2][0], position[2][1]);
if (Math.round(Area) === Math.round(Area1 + Area2 + Area3)) {
var newList = [];
var newPos = coordinates[coordinates.indexOf(position)];
coordinates.forEach(function (position2) {
if (position2 !== newPos) {
newList.push(position2);
}
});
coordinates = newList;
clearCanvas();
coordinates.forEach(function (position2) {
reDrawTriangles(position2[0][0], position2[0][1], position2[4], position2[3]);
});
return true;
}
});
isBeingDragged = false;
});
//one mousedown listener
canvas.addEventListener('mousedown', function (event) {
canvas.style.cursor = 'move';
event.preventDefault();
var mousePos = getCoordinates(canvas, event);
startCoords = mousePos;
endCoords = mousePos;
isBeingDragged = true;
flag = insideTriangle(mousePos);
startCoords = mousePos;
endCoords = mousePos;
randomColor = selectColor();
if (coordinates.length > 0) {
changeDistance.x = coordinates[TriIndex][0][0] - mousePos.x;
changeDistance.y = coordinates[TriIndex][0][1] - mousePos.y
}
console.log(changeDistance);
});
//movement listener
canvas.addEventListener('mousemove', function (event) {
endCoords = getCoordinates(canvas, event);
if (isBeingDragged && flag) {
clearCanvas();
canvas.style.cursor = 'ne-resize';
reDrawTriangles(startCoords.x, startCoords.y, calculateLineDistance(startCoords.x, startCoords.y, endCoords.x, endCoords.y), randomColor);
coordinates.forEach(function (position) {
reDrawTriangles(position[0][0], position[0][1], position[4], position[3]);
});
} else if (isBeingDragged) {
canvas.style.cursor = 'crosshair';
clearCanvas();
// doDragTranslationAtMove(endCoords.x, endCoords.y);
var newPos = coordinates[TriIndex];
var differenceX = endCoords.x - newPos[0][0] + changeDistance.x;
var differenceY = endCoords.y - newPos[0][1] + changeDistance.y;
newPos[0][0] += differenceX;
newPos[0][1] += differenceY;
newPos[1][0] += differenceX;
newPos[1][1] += differenceY;
newPos[2][0] += differenceX;
newPos[2][1] += differenceY;
reDrawTriangles(newPos[0][0], newPos[0][1], newPos[4], newPos[3]);
coordinates.forEach(function (position) {
if (position[0][0] !== startCoords.x && position[0][1] !== startCoords.y) {
reDrawTriangles(position[0][0], position[0][1], position[4], position[3]);
}
});
}
}, true);
//event-listener for mouseUp
canvas.addEventListener('mouseup', function (event) {
canvas.style.cursor = 'pointer';
var mousePos = getCoordinates(canvas, event);
if (!flag) {
isBeingDragged = false;
flag = false;
doDragTranslation(mousePos.x, mousePos.y);
} else if (isBeingDragged && calculateLineDistance(startCoords.x, startCoords.y, endCoords.x, endCoords.y) > 2) {
isBeingDragged = false;
flag = false;
endCoords = mousePos;
drawTriangle(1, startCoords.x, startCoords.y, endCoords.x, endCoords.y);
}
});
clearButton.addEventListener('click', function () {
coordinates = [];
clearCanvas();
});
function clearCanvas( ){
context.clearRect(0,0,canvas.width, canvas.height);
}
};
| 84309522f880d79195f8becbfb7847ed91e8f21d | [
"JavaScript"
] | 1 | JavaScript | sonalijoseph1205/simplepaintapp | c830b93060b5345f7689caf5759f29681abea132 | 6446174b156683f70bb3677106b9ac08f14ebeb0 | |
refs/heads/master | <file_sep>from PyQt5 import QtCore, QtGui, QtWidgets
from DataFrameModel import PandasModel
import pandas as pd
class FromInit(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent=None)
self.setWindowTitle('AMS')
self.resize(500,300)
self.rptDate = ''
self.rptAcct = ''
vLayout = QtWidgets.QVBoxLayout(self)
hLayout = QtWidgets.QHBoxLayout()
lblDate = QtWidgets.QLabel(self)
lblDate.setText('Date')
hLayout.addWidget(lblDate)
cal = QtWidgets.QCalendarWidget(self)
dtEdit = QtWidgets.QDateEdit(QtCore.QDate.currentDate(), self)
dtEdit.setCalendarPopup(True)
dtEdit.setCalendarWidget(cal)
dtEdit.setMaximumDate(QtCore.QDate.currentDate())
dtEdit.setDate(cal.selectedDate())
dtEdit.dateChanged.connect(self.saveDate)
hLayout.addWidget(dtEdit)
lblAcct = QtWidgets.QLabel(self)
lblAcct.setText('Account')
hLayout.addWidget(lblAcct)
comboAcct = QtWidgets.QComboBox()
comboAcct.addItems(['Citic', 'CMB', 'ALL'])
comboAcct.currentTextChanged.connect(self.saveAcct)
hLayout.addWidget(comboAcct)
hLayout.addStretch(1)
btnReport = QtWidgets.QPushButton("REPORT", self)
btnReport.clicked.connect(self.loadReport)
hLayout.addWidget(btnReport)
vLayout.addLayout(hLayout)
self.tblHold = QtWidgets.QTableView(self)
vLayout.addWidget(self.tblHold)
self.rptDate = dtEdit.date().toString('yyyyMMdd')
self.rptAcct = comboAcct.currentText()
def loadReport(self):
df = pd.read_excel('A_Shares.xlsx',sheet_name='Trans')
model = PandasModel(df)
self.tblHold.setModel(model)
self.tblHold.setSortingEnabled(True)
self.tblHold.horizontalHeader().setStyleSheet("QHeaderView::section {background-color:lightblue;color: black;padding-left: 4px;border: 1px solid #6c6c6c;font: bold;}")
def saveAcct(self, str):
self.rptAcct = str
def saveDate(self, date):
self.rptDate = date.toString('yyyyMMdd')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = FromInit()
w.show()
sys.exit(app.exec_())<file_sep># -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QWidget
from first import Ui_First
from second import Ui_Second
class Ui_MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent=None)
# initialize format of main form
self.setWindowTitle('AMS')
self.setFixedSize(900,600)
#self.resize(1200,600)
self.first = First()
self.second = Second()
self.mainSplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
# main form layout
mainWidget = QtWidgets.QWidget()
mainLayout = QtWidgets.QVBoxLayout()
mainLayout.setContentsMargins(3, 0, 3, 1)
mainWidget.setLayout(mainLayout)
mainLayout.addWidget(self.mainSplitter)
self.setCentralWidget(mainWidget)
# initialize menu widgets
menuSplitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
menuSplitter.setHandleWidth(0)
pixLogo = QtGui.QPixmap('logo.png')
lblLogo = QtWidgets.QLabel()
lblLogo.setScaledContents(True)
lblLogo.setFixedSize(150,60)
lblLogo.setPixmap(pixLogo)
menuSplitter.addWidget(lblLogo)
btnReport = QtWidgets.QPushButton('REPORT')
btnReport.setFixedSize(150,30)
menuSplitter.addWidget(btnReport)
btnFunc = QtWidgets.QPushButton('FUNCTION')
btnFunc.setFixedSize(150,30)
menuSplitter.addWidget(btnFunc)
#用frame占位,保持菜单按钮位置固定不变
frame = QtWidgets.QFrame()
menuSplitter.addWidget(frame)
# initialize main splitter
self.mainSplitter.addWidget(menuSplitter)
frameTest = QtWidgets.QFrame()
frameTest.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.mainSplitter.addWidget(frameTest)
#菜单默认关闭
self.mainSplitter.setSizes([1, 1])
# format handle of main splitter
self.mainSplitter.setHandleWidth(20)
self.handleLayout(self.mainSplitter)
self.mainSplitter.setStyleSheet('''
QWidget{border-style:solid;border-width:2;border-color:red}
''')
menuSplitter.setStyleSheet('''
QPushButton{border:none;color:white;;background-color:black}
QLabel{border:none;background-color:black}
QFrame{border:none;background-color:black}
''')
# connect button function
btnReport.clicked.connect(lambda :self.changeUI('REPORT'))
btnFunc.clicked.connect(lambda :self.changeUI('FUNCTION'))
def handleLayout(self, splitter):
handle = splitter.handle(1)
layout = QtWidgets.QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
button = QtWidgets.QToolButton(handle)
button.setArrowType(QtCore.Qt.LeftArrow)
button.setFixedSize(20,40)
button.clicked.connect(lambda: self.handleSplitterButton(True))
layout.addWidget(button)
handle.setLayout(layout)
def handleSplitterButton(self, left=True):
if not all(self.mainSplitter.sizes()):
self.mainSplitter.setSizes([1, 1])
elif left:
self.mainSplitter.setSizes([0, 1])
def changeUI(self,name):
if name == "REPORT":
self.mainSplitter.widget(1).setParent(None)
self.mainSplitter.insertWidget(1, self.first)
self.handleLayout(self.mainSplitter)
if name == "FUNCTION":
self.mainSplitter.widget(1).setParent(None)
self.mainSplitter.insertWidget(1, self.second)
self.handleLayout(self.mainSplitter)
class First(QWidget, Ui_First):
def __init__(self):
super(First,self).__init__()
# 子窗口初始化时实现子窗口布局
self.initUI(self)
# 设置子窗体最小尺寸
self.setMinimumWidth(30)
self.setMinimumHeight(30)
class Second(QWidget, Ui_Second):
def __init__(self):
super(Second,self).__init__()
self.initUI(self)
self.setMinimumWidth(30)
self.setMinimumHeight(30)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Ui_MainWindow()
ui.show()
sys.exit(app.exec_())<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'index.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QWidget
from first import Ui_First
from second import Ui_Second
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.splitter = QtWidgets.QSplitter(self.centralwidget)
self.splitter.setOrientation(QtCore.Qt.Horizontal)
self.splitter.setObjectName("splitter")
self.frame = QtWidgets.QFrame(self.splitter)
self.frame.setMaximumSize(QtCore.QSize(200, 16777215))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.verticalLayout = QtWidgets.QVBoxLayout(self.frame)
self.verticalLayout.setObjectName("verticalLayout")
self.pushButton = QtWidgets.QPushButton(self.frame)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
self.pushButton_2 = QtWidgets.QPushButton(self.frame)
self.pushButton_2.setObjectName("pushButton_2")
self.verticalLayout.addWidget(self.pushButton_2)
# 这里注释掉,因为不需要frame2。当初在qt 里面设计这个frame2的原因是为了占位,不至于到时候布局出现错乱。
# self.frame_2 = QtWidgets.QFrame(self.splitter)
# self.frame_2.setStyleSheet("background-color:white;")
# self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
# self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
# self.frame_2.setObjectName("frame_2")
self.horizontalLayout.addWidget(self.splitter)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
# 初始化两个对象,并把 first对象 加入到 splitter 中
self.first = First()
self.second = Second()
self.splitter.addWidget(self.first)
self.pushButton.clicked.connect(lambda :self.change(self.pushButton.objectName()))
self.pushButton_2.clicked.connect(lambda :self.change(self.pushButton_2.objectName()))
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "界面1"))
self.pushButton_2.setText(_translate("MainWindow", "界面2"))
def change(self,name):
if name == "pushButton":
self.splitter.widget(1).setParent(None)
self.splitter.insertWidget(1, self.first)
if name == "pushButton_2":
self.splitter.widget(1).setParent(None)
self.splitter.insertWidget(1, self.second)
class First(QWidget, Ui_First):
def __init__(self):
super(First,self).__init__()
# 子窗口初始化时实现子窗口布局
self.setupUi(self)
# 设置子窗体最小尺寸
self.setMinimumWidth(30)
self.setMinimumHeight(30)
class Second(QWidget, Ui_Second):
def __init__(self):
super(Second,self).__init__()
self.setupUi(self)
self.setMinimumWidth(30)
self.setMinimumHeight(30)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())<file_sep># -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from DataFrameModel import PandasModel
import pandas as pd
class Ui_DailySummary(object):
def initUI(self, Ui_DailySummary):
#初始化报告参数
self.rptDate = ''
self.rptAcct = ''
vLayout = QtWidgets.QVBoxLayout(self)
hLayout = QtWidgets.QHBoxLayout()
hLayout2 = QtWidgets.QHBoxLayout()
lblDate = QtWidgets.QLabel(self)
lblDate.setText('Date')
hLayout.addWidget(lblDate)
cal = QtWidgets.QCalendarWidget(self)
dtEdit = QtWidgets.QDateEdit(QtCore.QDate.currentDate(), self)
dtEdit.setCalendarPopup(True)
dtEdit.setCalendarWidget(cal)
dtEdit.setMaximumDate(QtCore.QDate.currentDate())
dtEdit.setDate(cal.selectedDate())
dtEdit.dateChanged.connect(self.saveDate)
#dtEdit.setFixedWidth(120)
hLayout.addWidget(dtEdit)
lblAcct = QtWidgets.QLabel(self)
lblAcct.setText('Account')
hLayout.addWidget(lblAcct)
comboAcct = QtWidgets.QComboBox()
comboAcct.setEditable(True)
comboAcct.lineEdit().setAlignment(QtCore.Qt.AlignLeft)
comboAcct.addItems(['Citic', 'CMB', 'ALL'])
comboAcct.currentTextChanged.connect(self.saveAcct)
comboAcct.setStyleSheet("background-color:white;")
hLayout.addWidget(comboAcct)
hLayout.addStretch(10)
btnReport = QtWidgets.QPushButton("RUN REPORT", self)
btnReport.clicked.connect(self.loadReport)
hLayout.addWidget(btnReport)
hLayout.addStretch(1)
widget = QtWidgets.QWidget()
widget.setLayout(hLayout)
#widget.setFixedHeight(50)
vLayout.addWidget(widget)
hLayout.setContentsMargins(0, 0, 0, 0)
hLayout2.setContentsMargins(0, 0, 0, 0)
vLayout.setContentsMargins(0, 0, 0, 0)
vLayout.setSpacing(0)
self.tblHold = QtWidgets.QTableView(self)
hLayout2.addWidget(self.tblHold)
vLayout.addLayout(hLayout2)
self.rptDate = dtEdit.date().toString('yyyyMMdd')
self.rptAcct = comboAcct.currentText()
def loadReport(self):
df = pd.read_excel('A_Shares.xlsx',sheet_name='Trans')
model = PandasModel(df)
self.tblHold.setModel(model)
self.tblHold.setSortingEnabled(True)
self.tblHold.horizontalHeader().setStyleSheet("QHeaderView::section {background-color:lightblue;color: black;padding-left: 4px;border: 1px solid #6c6c6c;font: bold;}")
def saveAcct(self, str):
self.rptAcct = str
def saveDate(self, date):
self.rptDate = date.toString('yyyyMMdd')<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'second.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Second(object):
def setupUi(self, Ui_Second):
Ui_Second.setObjectName("MainWindow")
Ui_Second.resize(800, 600)
# self.centralwidget = QtWidgets.QWidget(Ui_Second)
# self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(Ui_Second)
self.horizontalLayout.setObjectName("horizontalLayout")
self.frame_2 = QtWidgets.QFrame(Ui_Second)
self.frame_2.setStyleSheet("background-color:green;")
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.label = QtWidgets.QLabel(self.frame_2)
self.label.setGeometry(QtCore.QRect(300, 180, 181, 81))
font = QtGui.QFont()
font.setPointSize(20)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.frame_2)
# Ui_Second.setCentralWidget(self.centralwidget)
# self.menubar = QtWidgets.QMenuBar(Ui_Second)
# self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
# self.menubar.setObjectName("menubar")
# Ui_Second.setMenuBar(self.menubar)
# self.statusbar = QtWidgets.QStatusBar(Ui_Second)
# self.statusbar.setObjectName("statusbar")
# Ui_Second.setStatusBar(self.statusbar)
self.retranslateUi(Ui_Second)
QtCore.QMetaObject.connectSlotsByName(Ui_Second)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "这是界面2"))
<file_sep>import pandas as pd
import time
tuple_cur = ('CNY', 'HKD', 'USD')
def get_trans(date, account):
#读取交易数据
df_trans_all = pd.read_excel('A_Shares.xlsx',sheet_name='Trans')
df_trans_all['Date'] = df_trans_all[['Date','Symbol_Code']].astype(str)
df_trans = df_trans_all[df_trans_all['Date'] <= date]
df_trans = df_trans[df_trans['Account'].isin(account)]
df_trans = df_trans.round(4)
return df_trans
def get_cost(code, qt, df):
df_code = df[df['Symbol_Code'].isin([code])]
df_code.sort_values(by = ['Date'],axis = 0,ascending = False, inplace=True)
#从当前持仓日往前取买入即分红送股数据获取成本金额
#直至当前持仓数量扣除完整为止
amt_cost = 0
for i in df_code.index.tolist():
if qt <= 0:
break
else:
qt_trans = df_code.loc[i,'Quantity']
amt_trans = df_code.loc[i,'Settle_Amt']
amt_cost = amt_cost + (amt_trans * (qt/qt_trans if qt_trans>qt else 1)) * -1
qt = qt - qt_trans
return amt_cost
def get_holding(date, df_trans):
#取股票持仓
df_trans_stock = df_trans[~df_trans['Symbol_Code'].isin(tuple_cur)]
df_group_stock = df_trans_stock.loc[:, ['Symbol_Code', 'Symbol_Name', 'Cur', 'Quantity']]
df_group_stock = df_group_stock.groupby(['Symbol_Code', 'Symbol_Name', 'Cur']).sum()
df_group_stock = df_group_stock.reset_index()
df_group_stock.drop(index=(df_group_stock.loc[(df_group_stock['Quantity']==0)].index), inplace=True)
df_group_stock['Date'] = date
#取持仓股票成本
df_trans_buy = df_trans_stock[df_trans_stock['Quantity']>=0]
df_group_stock['Cost_Amt'] = float(0)
for i in df_group_stock.index.tolist():
code = df_group_stock.loc[i,'Symbol_Code']
hold_quantity = df_group_stock.loc[i,'Quantity']
if hold_quantity > 0:
cost_amt = get_cost(code, hold_quantity, df_trans_buy)
df_group_stock.at[i, 'Cost_Amt'] = cost_amt
#取现金持仓
df_trans_cur = df_trans
df_group_cur = df_trans_cur.loc[:, ['Cur', 'Settle_Amt']]
df_group_cur = df_group_cur.groupby(['Cur']).sum()
df_group_cur = df_group_cur.reset_index()
df_group_cur['Date'] = date
df_group_cur['Symbol_Code'] = df_group_cur['Cur']
df_group_cur['Symbol_Name'] = df_group_cur['Cur']
df_group_cur.rename(columns={'Settle_Amt':'Quantity'}, inplace=True)
df_group_cur['Cost_Amt'] = df_group_cur['Quantity']
#合并资金及股票持仓
df_hold = df_group_stock.append(df_group_cur, ignore_index=True)
df_hold = df_hold.round(4)
df_hold.sort_values(by = ['Cur', 'Symbol_Code'],axis = 0,ascending = True, inplace=True)
#获取行业信息
df_sector = pd.read_excel('A_Shares.xlsx',sheet_name='Sector')
df_hold = pd.merge(df_hold, df_sector, how='left')
df_hold = df_hold[['Date','Symbol_Code', 'Symbol_Name', 'Sector', 'Cur', 'Quantity', 'Cost_Amt']]
return df_hold
##############################################################################
trade_date = '20190814'
trade_date = time.strftime('%Y%m%d')
account_id = 'All'
if account_id == 'All':
account_id = ['CMS', 'Citic']
else:
account_id = [account_id]
trans_date = get_trans(trade_date, account_id)
hold = get_holding(trade_date, trans_date)
print(hold)
| 760b6db67450846c5ce888b83f0690ef69f03c40 | [
"Python"
] | 6 | Python | swordzeng/test | 4d12778f546cc8dde8a1d28f9a784f394a49a8de | be5e8455fecec4371c04f3c3e4db476022fef200 | |
refs/heads/master | <repo_name>astroshot/mini-spider-golang<file_sep>/src/main/mini_spider.go
/* mini_spider.go - program entry point */
/*
modification history
--------------------
2017/07/20, by <NAME>, create
*/
/*
DESCRIPTION
mini spider
*/
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
import (
"code.google.com/p/log4go"
"www.baidu.com/golang-lib/log"
)
import (
"mini_spider_config"
"mini_spider"
)
var (
confPath *string = flag.String("c", "../conf/spider.conf", "mini_spider configure path")
help *bool = flag.Bool("h", false, "show help")
logPath *string = flag.String("l", "../log", "dir path of log")
showVer *bool = flag.Bool("v", false, "show version")
stdOut *bool = flag.Bool("s", false, "to show log in stdout")
debugLog *bool = flag.Bool("d", false, "to show debug log (otherwise >= info)")
)
func Exit(code int) {
log.Logger.Close()
/* to overcome bug in log, sleep for a while */
time.Sleep(1 * time.Second)
os.Exit(code)
}
/* the main function */
func main() {
var logSwitch string
flag.Parse()
if *help {
flag.PrintDefaults()
return
}
if *showVer {
fmt.Printf("version is: 1.0.0\n")
return
}
// debug switch
if *debugLog {
logSwitch = "DEBUG"
} else {
logSwitch = "INFO"
}
fmt.Printf("mini_spider starts...\n")
/* initialize log */
/* set log buffer size */
log4go.SetLogBufferLength(10000)
/* if blocking, log will be dropped */
log4go.SetLogWithBlocking(false)
/* we want to get state of log4go */
log4go.SetWithModuleState(true)
err := log.Init("mini_spider", logSwitch, *logPath, *stdOut, "midnight", 5)
if err != nil {
fmt.Printf("main(): err in log.Init():%s\n", err.Error())
os.Exit(-1)
}
// load config
config, err := mini_spider_config.LoadConfig(*confPath)
if err != nil {
log.Logger.Error("main():err in ConfigLoad():%s", err.Error())
Exit(-1)
}
// load seeds
seeds, err := mini_spider.LoadSeedFile(config.Basic.UrlListFile)
if err != nil {
log.Logger.Error("main():err in loadSeedFile(%s):%s", config.Basic.UrlListFile, err.Error())
Exit(1)
}
// create mini-spider
miniSpider, err:= mini_spider.NewMiniSpider(&config, seeds)
if err != nil {
log.Logger.Error("main():err in NewMiniSpider():%s", err.Error())
Exit(1)
}
// run mini-spider
miniSpider.Run()
// waiting for all tasks to finish.
go func() {
for {
if miniSpider.GetUnfinished() == 0 {
log.Logger.Info("All task finished, quit")
Exit(0)
}
log.Logger.Debug("Waiting for %d tasks to finish\n", miniSpider.GetUnfinished())
// sleep for a while
time.Sleep(5 * time.Second)
}
} ()
// Handle SIGINT and SIGTERM.
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
// ensure that all logs are export and normal exit
Exit(0)
}
<file_sep>/src/web_package/webpage_parse.go
/* webpage_parse.go - parse urls from web page */
/*
modification history
--------------------
2017/07/18, by <NAME>, create
*/
/*
DESCRIPTION
*/
package web_package
import (
"bytes"
"fmt"
"net/url"
)
import (
"golang.org/x/net/html"
)
type HtmlLinks struct {
links []string
}
// create new HtmlLinks
func NewHtmlLinks() *HtmlLinks {
hl := new(HtmlLinks)
hl.links = make([]string, 0)
return hl
}
/*
get all href in given html node
Params:
- n: html node
- refUrl: reference url
*/
func (hl *HtmlLinks) getLinks(n *html.Node, refUrl *url.URL) {
if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr {
if a.Key == "href" {
linkUrl, err := refUrl.Parse(a.Val)
if err == nil {
hl.links = append(hl.links, linkUrl.String())
}
break
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
hl.getLinks(c, refUrl)
}
}
/*
get url links in given html page
Params:
- data: data for html page
- urlStr: url string of this html page
Returns:
- links: parsed links
- error: any failure
*/
func ParseWebPage(data []byte, urlStr string) ([]string, error) {
// parse html
doc, err := html.Parse(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("html.Parse():%s", err.Error())
}
// parse url
refUrl, err := url.ParseRequestURI(urlStr)
if err != nil {
return nil, fmt.Errorf("url.ParseRequestURI(%s):%s", urlStr, err.Error())
}
// get all links
hl := NewHtmlLinks()
hl.getLinks(doc, refUrl)
return hl.links, nil
}
<file_sep>/src/mini_spider/url_table_test.go
/* url_table_test.go - test for url_table.go */
/*
modification history
--------------------
2017/07/23, by <NAME>, create
*/
/*
DESCRIPTION
*/
package mini_spider
import (
"testing"
)
func TestUrlTable_case_1(t *testing.T) {
// create table
ut := NewUrlTable()
// check whether exist
if ut.Exist("www.baidu.com") {
t.Errorf("www.baidu.com should not exist")
}
// add to table
ut.Add("www.baidu.com")
// check whether exist
if !ut.Exist("www.baidu.com") {
t.Errorf("www.baidu.com should exist")
}
if ut.Exist("www.sina.com.cn") {
t.Errorf("www.sina.com.cn should not exist")
}
}
<file_sep>/src/mini_spider/webpage_parse_test.go
/* webpage_parse_test.go - test for webpage_parse.go */
/*
modification history
--------------------
2017/07/22, by <NAME>, create
*/
/*
DESCRIPTION
*/
package mini_spider
import (
"testing"
)
// test for parseWebPage()
func TestParseWebPage(t *testing.T) {
s := []byte(`<p>Links:</p><ul><li><a href="test">Test</a><li><a href="/test1/test2">Test1_est2</a></ul>`)
links, err := parseWebPage(s, "http://www.baidu.com/a/b.html")
if err != nil {
t.Errorf("err in parseWebPage():%s", err.Error())
return
}
if len(links) != 2 {
t.Errorf("len(links) should be 2, now it's %d", len(links))
return
}
if links[0] != "http://www.baidu.com/a/test" || links[1] != "http://www.baidu.com/test1/test2" {
t.Errorf("links:%s", links)
}
}
<file_sep>/build.sh
#!/usr/bin/bash
### dir structure
# /bfe
# /bfe-common
# /go
# /output
# /golang-lib
# /mini_spider
# build.sh
### restore working dir
WORKROOT=$(pwd)
cd ${WORKROOT}
# prepare PATH, GOROOT and GOPATH
export GOPATH=$(pwd)
# export golang-lib to GOPATH
cd ${WORKROOT}
export GOPATH=$(pwd)/../bfe-common/golang-lib:$GOPATH
# run go test for all subdirectory
cd ${WORKROOT}/src/mini_spider
go test -c -o ./testRun
if [ $? -ne 0 ];
then
echo "go compile test failed"
exit 1
fi
go test -run testRun
if [ $? -ne 0 ];
then
echo "go run test failed"
exit 1
fi
rm -rf ./testRun
echo "OK for go test"
### build
cd ${WORKROOT}/src/main
go build -o mini_spider
if [ $? -ne 0 ];
then
echo "fail to go build mini_spider.go"
exit 1
fi
echo "OK for go build mini_spider.go"
### create directory for output
cd ../../
if [ -d "./output" ]
then
rm -rf output
fi
mkdir output
# copy config
mkdir output/conf
cp conf/spider.conf output/conf
# copy data
cp -r data output/
# copy file to bin
mkdir output/bin
mv src/main/mini_spider output/bin
# create dir for log
mkdir output/log
# change mode of files in /bin
chmod +x output/bin/mini_spider
echo "OK for build mini_spider"
<file_sep>/src/mini_spider/queue.go
/* queue.go - FIFO */
/*
modification history
--------------------
2017/7/17, by linxiongmin, create
*/
/*
DESCRIPTION
*/
package mini_spider
import (
"container/list"
"errors"
"sync"
)
/* max queue length */
const (
MAX_QUEUE_LEN = 65535
)
/* queue */
type Queue struct {
lock sync.Mutex
cond *sync.Cond
tasks *list.List
maxLen int // max queue length
unfinished int // number of unfinished tasks
}
/* Initialize the queue */
func (q *Queue) Init() {
q.cond = sync.NewCond(&q.lock)
q.tasks = list.New()
q.maxLen = MAX_QUEUE_LEN
}
/* Add to the queue */
func (q *Queue) Add(task *CrawlTask) error {
q.cond.L.Lock()
defer q.cond.L.Unlock()
var err error
if q.tasks.Len() >= q.maxLen {
err = errors.New("Queue is full")
} else {
q.tasks.PushBack(task)
q.unfinished += 1
q.cond.Signal()
err = nil
}
return err
}
/* pop a task from the queue */
func (q *Queue) Pop() *CrawlTask {
q.cond.L.Lock()
defer q.cond.L.Unlock()
for q.tasks.Len() == 0 {
q.cond.Wait()
}
task := q.tasks.Front()
q.tasks.Remove(task)
return task.Value.(*CrawlTask)
}
/* Get length of the queue */
func (q *Queue) Len() int {
q.lock.Lock()
defer q.lock.Unlock()
var len int
len = q.tasks.Len()
return len
}
/* Finish one task */
func (q *Queue) FinishOneTask() {
q.lock.Lock()
defer q.lock.Unlock()
q.unfinished -= 1
}
/* get count of unfinished tasks */
func (q *Queue) GetUnfinished() int {
q.lock.Lock()
defer q.lock.Unlock()
ret := q.unfinished
return ret
}
/* set max queue length */
func (q *Queue) SetMaxLen(maxLen int) {
q.lock.Lock()
defer q.lock.Unlock()
q.maxLen = maxLen
}
<file_sep>/src/mini_spider/queue_test.go
/* queue_test.go - test for queue.go */
/*
modification history
--------------------
2017/07/23, by <NAME>, create
*/
/*
DESCRIPTION
*/
package mini_spider
import (
"testing"
)
func TestQueue(t *testing.T) {
var queue Queue
queue.Init()
queue.Add(&CrawlTask{"http://www.baidu.com", 2, nil})
queue.Add(&CrawlTask{"http://www.sina.com", 1, nil})
queue.SetMaxLen(2)
err := queue.Add(&CrawlTask{"http://www.test.com", 1, nil})
if err == nil {
t.Error("queue is full, qeueu.Add should occur an error")
}
task := queue.Pop()
if task == nil || task.Url != "http://www.baidu.com" {
t.Errorf("www.baidu.com should be poped first")
}
qLen := queue.Len()
if qLen != 1 {
t.Error("queue.Len() should be 1, now it's %d", qLen)
}
n := queue.GetUnfinished()
if n != 2 {
t.Error("queue.GetUnfinished() should be 2, now it's %d", n)
}
queue.FinishOneTask()
n = queue.GetUnfinished()
if n != 1 {
t.Error("queue.GetUnfinished() should be 1, now it's %d", n)
}
task = queue.Pop()
if task == nil || task.Url != "http://www.sina.com" || task.Depth != 1 {
t.Error("queue should pop http://www.sina.com with depth 1")
}
task = queue.Pop()
if task != nil {
t.Error("queue should pop nil")
}
queue.FinishOneTask()
n = queue.GetUnfinished()
if n != 0 {
t.Error("all tasks in queue had finished, GetUnfinished() should return 0")
}
}<file_sep>/src/mini_spider/mini_spider.go
/* mini_spider.go */
/*
modification history
--------------------
2017/07/20, by <NAME>, create
*/
/*
DESCRIPTION
- mini spider
*/
package mini_spider
import (
"mini_spider_config"
)
type MiniSpider struct {
config *mini_spider_config.MiniSpiderConf
urlTable *UrlTable
queue Queue
crawlers []*Crawler
}
// crawl task
type CrawlTask struct {
Url string // url to crawl
Depth int // depth of the url
Header map[string]string // http header
}
// create new mini-spider
func NewMiniSpider(conf *mini_spider_config.MiniSpiderConf, seeds []string) (*MiniSpider, error) {
ms := new(MiniSpider)
ms.config = conf
// create url table
ms.urlTable = NewUrlTable()
// initialize queue
ms.queue.Init()
// add seeds to queue
for _, seed := range seeds {
task := &CrawlTask{Url: seed, Depth: 1, Header: make(map[string]string)}
ms.queue.Add(task)
}
// create crawlers, thread count was defined in conf
ms.crawlers = make([]*Crawler, 0)
for i := 0; i < conf.Basic.ThreadCount; i++ {
crawler := NewCrawler(ms.urlTable, ms.config, &ms.queue)
ms.crawlers = append(ms.crawlers, crawler)
}
return ms, nil
}
// run mini spider
func (ms *MiniSpider) Run() {
// start all crawlers
for _, crawler := range ms.crawlers {
go crawler.Run()
}
}
// get number of unfinished task
func (ms *MiniSpider) GetUnfinished() int {
return ms.queue.GetUnfinished()
}<file_sep>/src/mini_spider/webpage_save_test.go
/* webpage_save_test.go - test for webpage_save.go */
/*
modification history
--------------------
2017/07/22, by <NAME>, create
*/
/*
DESCRIPTION
*/
package mini_spider
import (
"testing"
)
// test for genFilePath()
func TestGenFilePath(t *testing.T) {
rootPath := "./output"
url := "www.baidu.com"
filePath := genFilePath(url, rootPath)
if filePath != "./output/www.baidu.com" {
t.Errorf("err in genFilePath(), filePath=%s", filePath)
}
}
// test for saveWebPage()
func TestSaveWebPage(t *testing.T) {
rootPath := "./output"
url := "www.baidu.com"
data := []byte("this is a test")
err := saveWebPage(rootPath, url, data)
if err != nil {
t.Errorf("err in saveWebPage(%s, %s):%s", rootPath, url, err.Error())
}
}
<file_sep>/src/web_package/webpage_save.go
/* webpage_save.go */
/*
modification history
--------------------
2017/07/21, by <NAME>, create
*/
/*
DESCRIPTION
*/
package web_package
import (
"fmt"
"io/ioutil"
"net/url"
"os"
"path"
)
const (
OutputFileMode = 0644
)
/*
generate root directory to save web page
Params:
- rootPath: root path for saving file
Returns:
- error: any failure
*/
func genRootDir(rootPath string) error{
if _, err := os.Stat(rootPath); os.IsNotExist(err) {
if os.MkdirAll(rootPath, 0777) != nil {
return fmt.Errorf("os.MkdirAll(%s):%s", rootPath, err.Error())
}
}
return nil
}
/*
generate file path for given url
Params:
- url: url to crawl
- rootPath: root path for saving file
Returns:
- file path
*/
func genFilePath(urlStr, rootPath string) string {
filePath := url.QueryEscape(urlStr)
filePath = path.Join(rootPath, filePath)
return filePath
}
/*
save web page of given url to file
Params:
- rootPath: root path for saving file
- url: url to crawl
- data: data to save
Returns:
- error: any failure
*/
func SaveWebPage(rootPath string, url string, data []byte) error {
// create root dir, if not exist
if err := genRootDir(rootPath); err != nil {
return fmt.Errorf("genRootDir(%s):%s", rootPath, err.Error())
}
// generate full file path
filePath := genFilePath(url, rootPath)
// save to file
err := ioutil.WriteFile(filePath, data, OutputFileMode)
if err != nil {
return fmt.Errorf("ioutil.WriteFile(%s):%s", filePath, err.Error())
}
return nil
}
<file_sep>/src/mini_spider/mini_spider_test.go
/* mini_spider_test.go: test for mini_spider.go */
/*
modification history
--------------------
2017/07/21, by <NAME>, create
*/
/*
DESCRIPTION
*/
package mini_spider
import (
"testing"
)
import (
"mini_spider_config"
)
func TestNewMiniSpider(t *testing.T) {
conf, _ := mini_spider_config.LoadConfig("../mini_spider_config/test_data/spider.conf")
seeds, _ := LoadSeedFile(conf.Basic.UrlListFile)
_, err := NewMiniSpider(&conf, seeds)
if err != nil {
t.Errorf("err happen in NewMiniSpider:%s", err.Error())
}
}
<file_sep>/src/mini_spider/seedfile_load.go
/* seedfile_load.go: load seed file*/
/*
modification history
--------------------
2017/07/16, by <NAME>, create
*/
/*
DESCRIPTION
*/
package mini_spider
import (
"encoding/json"
"fmt"
"io/ioutil"
)
/*
load seed data from file
Params:
- filePath: full path of seed file
Returns:
- urls
- error
*/
func LoadSeedFile(filePath string) ([]string, error) {
// read json data from file
data, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("ioutil.ReadFile(%s): %s", filePath, err.Error())
}
// decode json data
var seeds []string
err = json.Unmarshal(data, &seeds)
if err != nil {
return nil, fmt.Errorf("json.Unmarshal(): %s", err.Error())
}
return seeds, nil
}<file_sep>/src/mini_spider_config/conf_basic.go
/* conf_basic.go - basic config for mini spider */
/*
modification history
--------------------
2017/07/20, by linxiongmin, create
*/
/*
DESCRIPTION
*/
package mini_spider_config
import (
"fmt"
"regexp"
)
type BasicConfig struct {
UrlListFile string
OutputDirectory string
MaxDepth int
CrawlInterval int
CrawlTimeout int
TargetUrl string
ThreadCount int
GracefulShutdownTimeout int
}
func (conf *BasicConfig) Check() error {
// check urlListFile
if conf.UrlListFile == "" {
return fmt.Errorf("UrlListFile not set\n")
}
// check OutputDirectory
if conf.OutputDirectory == "" {
return fmt.Errorf("OutputDirectory not set\n")
}
// check MaxDepth
if conf.MaxDepth < 1 {
return fmt.Errorf("MaxDepth should >= 1\n")
}
// check CrawlInterval
if conf.CrawlInterval < 1 {
return fmt.Errorf("CrawlInterval should >= 1\n")
}
// check CrawlTimeout
if conf.CrawlTimeout < 1 {
return fmt.Errorf("CrawlTimeout should >= 1\n")
}
// check TargetUrl
_, err := regexp.Compile(conf.TargetUrl)
if err != nil {
return fmt.Errorf("regexp.Compile(TargetUrl):%s", err.Error())
}
// check ThreadCount
if conf.ThreadCount < 1 {
return fmt.Errorf("ThreadCount should >= 1\n")
}
// check graceful shutdown timeout
if conf.GracefulShutdownTimeout < 1 || conf.GracefulShutdownTimeout > 60{
return fmt.Errorf("GracefulShutdownTimeout out of range [1, 60]\n")
}
return nil
}
<file_sep>/src/mini_spider/crawler.go
/* crawler.go - crawler thread*/
/*
modification history
--------------------
2017/07/18, by <NAME>, create
2017/08/01, by <NAME>, modify
- add crawlChild function
*/
/*
DESCRIPTION
*/
package mini_spider
import (
"fmt"
"regexp"
"time"
)
import (
"www.baidu.com/golang-lib/http_util"
"www.baidu.com/golang-lib/log"
)
import (
"mini_spider_config"
"web_package"
)
type Crawler struct {
urlTable *UrlTable
config *mini_spider_config.BasicConfig
queue *Queue
urlPattern *regexp.Regexp
stop bool
}
// create new crawler
func NewCrawler(urlTable *UrlTable, config *mini_spider_config.MiniSpiderConf, queue *Queue) *Crawler {
c := new(Crawler)
c.urlTable = urlTable
c.config = &config.Basic
c.queue = queue
// TargetUrl has been checked in conf load
c.urlPattern, _ = regexp.Compile(c.config.TargetUrl)
c.stop = false
return c
}
// start crawler
func (c *Crawler) Run() {
for !c.stop {
// get new task from queue
task := c.queue.Pop()
log.Logger.Debug("from queue: url=%s, depth=%d", task.Url, task.Depth)
// read data from given task
data, err := http_util.Read(task.Url, c.config.CrawlTimeout, task.Header)
if err != nil {
log.Logger.Error("http_util.Read(%s):%s", task.Url, err.Error())
c.queue.FinishOneTask()
continue
}
// save data to file
if c.urlPattern.MatchString(task.Url) {
err = web_package.SaveWebPage(c.config.OutputDirectory, task.Url, data)
if err != nil {
log.Logger.Error("web_package.SaveWebPage(%s):%s", task.Url, err.Error())
} else {
log.Logger.Debug("save to file: %s", task.Url)
}
}
// add to url table
c.urlTable.Add(task.Url)
// continue crawling until max depth
if task.Depth < c.config.MaxDepth {
err = c.crawlChild(data, task)
if(err != nil){
log.Logger.Error("crawlChild(%s):%s in depth of %d", task.Url, err.Error(), task.Depth)
}
}
// confirm to remove task from queue
c.queue.FinishOneTask()
// sleep for a while
time.Sleep(time.Duration(c.config.CrawlInterval) * time.Second)
}
}
// stop crawler
func (c *Crawler) Stop() {
c.stop = true
}
// crawl child url
func (c *Crawler) crawlChild(data []byte, task *CrawlTask ) error {
// parse url from web page
links, err := web_package.ParseWebPage(data, task.Url)
if err != nil {
return fmt.Errorf("web_package.ParseWebPage():%s", err.Error())
}
// add child task to queue
for _, link := range links {
// check whether url match the pattern, or url exists already
if c.urlTable.Exist(link) {
continue
}
taskNew := &CrawlTask{Url: link, Depth: task.Depth + 1, Header: make(map[string]string)}
log.Logger.Debug("add to queue: url=%s, depth=%d", taskNew.Url, taskNew.Depth)
c.queue.Add(taskNew)
}
return nil
}
<file_sep>/start.sh
#!/bin/bash
cd output/bin
./mini_spider -c ../../conf/spider.conf -l ../log/ -s -d
<file_sep>/src/mini_spider/crawler_test.go
/* crawler_test.go: test for crawler */
/*
modification history
--------------------
2017/07/21, by <NAME>, create
*/
/*
DESCRIPTION
*/
package mini_spider
import (
"sync"
"testing"
)
import (
"mini_spider_config"
)
func TestCrawler(t *testing.T) {
urlTable := NewUrlTable()
conf, _ := mini_spider_config.LoadConfig("../mini_spider_config/test_data/spider.conf")
var queue Queue
queue.Init()
queue.Add(&CrawlTask{"http://pycm.baidu.com:8081", 2, nil})
c := NewCrawler(urlTable, &conf, &queue)
// wait and check result
var wg sync.WaitGroup
wg.Add(1)
go func() {
c.Run()
wg.Done()
}()
wg.Wait()
// check visit result
verifyLinks := []string{
"http://pycm.baidu.com:8081/page1.html",
"http://pycm.baidu.com:8081/page2.html",
"http://pycm.baidu.com:8081/page3.html",
"http://pycm.baidu.com:8081/mirror/index.html",
"http://pycm.baidu.com:8081/page4.html",
}
for _, link := range verifyLinks {
if !c.urlTable.Exist(link) {
t.Errorf("%s not visited", link)
}
}
}
<file_sep>/src/mini_spider_config/config.go
/* config.go*/
/*
modification history
--------------------
2017/07/18, by linxiongmin, create
*/
/*
DESCRIPTION
*/
package mini_spider_config
import (
"fmt"
)
import (
"code.google.com/p/gcfg"
)
type MiniSpiderConf struct {
Basic BasicConfig
}
// load config and check for validation
func LoadConfig(confPath string) (MiniSpiderConf, error) {
conf, err := loadConfig(confPath)
if err != nil {
return conf, fmt.Errorf("configLoad(): %s\n", err.Error())
}
// check for validation
if err = conf.Check(); err != nil {
return conf, fmt.Errorf("conf.check(): %s\n", err.Error())
}
return conf, nil
}
func loadConfig(confPath string) (MiniSpiderConf, error) {
var conf MiniSpiderConf
var err error
//load conf file to conf struct
err = gcfg.ReadFileInto(&conf, confPath)
if err != nil {
return conf, fmt.Errorf("gcfg.ReadFileInto(): %s\n", err.Error())
}
return conf, nil
}
// check config validation
func (conf *MiniSpiderConf) Check() error {
var err error
// check conf data
if err = conf.Basic.Check(); err != nil {
return fmt.Errorf("Basic.Check(): %s", err.Error())
}
return nil
}
| 483d158e3ec42c78fe502798d4a6ab9af3a42084 | [
"Go",
"Shell"
] | 17 | Go | astroshot/mini-spider-golang | e7d883646eb545278168c0477bf83f93eeafd3a1 | b27f9ce729965b3904b41a45b0b6d042feab3e26 | |
refs/heads/master | <repo_name>marcos4503/windsoft-site<file_sep>/browser/microsite/painel/paginas/listar-arquivos-expansao.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem os dados de todos os jogos cadastrados
$consultaDeJogos = mysqli_query($DB_Metadados, "SELECT JogoID, Nome, UltimaVersao, PacoteOuNamespace, Plataforma FROM JogosDaWindsoft WHERE JogoID > 0");
$i = 0;
while($linha = mysqli_fetch_assoc($consultaDeJogos)) {
$jogoId[$i] = $linha["JogoID"];
$nome[$i] = $linha["Nome"];
$ultimaVersao[$i] = $linha["UltimaVersao"];
$pacote[$i] = $linha["PacoteOuNamespace"];
$plataforma[$i] = $linha["Plataforma"];
$i += 1;
}
?>
<center>
<h3>Listar Arquivos de Expansão</h3>
</center>
<center>
<form autocomplete="off" style="margin-bottom: 0px;">
<select id="selectSlide" onchange="aoTrocarJogo();">
<?php
for ($ii = 0; $ii < $i; $ii++) {
echo('<option value="'.$jogoId[$ii].'">'.$nome[$ii].' (v'.$ultimaVersao[$ii].') ('.$plataforma[$ii].')</option>');
}
?>
</select>
</form>
<input type="button" value="Listar" onclick="buscarArquivos();" />
</center>
<style>
.arquivo{
display: grid;
grid-template-columns: 10% 70% 20%;
background-color: #D6D6D6;
transition: all 200ms;
border-radius: 4px;
padding: 10px;
margin-bottom: 4px;
}
.arquivo:hover{
background-color: #BCBCBC;
}
.iconeArquivo{
display: flex;
align-items: center;
}
</style>
<div id="resultado" style="display: none; background-color: #F2F2F2; border-radius: 4px; margin-top: 10px; margin-bottom: 10px; padding: 10px;">
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
//Função que obtem os dados, ao trocar de jogo selecionado
plataformaDosJogos = ["", <?php
for ($iii = 0; $iii < $i; $iii++) {
echo('"'.$plataforma[$iii].'"');
if($iii != $i){
echo(",");
}
}
?>];
pacoteDosJogos = ["", <?php
for ($iii = 0; $iii < $i; $iii++) {
echo('"'.$pacote[$iii].'"');
if($iii != $i){
echo(",");
}
}
?>];
jogoSelect = document.getElementById("selectSlide");
jogoSelecionadoId = 1;
function aoTrocarJogo(){
jogoSelecionadoId = jogoSelect.value;
}
//Função que estabelece conexão para pesquisar os arquivos
function buscarArquivos(){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/buscar-arquivos-expansao.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
document.getElementById("resultado").style.display = "block";
document.getElementById("resultado").innerHTML = parent.textoDaConexao(conexao);
parent.redimensionarIframe();
});
};
parent.iniciarConexaoPost(conexao, "plataforma=" + plataformaDosJogos[parseInt(jogoSelecionadoId)] +
"&pacote=" + pacoteDosJogos[parseInt(jogoSelecionadoId)]);
}
aoTrocarJogo();
</script>
<?php
$conteudoQuadroDeAviso = ('
• Selecione o jogo ao qual você deseja visualizar os arquivos de expansão, associados a ele.
<br/>
• Os arquivos de expansão listados aqui, serão baixados pelo Windsoft Launcher automaticamente. O Launcher irá localizar a versão do arquivo de expansão automaticamente.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/paginas/registrar-novo-asset.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<center>
<h3>Cadastrar Novo Asset</h3>
</center>
<div id="formulario">
<center>
<form autocomplete="off">
<input id="titulo" type="text" placeholder="Nome do Asset" onkeyup="validarNome();" />
<div id="tituloStatus" class="statusCampo"></div>
<input id="preco" type="text" placeholder="Preço" onkeyup="validarPreco();" />
<div id="precoStatus" class="statusCampo"></div>
<textarea id="descricao" placeholder="Descrição" onkeyup="validarDescricao();"></textarea>
<div id="descricaoStatus" class="statusCampo"></div>
<input id="urlVideo" type="text" placeholder="URL do Vídeo Embed" onkeyup="validarUrlVideo();" />
<div id="urlVideoStatus" class="statusCampo"></div>
<input id="urlAs" type="text" placeholder="URL na Asset Store" onkeyup="validarUrlAs();" />
<div id="urlAsStatus" class="statusCampo"></div>
<input type="button" value="Cadastrar" onclick="salvarEdicao();" />
</form>
</center>
</div>
<div id="assetCadastrado" style="display: none;">
<center>
<img src="../imagens/sucesso.png" width="128px" />
<br>
<br>
O novo asset foi cadastrado com sucesso no Banco de Dados!
<br>
<br>
</center>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
campoNome = document.getElementById("titulo");
statusNome = document.getElementById("tituloStatus");
nomeValido = false;
function validarNome(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoNome.value.length, 30);
//Desvalida
campoNome.style.borderColor = "#990000";
campoNome.style.borderWidth = "1px";
statusNome.style.color = "#990000";
nomeValido = false;
if(campoNome.value == ""){
statusNome.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoNome.value.length > 30){
statusNome.innerHTML = "Nome muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoNome.value) == true){
statusNome.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoNome.style.borderColor = "";
campoNome.style.borderWidth = "";
statusNome.innerHTML = "";
nomeValido = true;
parent.redimensionarIframe();
}
campoPreco = document.getElementById("preco");
statusPreco = document.getElementById("precoStatus");
precoValido = false;
function validarPreco(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoPreco.value.length, 5);
//Desvalida
campoPreco.style.borderColor = "#990000";
campoPreco.style.borderWidth = "1px";
statusPreco.style.color = "#990000";
precoValido = false;
if(campoPreco.value == ""){
statusPreco.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoPreco.value.length > 5){
statusPreco.innerHTML = "Preço muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComNumeroFloat(campoPreco.value) == false || campoPreco.value.indexOf(',') > -1){
statusPreco.innerHTML = "Utilize apenas números e pontos.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoPreco.style.borderColor = "";
campoPreco.style.borderWidth = "";
statusPreco.innerHTML = "";
precoValido = true;
parent.redimensionarIframe();
}
campoDescricao = document.getElementById("descricao");
statusDescricao = document.getElementById("descricaoStatus");
descricaoValido = false;
function validarDescricao(){
//Desvalida
campoDescricao.style.borderColor = "#990000";
campoDescricao.style.borderWidth = "1px";
statusDescricao.style.color = "#990000";
descricaoValido = false;
if(campoDescricao.value == ""){
statusDescricao.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoDescricao.value) == true){
statusDescricao.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoDescricao.style.borderColor = "";
campoDescricao.style.borderWidth = "";
statusDescricao.innerHTML = "";
descricaoValido = true;
parent.redimensionarIframe();
}
campoUrlVideo = document.getElementById("urlVideo");
statusUrlVideo = document.getElementById("urlVideoStatus");
urlVideoValido = false;
function validarUrlVideo(){
//Desvalida
campoUrlVideo.style.borderColor = "#990000";
campoUrlVideo.style.borderWidth = "1px";
statusUrlVideo.style.color = "#990000";
urlVideoValido = false;
if(campoUrlVideo.value == ""){
statusUrlVideo.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComUrl(campoUrlVideo.value) == false){
statusUrlVideo.innerHTML = "O conteúdo digitado não é uma URL.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoUrlVideo.style.borderColor = "";
campoUrlVideo.style.borderWidth = "";
statusUrlVideo.innerHTML = "";
urlVideoValido = true;
parent.redimensionarIframe();
}
campoUrlAs = document.getElementById("urlAs");
statusUrlAs = document.getElementById("urlAsStatus");
urlAsValido = false;
function validarUrlAs(){
//Desvalida
campoUrlAs.style.borderColor = "#990000";
campoUrlAs.style.borderWidth = "1px";
statusUrlAs.style.color = "#990000";
urlAsValido = false;
if(campoUrlAs.value == ""){
statusUrlAs.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComUrl(campoUrlAs.value) == false){
statusUrlAs.innerHTML = "O conteúdo digitado não é uma URL.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoUrlAs.style.borderColor = "";
campoUrlAs.style.borderWidth = "";
statusUrlAs.innerHTML = "";
urlAsValido = true;
parent.redimensionarIframe();
}
//Função que verifica se todos os campos estão válidos
function todosOsCamposEstaoValidos(){
validarNome();
validarPreco();
validarDescricao();
validarUrlVideo();
validarUrlAs();
if(nomeValido == true && precoValido == true && descricaoValido == true && urlVideoValido == true && urlAsValido == true){
return true;
}
if(nomeValido == false || precoValido == false || descricaoValido == false || urlVideoValido == false || urlAsValido == false){
parent.mostrarNotificacao("Verifique o formulário em busca de erros e tente novamente.", "#750000", 3000);
return false;
}
}
//Função que cadastra o asset
function salvarEdicao(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/cadastrar-novo-asset.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"nome=" + document.getElementById("titulo").value +
"&preco=" + document.getElementById("preco").value +
"&descricao=" + document.getElementById("descricao").value +
"&urlVideo=" + document.getElementById("urlVideo").value +
"&urlAssetStore=" + document.getElementById("urlAs").value);
}
}
//Função que exibe a mensagem de sucesso após cadastrar asset
function exibirMensagemAssetCadastrado(){
document.getElementById("assetCadastrado").style.display = "block";
document.getElementById("formulario").style.display = "none";
document.getElementById("quadroDeAvisos").style.display = "none";
parent.redimensionarIframe();
}
//Redimensiona as textarea de acordo com seus conteúdos, automaticamente
var textAreas = document.getElementsByTagName("textarea");
for (var i = 0; i < textAreas.length; i++){
textAreas[i].style.height = (textAreas[i].scrollHeight) + "px";
textAreas[i].style.overflow = "hidden";
textAreas[i].style.resize = "none";
textAreas[i].style.minHeight = "80px";
textAreas[i].addEventListener("input", AoDigitarNasTextArea, false);
}
function AoDigitarNasTextArea(){
this.style.height = "auto";
this.style.height = (this.scrollHeight) + "px";
this.style.minHeight = "80px";
parent.redimensionarIframe();
}
</script>
<?php
$conteudoQuadroDeAviso = ('
• SOMENTE cadastre o Asset aqui, caso a Unity já tenha aceitado e publicado a sua primeira versão.
<br/>
• O Asset cadastrado aqui, também será exibido na Home Page do microsite da MT Assets.
<br/>
• Ao cadastrar um Asset aqui, será possível reportar suas vendas e etc.
<br/>
• Deixe o preço em zero, caso o Asset seja gratuíto.
<br/>
• Após cadastrar um Asset aqui, não se esqueça de carregar a Imagem de arte do mesmo. A arte também será exibida na Home Page da MT Assets.
<br/>
• Por favor, insira os dados (como Descrição) apenas em Inglês.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/ajax-query/editar-autoridade-staff.php
<?php
/*
* script que edita a autoridade do staff
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
include("../../../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$nick = mysqli_real_escape_string($DB_Registros, $_POST["nick"]);
$autoridade = mysqli_real_escape_string($DB_Registros, $_POST["autoridade"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Caso não tenha permissão total, cancela o script
if($_SESSION["autoridade"] < 4){
echo("".
'parent.mostrarNotificacao("Você não tem permissão para fazer isso.", "#7F0000", 3000);'
."");
exit();
}
//edita o cargo do staff
$consultaEdicao = mysqli_query($DB_Metadados, "UPDATE Staff SET Autoridade=$autoridade WHERE Nick='$nick'");
echo("".
'parent.mostrarNotificacao("A autoridade do usuário, foi editado com sucesso! O usuário deve se relogar para usufruir da nova autoridade.", "#1E7200", 3000);'
."autoridade = ".$autoridade.";"
."exibirPainelDeEdicao();"
."");
}
?><file_sep>/browser/politica-de-privacidade.php
<?php
/*
* Essa página HTML contém as informações de Política de Privacidade da Windsoft Games. Sempre que ela for atualizada, deve-ser
* atualizada a data de atualização.
*/
$tituloPagina = "Política de Privacidade - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("includes/cabecalho.inc");
?>
<br/>
<center><b>Política de privacidade da Windsoft Games</b>
<br/>
<br/>
<font color="#545454"><i>Esta Política de Privacidade é válida a partir de 21 de maio de 2018 e teve sua última modificação em 14 de dezembro de 2018.</i></font></center>
<br/>
<br/>
A Windsoft Games ("nós", "nosso(s)", "nos", "conosco") acredita que sua privacidade é muito importante. Essa política de privacidade demonstra os tipos de
informações privadas e outros dados que coletamos atráves de nossos jogos e aplicativos que distribuímos (serão referidos como serviços), como usamos estes
dados e quando poderemos revelá-los a terceiros. A instalação e/ou o uso dos nossos serviços e/ou o envio de informação constitui seu consentimento a esta
política de privacidade e a possibilidade de utilização dessa informação (pessoal e não pessoal) como descrito nesta política de privacidade.
<br/>
<br/>
<b>I. Tipos de informações que podemos colher com nossos serviços</b>
<br/>
<br/>
<b>1. Informação pessoal: </b>que pode ser usada para te contatar on-line, como o seu primeiro nome, endereço de e-mail, ID de usuário do Windsoft ID e
nome de usuário.
<br/>
<b>2. Informação não pessoal: </b>que não pode te identificar especificamente e que não pode ser usada para te contatar, como por exemplo, como data de
nascimento, idade, CEP, geolocalização imprecisa (como por exemplo sua cidade) e sexo. Assim como informações do seu dispositivo, como o ID de dispositivo,
endereço IP e outros identificadores de hardware(especificações do processador, ram e etc), software(dados técnicos do sistema operacional) e firmware.
Informação não pessoal tambem inclui dados de como você usa os nossos serviços, como ações tomadas dentro dos nossos serviços, hora e data de uso dos
nossos serviços, tempo de jogo, conquistas e etc.
<br/>
<br/>
<b>II. Como coletamos a sua informação pessoal e não pessoal</b>
<br/>
<br/>
<b>1. </b>Se você decidir criar uma conta na nossa rede (Windsoft ID), pedir ajuda ou realizar qualquer ato que necessite o envio de informações
pessoais e não pessoais.
<br/>
<b>2. </b>Se você decidir se conectar a um de nossos serviços atráves de terceiros como Facebook, Google Play Games e etc, poderemos coletar seus dados de
perfil nestas redes, como nome de usuário, foto, sexo e data de nascimento.
<br/>
<b>3. </b>Podemos coletar informações como o ID do seu aparelho para enviar notificações.
<br/>
<b>4. </b>Se você nos enviar sua informação pessoal por qualquer outra razão, nós coletaremos esta informação e a usaremos somente para o próposito ao qual
ela foi enviada.
<br/>
<b>5. </b>Não coletamos nenhuma informação pessoal se você apenas visitar nosso site.
<br/>
<b>6. </b>Tambem podemos coletar informações não pessoais enquanto você utiliza nossos serviços.
<br/>
<br/>
<b>III. Uso da informação não pessoal coletada</b>
<br/>
<br/>
As informações não pessoais podem ser utilizada para própositos de administração, análise, pesquisa, otimização, segurança e outros. Especificamente, poderemos
utilizar suas informações não pessoais para:
<br/>
<b>1. </b>Monitorar seu uso dos nossos serviços para entedermos suas preferências e tendências, o que nós ajudara a personalizar a experiência, ofertas e notificações
nos nossos serviços feitas sob medida para melhorar sua experiência nos nossos serviços.
<br/>
<b>2. </b>Personalizar seu conteúdo e ofertas.
<br/>
<b>3. </b>Compilar estatísitcas.
<br/>
<b>4. </b>Responder às perguntas do suporte.
<br/>
<b>5. </b>Proteger contra trapaça, crime, fraude ou outras medidas de segurança.
<br/>
<b>6. </b>Enviar notificações Push (se você permitir).
<br/>
<br/>
<b>IV. Uso da informação pessoal coletada</b>
<br/>
<br/>
Usaremos suas informações pessoais para:
<br/>
<b>1. </b>Fornecer bens, serviços ou funcionalidades requisitadas por você.
<br/>
<b>2. </b>Responder a qualquer pergunta feita atráves do suporte.
<br/>
<b>3. </b>Exibir informações superficias(como primeiro nome e nome de usuário) da sua conta do Windsoft ID(caso tenha uma) na sua página de perfil
em nossos serviços.
<br/>
<b>4. </b>Contratá-lo e promover nossos serviços, ou ofertas especiais.
<br/>
<br/>
<b>V. Quando revelamos informações pessoais ou não pessoais coletadas</b>
<br/>
<br/>
<b>1. </b>Não venderemos, alugaremos ou transferiremos suas informações pessoais para terceiros sem seu concentimento.
<br/>
<b>2. </b>Nossos serviços podem oferecer funções sociais de compartilhamento como "publicar" ou "curtir" no Facebook. Se você decidiu usar estas funções,
você permite o compartilhamento e coleta de informações pessoais e não pessoais com estas redes sociais. Você deve ler as políticas de privacidade destes
terceiros para mais informações sobre suas práticas coleta de informações.
<br/>
<b>3. </b>Podemos revelar suas informações pessoais ou outras informações coletadas se requeridas por lei ou ordem judicial, caso a informação esteja
ligada a ameaça ou real conduta de dano, servir para investigação e/ou tomada de ação contra atividades ilegais, suspeita de abuso ou uso
desautorizado dos serviçso ou para proteger a propriedade ou segurança de outrem.
<br/>
<b>4. </b>Em caso de venda da companhia ou de qualquer linha de negócios (incluindo os recursos relacionados aqui), as informações dos clientes são
geralmente recursos transferidos e tais informações (incluindo suas informações pessoais) serão transferidas ou vendidas ao comprador no evento da
compra de parte ou de todo o negócio.
<br/>
<br/>
<b>VI. Propaganda</b>
<br/>
<br/>
Ao usar nossos aplicativos/jogos, você pode encontrar conteúdo de propaganda. Nós ou a rede de publicidade que usamos podemos utilizar tecnologia de
publicidade que usa cookies, beacons, tracking pixels ou outras tecnologias que são colocadas nas propagandas e permitem a coleta de informações
não pessoais. Informações não pessoais como idade e sexo podem ser usadas para que propagandas apropriadas sejam oferecidas a você. Dados de uso
e informações não pessoais como identificadores de propaganda podem ser usados para determinar quantos cliques uma propaganda recebeu para medir
a eficácia de campanhas, determinar a quantidades de revisitas e/ou entregar as propagandas que melhor se enquadram nos seus interesses. Dependendo
do seu aparelho e sistema operacional, você pode impedir que o identificador de propaganda do seu aparelho seja usado para propagandas que
visem a lucro ou pode redefinir seu identificador de propaganda, mudando as configurações do seu aparelho.
<br/>
<br/>
<b>VII. Retenção de arquivos</b>
<br/>
<br/>
Nos reservamos o direito de reter um arquivo de sua informação pessoal por um tempo comercialmente razoável para assegurarmo-nos de que sua
remoção não venha afetar a integridade de nossos dados. Além disso, nos reservamos o direito de manter uma versão anônima desta informação em nosso
arquivo.
<br/>
<br/>
<b>VIII. Parcerias e fontes externas</b>
<br/>
<br/>
Nossos serviços podem apresentar links para sites externos que fogem ao nosso controle. Esta política de privacidade se aplica apenas à forma como
tratamos a informação pessoal e dados de uso coletados em nossos serviços. Ao acessar sites externos, você concorda com a política de privacidade
destes sites. Entenda que sites externos podem ter políticas diferentes no que diz respeito à coleta, uso e publicação de sua informação pessoal.
Não temos controle ou responsabilidade sobre as práticas de privacidade de terceiros. Portanto, o encorajamos a ler as políticas de privacidade
de todos os websites e aplicativos de terceiros. Sem limitar o apresentado na seção a seguir, não somos responsáveis de forma alguma pelas ações,
inações ou políticas de qualquer serviço externo.
<br/>
<br/>
<b><NAME></b>
<br/>
<br/>
Muitos de nossos serviços são de classificação livre e nós não coletamos ou usamos voluntariamente nenhuma informação pessoal de crianças com menos
de 13 anos. Quando usuários forem identificados como menores de 13 anos, nós bloquearemos este usuário de fornecer qualquer informação pessoal
ou garantir que a autorização dos pais seja dada antes de colher qualquer informação pessoal. Quando nossos serviços forem direcionados para
crianças menores de 13 anos, não colheremos nenhuma informação pessoal dos usuários destes serviços. Caso você seja responsável por uma criança
menor de 13 anos e julgue que esta criança tenha fornecido informações pessoais, entre em contato pelo e-mail <EMAIL> e nós apagaremos
os dados em nosso sistema. Nós podemos coletar informação não pessoal como um identificador do aparelho ou qualquer outra forma de identificação
não pessoal relevante relacionada ao dispositivo usado pela criança para utilizar nossos serviços. Os dados coletados serão anônimos e não serão
vinculados a qualquer informação pessoal. Além disso, estes dados serão utilizados unicamente para objetivos internos, como personalização de
conteúdo, segurança e publicidade contextual (não comportamental). Alguns de nossos serviços podem permitir compras no jogo, mesmo que o download
e instalação do jogo sejam gratuitos. Elas podem ser realizadas via uma conta de terceiros (por exemplo, uma conta Google Play). Caso você seja
responsável por uma criança e esteja preocupado com esta função, você pode desativar a possibilidade de compras no nosso serviços ao acessar
a guia de configurações do aplicativo/jogo e seguir os passos necessários para tal efeito. Caso você tenha entre 13 e 18 anos de idade, favor
obter a permissão dos seus pais antes de se registrar em nossa plataforma ou de fornecer informações pessoais.
<br/>
<br/>
<b>X. Alterações</b>
<br/>
<br/>
Nós nos reservamos o direito de alterar esta política de privacidade a qualquer momento. Caso façamos alterações materiais a esta política
de privacidade, tal política será republicada na seção Privacidade de nossos serviços e a data da alteração será informada no topo da página.
Portanto, favor revisar esta política de privacidade de tempos em tempos para tomar conhecimento de todas as alterações. O uso continuado de
nossos serviços após tais alterações representa que você as aceita. Caso você não aceite as alterações realizadas, você tem o direito de
escolher não utilizar mais os serviços.
<br/>
<br/>
<b>XI. Segurança dos serviços</b>
<br/>
<br/>
Fornecer ou não suas informações pessoais é uma decisão integralmente sua. Nós disponibilizamos procedimentos eletrônicos e gerenciais com o objetivo
de prevenir acesso não autorizado, manter a segurança dos dados e assegurar a utilização correta das informações pessoais recolhidas por nossos
serviços. Entretanto, esteja ciente de que nenhuma transmissão de dados via internet ou qualquer rede sem fio é 100% segura. Como resultado, por mais
que nós nos esforcemos para proteger suas informações pessoais, não podemos garantir a segurança de qualquer informação que nos é enviada ou que
nós enviamos, de forma que o risco do envio é seu. Não podemos garantir a segurança de qualquer informação enviada por e-mail. Envie por seu próprio
risco. Caso você acredite que suas informações pessoais estejam sendo usadas indevidamente por nós, favor enviar uma notificação imediata a
<EMAIL>. Caso você escolha ter uma conta conosco, você não deve compartilhar seus dados de acesso com ninguém.
<br/>
<br/>
<b>XII. Aviso legal</b>
<br/>
<br/>
Nossos serviços operam da forma em que são apresentados, e nós não representamos ou garantimos que nossos serviços estarão sempre disponíveis, ou que
o seu uso dos serviços será ininterrupto ou livre de falhas. Não nos responsabilizamos por sua capacidade de acessar os serviços ou por outros aspectos
que fogem ao nosso controle. Esta política de privacidade é governada pela lei do Brasil, excluídas suas provisões de escolha de lei. Caso você tenha
alguma questão geral sobre nossa política de privacidade, entre em contato pelo e-mail <EMAIL>.
<br/>
<br/>
<?php
include("includes/rodape.inc");
?><file_sep>/browser/microsite/painel/ajax-query/cadastrar-novo-asset.php
<?php
/*
* script que insere o novo jogo no banco de dados
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$nome = mysqli_real_escape_string($DB_Metadados, $_POST["nome"]);
$preco = mysqli_real_escape_string($DB_Metadados, $_POST["preco"]);
$descricao = mysqli_real_escape_string($DB_Metadados, $_POST["descricao"]);
$urlVideo = mysqli_real_escape_string($DB_Metadados, $_POST["urlVideo"]);
$urlAssetStore = mysqli_real_escape_string($DB_Metadados, $_POST["urlAssetStore"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Filtra o nome do asset para gerar o URL de imagem sem caracteres especiais, e minusculo
$nomeSemEspacos = str_replace(" ", "-", $nome);
$nomeParaUrl = strtolower(preg_replace("/[^A-Za-z0-9\-]/", "", $nomeSemEspacos));
$urlImagem = "https://windsoft.xyz/browser/microsite/mt-assets/asset-images/" . $nomeParaUrl . ".png";
$nomeArquivoArte = $nomeParaUrl . ".png";
//Obtem a data atual
$dataDePublicacao = date("Y")."-".date("m")."-".date("d");
//Insere o novo asset no banco de dados
$consultaCadastro = mysqli_query($DB_Metadados, "INSERT INTO AssetStore(Nome, PrecoAtual, VendasPorData_Json, Descricao, UrlImagem, NomeArquivoArte, UrlVideo, UrlAssetStore, DataPublicacao) VALUES('$nome', '$preco', '', '$descricao', '$urlImagem', '$nomeArquivoArte', '$urlVideo', '$urlAssetStore', '$dataDePublicacao')");
echo("".
'parent.mostrarNotificacao("'.$nome.' foi cadastrado com sucesso!", "#117700", 2500);'.
'exibirMensagemAssetCadastrado();'
."");
}
?><file_sep>/browser/links/you-tube.php
<?php
/*
* Essa página funciona como um redirecionamento para a página da Windsoft Games no Youtube.
* O arquivo .htaccess possui uma configuração para que seja possível acessa-la com uma URL mais curta.
*/
$tituloPagina = "Youtube - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("../includes/cabecalho.inc");
RedirecionarPara("https://www.youtube.com/channel/UCehJit--43uLtn_sf4ELVJg", 3);
?>
<center>
<br/>
Por favor, aguarde, estamos lhe redirecionando para nosso canal do YouTube!
<br/>
<br/>
<small>
<a href="https://www.youtube.com/channel/UCehJit--43uLtn_sf4ELVJg">Clique aqui caso não seja redirecionado</a>
</small>
</center>
<?php
include("../includes/rodape.inc");
?><file_sep>/browser/microsite/painel/ajax-query/tornar-membro-da-staff.php
<?php
/*
* script que adiciona o usuario a staff
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
include("../../../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$nick = mysqli_real_escape_string($DB_Registros, $_POST["nick"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Caso não tenha permissão total, cancela o script
if($_SESSION["autoridade"] < 4){
echo("".
'parent.mostrarNotificacao("Você não tem permissão para fazer isso.", "#7F0000", 3000);'
."");
exit();
}
//Verifica se o usuário já está cadastrado como staff
$consultaUsuario = mysqli_query($DB_Metadados, "SELECT Cargo, Autoridade FROM Staff WHERE Nick='$nick'");
//Caso não esteja cadastrado
if(mysqli_num_rows($consultaUsuario) == 0){
$consultaInsercao = mysqli_query($DB_Metadados, "INSERT INTO Staff(Nick, Cargo, Autoridade) VALUES('$nick', 'Sem Cargo', 0)");
}
echo("".
'parent.mostrarNotificacao("O usuário foi adicionado a Staff, com êxito!", "#1E7200", 3000);'
."staff = true;"
."cargo = 'Sem Cargo';"
."autoridade = 0;"
."exibirPainelDeEdicao();"
."");
}
?><file_sep>/browser/ajax-query/editar-perfil.php
<?php
/*
* script que faz consulta de edição do perfil
*/
include("../../global/sessoes/verificador-de-sessao.inc");
include("../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Obtem as variaveis
$nome = mysqli_real_escape_string($DB_Registros, $_POST["nome"]);
$genero = mysqli_real_escape_string($DB_Registros, $_POST["genero"]);
$idade = mysqli_real_escape_string($DB_Registros, $_POST["idade"]);
//obtem o id do usuário
$id = $_SESSION["id"];
//Obtem o ano de nascimento
$anoNascimento = date("Y") - $idade;
//Faz a consulta de edição
$consultaEdicao = mysqli_query($DB_Registros, "UPDATE Perfis SET Nome='$nome', Genero='$genero', AnoNascimento=$anoNascimento WHERE ID=$id");
echo("".
"mostrarNotificacao(\"O perfil foi editado com sucesso!\", \"#117700\", 5000); ".
"trocarModoExibicao();".
"");
?><file_sep>/browser/microsite/painel/paginas/criar-noticia.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Função que verifica se o arquivo temporário de edição, existe, caso exista, retorna o seu conteúdo, se não retorna uma string vazia
function arquivoExiste($nome){
//Configura o diretorio
$diretorioDoArquivo = "noticias/temp/" . $nome;
//Verifica sua existência
if(file_exists($diretorioDoArquivo) == false){
return "";
}
if(file_exists($diretorioDoArquivo) == true){
return file_get_contents($diretorioDoArquivo);
}
}
//Função que verifica se existe uma edição salva
$existeEdicaoSalva = false;
if(arquivoExiste($_SESSION["id"] . "_noticia-existeEdicaoSalva.tmp") == true){
if(arquivoExiste($_SESSION["id"] . "_noticia-existeEdicaoSalva.tmp") == "true"){
$existeEdicaoSalva = true;
}
}
?>
<center>
<h3>Criar Arquivo de Notícia</h3>
</center>
<div id="formulario" style="display: block;">
<center>
<form autocomplete="off">
<input id="titulo" type="text" placeholder="Título da Notícia" onkeyup="validarTitulo();"
value="<?php
$nome = $_SESSION["id"] . "_noticia-titulo.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?>"/>
<div id="tituloStatus" class="statusCampo"></div>
<input id="urlCapa" type="text" placeholder="URL Imagem de Capa" onkeyup="validarUrlCapa();"
value="<?php
$nome = $_SESSION["id"] . "_noticia-urlCapa.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?>"/>
<div id="urlCapaStatus" class="statusCampo"></div>
<textarea id="descricao" placeholder="Descrição da Notícia" onkeyup="validarDescricao();"><?php
$nome = $_SESSION["id"] . "_noticia-descricao.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?></textarea>
<div id="descricaoStatus" class="statusCampo"></div>
<textarea id="intro" placeholder="Introdução da Notícia" onkeyup="validarIntroducao();"
onfocus="parent.exibirIconeEmote(true, true, this);" onblur="parent.exibirIconeEmote(false, true, this);"><?php
$nome = $_SESSION["id"] . "_noticia-introducao.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?></textarea>
<div id="introStatus" class="statusCampo"></div>
<input id="subtitulo1" type="text" placeholder="Subtítulo 1" onkeyup="validarSubtitulo1();"
value="<?php
$nome = $_SESSION["id"] . "_noticia-subtitulo1.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?>"/>
<div id="subtitulo1status" class="statusCampo"></div>
<textarea id="texto1" placeholder="Texto do subtítulo 1"
onfocus="parent.exibirIconeEmote(true, true, this);" onblur="parent.exibirIconeEmote(false, true, this);"><?php
$nome = $_SESSION["id"] . "_noticia-texto1.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?></textarea>
<div id="texto1status" class="statusCampo"></div>
<div id="item2" style="<?php if(arquivoExiste($_SESSION["id"]."_noticia-subtitulo2.tmp") == true || arquivoExiste($_SESSION["id"]."_noticia-texto2.tmp") == true && $existeEdicaoSalva == true){if(arquivoExiste($_SESSION["id"]."_noticia-subtitulo2.tmp") == false || arquivoExiste($_SESSION["id"]."_noticia-texto2.tmp") == false || $existeEdicaoSalva == false)("opacity: 1;");} if(arquivoExiste($_SESSION["id"]."_noticia-subtitulo2.tmp") == false || arquivoExiste($_SESSION["id"]."_noticia-texto2.tmp") == false || $existeEdicaoSalva == false){echo("opacity: 0; max-height: 0px;");} ?> overflow: hidden; transition: 0.5s;">
<input id="subtitulo2" type="text" placeholder="Subtítulo 2" onkeyup="validarSubtitulo2();"
value="<?php
$nome = $_SESSION["id"] . "_noticia-subtitulo2.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?>"/>
<div id="subtitulo2status" class="statusCampo"></div>
<textarea id="texto2" placeholder="Texto do subtítulo 2"
onfocus="parent.exibirIconeEmote(true, true, this);" onblur="parent.exibirIconeEmote(false, true, this);"><?php
$nome = $_SESSION["id"] . "_noticia-texto2.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?></textarea>
<div id="texto2status" class="statusCampo"></div>
</div>
<div id="item3" style="<?php if(arquivoExiste($_SESSION["id"]."_noticia-subtitulo3.tmp") == true || arquivoExiste($_SESSION["id"]."_noticia-texto3.tmp") == true && $existeEdicaoSalva == true){echo("opacity: 1;");} if(arquivoExiste($_SESSION["id"]."_noticia-subtitulo2.tmp") == false || arquivoExiste($_SESSION["id"]."_noticia-texto2.tmp") == false || $existeEdicaoSalva == false){echo("opacity: 0; max-height: 0px;");} ?> overflow: hidden; transition: 0.5s;">
<input id="subtitulo3" type="text" placeholder="Subtítulo 3" onkeyup="validarSubtitulo3();"
value="<?php
$nome = $_SESSION["id"] . "_noticia-subtitulo3.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?>"/>
<div id="subtitulo3status" class="statusCampo"></div>
<textarea id="texto3" placeholder="Texto do subtítulo 3"
onfocus="parent.exibirIconeEmote(true, true, this);" onblur="parent.exibirIconeEmote(false, true, this);"><?php
$nome = $_SESSION["id"] . "_noticia-texto3.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?></textarea>
<div id="texto3status" class="statusCampo"></div>
</div>
<div id="item4" style="<?php if(arquivoExiste($_SESSION["id"]."_noticia-subtitulo4.tmp") == true || arquivoExiste($_SESSION["id"]."_noticia-texto4.tmp") == true && $existeEdicaoSalva == true){echo("opacity: 1;");} if(arquivoExiste($_SESSION["id"]."_noticia-subtitulo2.tmp") == false || arquivoExiste($_SESSION["id"]."_noticia-texto2.tmp") == false || $existeEdicaoSalva == false){echo("opacity: 0; max-height: 0px;");} ?> overflow: hidden; transition: 0.5s;">
<input id="subtitulo4" type="text" placeholder="Subtítulo 4" onkeyup="validarSubtitulo4();"
value="<?php
$nome = $_SESSION["id"] . "_noticia-subtitulo4.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?>"/>
<div id="subtitulo4status" class="statusCampo"></div>
<textarea id="texto4" placeholder="Texto do subtítulo 4"
onfocus="parent.exibirIconeEmote(true, true, this);" onblur="parent.exibirIconeEmote(false, true, this);"><?php
$nome = $_SESSION["id"] . "_noticia-texto4.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?></textarea>
<div id="texto4status" class="statusCampo"></div>
</div>
<div id="item5" style="<?php if(arquivoExiste($_SESSION["id"]."_noticia-subtitulo5.tmp") == true || arquivoExiste($_SESSION["id"]."_noticia-texto5.tmp") == true && $existeEdicaoSalva == true){echo("opacity: 1;");} if(arquivoExiste($_SESSION["id"]."_noticia-subtitulo2.tmp") == false || arquivoExiste($_SESSION["id"]."_noticia-texto2.tmp") == false || $existeEdicaoSalva == false){echo("opacity: 0; max-height: 0px;");} ?> overflow: hidden; transition: 0.5s;">
<input id="subtitulo5" type="text" placeholder="Subtítulo 5" onkeyup="validarSubtitulo5();"
value="<?php
$nome = $_SESSION["id"] . "_noticia-subtitulo5.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?>"/>
<div id="subtitulo5status" class="statusCampo"></div>
<textarea id="texto5" placeholder="Texto do subtítulo 5"
onfocus="parent.exibirIconeEmote(true, true, this);" onblur="parent.exibirIconeEmote(false, true, this);"><?php
$nome = $_SESSION["id"] . "_noticia-texto5.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?></textarea>
<div id="texto5status" class="statusCampo"></div>
</div>
<img id="adicionarEspaco" src="../imagens/adicionar.png" style="display: block; margin-left: auto; margin-right: auto; width: 32px; cursor: pointer; opacity: 0.6; margin-bottom: 32px;" onclick="adicionarSlot();" />
<br>
<br>
<div id="alteracoes" style="text-align: center;">
<?php
if($existeEdicaoSalva == false){
echo("Nenhuma alteração salva.");
}
if($existeEdicaoSalva == true){
echo(arquivoExiste($_SESSION["id"] . "_noticia-dataSalvamento.tmp"));
}
?>
</div>
<br>
<br>
<div style="display: grid; grid-template-columns: 50% 50%; width: 80%; max-width: 300px;">
<input type="button" value="Salvar" style="width: calc(100% - 8px); margin: 8px 8px 8px 0px;" onclick="salvarEdicao();" />
<input type="button" value="Pré-Visualizar" style="width: calc(100% - 8px); margin: 8px 0px 8px 8px;" onclick="previsualizar();" />
</div>
<input type="button" value="Criar Arquivo" onclick="criarArquivo();" />
</form>
</center>
</div>
<div id="noticiaCriada" style="display: none;">
<center>
<img src="../imagens/sucesso.png" width="128px" />
<br>
<br>
O arquivo de notícia foi criado com sucesso! Você pode obter o link para o arquivo abaixo.
<br>
<br>
<input type="text" id="urlDaNoticia" onfocus="copiarConteudo();" style="width: 100%;" readonly/>
</center>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
campoTitulo = document.getElementById("titulo");
statusTitulo = document.getElementById("tituloStatus");
tituloValido = false;
function validarTitulo(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoTitulo.value.length, 40);
//Desvalida
campoTitulo.style.borderColor = "#990000";
campoTitulo.style.borderWidth = "1px";
statusTitulo.style.color = "#990000";
tituloValido = false;
if(campoTitulo.value == ""){
statusTitulo.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoTitulo.value.length > 40){
statusTitulo.innerHTML = "Título muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoTitulo.value) == true){
statusTitulo.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoTitulo.style.borderColor = "";
campoTitulo.style.borderWidth = "";
statusTitulo.innerHTML = "";
tituloValido = true;
parent.redimensionarIframe();
}
campoUrlCapa = document.getElementById("urlCapa");
statusUrlCapa = document.getElementById("urlCapaStatus");
urlCapaValido = false;
function validarUrlCapa(){
//Desvalida
campoUrlCapa.style.borderColor = "#990000";
campoUrlCapa.style.borderWidth = "1px";
statusUrlCapa.style.color = "#990000";
urlCapaValido = false;
if(campoUrlCapa.value == ""){
statusUrlCapa.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComUrl(campoUrlCapa.value) == false){
statusUrlCapa.innerHTML = "O conteúdo digitado não é uma URL.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoUrlCapa.style.borderColor = "";
campoUrlCapa.style.borderWidth = "";
statusUrlCapa.innerHTML = "";
urlCapaValido = true;
parent.redimensionarIframe();
}
campoDescricao = document.getElementById("descricao");
statusDescricao = document.getElementById("descricaoStatus");
descricaoValido = false;
function validarDescricao(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoDescricao.value.length, 160);
//Desvalida
campoDescricao.style.borderColor = "#990000";
campoDescricao.style.borderWidth = "1px";
statusDescricao.style.color = "#990000";
descricaoValido = false;
if(campoDescricao.value == ""){
statusDescricao.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoDescricao.value.length > 160){
statusDescricao.innerHTML = "Descrição muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoDescricao.value) == true){
statusDescricao.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoDescricao.style.borderColor = "";
campoDescricao.style.borderWidth = "";
statusDescricao.innerHTML = "";
descricaoValido = true;
parent.redimensionarIframe();
}
campoIntro = document.getElementById("intro");
statusIntro = document.getElementById("introStatus");
introValido = false;
function validarIntroducao(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoIntro.value.length, 250);
//Desvalida
campoIntro.style.borderColor = "#990000";
campoIntro.style.borderWidth = "1px";
statusIntro.style.color = "#990000";
introValido = false;
if(campoIntro.value == ""){
statusIntro.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoIntro.value.length > 250){
statusIntro.innerHTML = "Introdução muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoIntro.value) == true){
statusIntro.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoIntro.style.borderColor = "";
campoIntro.style.borderWidth = "";
statusIntro.innerHTML = "";
introValido = true;
parent.redimensionarIframe();
}
campoSubtitulo1 = document.getElementById("subtitulo1");
statusSubtitulo1 = document.getElementById("subtitulo1status");
subtitulo1Valido = false;
function validarSubtitulo1(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoSubtitulo1.value.length, 80);
//Desvalida
campoSubtitulo1.style.borderColor = "#990000";
campoSubtitulo1.style.borderWidth = "1px";
statusSubtitulo1.style.color = "#990000";
subtitulo1Valido = false;
if(campoSubtitulo1.value.length > 80){
statusSubtitulo1.innerHTML = "Subtítulo muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoSubtitulo1.value) == true){
statusSubtitulo1.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoSubtitulo1.style.borderColor = "";
campoSubtitulo1.style.borderWidth = "";
statusSubtitulo1.innerHTML = "";
subtitulo1Valido = true;
parent.redimensionarIframe();
}
campoSubtitulo2 = document.getElementById("subtitulo2");
statusSubtitulo2 = document.getElementById("subtitulo2status");
subtitulo2Valido = true;
function validarSubtitulo2(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoSubtitulo2.value.length, 80);
//Desvalida
campoSubtitulo2.style.borderColor = "#990000";
campoSubtitulo2.style.borderWidth = "1px";
statusSubtitulo2.style.color = "#990000";
subtitulo2Valido = false;
if(campoSubtitulo2.value.length > 80){
statusSubtitulo2.innerHTML = "Subtítulo muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoSubtitulo2.value) == true){
statusSubtitulo2.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoSubtitulo2.style.borderColor = "";
campoSubtitulo2.style.borderWidth = "";
statusSubtitulo2.innerHTML = "";
subtitulo2Valido = true;
parent.redimensionarIframe();
}
campoSubtitulo3 = document.getElementById("subtitulo3");
statusSubtitulo3 = document.getElementById("subtitulo3status");
subtitulo3Valido = true;
function validarSubtitulo3(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoSubtitulo3.value.length, 80);
//Desvalida
campoSubtitulo3.style.borderColor = "#990000";
campoSubtitulo3.style.borderWidth = "1px";
statusSubtitulo3.style.color = "#990000";
subtitulo3Valido = false;
if(campoSubtitulo3.value.length > 80){
statusSubtitulo3.innerHTML = "Subtítulo muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoSubtitulo3.value) == true){
statusSubtitulo3.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoSubtitulo3.style.borderColor = "";
campoSubtitulo3.style.borderWidth = "";
statusSubtitulo3.innerHTML = "";
subtitulo3Valido = true;
parent.redimensionarIframe();
}
campoSubtitulo4 = document.getElementById("subtitulo4");
statusSubtitulo4 = document.getElementById("subtitulo4status");
subtitulo4Valido = true;
function validarSubtitulo4(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoSubtitulo4.value.length, 80);
//Desvalida
campoSubtitulo4.style.borderColor = "#990000";
campoSubtitulo4.style.borderWidth = "1px";
statusSubtitulo4.style.color = "#990000";
subtitulo4Valido = false;
if(campoSubtitulo4.value.length > 80){
statusSubtitulo4.innerHTML = "Subtítulo muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoSubtitulo4.value) == true){
statusSubtitulo4.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoSubtitulo4.style.borderColor = "";
campoSubtitulo4.style.borderWidth = "";
statusSubtitulo4.innerHTML = "";
subtitulo4Valido = true;
parent.redimensionarIframe();
}
campoSubtitulo5 = document.getElementById("subtitulo5");
statusSubtitulo5 = document.getElementById("subtitulo5status");
subtitulo5Valido = true;
function validarSubtitulo5(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoSubtitulo5.value.length, 80);
//Desvalida
campoSubtitulo5.style.borderColor = "#990000";
campoSubtitulo5.style.borderWidth = "1px";
statusSubtitulo5.style.color = "#990000";
subtitulo5Valido = false;
if(campoSubtitulo5.value.length > 80){
statusSubtitulo5.innerHTML = "Subtítulo muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoSubtitulo5.value) == true){
statusSubtitulo5.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoSubtitulo5.style.borderColor = "";
campoSubtitulo5.style.borderWidth = "";
statusSubtitulo5.innerHTML = "";
subtitulo5Valido = true;
parent.redimensionarIframe();
}
//Adicionar slot
function adicionarSlot(){
var slot2 = document.getElementById("item2");
var slot3 = document.getElementById("item3");
var slot4 = document.getElementById("item4");
var slot5 = document.getElementById("item5");
if(slot2.style.maxHeight == "0px"){
slot2.style.maxHeight = "";
slot2.style.opacity = "1";
parent.redimensionarIframe();
return;
}
if(slot3.style.maxHeight == "0px"){
slot3.style.maxHeight = "";
slot3.style.opacity = "1";
parent.redimensionarIframe();
return;
}
if(slot4.style.maxHeight == "0px"){
slot4.style.maxHeight = "";
slot4.style.opacity = "1";
parent.redimensionarIframe();
return;
}
if(slot5.style.maxHeight == "0px"){
slot5.style.maxHeight = "";
slot5.style.opacity = "1";
document.getElementById("adicionarEspaco").style.display = "none";
parent.redimensionarIframe();
return;
}
}
//Verifica se todos os slots já estão sendo exibidos, para ocultar o botão de adicionar
function ocultarBotaoDeAdicionarSlotCasoNaoSejaNecessario(){
var slot2 = document.getElementById("item2");
var slot3 = document.getElementById("item3");
var slot4 = document.getElementById("item4");
var slot5 = document.getElementById("item5");
if(slot2.style.maxHeight == "" && slot3.style.maxHeight == "" &&
slot4.style.maxHeight == "" && slot5.style.maxHeight == ""){
document.getElementById("adicionarEspaco").style.display = "none";
parent.redimensionarIframe();
return;
}
}
//Função que verifica se todos os campos estão válidos
function todosOsCamposEstaoValidos(){
validarTitulo();
validarUrlCapa();
validarDescricao();
validarIntroducao();
validarSubtitulo1();
validarSubtitulo2();
validarSubtitulo3();
validarSubtitulo4();
validarSubtitulo5();
if(tituloValido == true && urlCapaValido == true && descricaoValido == true && introValido == true &&
subtitulo1Valido == true && subtitulo2Valido == true && subtitulo3Valido == true && subtitulo4Valido == true && subtitulo5Valido == true){
return true;
}
if(tituloValido == false || urlCapaValido == false || descricaoValido == false || introValido == false ||
subtitulo1Valido == false || subtitulo2Valido == false || subtitulo3Valido == false || subtitulo4Valido == false || subtitulo5Valido == false){
parent.mostrarNotificacao("Verifique o formulário em busca de erros e tente novamente.", "#750000", 3000);
return false;
}
}
//Função que salva o conteúdo digitado, no servidor, através do ajax
function salvarEdicao(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/salvar-edicao-criar-noticia.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"titulo=" + document.getElementById("titulo").value +
"&urlCapa=" + document.getElementById("urlCapa").value +
"&descricao=" + document.getElementById("descricao").value +
"&introducao=" + document.getElementById("intro").value +
"&subtitulo1=" + document.getElementById("subtitulo1").value +
"&texto1=" + document.getElementById("texto1").value +
"&subtitulo2=" + document.getElementById("subtitulo2").value +
"&texto2=" + document.getElementById("texto2").value +
"&subtitulo3=" + document.getElementById("subtitulo3").value +
"&texto3=" + document.getElementById("texto3").value +
"&subtitulo4=" + document.getElementById("subtitulo4").value +
"&texto4=" + document.getElementById("texto4").value +
"&subtitulo5=" + document.getElementById("subtitulo5").value +
"&texto5=" + document.getElementById("texto5").value);
}
}
//Função que comando o servidor para gerar uma página temporária somente para pre-visualização da notícia
function previsualizar(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/gerar-arquivo-noticia.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"titulo=" + document.getElementById("titulo").value +
"&urlCapa=" + document.getElementById("urlCapa").value +
"&descricao=" + document.getElementById("descricao").value +
"&introducao=" + document.getElementById("intro").value +
"&subtitulo1=" + document.getElementById("subtitulo1").value +
"&texto1=" + document.getElementById("texto1").value +
"&subtitulo2=" + document.getElementById("subtitulo2").value +
"&texto2=" + document.getElementById("texto2").value +
"&subtitulo3=" + document.getElementById("subtitulo3").value +
"&texto3=" + document.getElementById("texto3").value +
"&subtitulo4=" + document.getElementById("subtitulo4").value +
"&texto4=" + document.getElementById("texto4").value +
"&subtitulo5=" + document.getElementById("subtitulo5").value +
"&texto5=" + document.getElementById("texto5").value +
"&modoPrevia=true");
}
}
//Função que comando o servidor para gerar a página da notícia
function criarArquivo(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/gerar-arquivo-noticia.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"titulo=" + document.getElementById("titulo").value +
"&urlCapa=" + document.getElementById("urlCapa").value +
"&descricao=" + document.getElementById("descricao").value +
"&introducao=" + document.getElementById("intro").value +
"&subtitulo1=" + document.getElementById("subtitulo1").value +
"&texto1=" + document.getElementById("texto1").value +
"&subtitulo2=" + document.getElementById("subtitulo2").value +
"&texto2=" + document.getElementById("texto2").value +
"&subtitulo3=" + document.getElementById("subtitulo3").value +
"&texto3=" + document.getElementById("texto3").value +
"&subtitulo4=" + document.getElementById("subtitulo4").value +
"&texto4=" + document.getElementById("texto4").value +
"&subtitulo5=" + document.getElementById("subtitulo5").value +
"&texto5=" + document.getElementById("texto5").value +
"&modoPrevia=false");
}
}
//Função que seleciona e copia a URL automaticamente, da caixa de texto
function copiarConteudo(){
document.getElementById("urlDaNoticia").select();
document.execCommand("Copy");
parent.mostrarNotificacao("URL copiado para a área de trasferência!", "#467200", 2500);
}
//Função que exibe a mensagem de sucesso após criar arquivo de notícia
function exibirMensagemArquivoCriado(url){
document.getElementById("urlDaNoticia").value = url;
document.getElementById("noticiaCriada").style.display = "block";
document.getElementById("formulario").style.display = "none";
document.getElementById("quadroDeAvisos").style.display = "none";
parent.redimensionarIframe();
}
//Redimensiona as textarea de acordo com seus conteúdos, automaticamente
var textAreas = document.getElementsByTagName("textarea");
for (var i = 0; i < textAreas.length; i++){
textAreas[i].style.height = (textAreas[i].scrollHeight) + "px";
textAreas[i].style.overflow = "hidden";
textAreas[i].style.resize = "none";
textAreas[i].style.minHeight = "80px";
textAreas[i].addEventListener("input", AoDigitarNasTextArea, false);
}
function AoDigitarNasTextArea(){
this.style.height = "auto";
this.style.height = (this.scrollHeight) + "px";
this.style.minHeight = "80px";
parent.redimensionarIframe();
}
<?php
//Caso encontre uma edição salva, avisa
if($existeEdicaoSalva == true){
echo('parent.mostrarNotificacao("Sua última edição da notícia, foi restaurada.", "#167200", 3500);'.
'todosOsCamposEstaoValidos();'.
'ocultarBotaoDeAdicionarSlotCasoNaoSejaNecessario();'.
'parent.redimensionarIframe();');
}
?>
</script>
<?php
$conteudoQuadroDeAviso = ('
• Para inserir imagens neste arquivo de notícia, primeiro faça upload delas usando a função de carregar imagem.
<br/>
• Lembre-se de salvar as alterações caso precise deixar esta página.
<br/>
• Após criar o arquivo de notícia, você precisa publica-lo para que ele apareça nos slides.
<br/>
• O campo de "Breve descrição" será a descrição da notícia, exibida nas redes sociais, quando o usuário compartilhar o link desta notícia.
<br/>
• Caso não precise usar algum campo, basta deixa-lo vazio, por exemplo, deixe os campos de subtítulos vazios se sua notícia não terá subtítutlos, e somente um texto único.
<br/>
• O código HTML é livre para uso nos campos de texto.
<br/>
• Quebras de linhas serão formatadas para código <br> automaticamente.
<br/>
• Se houver uma notícia com o mesmo título na mesma data, a mesma será sobrescrita pela nova notícia.
<br/>
• Fornecer uma imagem de capa inválida, ou inexistente fará com que a página da notícia seja carregada duas vezes pelo navegador.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/paginas/listar-jogos-cadastrados.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem os dados de todos jogos cadastrados
$jogosConsulta = mysqli_query($DB_Metadados, "SELECT JogoID, Nome, UrlIconeJogo, UltimaVersao, PacoteOuNamespace, UrlIconePlataforma FROM JogosDaWindsoft WHERE JogoID > 0");
$i = 0;
while($linha = mysqli_fetch_assoc($jogosConsulta)) {
$jogoId[$i] = $linha["JogoID"];
$nome[$i] = $linha["Nome"];
$urlIconeJogo[$i] = $linha["UrlIconeJogo"];
$ultimaVersao[$i] = $linha["UltimaVersao"];
$pacote[$i] = $linha["PacoteOuNamespace"];
$urlIconePlataforma[$i] = $linha["UrlIconePlataforma"];
$i += 1;
}
?>
<center>
<h3>Listar Jogos Cadastrados</h3>
</center>
<?php
for ($ii = 0; $ii < $i; $ii++) {
//Imprime o código HTML para representar este jogo
echo('
<div style="display: grid; grid-template-columns: 30px 75px auto; background-color: #DBDBDB; padding: 4px; border-radius: 4px; margin-bottom: 4px;">
<div style="display: flex; justify-content: center; align-items: center; font-weight: bolder;">
#'.$jogoId[$ii].'
</div>
<div style="height: 60px; width: 60px;">
<img src="'.$urlIconeJogo[$ii].'" width="100%" height="100%" style="border-radius: 50%;" />
<div style="width: 25px; height: 25px; position: relative; border-radius: 25px; top: -25px; left: 40px; background-color: #ffffff;">
<div style="width: 17px; height: 17px; padding: 4px;">
<img src="'.$urlIconePlataforma[$ii].'" width="100%" height="100%" />
</div>
</div>
</div>
<div style="display: grid; grid-template-rows: 50% 50%;">
<div style="padding-top: 14px; font-weight: bold; font-size: 18px;">
'.$nome[$ii].'
</div>
<div style="padding-top: 4px; font-size: 12px; color: #828282;">
Versão '.$ultimaVersao[$ii].' ('.$pacote[$ii].')
</div>
</div>
</div>');
}
?>
<!-- código javascript desta página -->
<script type="text/javascript">
</script>
<?php
$conteudoQuadroDeAviso = ('
• Todos os jogos cadastrados no banco de dados da Windsoft, são mostrados aqui.
<br/>
• Quando um jogo é cadastrado no banco de dados da Windsoft, os dados sobre o mesmo são todos reunidos em um só lugar. Assim o Windsoft Launcher dos jogos, podem obter metadados e saber informações, como última versão lançada e etc.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/global/mysql/metadados.inc
<?php
/*
* Essa classe é responsável por fazer a conexão ao banco de dados "metadados"
*/
//Este script deve ser incluído no topo dos scripts.
//Abre a conexão para o banco de dados "Metadados"
$DB_Metadados = mysqli_connect("metadados.mysql.uhserver.com", "metadata", "45032978m@rC", "metadados");
mysqli_query($DB_Metadados, "SET NAMES 'utf8'");
mysqli_query($DB_Metadados, 'SET character_set_connection=utf8');
mysqli_query($DB_Metadados, 'SET character_set_client=utf8');
mysqli_query($DB_Metadados, 'SET character_set_results=utf8');
?><file_sep>/browser/noticias/por-data/2019/08/19/a.php
<?php
/*
* Essa é a página de código base para a geração dos arquivos de notícia da Windsoft.
* Ao gerar os arquivos PHP de notícia, as variaveis com %ALGO% serão substituidas por conteudo.
*/
$tituloPagina = "a - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
$aplicarHtmlMetaTagsAdicionais = true;
$metaTitulo = "a - Windsoft Notícias";
$metaCapaUrl = "https://a.cp";
$metaCapaWidth = "400px";
$metaCapaHeight = "400px";
$metaUrlPagina = "https://windsoft.xyz/browser/noticias/por-data/2019/08/19/".basename($_SERVER['PHP_SELF']);
$metaDescricao = "";
include("../../../../../includes/cabecalho.inc");
?>
</div>
<div class="paginaDeNoticiaCapaFundo" style="background-image: url(https://a.cp);">
<div class="paginaDeNoticiaCapaEscurecimento">
<div class="paginaDeNoticiaCapaTitulo">
a
</div>
</div>
</div>
<div class="content">
<center>
<div style="height: auto; display: inline-block;">
<div style="float: left;">
<img src="https://windsoft.xyz/browser/noticias/arquivos/data.png" width="20px" height="20px" style="opacity: 0.4;" title="Escrito em" />
<div style="font-size: 10px; line-height: 20px; vertical-align: middle; color: #afafaf; float: right;">
19 de Ago de 2019 as 14:55
</div>
</div>
<div style="margin-left: 5px; float: left;">
<img src="https://windsoft.xyz/browser/noticias/arquivos/autor.png" width="20px" height="20px" style="opacity: 0.4;" title="Escrito por" />
<div style="font-size: 10px; line-height: 20px; vertical-align: middle; color: #afafaf; float: right;">
marcos4503 (CEO)
</div>
</div>
</div>
</center>
<center>
<div class="fb-like" data-href="https://facebook.com/windsoft.games" data-layout="button_count" data-action="like" data-size="small" data-show-faces="false" data-share="true"></div>
</center>
<br/>
<br/>
<center>
fd
</center>
<br/>
<br/>
<center>
<h2></h2>
</center>
<center>
<h2></h2>
</center>
<center>
<h2></h2>
</center>
<center>
<h2></h2>
</center>
<center>
<h2></h2>
</center>
<br/>
<br/>
<br/>
<center>
<div class="paginaDeNoticiaBotoesShare">
<!-- Botao Facebook -->
<img class="paginaDeNoticiaBotaoShare" src="https://windsoft.xyz/browser/noticias/arquivos/facebook.png" width="40px" height="40px"
onclick="AbrirPopUp('https://www.facebook.com/sharer/sharer.php?u=https://windsoft.xyz/browser/noticias/por-data/2019/08/19/<?php echo basename($_SERVER['PHP_SELF']); ?>')"/>
<!-- Botao LinkedIn -->
<img class="paginaDeNoticiaBotaoShare" src="https://windsoft.xyz/browser/noticias/arquivos/linked-in.png" width="40px" height="40px"
onclick="AbrirPopUp('https://www.linkedin.com/shareArticle?mini=true&url=https://windsoft.xyz/browser/noticias/por-data/2019/08/19/<?php echo basename($_SERVER['PHP_SELF']); ?>&title=Veja esta notícia do Windsoft Notícias!')" />
<!-- Botao Twitter -->
<img class="paginaDeNoticiaBotaoShare" src="https://windsoft.xyz/browser/noticias/arquivos/twitter.png" width="40px" height="40px"
onclick="AbrirPopUp('https://twitter.com/intent/tweet?text=Veja esta notícia do Windsoft Notícias! https://windsoft.xyz/browser/noticias/por-data/2019/08/19/<?php echo basename($_SERVER['PHP_SELF']); ?>')" />
<!-- Botao WhatsApp -->
<a href="whatsapp://send?text=Veja está notícia do Windsoft Notícias! https://windsoft.xyz/browser/noticias/por-data/2019/08/19/<?php echo basename($_SERVER['PHP_SELF']); ?>" data-action="share/whatsapp/share">
<img class="paginaDeNoticiaBotaoShare" src="https://windsoft.xyz/browser/noticias/arquivos/whatsapp.png" width="40px" height="40px" />
</a>
</div>
</center>
<!-- Abrir popup script -->
<script>
function AbrirPopUp(URL){
window.open(URL, 'targetWindow', 'toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=450px, height=450px')
}
</script>
<!-- script do facebook -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = 'https://connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v3.2&appId=1100512010112474&autoLogAppEvents=1';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<?php
include("../../../../../includes/rodape.inc");
//Registra a estatística de notícia aberta. Fica no fim para não influenciar a renderição do documento e suas META TAGS
include("../../../../../../global/mysql/metadados.inc");
$consultaEstatistica = mysqli_query($DB_Metadados, "UPDATE NoticiasStats SET NewsAbertasDia = NewsAbertasDia + 1, NewsAbertasSem = NewsAbertasSem + 1, NewsAbertasMes = NewsAbertasMes + 1 WHERE Idade='Atual'");
?><file_sep>/browser/links/facebook.php
<?php
/*
* Essa página funciona como um redirecionamento para a página da Windsoft Games no Facebook.
* O arquivo .htaccess possui uma configuração para que seja possível acessa-la com uma URL mais curta.
*/
$tituloPagina = "Facebook - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("../includes/cabecalho.inc");
RedirecionarPara("https://facebook.com/windsoft.games", 3);
?>
<center>
<br/>
Por favor, aguarde, estamos lhe redirecionando para nossa página do Facebook!
<br/>
<br/>
<small>
<a href="https://facebook.com/windsoft.games">Clique aqui caso não seja redirecionado</a>
</small>
</center>
<?php
include("../includes/rodape.inc");
?><file_sep>/browser/microsite/painel/paginas/home.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<!-- Código da página inicial-->
<center>
<h3>Página Inicial</h3>
<img src="../imagens/android.png" style="width: 200px;" />
<br>
Olá
<?php
$id = $_SESSION["id"];
$consultaPerfil = mysqli_query($DB_Registros, "SELECT Nome FROM Perfis WHERE ID=$id");
$dadosPerfil = mysqli_fetch_array($consultaPerfil);
echo($dadosPerfil[0]);
?>! Boas vindas ao painel de administração do servidor da Windsoft Games, lembre-se de verificar a anotação atual no Post-it abaixo e atualizar a Documentação do servidor sempre que mudar algo (se necessário). Tenha um bom dia!
<br>
<br>
<br>
<br>
</center>
<?php
//Faz a consulta de contagem de tickets
$consultaBugs = mysqli_query($DB_Feedbacks, "SELECT TABLE_ROWS FROM information_schema.TABLES WHERE TABLE_NAME='Bugs'");
$dadosBugs = mysqli_fetch_array($consultaBugs);
$consultaOpinioes = mysqli_query($DB_Feedbacks, "SELECT TABLE_ROWS FROM information_schema.TABLES WHERE TABLE_NAME='Opinioes'");
$dadosOpinioes = mysqli_fetch_array($consultaOpinioes);
?>
<center>
<div style="padding: 10px; border-radius: 4px; background-color: #016F91; margin-bottom: 20px; color: #F2F2F2;">
Total de tickets enviados por usuários
<div style="overflow: auto; display: grid; grid-template-columns: 50% 50%; width: 100%;">
<div>
<font style="font-size: 20px; font-style: bolder;"><?php echo($dadosOpinioes[0]); ?></font><br>
<font style="font-size: 12px;">Opiniões</font>
</div>
<div>
<font style="font-size: 20px; font-style: bolder;"><?php echo($dadosBugs[0]); ?></font><br>
<font style="font-size: 12px;">Bugs</font>
</div>
</div>
</div>
</center>
<?php
//Faz a consulta e obtem os dados do post-it
$consultaPostIt = mysqli_query($DB_Metadados, "SELECT Texto, CorPostIt, CorFonte FROM StaffPostIt WHERE ID=0");
$dadosPostIt = mysqli_fetch_array($consultaPostIt);
?>
<center>
<div style="position: relative; margin-left: auto; margn-right: auto; width: 100%; min-height: 80px;">
<textarea id="post-it" disabled style="border-radius: 4px; background-color: <?php echo($dadosPostIt[1]); ?>; color: #262626; width: 100%; resize: vertical; padding-bottom: 20px; padding-top: 30px; border-style: none; border-width: 0px; max-width: 100%; margin: 0px; padding-left: 0px; padding-right: 0px; min-height: 120px; display: block; border: none; padding-left: 10px; padding-right: 10px;">
<?php echo($dadosPostIt[0]); ?>
</textarea>
<?php
$codigoEdicaoPostIt = '
<div id="edicao" style="display: none; position: absolute; height: 18px; width: 200px; bottom: 0px; left: 0px; margin-bottom: 4px; margin-left: 4px;">
<div style="float: left; margin-right: 5px; background-color: #2A91C9; width: 18px; height: 18px; cursor: pointer;" onclick="alterarCorPostIt(\'0\');">
</div>
<div style="float: left; margin-right: 5px; background-color: #E4E800; width: 18px; height: 18px; cursor: pointer;" onclick="alterarCorPostIt(\'1\');">
</div>
<div style="float: left; margin-right: 5px; background-color: #FFAC30; width: 18px; height: 18px; cursor: pointer;" onclick="alterarCorPostIt(\'2\');">
</div>
<div style="float: left; margin-right: 5px; background-color: #3BC61B; width: 18px; height: 18px; cursor: pointer;" onclick="alterarCorPostIt(\'3\');">
</div>
<div style="float: left; margin-right: 5px; background-color: #DB00C9; width: 18px; height: 18px; cursor: pointer;" onclick="alterarCorPostIt(\'4\');">
</div>
<img src="../imagens/icones/salvar.png" style="float: left; height: 18px; width: 18px; cursor: pointer;" onclick="salvarPostIt();">
</div>
<div id="editor" style="display: block; position: absolute; height: 18px; width: 200px; bottom: 0px; left: 0px; margin-bottom: 4px; margin-left: 4px;">
<img src="../imagens/icones/editar.png" style="float: left; height: 18px; width: 18px; cursor: pointer;" onclick="modoEdicaoPostIt();">
</div>
<div id="editor" style="display: block; position: absolute; height: 30px; width: 100%; top: 0px; margin-bottom: 4px; text-align: center; line-height: 30px;">
Post-It
</div>
';
if($_SESSION["autoridade"] == 4){
echo($codigoEdicaoPostIt);
}
?>
</div>
</center>
<?php
if($_SESSION["autoridade"] == 4){
echo('
<br>
<br>
<center><h3 style="margin-bottom: 0px;">Requisições diárias feitas pelo MT Assets Patcher Updater</h3></center>
<div id="chart" style="width: 100%; height: 250px;"></div>
<center><small>* Sempre que uma requisição for feita no ínicio do mês, os dados dos dias seguintes serão excluídos. Sempre que o MT Assets Patcher Updater se conecta ao servidor, seja para verificar se há uma atualização, ou para atualizar o Patcher do projeto do cliente, o acesso é contato como uma Requisição.</small></center>
');
}
?>
<!-- código javascript desta página -->
<script type="text/javascript">
function modoEdicaoPostIt(){
document.getElementById("edicao").style.display = "block";
document.getElementById("editor").style.display = "none";
document.getElementById("post-it").disabled = false;
}
function salvarPostIt(){
parent.mostrarSpinner(true);
//Cria a conexão e inicia
var conexao = parent.novaConexaoPost("ajax-query/atualizar-post-it.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
document.getElementById("edicao").style.display = "none";
document.getElementById("editor").style.display = "block";
document.getElementById("post-it").disabled = true;
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "texto=" + document.getElementById("post-it").value + "&corDeFundo=" + document.getElementById("post-it").style.backgroundColor);
}
function alterarCorPostIt(cor){
if(cor == 0){
document.getElementById("post-it").style.color = "#262626";
document.getElementById("post-it").style.backgroundColor = "#227CAD";
}
if(cor == 1){
document.getElementById("post-it").style.color = "#262626";
document.getElementById("post-it").style.backgroundColor = "#d2d600";
}
if(cor == 2){
document.getElementById("post-it").style.color = "#262626";
document.getElementById("post-it").style.backgroundColor = "#EAA02A";
}
if(cor == 3){
document.getElementById("post-it").style.color = "#262626";
document.getElementById("post-it").style.backgroundColor = "#34A81A";
}
if(cor == 4){
document.getElementById("post-it").style.color = "#262626";
document.getElementById("post-it").style.backgroundColor = "#BF00B2";
}
}
<?php
//Obtem a contagem de requisições
$consultaStatsMTPatcherUpdater = mysqli_query($DB_Metadados, "SELECT DadosDestaEstatistica FROM AssetStoreStats WHERE TipoDeEstatistica='MTAssets-PatcherUpdater-Requisicoes'");
$dadosStats = mysqli_fetch_array($consultaStatsMTPatcherUpdater);
$armazenamentoStats = json_decode($dadosStats[0]);
$arrayRequisicoesDiarias = $armazenamentoStats->diasDoMes;
?>
//Desenha o gráfico de requisições efetuadas pelo MT Assets Patcher Updater
google.charts.load('current', {'packages':['corechart', 'bar']});
google.charts.setOnLoadCallback(desenharGrafico);
//Dados de exibição diário
dadosPorDia = [["Dia", "Requisições"],<?php
for ($i = 0; $i < 31; $i++) {
echo("["."'".($i + 1)."'".",".$arrayRequisicoesDiarias[$i]->requisicoes."]");
if($i >= 0){
echo(",");
}
}
?>];
function desenharGrafico() {
var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
chart.draw(google.visualization.arrayToDataTable(dadosPorDia), {legend: {position: "none"}, "chartArea": {"width": "100%", "height": "300px"}});
}
</script>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/client/metadados/noticias/noticias-metadata.php
<?php
/*
* Essa classe é responsável por fornecer os metadados de notícias ao client
*/
include("../../../global/sessoes/verificador-de-sessao.inc");
include("../../../global/mysql/metadados.inc");
IgnorarSessaoImprimirMensagemDeConteudoCarregado();
$tempoInicio = microtime(true);
$jsonResposta = new stdClass();
//<!---------------------- Inicio do Script ----------------------------->
$noticiasConsulta = mysqli_query($DB_Metadados, "SELECT Titulo, UrlDaPagina, UrlDaCapa FROM Noticias WHERE Noticia IN (".implode(',', $a=array(1, 2, 3, 4, 5)).")");
$i = 0;
while($linha = mysqli_fetch_assoc($noticiasConsulta)) {
$titulo[$i] = $linha["Titulo"];
$urlPagina[$i] = $linha["UrlDaPagina"]
$urlCapa[$i] = $linha["UrlDaCapa"];
$i += 1;
}
//Retorna os metadados da noticia 1
$jsonResposta->tituloNoticia1 = $titulo[0];
$jsonResposta->urlPaginaNoticia1 = $urlPagina[0];
$jsonResposta->urlImgCapaNoticia1 = $urlCapa[0];
//Retorna os metadados da noticia 2
$jsonResposta->tituloNoticia2 = $titulo[1];
$jsonResposta->urlPaginaNoticia2 = $urlPagina[1];
$jsonResposta->urlImgCapaNoticia2 = $urlCapa[1];
//Retorna os metadados da noticia 3
$jsonResposta->tituloNoticia3 = $titulo[2];
$jsonResposta->urlPaginaNoticia3 = $urlPagina[2];
$jsonResposta->urlImgCapaNoticia3 = $urlCapa[2];
//Retorna os metadados da noticia 4
$jsonResposta->tituloNoticia4 = $titulo[3];
$jsonResposta->urlPaginaNoticia4 = $urlPagina[3];
$jsonResposta->urlImgCapaNoticia4 = $urlCapa[3];
//Retorna os metadados da noticia 5
$jsonResposta->tituloNoticia5 = $titulo[4];
$jsonResposta->urlPaginaNoticia5 = $urlPagina[4];
$jsonResposta->urlImgCapaNoticia5 = $urlCapa[4];
//Insere o tempo da duração das contas no JSON Resposta
$jsonResposta->tempoExecucaoDoScript = number_format(microtime(true) - $tempoInicio, 5) . "ms";
//Imprime o JSON resposta
echo("<pre>" . json_encode($jsonResposta, JSON_PRETTY_PRINT) . "</pre>");
?><file_sep>/browser/javascript/funcoes-ajax.js
/*
* Essa código force métodos e funções úteis para usar no AJAX do site
*/
function mostrarSpinner(mostrar){
//Exibe ou oculta o spinner de carregamento
if(mostrar == true){
document.getElementById("loadSpinner").style.opacity = "1";
document.getElementById("blockPointerEvents").style.display = "block";
}
if(mostrar == false){
document.getElementById("loadSpinner").style.opacity = "0";
document.getElementById("blockPointerEvents").style.display = "none";
}
}
var funcaoDeCancelamentoNotificacao;
function mostrarNotificacao(mensagem, corDeFundo, tempo){
//Reseta a notificação, a fazendo reaparecer caso já esteja na tela
clearTimeout(funcaoDeCancelamentoNotificacao);
document.getElementById("notificacao").style.transition = "max-height 0ms";
document.getElementById("notificacao").style.maxHeight = "0px";
//Exibe uma mensagem de notificação (apos um curto periodo)
setTimeout(function () {
document.getElementById("notificacao").style.transition = "max-height 300ms";
document.getElementById("notificacao").style.backgroundColor = corDeFundo;
document.getElementById("notificacao").innerHTML = "<center><div style=\"height: 10px;\"></div>" + mensagem + "<div style=\"height: 10px;\"></div></center>";
document.getElementById("notificacao").style.maxHeight = "200px";
}, 25);
//Define a função para limpar a notificação após um tempo
funcaoDeCancelamentoNotificacao = setTimeout(function () {
document.getElementById("notificacao").style.maxHeight = "0px";
}, tempo);
}
function novaConexaoPost(url){
//Criar um novo objeto XML
var xmlreq = new XMLHttpRequest();
//Inicia a conexão
xmlreq.open("POST", url, true);
xmlreq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//Processa a conexão de acordo com a função criada e retorna o XMLRequest
return xmlreq;
}
function definirFuncaoDeSucessoOuErro(xmlreq, funcaoErro, funcaoSucesso){
//Aguarda a conexão completar
if(xmlreq.readyState === 4){
//Verifica o código de resposta
if(xmlreq.status === 200){
funcaoSucesso();
}
else{
funcaoErro();
}
}
}
function iniciarConexaoPost(xmlreq, dadosPost){
//Inicia a conexão
setTimeout(function () { xmlreq.send(dadosPost); }, 2000);
}
function textoDaConexao(xmlreq){
//Obtem o texto resposta da conexão
return xmlreq.responseText;
}
//método que exibe o contador de caracteres por alguns segundos
var funcaoEsconderContador;
function exibirContadorDeCaracteres(quantia, quantiaMaxima){
var contador = document.getElementById("contadorDeCaracteres");
var contadorTexto = document.getElementById("contadorDeCaracteresTexto");
contador.style.left = "0px";
if(quantiaMaxima > 0 && quantia <= quantiaMaxima){
contadorTexto.innerHTML = quantia + " / " + quantiaMaxima;
contador.style.backgroundColor = "#319B00";
}
if(quantiaMaxima > 0 && quantia > quantiaMaxima){
contadorTexto.innerHTML = quantia + " / " + quantiaMaxima;
contador.style.backgroundColor = "#990000";
}
if(quantiaMaxima == 0){
contadorTexto.innerHTML = quantia;
contador.style.backgroundColor = "#319B00";
}
clearTimeout(funcaoEsconderContador);
funcaoEsconderContador = setTimeout(function(){
contador.style.left = "-300px";
}, 2500);
}
//Método que exibe ou oculta o ícone de emote
var textAreaAlvo;
var ocultarIconeEmoteAposTempo;
function exibirIconeEmote(exibir, textAreaDentroDeUmIframe, textarea){
//Caso o input esteja dentro do documento principal
if(textAreaDentroDeUmIframe == false){
textAreaAlvo = textarea;
}
//Caso o input não esteja dentro do documento principal, mas dentro de um iframe
if(textAreaDentroDeUmIframe == true){
var iframe = document.getElementsByTagName("iframe")[0];
textAreaAlvo = iframe.contentWindow.document.getElementById(textarea.id);
}
if(exibir == true){
clearTimeout(ocultarIconeEmoteAposTempo);
document.getElementById("gavetaDeEmotesRaiz").style.opacity = "1";
document.getElementById("gavetaDeEmotesRaiz").style.pointerEvents = "auto";
}
if(exibir == false){
ocultarIconeEmoteAposTempo = setTimeout(function(){
document.getElementById("gavetaDeEmotesRaiz").style.opacity = "0";
document.getElementById("gavetaDeEmotesRaiz").style.pointerEvents = "none";
document.getElementById("gavetaDeEmotesRaiz").style.bottom = "-100px";
}, 150);
}
}
//Método que abre ou fecha a gaveta de emotes
function abrirFecharGavetaDeEmotes(){
var gaveta = document.getElementById("gavetaDeEmotesRaiz");
if(gaveta.style.bottom == "-100px"){
gaveta.style.bottom = "0px";
textAreaAlvo.focus();
return;
}
if(gaveta.style.bottom == "0px"){
gaveta.style.bottom = "-100px";
textAreaAlvo.focus();
return;
}
}
//Método que adiciona o emote desejado no campo de texto
function adicionarEmote(emote){
textAreaAlvo.focus();
if (textAreaAlvo.selectionStart || textAreaAlvo.selectionStart == '0') {
var startPos = textAreaAlvo.selectionStart;
var endPos = textAreaAlvo.selectionEnd;
textAreaAlvo.value = textAreaAlvo.value.substring(0, startPos) + emote + textAreaAlvo.value.substring(endPos, textAreaAlvo.value.length);
}
else {
textAreaAlvo.value += emote;
}
textAreaAlvo.focus();
}
<file_sep>/browser/microsite/painel/paginas/reportar-venda-asset.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<!-- Código PHP que processa o armazenamento de dados de vendas dos assets e carrega todos os dados dos assets -->
<?php include("includes/mt-assets-historico-de-vendas.inc"); ?>
<center>
<h3>Reportar Nova Venda</h3>
</center>
<div id="formulario" style="display: block;">
<center>
<form autocomplete="off">
<select id="selectSlide" onchange="aoTrocarAsset();">
<?php
for ($x = 1; $x < $i; $x++) {
echo('<option value="'.$id[$x].'">'.$nome[$x].'</option>');
}
?>
</select>
<input id="copias" type="text" placeholder="Cópias Vendidas" onkeyup="validarCopias();" />
<div id="copiasStatus" class="statusCampo"></div>
<input type="button" value="Reportar" onclick="salvarReporte();" />
</form>
</center>
</div>
<br>
<br>
<center>
<h3 id="tituloAssetSelecionado"></h3>
</center>
<table style="width: 100%; border-collapse: collapse; font-size: 14px;">
<tr>
<th style="width: 33.3%; border: 1px solid #ddd; padding: 4px; text-align: left;">Este Mês</th>
<th style="width: 33.3%; border: 1px solid #ddd; padding: 4px; text-align: center;">Hoje</th>
<th style="width: 33.3%; border: 1px solid #ddd; padding: 4px; text-align: right;">Gerado Hoje</th>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 4px; text-align: left;" id="vendasDesteAssetMes"></td>
<td style="border: 1px solid #ddd; padding: 4px; text-align: center;" id="vendasDesteAssetHoje"></td>
<td style="text-align: right; border: 1px solid #ddd; padding: 4px;" id="receitaDesteAssetHoje"></td>
</tr>
</table>
<br>
<center>
<small id="dataPublicacao">Data de Publicação</small>
</center>
<!-- código javascript desta página -->
<script type="text/javascript">
//Obtem os dados de cada asset
nomesDosAssets = ["", <?php
for ($x = 1; $x < $i; $x++) {
echo('"'.$nome[$x].'"');
if($x != $i){
echo(",");
}
}
?>];
vendasDeHojeCadaAsset = ["", <?php
for ($x = 1; $x < $i; $x++) {
echo('"'.ObterVendasDeHoje($vendasPorDataJson[$x]).'"');
if($x != $i){
echo(",");
}
}
?>];
receitaDeHojeCadaAsset = ["", <?php
for ($x = 1; $x < $i; $x++) {
echo('"'.ObterReceitaDeHoje($vendasPorDataJson[$x]).'"');
if($x != $i){
echo(",");
}
}
?>];
vendasDesteMesCadaAsset = ["", <?php
for ($x = 1; $x < $i; $x++) {
echo('"'.ObterVendasDesteMes($vendasPorDataJson[$x]).'"');
if($x != $i){
echo(",");
}
}
?>];
precoDosAssets = ["", <?php
for ($x = 1; $x < $i; $x++) {
echo('"'.$precoAtual[$x].'"');
if($x != $i){
echo(",");
}
}
?>];
dataPublicacaoAssets = ["", <?php
for ($x = 1; $x < $i; $x++) {
echo('"'.$dataPublicacao[$x].'"');
if($x != $i){
echo(",");
}
}
?>];
//Preenche os campos ao trocar o asset
assetSelect = document.getElementById("selectSlide");
assetSelecionadoId = 1;
function aoTrocarAsset(){
assetSelecionadoId = assetSelect.value;
document.getElementById("tituloAssetSelecionado").innerHTML = "Vendas de " + nomesDosAssets[assetSelecionadoId];
document.getElementById("receitaDesteAssetHoje").innerHTML = "US$ " + Number(receitaDeHojeCadaAsset[assetSelecionadoId]).toFixed(2);
document.getElementById("vendasDesteAssetHoje").innerHTML = vendasDeHojeCadaAsset[assetSelecionadoId];
document.getElementById("vendasDesteAssetMes").innerHTML = vendasDesteMesCadaAsset[assetSelecionadoId];
var dataPublicacao = dataPublicacaoAssets[assetSelecionadoId].split("-");
document.getElementById("dataPublicacao").innerHTML = nomesDosAssets[assetSelecionadoId] + " foi publicado na Asset Store pela primeira vez em " + dataPublicacao[2] + "/" + dataPublicacao[1] + "/" + dataPublicacao[0] + ".";
}
campoCopias = document.getElementById("copias");
statusCopias = document.getElementById("copiasStatus");
copiasValido = false;
function validarCopias(){
//Desvalida
campoCopias.style.borderColor = "#990000";
campoCopias.style.borderWidth = "1px";
statusCopias.style.color = "#990000";
copiasValido = false;
if(campoCopias.value == ""){
statusCopias.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComNumeroFloat(campoCopias.value) == false || campoCopias.value.indexOf(',') > -1 || campoCopias.value.indexOf('.') > -1){
statusCopias.innerHTML = "Utilize apenas números inteiros.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoCopias.style.borderColor = "";
campoCopias.style.borderWidth = "";
statusCopias.innerHTML = "";
copiasValido = true;
parent.redimensionarIframe();
}
//Função que verifica se todos os campos estão válidos
function todosOsCamposEstaoValidos(){
validarCopias();
if(copiasValido == true){
return true;
}
if(copiasValido == false){
parent.mostrarNotificacao("Verifique o formulário em busca de erros e tente novamente.", "#750000", 3000);
return false;
}
}
//Função que reporta a venda
function salvarReporte(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/reportar-venda-asset.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"id=" + assetSelecionadoId +
"&copiasVendidas=" + document.getElementById("copias").value +
"&precoAsset=" + precoDosAssets[assetSelecionadoId]);
}
}
//Função que atualiza os dados na tela
function AtualizarDadosNaTela(id, quantidadeVendida, precoVenda){
document.getElementById("copias").value = "";
vendasDeHojeCadaAsset[id] = parseInt(vendasDeHojeCadaAsset[id]) + quantidadeVendida;
receitaDeHojeCadaAsset[id] = parseInt(receitaDeHojeCadaAsset[id]) + precoVenda;
vendasDesteMesCadaAsset[id] = parseInt(vendasDesteMesCadaAsset[id]) + quantidadeVendida;
document.getElementById("vendasDesteAssetHoje").innerHTML = vendasDeHojeCadaAsset[assetSelecionadoId];
document.getElementById("vendasDesteAssetMes").innerHTML = vendasDesteMesCadaAsset[assetSelecionadoId];
document.getElementById("receitaDesteAssetHoje").innerHTML = "US$ " + Number(receitaDeHojeCadaAsset[assetSelecionadoId]).toFixed(2);
}
aoTrocarAsset();
</script>
<?php
$conteudoQuadroDeAviso = ('
• Utilize essa tela para informar que uma ou mais cópias de um determinado asset, foram vendidas.
<br>
• Utilize um número negativo para reduzir a quantidade de vendas hoje.
<br>
• Caso já haja uma venda para o determinado asset, na data de hoje, e uma nova venda for informada, a venda será somada com as vendas existentes na data de hoje.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/javascript/validadores-regex.js
/*
* Classe responsável por fornecer métodos para validar strings
*/
function contemNumeros(string) {
var regex = /[0-9]/;
return regex.test(string);
}
function contemLetrasMaiusculas(string) {
var regex = /[A-Z]/;
return regex.test(string);
}
function contemCaracteresEspeciais(string) {
var regex = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
return regex.test(string);
}
function pareceComEmail(string) {
var regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return regex.test(string);
}
function somenteLetrasNumeros(string) {
var regex = /^[0-9a-zA-Z]+$/;
return regex.test(string);
}
function somenteLetras(string) {
var regex = /^[a-zA-Z]+$/;
return regex.test(string);
}
function somenteNumeros(string) {
var regex = /^[0-9]+$/;
return regex.test(string);
}
function contemHtml(string) {
var regex = /<(\"[^\"]*\"|'[^']*'|[^'\">])*>/;
return regex.test(string);
}
function pareceComUrl(string) {
var regex = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/;
return regex.test(string);
}
function pareceComNumeroFloat(string) {
var regex = /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/;
return regex.test(string);
}<file_sep>/browser/includes/cabecalho.inc
<?php
/*
* Essa classe é responsável por fornecer o cabeçalho das páginas. Essa classe fornece um cabeçalho diferente para
* usuários não logados e um cabeçalho diferente para usuários logados.
*
* É possível esconder o cabeçalho setando a variavel "?modoApp" no fim da URL
*/
//A OPÇÃO ABAIXO, DESABILITA TODAS AS MENSAGENS DE ERRO GERADAS PELO PHP. É ÚTIL QUANDO
//UMA PÁGINA ESTÁ PÚBLICA E NÃO É DESEJADO A EXIBIÇÃO DAS MENSAGENS DE DEPURAÇÃO
//QUANDO UMA PÁGINA ESTIVER EM DESENVOLVIMENTO, NÃO É RECOMENDADO A UTILIZAÇÃO DISTO.
if($exibirLogsDeDepuracaoDoPHP == false){
error_reporting(E_ERROR | E_PARSE);
}
include __DIR__ . ("/../../global/sessoes/verificador-de-sessao.inc");
//Método para redirecionar o usuário
function RedirecionarPara($url, $tempoSegundos){
header( "refresh:".$tempoSegundos.";url=".$url);
}
//Verificar se já está logado. Redireciona o usuário para a página inicial, caso possua sessão
function RedirecionarParaHomeCasoEstejaLogado(){
if(VerificarSessao(false, false) == true){
header("Location:"."https://windsoft.xyz");
exit();
}
}
//Verificar se não está logado. Redireciona o usuário para a página de login, caso não possua sessão
function RedirecionarParaLoginCasoNaoEstejaLogado(){
if(VerificarSessao(false, false) == false){
header("Location:"."https://windsoft.xyz/browser/login.php");
exit();
}
}
//Verifica a sessão (A inicializa e obtem os dados)
VerificarSessao(false, false);
//------------- Codigo do menu da direita, quando o usuário não estiver logado
$htmlMenuSemSessao = ('
<a href="https://windsoft.xyz/browser/registrar.php">
<div style="height: 100%; float: left; margin-right: 10px">
<div class="botoesTopbar">
Registrar
</div>
</div>
</a>
<a href="https://windsoft.xyz/browser/login.php">
<div style="height: 100%; float: left;">
<div class="botoesTopbar">
Entrar
</div>
</div>
</a>
');
//------------- Codigo do menu da direita, quando o usuário estiver logado
//Caso a autoridade seja maior que 0, cria o código HTML para a opção de acessar o painel
if($_SESSION["autoridade"] > 0){
$codigoDeAcessoPainel = "<a href=\"https://windsoft.xyz/browser/microsite/painel/client.php\">Admin Painel</a>";
}
$htmlMenuComSessao = ('
<div style="height: 100%; float: left; margin-right: 4px">
<img src="https://windsoft.xyz/global/repositorio/arquivos-de-perfil/icones-de-perfil/icone_'.$_SESSION["idIcone"].'.png" heigth="30px" width="30px" onclick="myFunction()" class="botaoMenuLogado" id="iconeTopbar" />
</div>
<div style="height: 100%; float: left;">
<img src="https://windsoft.xyz/browser/imagens/menu.png" heigth="30px" width="30px" onclick="myFunction()" class="botaoMenuLogado" />
</div>
<div class="menuLogado">
<div id="menuLogadoId" class="menuLogadoConteudo">
<a href="#"><font color="#686868">'. $_SESSION["nick"] .'</font></a>
<a href="https://windsoft.xyz/">Página Inicial</a>
'.$codigoDeAcessoPainel.'
<a href="https://windsoft.xyz/browser/perfil.php">Meu Perfil</a>
<a href="https://windsoft.xyz/browser/preferencias.php">Preferências</a>
<a href="https://windsoft.xyz/browser/logout.php">Desconectar</a>
</div>
</div>
');
//Cria o código para meta tags das redes sociais, caso seja executado a função
if($aplicarHtmlMetaTagsAdicionais == false){
$htmlMetaTagsAdicionais = "";
}
if($aplicarHtmlMetaTagsAdicionais == true){
$htmlMetaTagsAdicionais = '
<meta property="og:title" content="'.$metaTitulo.'" />
<meta property="og:type" content="article" />
<meta property="og:image" content="'.$metaCapaUrl.'" />
<meta property="og:image:width" content="'.$metaCapaWidth.'" />
<meta property="og:image:height" content="'.$metaCapaHeight.'" />
<meta property="og:url" content="'.$metaUrlPagina.'" />
<meta property="og:description" content="'.$metaDescricao.'" />
<meta property="fb:app_id" content="1100512010112474" />
';
}
//------------- Codigo base do cabeçalho
$htmlCabecalho = ('
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>'.$tituloPagina.'</title>
<link rel="icon" href="'. __DIR__ . '/../favicons/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="'. __DIR__ . '/../favicons/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="' . __DIR__ . '/../estilos/estilo-base.css" media="screen and (min-width: 128px)" />
<link rel="stylesheet" href="' . __DIR__ . '/../estilos/estilo-scrollbar.css" media="screen and (min-width: 128px)" />
<link rel="stylesheet" href="' . __DIR__ . '/../estilos/estilo-inputs.css" media="screen and (min-width: 128px)" />
<link rel="stylesheet" href="' . __DIR__ . '/../estilos/estilo-divs.css" media="screen and (min-width: 128px)" />
<link rel="stylesheet" href="' . __DIR__ . '/../estilos/estilo-pag-noticia.css" media="screen and (min-width: 128px)" />
<link rel="stylesheet" href="' . __DIR__ . '/../estilos/estilo-animations.css" media="screen and (min-width: 128px)" />
<meta name="viewport" content="width=device-width" />
<meta name="theme-color" content="#0055A5" />
%METATAGS_ADICIONAIS%
<script src="' . __DIR__ . '/../javascript/funcoes-ajax.js" type="text/javascript"></script>
<script src="' . __DIR__ . '/../javascript/validadores-regex.js" type="text/javascript"></script>
</head>
<body>
<div id="blockPointerEvents"></div>
<div id="loadSpinner" class="loadingSpinner">
<div style="position: absolute; background-color: #F2F2F2; border-radius: 6px; padding: 10px; display: flex; justify-content: center; align-items: center;">
<img src="' . __DIR__ .'/../imagens/spinner.gif" width="40px" height="40px" />
</div>
</div>
<div class="topBar">
<div style="width: 100%; max-width: 640px; margin-left: auto; margin-right: auto; display: block; overflow: visible;">
<a href="https://windsoft.xyz">
<img src="' . __DIR__ . '/../imagens/logotipo.png' . '" title="Logotipo da Windsoft" class="logoImg" height="30px" style="margin-left: 10px; margin-top: 5px; margin-bottom: 5px;" />
</a>
<div style="float: right; display: inline-block; height: 30px; margin-right: 10px; margin-top: 5px; margin-bottom: 5px;">
%MENU%
</div>
</div>
</div>
<div class="notificacao" id="notificacao"></div>
<div id="contadorDeCaracteres" class="contadorDeCaracteres">
<div class="contadorDeCaracteresConteudo">
<small>
Chars
</small>
<div id="contadorDeCaracteresTexto">
0/0
</div>
</div>
</div>
<div id="gavetaDeEmotesRaiz" class="gavetaDeEmotesRaiz" style="bottom: -100px; opacity: 0; pointer-events: none;">
<div class="botaoDaGavetaDeEmotes" onclick="abrirFecharGavetaDeEmotes();">
<center>
<img src="' . __DIR__ . '/../imagens/emote.png" width="20px" height="20px"/>
</center>
</div>
<div class="gavetaDeEmotes">
<div style="padding: 10px; display: grid; grid-template-columns: 20% 20% 20% 20% 20%;">
<div class="emoteDaGaveta" onclick="adicionarEmote(\'☺\');">☺</div>
<div class="emoteDaGaveta" onclick="adicionarEmote(\'☹\');">☹</div>
<div class="emoteDaGaveta" onclick="adicionarEmote(\'✌\');">✌</div>
<div class="emoteDaGaveta" onclick="adicionarEmote(\'★\');">★</div>
<div class="emoteDaGaveta" onclick="adicionarEmote(\'♫\');">♫</div>
<div class="emoteDaGaveta" onclick="adicionarEmote(\'♥\');">♥</div>
</div>
</div>
</div>
<div class="content">
<div style="height: 50px;"></div>
');
//Imprime o código de cabeçalho com o código de MENU se o usuário estiver logado, ou não
if(VerificarSessao(false, false) == false){
echo(str_replace(array("%MENU%", "%METATAGS_ADICIONAIS%"), array($htmlMenuSemSessao, $htmlMetaTagsAdicionais), $htmlCabecalho));
}
if(VerificarSessao(false, false) == true){
echo(str_replace(array("%MENU%", "%METATAGS_ADICIONAIS%"), array($htmlMenuComSessao, $htmlMetaTagsAdicionais), $htmlCabecalho));
}
?><file_sep>/browser/termos-de-uso.php
<?php
/*
* Essa página HTML contém as informações de Termos de Uso da Windsoft Games. Sempre que ela for atualizada, deve-ser
* atualizada a data de atualização.
*/
$tituloPagina = "Termos de Uso - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("includes/cabecalho.inc");
?>
<br/>
<center><b>Termos de uso da Windsoft Games</b>
<br/>
<br/>
<font color="#545454"><i>Este termo de uso está em vigor desde 22 de maio de 2018 e foi modificado pela última vez em 14 de dezembro de 2018.</i></font></center>
<br/>
<br/>
<b>1. </b>Se você quiser remover todos os seus dados que a Windsoft Games acessa atráves da sua conta Windsoft ID, de acordo com seu concentimento,
entre em contato em nosso e-mail (<EMAIL>) para fazer isso. Para obter ajuda, utilize tambem o suporta da Windsoft ou entre em contato atráves
do e-mail <EMAIL>.
<br/>
<br/>
Windsoft Games ("nós" ou "nosso(s)"), oferece aplicativos, jogos ("os apps") ou conteúdos adicionais que adiante serão referidos como "Serviços".
<br/>
Estes termos de uso ("Acordo") incluem noss política de uso dos nossos serviços, obrigações e restrições em relação ao uso dos mesmos. Você
só pode usar este serviços se concordar com estes termos. Ao usar os nossos serviços você concorda em estar vinculado a estes termos.
<br/>
<br/>
Sua privacidade é importante para nós. Este acordo inclui também nossa política de privacidade (https://windsoft.xyz/privacy), que explica
como coletamos seus dados sob seu concentimento e como o processamos. Por favor, leia nossa política de privacidade.
<br/>
<br/>
Podemos modificar estes termos de tempos em tempos. Você irá concordar com qualquer modificação ao continuar utilizando nossos serviços. Por isso é
importante que você revise este acordo sempre que possível. Caso não concorde com algum termo ou modificação, interrompa o uso dos nossos serviços.
<br/>
<br/>
<b>I. Nosso centro dos serviços o "Windsoft ID" / Sua conta / Suspensão e Banimento</b>
<br/>
<br/>
A Windsoft Games possui uma central, o Windsoft ID, onde todos os nossos clientes podem pedir ajuda, ter notícias e notificações sobre nós,
criarem perfis e obter recursos exclusivos como suporte rápido, recebimento gratuito de itens virtuais (será explicado mais adiante) e etc.
Essa central pode ser acessada atráves do nosso site (windsoft.xyz) ou atráves dos nossos jogos (que por sua vez, podem ser baixados em mercados como o Google Play).
Alguns de nossos serviços possuem conexão com o Windsoft ID permitindo que nossos clientes possam fazer uso destes recursos atráves de nossos serviços.
Para utilizar um ID você precisa registrar uma conta "uma conta, ou Windsoft ID". Ao criar ou utilizar uma conta você concorda que:
<br/>
<b>1. </b>Tem 13 (treze) anos ou mais;
<br/>
<b>2. </b>Você possui permissão de um dos seus pais ou de um guardião legal para utiliza-lo caso tenha entre 13 e 18 anos;
<br/>
<b>3. </b>Podemos recolher algumas informações pessoais superficiais para o registro (como nome, idade, gênero e endereço de e-mail) como definido
em nossa política de privacidade (https://windsoft.xyz/privacy);
<br/>
<b>4. </b>Assume total responsabilidade pelo uso indevido de sua conta, feita por outras pessoas com ou sem sua autorização;
<br/>
<b>5. </b>Assume responsabilidade por manter confidencial suas credencias de acesso (login, senha e etc).
<br/>
Sem limitar qualquer coisa neste acordo, nos reservamos o direito de excluir, suspender, ou encerrar o acesso total a sua conta caso constatemos a nosso
exclusivo critério que você descumpriu qualquer um dos termos presentes neste acordo, tambem podemos fazer isso por qualquer motivo, a qualquer
momento ou sem motivo, com ou sem aviso prévio e sem responsabilidade, inclusive no momento que determinarmos que não iremos mais oferecer este serviço.
O Windsoft ID tambem é considerado um de nossos serviços.
<br/>
<br/>
<b>II. Compras / Pagamentos / Reembolsos</b>
<br/>
<br/>
Podemos vender itens virtuais, ou desbloqueio de conteúdos adicionais em nossos serviços (vamos referir a esses itens e conteúdos como "produtos")
como determinado abaixo neste termo. Essas vendas ocorrem dentro dos nossos serviços. O preço de qualquer um desses produtos é especificado no momento
da compra. Nós vendemos estes produros atráves de terceiros (como o Google Play), e estes processam seus dados (como numero de cartão de crédito)
e permitem a compra via cartão de crédito ou outros meios.
Você concorda que não somos responsáveis por qualquer erro na compra ou no débito causadas por terceiros. Estes terceiros tem seus próprios termos
e política de privacidade, ao utilizar um deles para fazer a compra de nossos produtos, leia seus termos e política de privacidade.
Nossos produtos podem estar disponíveis a venda dentro dos nossos aplicativos ou jogos, gratuitos para download ou não. Alguns de nossos serviços
gratuitos ou não, podem conter anúncios de terceiros que podem te redirecionar para o site dos mesmos. Nenhum reembolso é concedido na compra de
itens virtuais, mas um reembolso pode ou não ser concedido na compra de um serviço pago para download em um mercado de terceiros (como o Gooogle Play).
Lembre-se de ler as políticas e termos destes para saber quais são suas políticas de reembolso e compra.
<br/>
<br/>
<b>III. Itens virtuais</b>
<br/>
<br/>
Alguns de nossos serviços podem permitir que você "ganhe" ou "compre":
<br/>
<b>1. </b>a moeda virtual, incluindo, mas não limitando, a moedas, cédulas, fichas, diamantes ou pontos, todos para uso de nossos serviços;
<br/>
<b>2. </b>itens virtuais no jogo(justamente com moeda virtual ou dinheiro real);
<br/>
<b>3. </b>determinados beneficios em nossos serviços ("itens virtuais").
<br/>
Itens virtuais não tem valor no mundo real e não podem ser trocados por moeda real, bens ou outros itens de valor monetário. Mesmo no caso de você ter
itens virtuais não utilizados em sua conta no momento do banimento, encerramento ou fechamento da mesma, quer tenha acontecido voluntáriamente ou
não, todas as vendas são finais, nenhum reembolso será concedido a não ser em nosso exclusivo e absoluto critério. A compra de qualquer item virtual
é apenas a aquisição de uma licensa para usar o item virtual nos serviços aplicáveis e não transfere a propríedade do item virtual a você. Esta licensa
é pessoal e não pode ser comercializada ou transferida, cedida, dada ou sublicenciada. Dessa forma, não reconhecemos qualquer venda, transferência,
atribuição, presente comercialização ou subliciamento destes itens virtuais, seja por "dinheiro real", bens ou por troca de serviços ou favores.
Qualquer transferência pode estar sujeita a encerramento de sua conta nos nossos serviços.
<br/>
<br/>
<b>IV. Conduta online</b>
<br/>
<br/>
Como usuário de qualquer um dos nossos serviços, você concorda em usa-los somente para fins legais. Atividades proibidas específicas incluem, mas não se
limitam a:
<br/>
<b>1. </b>tentativa de burlar, desativar ou de qualquer forma interferir com as características relacionadas à segurança dos nossos serviços ou caracterísitcas
que previnam ou restrinjam o uso ou cópia de qualquer conteúdo ou imponham limitação sobre o uso dos serviços ou conteúdo nele;
<br/>
<b>2. </b>uso de trapaças, tirar proveito de vulnerabilidades, softwares de automação, bots, hacks ou qualquer outro software não autorizado projetado
para interferir ou modificar com os serviços e se aproveitar dessas trapaças ou vunerabilidades;
<br/>
<b>3. </b>uso de qualquer software que intercepte, processe ou de alguma forma colete informações sobre outros usuários ou cópias;
<br/>
<b>4. </b>interferir, interromper ou criar uma sobrecarga em nossos serviços, servidores ou rede de dos serviços conectados;
<br/>
<b>5. </b>tentar se passar por outro usuário ou pessoa;
<br/>
<b>6. </b>coletar, solicitar ou postar senhas ou informações de identificação de pessoas;
<br/>
<b>7. </b>usar o nome de usuário e senha de outro titular da conta em qualquer momento ou divulgar estas credencias a terceiros;
<br/>
<b>8. </b>sublicenciar, vender, trocar, alugar, arrendar, presentear, transmitir ou transferir itens virtuais na sua conta ou sua própria conta a terceiros;
<br/>
<b>9. </b>usar várias contas, procedimentos manuais, bots, scripts ou outros processos a fim de acumular itens virtuais;
<br/>
<b>10. </b>usar os serviços de forma comercial, incluindo transferência de itens virtuais em troca de dinheiro real.
<br/>
Você terá qualquer conta de nossos serviços encerrada caso participe de alguma dessas atividades.
<br/>
<br/>
<b>V. Conteúdo</b>
<br/>
<br/>
<b>1. Direitos de propriedade</b>
<br/>
Com exceção de conteúdos postados por usuários em nossos serviços ("conteúdo de usuário"), todos os materiais contidos nos serviços, itens virtuais,
e o software, gráficos e todas as marcas (incluido Windsoft Games, Windsoft ID e o titúlo dos nossos serviços) são de propríedade ou controladas pela
Windsoft Games. Você não pode remover, apagar, publicar, transmitir, participar na transferência ou venda de, ou de qualquer forma explorar quaisquer
materiais de propriedade total ou em parte. Sujeito à sua conformidade com este acordo e quaisquer outras políticas pertinentes relacionadas a nossos
serviços, nós lhe concedemos uma licensa limitada não-exclusiva, intransferível e revogável sujeita às limitações aqui para acessar e usar os serviços
e materiais de propriedade para os próprios fins de entretenimento não comerciais compativéis e com finalidade dos serviços. Você concorda
em não utilizar os serviços para qualquer outra finalidade.
<b>2. Distribuição/Envio de conteúdo</b>
<br/>
Ao nos enviar conteúdo ou materiais ("seu conteúdo") por meio dos serviços, incluindo, sem limitação, o upload de quaisquer materiais, você nos concede
automaticamente, ou garante que o propietário de tal conteúdo expressamente nos concedeu direito livre e licença de royalties irrevogável, sublicenciavel,
transferível e não-exclusivo para utilizar, reproduzir, publicar, traduzir, preparar trabalhos derivados, copiar, executar, e distribuir o seu conteúdo,
incluindo todas as patentes, marcas, segredo comercial, direitos autorais ou outros direitos de propriedade, bem como conteúdo e seu nome de usuário,
nome real e semelhança (se submetido), no todo ou em parte, em todo o mundo. Você também concede a cada usuário dos serviços uma licensa não-exclusiva
para acessar o seu conteúdo, por meio dos serviços e usar, reproduzir, distribuir, exibir e executar seu conteúdo conforme permitido pela funcionalidade
dos serviços e nos termos deste contrato. As licensas concedidas acima em seu conteúdo são perpétuas e só terminarão se você remover ou solicitar a remoção
do conteúdo dos serviços (tal licença terminará dentro de um tempo rasoável após o seu pedido para remover, ou remoção do conteúdo).
Você entende e concorda, porém, que podemos reter, mas não exibir, distribuir ou executar as cópias do servidor, de seu conteúdo que foram removidas
ou apagadas. Sujeito a estas concessões, você retém todos e qualquer direitos que possam existir em seu conteúdo. Podemos divulgar qualquer
um dos seus conteúdos ou comunicação eletrônica de qualquer tipo (I) para satisfazer qualquer lei, regulamento ou solicitação governamenta,
(II) se tal revelação for necessária ou apropriada para operar os nossos serviços, (III) para proteger os direitos de propriedade da Windsoft Games
e nossos integrantes ou (IV) para proteger qualquer usuário.
<br/>
<b>3. Publicidade</b>
<br/>
Ao usar nossos serviços, você poderá encontrar publicidade. Assim, você concorda com nossa Política de Privacidade em relação a publicidade. Para
mais informações leia nossa política de privacidade, disponível em https://windsoft.xyz/privacy. A Windsoft Games não é responsável pelos produtos
e serviços mostrados por terceiros.
<br/>
<b>4. Envios não solicitados</b>
<br/>
Nós gostamos de ouvir nossos usuários e receber comentários sobre nossos serviços. Infelizmente porém, não podemos simplesmente aceitar ideias criativas,
sugestões ou algo parecido que não foram solicitadas. Esperamos que você entenda que a intenção desta política é evitar mal-entendidos futuros quando
projetos desenvolvidos por nós sejam semelhantes a outros trabalhos criativos. Portanto, devemos, infelizmente, pedir que você não nos envie quaisquer
materiais criativo originais, tais como ideias de jogo ou arte original. Valorizamos seus comentários sobre nossos serviços e produtos. Se apesar
de nossa solicitação que você não envie quaisquer outros materiais criativos, você nos enviar sugestões, ideias, notas, desenhos, conceitos ou outras
informações (coletivamente, os "envios não solicitados"), os envios não-solicitados serão considerados, devendo permanecer de propriedade da Windsoft Games.
Nenhum dos envios não-solicitados ficará sujeito a qualquer obrigação de confiança por parte de nós, e não seremos responsáveis por qualquer uso ou
divulgação de quaisquer envios não solicitados. Sem limitação do acima exposto, seremos proprietários exclusivos de todos os direitos existentes
atualmente conhecidos ou futuros para os envios não-solicitados de qualquer tipo de natureza. Você renuncia a todos e quaisquer direitos morais
em tais envios não-solicitados, bem como qualquer reinvidicação de direito de crédito ou de aprovação. O anterior é igualmente aplicável a todos
os envios criativos que você fizer a nosso pedido específico, salvo acordo em contrário por escrito.
<br/>
<br/>
<b>VI. Aviso de infração</b>
<br/>
<br/>
Sem limitar precedente, se você acredita que qualquer conteúdo, incluindo o conteúdo do usuário ou outros materiais publicados nos nossos serviços constitui,
uma violação dos seus direitos autorais ou marcas registradas, vamos responder protamente a qualquer notificação devidamente apresentada contendo as informações
detalhadas abaixo. Por favor, envie todos os avisos para o seguinte endereço de e-mail <EMAIL>.
<br/>
<b>1. </b>Uma assinatura física ou eletrônica da pessoa autorizada a agir em nome do proprietário de um direito exclusivo que supostamente foi violado.
<br/>
<b>2. </b>Identificação da obra cujos direitos se alega terem sido violados.
<br/>
<b>3. </b>Identificação do material tido como violado ou como objeto de atividade ilícita que deve ser removido ou cujo acesso deve ser desativado, alem de informações
suficientes para que possamos localizar o material.
<br/>
<b>4. </b>Informações razoavelmente suficientes para nos permitir entrar em contato com o reclamante, tais como e-mail ou rede social.
<br/>
<b>5. </b>Uma declaração de que a parte reclamante acredita de boa fé de que o uso do material da forma reclamada não está autorizado pelo proprietário dos
direitos autorais, seu agente ou pela lei;
<br/>
<b>6. </b>Uma declaração de que as informações contidas na notificação são precisas e, sob pena de perjúrio, que a parte reclamante está autorizada a
agir em nome do proprietário de um direito exclusivo que supostamente está sendo infringido.
<br/>
<br/>
<b>VII. Comunicações eletrônicas</b>
<br/>
<br/>
Quando você usa os serviços ou envia e-mails para nós, você esta se comunicando eletrônicamente conosoco. Você concorda em receber nossas comunicações
eletrônicamente. Nós iremos nos comunicar com você por e-mail ou postando notícias no aplicativo Windsoft. Você concorda que todos os acordos,
notificações, divulgações e outras comunicações que fornecemos eletronicamente satisfazem quaisquer requisitos legais tanto quanto comunicações que sejam
feitas por escrito.
<br/>
<br/>
<b>VIII. Links</b>
<br/>
<br/>
Os serviços podem conter links para sites operados por terceiros, inclusive por meio de anúncios dentro dos serviços. Nós não monitoramos ou controlamos
os sites linkados e não responsabilizamos pela exatidão, integridade, pontualidade, confiabilidade ou disponibilidade de qualquer parte do conteúdo carregado,
exibido, ou distribuído, ou dos produtos ou serviços disponíveis nestes locais. Se você optar por acessar qualquer site de terceiros, você o faz por sua
conta e risco. A presença de um link para um site de terceiro não constitui ou implica a nossa aprovação, patrocínio ou recomendação do terceiro ou do
conteúdo, dos produtos ou dos serviços contidos ou disponíveis no site de terceiros. Reservamo-nos o direito de desabilitar links de ou para site de
terceiros.
<br/>
<br/>
<b>IX. Isenções e limitações de responsabilidades</b>
<br/>
<br/>
Os serviços são prestados por nós e baseado em nossa hospedagem "como está" e "como disponível". Até ao limite máximo permitido pela lei aplicável, isentamos
todas as garantias implícitas, incluindo, mas não limitados a garantias de comercialização e adequado a um determinado fim. Sem limitar o precedente, nós
não fazemos qualquer representação ou garantia de qualquer tipo, expressa ou implícita: (I) Quanto ao funcionamento dos serviços ou a informação, conteúdo,
materiais ou produtos incluídos nela; (II) Que o uso dos serviços será 100% seguro, initerrupto ou livre de erros; (III) Quanto à precisão, confiabilidade,
ou atualidade de qualquer informação, conteúdo ou serviço providos; ou (IV) que os servidores ou e-mails enviados a partir ou em nome da Windsoft Games
estão livres de vírus ou outros componentes nocivos.
Sob nenhuma circustância nós nos responsabilizamos por quaisquer danos que resultem do uso ou da incapacidade de utilizar os serviços, incluindo, mas
não limitando a confiança de um usuário em qualquer informação obtida a partir dos serviços ou que resultem de erros, omissões, interrupções, exclusão
de arquivos ou e-mail, defeitos, vírus, atrasos na operação ou transmissão ou qualquer falha de desempenho, resultantes ou não de forma maior, falha
de comunicação, roubo, destruição ou acesso não autorizado aos registros, programas ou serviços da Windsoft Games. Você reconhece que este parágrafo
assim como todo este termo é aplicável a todos os conteúdos, produtos e serviços disponíveis por meio de serviços.
Nós não seremos responsáveis por quaisquer danos indiretos, incidentais, especiais ou consequentes decorrentes da utilização dos serviços ou a
compra de qualquer produto, real ou virtual, ainda que nós tenhamos sido avisados da possibilidade de tais danos.
<br/>
<br/>
<b>X. Legalidade</b>
<br/>
<br/>
Você está sujeito a todas as leis do(s) estado(s) e país(es) em que você reside a partir do qual você acessa os serviços e é o único resposável por obedecer
essas leis. Você concorda que não podemos ser responsabilizados se as leis aplicáveis a você restringem ou proíbem a sua participação. Nós não fazemos
representações ou garantias, implícitas ou explícitas, a partir de seu direito legal de participar de quaisquer aplicativos e passatempos oferecidos por
meio dos serviços nem qualquer pessoa afiliada ou aleganddo afiliação com os serviços têm autoridade para fazer tais representações ou garantias.
<br/>
<br/>
<b>XI. Leis aplicáveis / Jurisdição</b>
<br/>
<br/>
Os serviços são criados e controlados por nós no seu país de residência. Como tal, as leis do seu páis de residência irão reger estes termos de uso sem dar
efeito a quaisquer disposições de lei que direciona a escolha das leis de outro Estado.
Você de forma irrevogável e incondicional, concorda em submeter à exclusiva jurisdição dos tribunais do seu país de residência para qualquer litígio emergente
ou relacionado ao uso ou compra feita por meio dos serviços (e concorda em não iniciar qualquer litígio que lhe diz respeito, exceto em tais tribunais).
Você concorda em indenizar e insentar a Windsoft Games, e/ou nossos respectivos integrantes, funcionários, agentes, parceiros e funcionários, de qualquer
perda, responsabilidade, reclamação, ou demanda, incluindo honorários advocáticos razoáveis, feitos por qualquer terceiro devido a ou resultantes da sua
utilização dos serviços em violação do presente acordo e/ou decorrente de uma violação do presente acordo e/ou qualquer violação de seus representações
e garantias estabelecidas acima e/ou se o seu conteúdo nos atribui a responsabilidade de terceiros.
<br/>
<br/>
<b>XII. Separação</b>
<br/>
<br/>
As disposições do presente acordo destinam-se a ser divisíveis. Se por algum motivo qualquer disposição do presente acordo for considerada inválida ou
inexequível, no todo ou em parte, em qualquer jurisdição, tal disposição, como tal jursidição, ser ineficaz na medida de tal invalidade ou inéficacia de
qualquer forma, isso não afeta a válidade ou mesmo aplicabilidade em qualquer outra jurisdição ou as demais disposições deste acordo em qualquer jurisdição.
<br/>
<br/>
<b>XIII. Suporte</b>
<br/>
<br/>
Sem prejuízo das demais disposições do presente acordo, nós tentaremos lhe ajuda-lo da maneira que pudermos e como nós é possivel, em qualquer dúvidas ou
problemas que você pode ter com os serviços ou qualquer uma de suas compras por meio dos serviços. Para nos contatar, envie um e-mail para <EMAIL>.
Ele vai acelerar seu pedido de assistência, proporcionando a nós todas informações necessárias para resolver seu problema o mais rápido possível.
<br/>
<br/>
<b>XIV. Outro</b>
<br/>
<br/>
Este acordo é considerado aceito no momento em que qualquer um dos nossos serviços for utilizado. Este acordo constitui a totalidade do acordo entre você
e nós em relação ao uso dos serviços. Nossa incapacidade de exercer ou executar qualquer direito ou disposição do presente acordo não deverá funcionar
como renúncia de tal direito ou disposição. Os títulos das seções deste acordo são apenas para conveniência e não tem efeito legal ou contratual.
<br/>
<br/>
<b>XV. Mercados de terceiros</b>
<br/>
<br/>
Estes termos de uso são entre você e Windsoft Games apenas, não com a Apple, Google, Facebook ou qualquer outro terceiro por meio do qual você pode ter
comprado qualquer um dos aplicativos ("mercados"). Os mercados não são responsáveis pelo aplicativo que você comprou ou pelos nossos serviços. Os mercados
não têm obrigação de fornecer qualquer serviço de manutenção ou suporte com relação aos aplicativos. Até o limite máximo aplicável pela lei, os mercados
não têm outra obrigação ou garantia em relação aos aplicativos.
<br/>
<br/>
<b>XVI. Modificação</b>
<br/>
<br/>
Reservamo-nos o direito de fazer alterações nos serviços, políticas e nos termos de uso a qualquer momento sem aviso prévio. A continuação da utilização
dos serviços representará a sua aceitação de tais alterações. Entre em contato com <EMAIL> se tiver qualquer dúvida sobre nossas relações
com os consumidores e sobre qualquer problema na atividade de nossos serviços.
<br/>
<br/>
<?php
include("includes/rodape.inc");
?><file_sep>/browser/microsite/painel/paginas/listar-arquivos-noticia.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<center>
<h3>Listar Arquivos de Notícia</h3>
</center>
<center>
<form autocomplete="off" style="margin-bottom: 0px;">
<input type="text" id="data" placeholder="Data dos Arquivos DD/MM/YYYY" onkeypress="formatarComoData(this);" />
</form>
<div style="display: grid; grid-template-columns: 50% 50%; width: 80%; max-width: 300px;">
<input type="button" value="Data de Hoje" style="width: calc(100% - 8px); margin: 8px 8px 8px 0px;" onclick="definirDataDeHoje();" />
<input type="button" value="Pesquisar" style="width: calc(100% - 8px); margin: 8px 0px 8px 8px;" onclick="buscarArquivos();" />
</div>
</center>
<style>
.arquivo{
display: grid;
grid-template-columns: 10% 70% 10% 10%;
background-color: #D6D6D6;
transition: all 200ms;
border-radius: 4px;
padding: 10px;
margin-bottom: 4px;
}
.arquivo:hover{
background-color: #BCBCBC;
}
.iconeArquivo{
display: flex;
align-items: center;
}
</style>
<div id="resultado" style="display: none; background-color: #F2F2F2; border-radius: 4px; margin-top: 10px; margin-bottom: 10px; padding: 10px;">
</div>
<input type="text" style="display: none;" id="campoDeTexto" />
<!-- código javascript desta página -->
<script type="text/javascript">
//Função que insere a data de hoje
function definirDataDeHoje(){
var data = new Date();
var dia = data.getDate();
var mes = data.getMonth();
var ano = data.getFullYear();
if(dia < 10){
dia = "0" + dia;
}
mes += 1;
if(mes < 10){
mes = "0" + mes;
}
document.getElementById("data").value = dia + "/" + mes + "/" + ano;
}
//Função que estabelece conexão para pesquisar os arquivos
function buscarArquivos(){
if(document.getElementById("data").value == ""){
parent.mostrarNotificacao("Por favor, insira uma data.", "#750000", 3500);
return;
}
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/buscar-arquivos-noticia.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
document.getElementById("resultado").style.display = "block";
document.getElementById("resultado").innerHTML = parent.textoDaConexao(conexao);
parent.redimensionarIframe();
});
};
parent.iniciarConexaoPost(conexao, "data=" + document.getElementById("data").value);
}
//Função que copia o link
function copiarUrl(url){
var tempInput = document.createElement("input");
tempInput.style = "position: absolute; left: -1000px; top: -1000px";
tempInput.value = url;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand("copy");
document.body.removeChild(tempInput);
parent.mostrarNotificacao("URL copiado para a área de trasferência!", "#467200", 2500);
}
//Função que abre o arquivo numa nova aba
function abrirEmNovaAba(url){
window.open(url, '_blank');
}
//Função que transforma o conteúdo digitado para formato de data
function formatarComoData(val) {
var pass = val.value;
var expr = /[0123456789]/;
for (i = 0; i < pass.length; i++) {
var lchar = val.value.charAt(i);
var nchar = val.value.charAt(i + 1);
if (i == 0) {
if ((lchar.search(expr) != 0) || (lchar > 3)) {
val.value = "";
}
}
else if (i == 1) {
if (lchar.search(expr) != 0) {
var tst1 = val.value.substring(0, (i));
val.value = tst1;
continue;
}
if ((nchar != '/') && (nchar != '')) {
var tst1 = val.value.substring(0, (i) + 1);
if (nchar.search(expr) != 0){
var tst2 = val.value.substring(i + 2, pass.length);
}
else{
var tst2 = val.value.substring(i + 1, pass.length);
}
val.value = tst1 + '/' + tst2;
}
}
else if (i == 4) {
if (lchar.search(expr) != 0) {
var tst1 = val.value.substring(0, (i));
val.value = tst1;
continue;
}
if ((nchar != '/') && (nchar != '')) {
var tst1 = val.value.substring(0, (i) + 1);
if (nchar.search(expr) != 0){
var tst2 = val.value.substring(i + 2, pass.length);
}
else{
var tst2 = val.value.substring(i + 1, pass.length);
}
val.value = tst1 + '/' + tst2;
}
}
if (i >= 6) {
if (lchar.search(expr) != 0) {
var tst1 = val.value.substring(0, (i));
val.value = tst1;
}
}
}
if (pass.length > 10){
val.value = val.value.substring(0, 10);
}
return true;
}
</script>
<?php
$conteudoQuadroDeAviso = ('
• Digite a data ao qual você deseja obter os arquivos ligados a ela e clique em pesquisar.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/global/mysql/registros.inc
<?php
/*
* Essa classe é responsável por fazer a conexão ao banco de dados "registros"
*/
//Este script deve ser incluído no topo dos scripts.
//Abre a conexão para o banco de dados "Registros"
$DB_Registros = mysqli_connect("registros.mysql.uhserver.com", "account", "<KEY>", "registros");
mysqli_query($DB_Registros, "SET NAMES 'utf8'");
mysqli_query($DB_Registros, 'SET character_set_connection=utf8');
mysqli_query($DB_Registros, 'SET character_set_client=utf8');
mysqli_query($DB_Registros, 'SET character_set_results=utf8');
?><file_sep>/browser/microsite/painel/ajax-query/remover-membro-da-staff.php
<?php
/*
* script que remove o usuario da staff
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
include("../../../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$nick = mysqli_real_escape_string($DB_Registros, $_POST["nick"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Caso não tenha permissão total, cancela o script
if($_SESSION["autoridade"] < 4){
echo("".
'parent.mostrarNotificacao("Você não tem permissão para fazer isso.", "#7F0000", 3000);'
."");
exit();
}
//Verifica se o usuário já está cadastrado como staff
$consultaUsuario = mysqli_query($DB_Metadados, "SELECT Cargo, Autoridade FROM Staff WHERE Nick='$nick'");
//Caso esteja cadastrado
if(mysqli_num_rows($consultaUsuario) == 1){
$consultaRemocao = mysqli_query($DB_Metadados, "DELETE FROM Staff WHERE Nick='$nick'");
}
echo("".
'parent.mostrarNotificacao("O usuário foi removido da Staff, com êxito!", "#1E7200", 3000);'
."staff = false;"
."cargo = '';"
."autoridade = 0;"
."exibirPainelDeEdicao();"
."");
}
?><file_sep>/browser/microsite/painel/ajax-query/editar-versao-jogo.php
<?php
/*
* script que atualiza a versão do jogo, no banco de dados
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$id = mysqli_real_escape_string($DB_Metadados, $_POST["id"]);
$ultimaVersao = mysqli_real_escape_string($DB_Metadados, $_POST["ultimaVersao"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Atualiza a versão do jogo no banco de dados
$consulta = mysqli_query($DB_Metadados, "UPDATE JogosDaWindsoft SET UltimaVersao='$ultimaVersao' WHERE JogoID=$id");
echo("".
'parent.mostrarNotificacao("A versão do jogo foi atualizada com sucesso!", "#117700", 5000);'
."");
}
?><file_sep>/browser/ajax-query/alterar-senha.php
<?php
/*
* script que faz consulta de alteração da senha
*/
include("../../global/sessoes/verificador-de-sessao.inc");
include("../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Obtem as variaveis
$senha = md5($_POST["senha"]);
$senhaNova = md5($_POST["senhaNova"]);
//obtem o id do usuário
$id = $_SESSION["id"];
//Verifica se a senha informada bate com a senha da conta
$verificaSenha = mysqli_query($DB_Registros, "SELECT Senha FROM Acesso WHERE ID=$id");
$dadosSenha = mysqli_fetch_array($verificaSenha);
//Caso a senha não bata
if($senha != $dadosSenha[0]){
echo("exibirSenhaErrada();");
exit();
}
//Realiza a alteração do email
$consultaTroca = mysqli_query($DB_Registros, "UPDATE Acesso SET Senha='$senhaNova' WHERE ID=$id");
echo("".
"mostrarNotificacao(\"Sua senha foi alterada com sucesso!\", \"#117700\", 5000);".
"limparCamposDeSenha();".
"");
?><file_sep>/browser/microsite/painel/ajax-query/buscar-arquivos-noticia.php
<?php
/*
* script que recebe o conteúdo da edição e o salva em arquivos temporários,
* para persistir a edição
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$dataParaPesquisar = $_POST["data"];
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Divide a string de data
$data = explode("/", $dataParaPesquisar);
//Verifica se o formato de data está correto
if(strlen($dataParaPesquisar) != 10 || strpos($dataParaPesquisar, "/") == false){
echo("<br/><center>A data \"".$dataParaPesquisar."\" digitada está no formato incorreto. O formato da data precisa ser númerico, no seguinte formato DD/MM/YYYY.</center><br/>");
return;
}
//Obtem o diretório alvo com base na data digitada pelo usuario
$diretorioAlvoString = ("../../../noticias/por-data/".$data[2]."/".$data[1]."/".$data[0]);
//Verifica se o diretório existe ou não
if(is_dir($diretorioAlvoString) == false){
echo("<br/><center>Nenhum arquivo encontrado para a data de ".$dataParaPesquisar.".</center><br/>");
}
if(is_dir($diretorioAlvoString) == true){
//Escaneia o diretório alvo
$listaDeArquivos = scandir($diretorioAlvoString);
//Conta a quantidade de arquivos no diretorio
if(count($listaDeArquivos) <= 2){
echo("<br/><center>A pasta referente a data de ".$dataParaPesquisar.", está vazia.</center><br/>");
}
if(count($listaDeArquivos) > 2){
echo("<center>Listando arquivos referentes a data de ".$dataParaPesquisar.".</center><br/>");
//Rastreia os arquivos do diretório
foreach($listaDeArquivos as $arquivo){
//Verifica se o arquivo é apenas um ponto, ou dois pontos
if($arquivo != "." && $arquivo != ".."){
//Obtem a extensão do arquivo
$extensao = pathinfo($diretorioAlvoString . "/" . $arquivo, PATHINFO_EXTENSION);
//Gera o código do ícone
if($extensao == "php"){
$codigoIcone = '<img src="../imagens/documento.png" width="16px" />';
}
if($extensao == "jpg" || $extensao == "jpeg"){
$codigoIcone = '<img src="../imagens/imagem.png" width="16px" />';
}
//Gera a URL do arquivo
$url = "https://windsoft.xyz/browser/noticias/por-data/" . $data[2] . "/" . $data[1] . "/" . $data[0] . "/" . $arquivo;
//Imprime o código HTML para representar este arquivo
echo('<div class="arquivo">
<div class="iconeArquivo" style="justify-content: flex-start;">
'.$codigoIcone.'
</div>
<div>'.$arquivo.'</div>
<div class="iconeArquivo" style="justify-content: flex-end; cursor: pointer;">
<img src="../imagens/copiar.png" width="16px" title="Copiar URL" onclick="copiarUrl(\''.$url.'\');" />
</div>
<div class="iconeArquivo" style="justify-content: flex-end; cursor: pointer;">
<img src="../imagens/visualizar.png" width="16px" title="Visualizar Arquivo" onclick="abrirEmNovaAba(\''.$url.'\');" />
</div>
</div>');
}
}
}
}
}
?><file_sep>/browser/gerador-de-senha.php
<?php
/*
* Essa página é responsável por gerar uma nova senha ao usuário, com base no seu token de
* recuperação e ID
*/
$tituloPagina = "Gerador de Senha - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("includes/cabecalho.inc");
?>
<?php
include("../global/mysql/registros.inc");
function RetornarCaractereAleatorio(){
$arrayDeCaracteres = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
$numeroAleatorio = rand(0, count($arrayDeCaracteres));
return $arrayDeCaracteres[$numeroAleatorio];
}
$codigoErro = '
<br>
<br>
<div style="width: 60%; margin-left: auto; margin-right: auto; display: table;">
<img src="imagens/erro.png" width="30px" style="float: left; margin-right: 10px; display: table-cell; vertical-align: middle;" />
<div style="display: table-cell; vertical-align: middle;">
Este link de recuperação de senha está expirado, é inválido ou já foi usado.
</div>
</div>
';
//Variaveis do script
$id = mysqli_real_escape_string($DB_Registros, $_GET["id"]);
$tokenRecuperacao = mysqli_real_escape_string($DB_Registros, $_GET["tokenRecuperacao"]);
//Verifica se as variaveis estão definidas
if($id != "" && $tokenRecuperacao != ""){
//Consulta o token pertencente a este ID
$consultaToken = mysqli_query($DB_Registros, "SELECT Nick, TokenRecuperacao FROM Acesso WHERE ID = $id");
//Verifica se encontrou resultados para este ID
if(mysqli_num_rows($consultaToken) == 1){
//Obtem os dados
$consultaTokenResultado = mysqli_fetch_array($consultaToken);
//Analisa se o token do banco de dados é igual o informado
if($consultaTokenResultado[1] == $tokenRecuperacao && $consultaTokenResultado[1] != ""){
//Cria uma senha aleatória de 6 dígitos
$senhaCriada = "";
for($i = 0; $i < 6; ++$i){
$senhaCriada .= RetornarCaractereAleatorio();
}
$senhaCriadaMd5 = md5($senhaCriada);
//Limpa o token do servidor e altera a senha do usuário para a senha criada
$consultaAlteracaoSenha = mysqli_query($DB_Registros, "UPDATE Acesso SET Senha='$sen<PASSWORD>', TokenRecuperacao='' WHERE ID = $id");
//Exibe a senha do usuário
echo('
<br>
<br>
<div style="width: 80%; margin-left: auto; margin-right: auto; display: table;">
<img src="imagens/sucesso.png" width="30px" style="float: left; margin-right: 10px; display: table-cell; vertical-align: middle;" />
<div style="display: table-cell; vertical-align: middle;">
Ok, tudo certo! Conseguimos gerar uma nova senha de acesso para sua conta!
</div>
</div>
<br>
<br>
<center>
Nome de usuário
<br>
<div style="width: 80%; max-width: 200px; background-color: #4a5e84; color: #fcfcfc; border-radius: 4px; padding: 10px; margin-top: 4px; font-size: 18px;">
'.$consultaTokenResultado[0].'
</div>
<br>
Sua nova senha
<br>
<div style="width: 80%; max-width: 200px; background-color: #4a5e84; color: #fcfcfc; border-radius: 4px; padding: 10px; margin-top: 4px; font-size: 18px;">
'.$senhaCriada.'
</div>
<br>
<br>
Anote e utilize os dados acima para fazer login na sua conta do Windsoft ID. Depois de ter feito login, por favor, altere a senha de sua conta para uma senha que você consiga memorizar, combinado?
</center>
');
}
if($consultaTokenResultado[1] != $tokenRecuperacao || $consultaTokenResultado[1] == ""){
echo($codigoErro);
}
}
if(mysqli_num_rows($consultaToken) == 0){
echo($codigoErro);
}
}
if($id == "" || $tokenRecuperacao == ""){
echo($codigoErro);
}
?>
<?php
include("includes/rodape.inc");
?><file_sep>/client/mtassets-patcher/Patcher.cs
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
namespace MTAssets
{
/*
* This is the MT Assets Patcher. This file is responsible for applying emergency fixes, enhancements,
* or feature additions to your MT Assets tools without having to update anything.
*
* This file is updated automatically. No Patcher files will be included in your game builds.
*/
[InitializeOnLoad]
public class Patcher
{
static Patcher()
{
//Run the patcher code after Unity compiles
EditorApplication.delayCall += StartPatcherCode;
}
//<------- Start of code -------->
public static void StartPatcherCode()
{
//Run garbage collector
CreateTempFolderAndClearUnusefulFiles();
//Warn about NAT bug
if (AssetDatabase.LoadAssetAtPath("Assets/MT Assets/_AssetsData/Greetings/GreetingsData.Nat.ini", typeof(object)) != null)
{
if(AssetDatabase.LoadAssetAtPath("Assets/MT Assets/_AssetsData/Patcher/Temp/NatOk0.ini", typeof(object)) == null)
{
int option = EditorUtility.DisplayDialogComplex("MT Assets Warning", "The latest version of Native Android Toolkit (2.2.1) is now available for download from the Asset Store. This update fixes problems saving preferences and brings enhancements to NAT, it's worth download it!", "Ok", "Do not show again", "Close");
switch (option)
{
case 1:
File.WriteAllText("Assets/MT Assets/_AssetsData/Patcher/Temp/NatOk0.ini", System.DateTime.Now.Day.ToString());
break;
}
AssetDatabase.Refresh();
}
}
}
public static void CreateTempFolderAndClearUnusefulFiles()
{
//Create temp folder for patcher data
if (!AssetDatabase.IsValidFolder("Assets/MT Assets/_AssetsData/Patcher/Temp"))
{
AssetDatabase.CreateFolder("Assets/MT Assets/_AssetsData/Patcher", "Temp");
}
//Clear unuseful files
if (AssetDatabase.LoadAssetAtPath("Assets/MT Assets/_AssetsData/Patcher/Temp/NatWarn.ini", typeof(object)) != null)
AssetDatabase.DeleteAsset("Assets/MT Assets/_AssetsData/Patcher/Temp/NatWarn.ini");
if (AssetDatabase.LoadAssetAtPath("Assets/MT Assets/_AssetsData/Patcher/Temp/NatOk.ini", typeof(object)) != null)
AssetDatabase.DeleteAsset("Assets/MT Assets/_AssetsData/Patcher/Temp/NatOk.ini");
}
}
}<file_sep>/browser/registrar.php
<?php
/*
* Essa página é responsável pela criação de contas Windsoft no site
*/
$tituloPagina = "Registro - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("includes/cabecalho.inc");
RedirecionarParaHomeCasoEstejaLogado();
?>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<center>
<h3>Criar sua conta da Windsoft</h3>
Crie sua conta e aproveite todos os serviços e funções do site e dos jogos da Windsoft!
<br>
<br>
<br>
<form autocomplete="off">
<h3>Dados da Conta</h3>
<input type="text" id="nick" placeholder="Nome de Usuário" onKeyUp="validarNick();">
<div id="nickStatus" class="statusCampo"></div>
<input type="password" id="senha" placeholder="Senha" onKeyUp="validarSenha(); validarRepetirSenha();">
<div id="senhaStatus" class="statusCampo"></div>
<input type="password" id="repetirSenha" placeholder="Repita a Senha" onKeyUp="validarRepetirSenha();">
<div id="repetirSenhaStatus" class="statusCampo"></div>
<input type="email" id="email" placeholder="E-mail" onKeyUp="validarEmail(); validarRepetirEmail();">
<div id="emailStatus" class="statusCampo"></div>
<input type="email" id="repetirEmail" placeholder="Repita o E-mail" onKeyUp="validarRepetirEmail();">
<div id="repetirEmailStatus" class="statusCampo"></div>
<h3>Dados de Perfil</h3>
<input type="text" id="nome" placeholder="Nome" onKeyUp="validarNome();">
<div id="nomeStatus" class="statusCampo"></div>
<select id="genero" onChange="validarGenero();">
<option value="">Gênero</option>
<option value="F">Feminino</option>
<option value="M">Masculino</option>
<option value="V">Não Informar</option>
</select>
<div id="generoStatus" class="statusCampo"></div>
<input type="text" id="idade" placeholder="Sua Idade" onKeyUp="validarIdade();">
<div id="idadeStatus" class="statusCampo"></div>
<br>
<br>
<div class="checkboxMainContainer">
<label class="container">
<div>
Concordo com os <a href="https://windsoft.xyz/terms">termos de uso</a> e <a href="https://windsoft.xyz/policy">política de privacidade</a> da Windsoft.
</div>
<input type="checkbox" id="contrato" onclick="validarContrato();">
<span class="checkmark"></span>
</label>
</div>
<div id="contratoStatus" class="statusCampo"></div>
<br>
<br>
<div class="g-recaptcha"
data-sitekey="<KEY>"
data-callback="aoObterRespostaCaptcha"
data-expired-callback="aoExpirarCaptcha"
data-error-callback="aoOcorrerErro"></div>
<div id="captchaStatus" class="statusCampo"></div>
<input type="button" value="Criar Conta" onclick="processarRegistro();">
</form>
</center>
<!-- Javascript da página -->
<script type"text/javascript">
//Inicio
campoNick = document.getElementById("nick");
statusNick = document.getElementById("nickStatus");
campoSenha = document.getElementById("senha");
statusSenha = document.getElementById("senhaStatus");
campoRepetirSenha = document.getElementById("repetirSenha");
statusRepetirSenha = document.getElementById("repetirSenhaStatus");
campoEmail = document.getElementById("email");
statusEmail = document.getElementById("emailStatus");
campoRepetirEmail = document.getElementById("repetirEmail");
statusRepetirEmail = document.getElementById("repetirEmailStatus");
campoNome = document.getElementById("nome");
statusNome = document.getElementById("nomeStatus");
campoGenero = document.getElementById("genero");
statusGenero = document.getElementById("generoStatus");
campoIdade = document.getElementById("idade");
statusIdade = document.getElementById("idadeStatus");
statusCaptcha = document.getElementById("captchaStatus");
campoContrato = document.getElementById("contrato");
statusContrato = document.getElementById("contratoStatus");
nickValido = false;
senhaValida = false;
repetirSenhaValida = false;
emailValido = false;
repetirEmailValido = false;
nomeValido = false;
generoValido = false;
idadeValida = false;
contratoValido = false;
tokenDoCaptcha = "";
function validarNick(){
//Desvalida
campoNick.style.borderColor = "#990000";
campoNick.style.borderWidth = "1px";
statusNick.style.color = "#990000";
nickValido = false;
if(campoNick.value == ""){
statusNick.innerHTML = "Por favor, preencha este campo.";
return;
}
if(campoNick.value.length < 2){
statusNick.innerHTML = "Nome de usuário muito curto.";
return;
}
if(campoNick.value.length > 12){
statusNick.innerHTML = "Nome de usuário muito longo.";
return;
}
if(somenteLetrasNumeros(campoNick.value) == false){
statusNick.innerHTML = "O nome de usuário só pode conter letras e números.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoNick.style.borderColor = "";
campoNick.style.borderWidth = "";
statusNick.innerHTML = "";
nickValido = true;
}
function validarSenha(){
var pontuacao = 0;
if(campoSenha.value.length >= 6){
pontuacao += 1;
}
if(campoSenha.value.length >= 12){
pontuacao += 1;
}
if(contemNumeros(campoSenha.value) == true && campoSenha.value.length >= 6){
pontuacao += 1;
}
if(contemLetrasMaiusculas(campoSenha.value) == true && campoSenha.value.length >= 6){
pontuacao += 1;
}
if(contemCaracteresEspeciais(campoSenha.value) == true && campoSenha.value.length >= 6){
pontuacao += 1;
}
//Cria a barra de força
if(statusSenha.innerHTML == ""){
statusSenha.innerHTML = "<div style=\"border-radius: 2px; width: 100%; background-color: #DBDBDB; height: 4px;\"><div id=\"barraForca\" style=\"border-radius: 2px; transition: width 500ms; width: 0%; height: 100%;\"></div></div>";
}
if(pontuacao == 0){
document.getElementById("barraForca").style.width = "0%";
document.getElementById("barraForca").style.backgroundColor = "#770000";
campoSenha.style.borderColor = "#990000";
campoSenha.style.borderWidth = "1px";
senhaValida = false;
}
if(pontuacao == 1){
document.getElementById("barraForca").style.width = "20%";
document.getElementById("barraForca").style.backgroundColor = "#770000";
campoSenha.style.borderColor = "";
campoSenha.style.borderWidth = "";
senhaValida = true;
}
if(pontuacao == 2){
document.getElementById("barraForca").style.width = "40%";
document.getElementById("barraForca").style.backgroundColor = "#CE7800";
campoSenha.style.borderColor = "";
campoSenha.style.borderWidth = "";
senhaValida = true;
}
if(pontuacao == 3){
document.getElementById("barraForca").style.width = "60%";
document.getElementById("barraForca").style.backgroundColor = "#B7B400";
campoSenha.style.borderColor = "";
campoSenha.style.borderWidth = "";
senhaValida = true;
}
if(pontuacao == 4){
document.getElementById("barraForca").style.width = "80%";
document.getElementById("barraForca").style.backgroundColor = "#159100";
campoSenha.style.borderColor = "";
campoSenha.style.borderWidth = "";
senhaValida = true;
}
if(pontuacao == 5){
document.getElementById("barraForca").style.width = "100%";
document.getElementById("barraForca").style.backgroundColor = "#0092BF";
campoSenha.style.borderColor = "";
campoSenha.style.borderWidth = "";
senhaValida = true;
}
}
function validarRepetirSenha(){
//Desvalida
campoRepetirSenha.style.borderColor = "#990000";
campoRepetirSenha.style.borderWidth = "1px";
statusRepetirSenha.style.color = "#990000";
repetirSenhaValida = false;
if(campoRepetirSenha.value == ""){
statusRepetirSenha.innerHTML = "Por favor, preencha este campo.";
return;
}
if(campoRepetirSenha.value != campoSenha.value){
statusRepetirSenha.innerHTML = "A senha não bate com a digitada acima.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoRepetirSenha.style.borderColor = "";
campoRepetirSenha.style.borderWidth = "";
statusRepetirSenha.innerHTML = "";
repetirSenhaValida = true;
}
function validarEmail(){
//Desvalida
campoEmail.style.borderColor = "#990000";
campoEmail.style.borderWidth = "1px";
statusEmail.style.color = "#990000";
emailValido = false;
if(campoEmail.value == ""){
statusEmail.innerHTML = "Por favor, preencha este campo.";
return;
}
if(pareceComEmail(campoEmail.value) == false){
statusEmail.innerHTML = "O conteúdo digitado não parece com um e-mail!";
return;
}
//Deixa como válido caso não haja nenhum problema
campoEmail.style.borderColor = "";
campoEmail.style.borderWidth = "";
statusEmail.innerHTML = "";
emailValido = true;
}
function validarRepetirEmail(){
//Desvalida
campoRepetirEmail.style.borderColor = "#990000";
campoRepetirEmail.style.borderWidth = "1px";
statusRepetirEmail.style.color = "#990000";
repetirEmailValido = false;
if(campoRepetirEmail.value == ""){
statusRepetirEmail.innerHTML = "Por favor, preencha este campo.";
return;
}
if(campoRepetirEmail.value != campoEmail.value){
statusRepetirEmail.innerHTML = "O e-mail digitado não bate com o de cima.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoRepetirEmail.style.borderColor = "";
campoRepetirEmail.style.borderWidth = "";
statusRepetirEmail.innerHTML = "";
repetirEmailValido = true;
}
function validarNome(){
//Desvalida
campoNome.style.borderColor = "#990000";
campoNome.style.borderWidth = "1px";
statusNome.style.color = "#990000";
nomeValido = false;
if(campoNome.value == ""){
statusNome.innerHTML = "Por favor, preencha este campo.";
return;
}
if(campoNome.value.length > 18){
statusNome.innerHTML = "Nome muito longo.";
return;
}
if(somenteLetras(campoNome.value) == false){
statusNome.innerHTML = "O nome só pode conter letras.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoNome.style.borderColor = "";
campoNome.style.borderWidth = "";
statusNome.innerHTML = "";
nomeValido = true;
}
function validarGenero(){
//Desvalida
campoGenero.style.borderColor = "#990000";
campoGenero.style.borderWidth = "1px";
statusGenero.style.color = "#990000";
generoValido = false;
if(campoGenero.options[campoGenero.selectedIndex].value == ""){
statusGenero.innerHTML = "Por favor, escolha uma opção.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoGenero.style.borderColor = "";
campoGenero.style.borderWidth = "";
statusGenero.innerHTML = "";
generoValido = true;
}
function validarIdade(){
//Desvalida
campoIdade.style.borderColor = "#990000";
campoIdade.style.borderWidth = "1px";
statusIdade.style.color = "#990000";
idadeValida = false;
if(campoIdade.value == ""){
statusIdade.innerHTML = "Por favor, preencha este campo.";
return;
}
if(campoIdade.value.lenght > 3 ){
statusIdade.innerHTML = "Idade inválida.";
return;
}
if(campoIdade.value < 13 ){
statusIdade.innerHTML = "Você precisa ter 13 anos ou mais para se registrar.";
return;
}
if(somenteNumeros(campoIdade.value) == false){
statusIdade.innerHTML = "A idade só pode conter números.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoIdade.style.borderColor = "";
campoIdade.style.borderWidth = "";
statusIdade.innerHTML = "";
idadeValida = true;
}
function validarContrato(){
//Desvalida
if(campoContrato.checked == false){
statusContrato.style.color = "#990000";
statusContrato.innerHTML = "Você precisa concordar com os Termos de Uso e Política de Privacidade para criar sua conta.";
}
if(campoContrato.checked == true){
statusContrato.style.color = "#990000";
statusContrato.innerHTML = "";
}
contratoValido = campoContrato.checked;
}
//Callback que recebe a resposta do reCaptcha v2
var aoObterRespostaCaptcha = function(response) {
tokenDoCaptcha = response;
statusCaptcha.innerHTML = "";
};
//Callback processado ao expirar resposta captcha
var aoExpirarCaptcha = function() {
tokenDoCaptcha = "";
statusCaptcha.style.color = "#990000";
statusCaptcha.innerHTML = "Por favor, resolva novamente.";
};
//Callback processado ao ocorrer erro no captcha
var aoOcorrerErro = function() {
tokenDoCaptcha = "";
statusCaptcha.style.color = "#990000";
statusCaptcha.innerHTML = "Erro ao resolver. Tente novamente.";
};
//Envia todos os dados do formulario e re-captcha para validação
function processarRegistro(){
validarNick();
validarSenha();
validarRepetirSenha();
validarEmail();
validarRepetirEmail();
validarNome();
validarIdade();
validarContrato();
//Verifica se os campos forão preenchidos
if(nickValido == false || senhaValida == false || repetirSenhaValida == false || emailValido == false ||
repetirEmailValido == false || nomeValido == false || idadeValida == false){
mostrarNotificacao("Por favor, preencha e verifique cada campo em busca de erros.", "#750000", 2000);
return;
}
if(generoValido == false){
mostrarNotificacao("Por favor, selecione uma opção de gênero.", "#750000", 2000);
return;
}
if(contratoValido == false){
mostrarNotificacao("Você precisa concordar com os Termos de Uso e Política de Privacidade.", "#750000", 2000);
return;
}
if(tokenDoCaptcha == ""){
statusCaptcha.style.color = "#990000";
statusCaptcha.innerHTML = "Por favor, resolva o captcha.";
mostrarNotificacao("Por favor, resolva o captcha.", "#750000", 2000);
return;
}
mostrarSpinner(true);
//Cria a conexão e inicia
var conexao = novaConexaoPost("ajax-query/processar-registro.php");
conexao.onreadystatechange = function(){
mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
definirFuncaoDeSucessoOuErro(conexao,
function()
{
mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(textoDaConexao(conexao));
//Reseta o reCaptcha após a solicitação, pois cada chave só pode ser validade uma vez.
grecaptcha.reset();
tokenDoCaptcha = "";
});
};
iniciarConexaoPost(conexao, "tokenCaptcha=" + tokenDoCaptcha +
"&nick=" + campoNick.value + "&senha=" + campoSenha.value +
"&email=" + campoEmail.value + "&nome=" + campoNome.value +
"&genero=" + campoGenero.options[campoGenero.selectedIndex].value +
"&idade=" + campoIdade.value);
}
function exibirNickEmUso(){
//Exibe a mensagem de nome de usuário em uso
statusNick.style.color = "#990000";
statusNick.innerHTML = "Este nome de usuário já está em uso!";
mostrarNotificacao("Por favor, verifique cada campo em busca de erros.", "#750000", 2000);
nickValido = false;
}
function exibirEmailEmUso(){
//Exibe a mensagem de email em uso
statusEmail.style.color = "#990000";
statusEmail.innerHTML = "Este e-mail já está em uso!";
mostrarNotificacao("Por favor, verifique cada campo em busca de erros.", "#750000", 2000);
emailValido = false;
}
</script>
<?php
include("includes/rodape.inc");
?><file_sep>/browser/microsite/painel/paginas/lancar-notificacao.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Configura a data
date_default_timezone_set('America/Sao_Paulo');
$Date = date('Y-m-d H:i:s', time());
$data = date('Y-m-d', time());
$hora = date('H:i:s', time());
//Obtem os dados da ultima notificação enviada aos usuários
$consultaNotificacao = mysqli_query($DB_Metadados, "SELECT Texto, DataDeEnvio_Millis FROM Notificacao WHERE Canal='Global'");
$dadosUltimaNotificacao = mysqli_fetch_array($consultaNotificacao);
?>
<center>
<h3>Lançar Nova Notificação</h3>
</center>
<center>
<form autocomplete="off">
<textarea id="texto" placeholder="Texto da Notificação" onkeyup="validarTexto();"></textarea>
<div id="textoStatus" class="statusCampo"></div>
<input type="button" value="Lançar" onclick="salvarEdicao();" />
</form>
</center>
<!-- exibidor da ultima notificação enviada -->
<center>
<h3>Última Notificação Enviada</h3>
</center>
<div id="textoNotificacao" style="margin-left: auto; margin-right: auto; width: 80%; max-width: 300px; padding: 10px; background-color: #F2F2F2; border-radius: 4px; min-height: 100px;">
<?php
echo($dadosUltimaNotificacao[0]);
?>
</div>
<center><small><div id="horarioNotificacao" style="color: #606060; margin-top: 2px;">Enviada em <?php echo(date("d/m/Y", ($dadosUltimaNotificacao[1] / 1000) ) . " às " . date("H:i", ($dadosUltimaNotificacao[1] / 1000) )); ?></div></small></center>
<!-- código javascript desta página -->
<script type="text/javascript">
campoTexto = document.getElementById("texto");
statusTexto = document.getElementById("textoStatus");
textoValido = false;
function validarTexto(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoTexto.value.length, 160);
//Desvalida
campoTexto.style.borderColor = "#990000";
campoTexto.style.borderWidth = "1px";
statusTexto.style.color = "#990000";
textoValido = false;
if(campoTexto.value == ""){
statusTexto.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoTexto.value.length > 160){
statusTexto.innerHTML = "Descrição muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoTexto.value) == true){
statusTexto.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoTexto.style.borderColor = "";
campoTexto.style.borderWidth = "";
statusTexto.innerHTML = "";
textoValido = true;
parent.redimensionarIframe();
}
//Função que verifica se todos os campos estão válidos
function todosOsCamposEstaoValidos(){
validarTexto();
if(textoValido == true){
return true;
}
if(textoValido == false){
parent.mostrarNotificacao("Verifique o formulário em busca de erros e tente novamente.", "#750000", 3000);
return false;
}
}
//Função que salva o conteúdo digitado, no servidor, através do ajax
function salvarEdicao(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/lancar-nova-notificacao.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
document.getElementById("textoNotificacao").innerHTML = document.getElementById("texto").value;
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
var hh = String(today.getHours()).padStart(2, '0');
var ii = String(today.getMinutes()).padStart(2, '0');
document.getElementById("horarioNotificacao").innerHTML = "Enviada em " + dd + "/" + mm + "/" + yyyy + " às " + hh + ":" + ii;
document.getElementById("texto").value = "";
});
};
parent.iniciarConexaoPost(conexao,
"texto=" + document.getElementById("texto").value);
}
}
//Redimensiona as textarea de acordo com seus conteúdos, automaticamente
var textAreas = document.getElementsByTagName("textarea");
for (var i = 0; i < textAreas.length; i++){
textAreas[i].style.height = (textAreas[i].scrollHeight) + "px";
textAreas[i].style.overflow = "hidden";
textAreas[i].style.resize = "none";
textAreas[i].style.minHeight = "80px";
textAreas[i].addEventListener("input", AoDigitarNasTextArea, false);
}
function AoDigitarNasTextArea(){
this.style.height = "auto";
this.style.height = (this.scrollHeight) + "px";
this.style.minHeight = "80px";
parent.redimensionarIframe();
}
</script>
<?php
$conteudoQuadroDeAviso = ('
• As notificações emitidas aqui, serão exibidas dentro dos jogos da Windsoft, no site ou no Windsoft Launcher.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/ajax-query/obter-graficos-desta-data.php
<?php
/*
* script que adiciona a venda ao historico de vendas do asset
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Código PHP que processa o armazenamento de dados de vendas dos assets e carrega todos os dados dos assets
include("../paginas/includes/mt-assets-historico-de-vendas.inc");
//Variaveis do script
$ano = mysqli_real_escape_string($DB_Metadados, $_POST["ano"]);
$mes = mysqli_real_escape_string($DB_Metadados, $_POST["mes"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//----- Receitas deste ano
$receitaTotalPorMes = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
for($x = 1; $x < $i; $x++){
$armazenamentoDesteAsset = json_decode($vendasPorDataJson[$x]);
$arrayAnos = $armazenamentoDesteAsset->anosArmazenados;
for ($w = 0; $w < count($arrayAnos); $w++) {
if($arrayAnos[$w]->numeroAno == $ano){
$anoSelecionado = $arrayAnos[$w];
}
}
for($y = 0; $y < 12; $y++){
$mesAtual = $anoSelecionado->mesesDoAno[$y];
$receitaMesAtual = 0;
for($z = 0; $z < 31; $z++){
$receitaMesAtual += $mesAtual->diasDoMes[$z]->receitaDoDia;
}
$receitaTotalPorMes[$y] += $receitaMesAtual;
}
}
$codigoJsArray_receitaDesteAno = '["Mês", "US$"],';
$codigoJsArray_receitaDesteAno .= '["Janeiro", '.($receitaTotalPorMes[0] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Fevereiro", '.($receitaTotalPorMes[1] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Março", '.($receitaTotalPorMes[2] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Abril", '.($receitaTotalPorMes[3] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Maio", '.($receitaTotalPorMes[4] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Junho", '.($receitaTotalPorMes[5] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Julho", '.($receitaTotalPorMes[6] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Agosto", '.($receitaTotalPorMes[7] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Setembro", '.($receitaTotalPorMes[8] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Outubro", '.($receitaTotalPorMes[9] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Novembro", '.($receitaTotalPorMes[10] * 0.7).'],';
$codigoJsArray_receitaDesteAno .= '["Dezembro", '.($receitaTotalPorMes[11] * 0.7).']';
//-------- Vendas de cada asset por mes
$codigoJsArray_vendasMensaisPorAsset = '["Asset", "Quantidade"]';
for($x = 1; $x < $i; $x++){
$armazenamentoDesteAsset = json_decode($vendasPorDataJson[$x]);
$arrayAnos = $armazenamentoDesteAsset->anosArmazenados;
for ($w = 0; $w < count($arrayAnos); $w++) {
if($arrayAnos[$w]->numeroAno == $ano){
$anoSelecionado = $arrayAnos[$w];
}
}
$mesSelecionado = $anoSelecionado->mesesDoAno[$mes];
$vendasDesteMes = 0;
for($z = 0; $z < 31; $z++){
$vendasDesteMes += $mesSelecionado->diasDoMes[$z]->quantiaDeVendas;
}
$codigoJsArray_vendasMensaisPorAsset .= ',["'.$nome[$x].'", '.$vendasDesteMes.']';
}
//----------- Vendas diárias de ada asset
$codigoJsArray_vendasDiariasTodosAsset = "";
for($x = 1; $x < $i; $x++){
$codigoJsArray_vendasDiariasTodosAsset .= ", ";
$armazenamentoDesteAsset = json_decode($vendasPorDataJson[$x]);
$arrayAnos = $armazenamentoDesteAsset->anosArmazenados;
for ($w = 0; $w < count($arrayAnos); $w++) {
if($arrayAnos[$w]->numeroAno == $ano){
$anoSelecionado = $arrayAnos[$w];
}
}
$mesSelecionado = $anoSelecionado->mesesDoAno[$mes];
$vendasDesteMesArrayJs = "[['Dia', 'Quantidade']";
for($z = 0; $z < 31; $z++){
$vendasDesteMesArrayJs .= ",['".($z + 1)."', ".$mesSelecionado->diasDoMes[$z]->quantiaDeVendas."]";
}
$vendasDesteMesArrayJs .= "]";
$codigoJsArray_vendasDiariasTodosAsset .= $vendasDesteMesArrayJs;
}
echo("".
'atualizarDadosDosGraficos(['.$codigoJsArray_receitaDesteAno.'], ['.$codigoJsArray_vendasMensaisPorAsset.']'.$codigoJsArray_vendasDiariasTodosAsset.');'
."");
}
?><file_sep>/browser/microsite/painel/paginas/includes/rodape.inc
<?php
//Exibe o quadro de aviso da página, caso a variavel não seja vazia
if(empty($conteudoQuadroDeAviso) == false){
echo('<div id="quadroDeAvisos" style="margin-top: 30px; background-color: #E5E5E5; padding: 10px; border-radius: 4px;">'
.$conteudoQuadroDeAviso.
'</div>');
}
?>
</body>
</html><file_sep>/browser/links/termos-de-uso.php
<?php
/*
* Essa página funciona como um redirecionamento para a página da Windsoft Games dos Termos de Uso.
* O arquivo .htaccess possui uma configuração para que seja possível acessa-la com uma URL mais curta.
*/
$tituloPagina = "Termos de Uso - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("../includes/cabecalho.inc");
RedirecionarPara("../termos-de-uso.php", 3);
?>
<center>
<br/>
Por favor, aguarde, estamos lhe redirecionando para nossa página de Termos de Uso!
<br/>
<br/>
<small>
<a href="../termos-de-uso.php">Clique aqui caso não seja redirecionado</a>
</small>
</center>
<?php
include("../includes/rodape.inc");
?><file_sep>/browser/home.php
<?php
/*
* Essa é a página inicial do site da Windsoft Games
*/
$tituloPagina = "Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("includes/cabecalho.inc");
?>
<?php
include("../global/mysql/metadados.inc");
//Consulta as noticias
$noticiasConsulta = mysqli_query($DB_Metadados, "SELECT Titulo, UrlDaPagina, UrlDaCapa FROM Noticias WHERE Noticia IN (".implode(',', $a=array(1, 2, 3, 4, 5)).")");
$i = 0;
while($linha = mysqli_fetch_assoc($noticiasConsulta)) {
$titulo[$i] = $linha["Titulo"];
$urlPagina[$i] = $linha["UrlDaPagina"];
$urlCapa[$i] = $linha["UrlDaCapa"];
$i += 1;
}
?>
<a href="<?php echo($urlPagina[0]); ?>">
<div class="noticiaContainer" style="background-image: url(<?php echo($urlCapa[0]); ?>); border-top-left-radius: 20px; border-top-right-radius: 20px;">
<div class="noticiaEscurecimento" style="border-top-left-radius: 20px; border-top-right-radius: 20px;">
<div class="noticiaTxt">
<?php echo($titulo[0]); ?>
</div>
</div>
</div>
</a>
<a href="<?php echo($urlPagina[1]); ?>">
<div class="noticiaContainer" style="background-image: url(<?php echo($urlCapa[1]); ?>);">
<div class="noticiaEscurecimento">
<div class="noticiaTxt">
<?php echo($titulo[1]); ?>
</div>
</div>
</div>
</a>
<a href="<?php echo($urlPagina[2]); ?>">
<div class="noticiaContainer" style="background-image: url(<?php echo($urlCapa[2]); ?>);">
<div class="noticiaEscurecimento">
<div class="noticiaTxt">
<?php echo($titulo[2]); ?>
</div>
</div>
</div>
</a>
<a href="<?php echo($urlPagina[3]); ?>">
<div class="noticiaContainer" style="background-image: url(<?php echo($urlCapa[3]); ?>);">
<div class="noticiaEscurecimento">
<div class="noticiaTxt">
<?php echo($titulo[3]); ?>
</div>
</div>
</div>
</a>
<a href="<?php echo($urlPagina[4]); ?>">
<div class="noticiaContainer" style="background-image: url(<?php echo($urlCapa[4]); ?>); border-bottom-left-radius: 20px; border-bottom-right-radius: 20px;">
<div class="noticiaEscurecimento" style="border-bottom-left-radius: 20px; border-bottom-right-radius: 20px;">
<div class="noticiaTxt">
<?php echo($titulo[4]); ?>
</div>
</div>
</div>
</a>
<?php
//Consulta os jogos
$jogosConsulta = mysqli_query($DB_Metadados, "SELECT Nome, UrlIconeJogo, LinkNaLoja, UrlIconePlataforma, ExibirNaHomePage FROM JogosDaWindsoft");
//Gera o HTML de items para a lista de jogos
$codigoJogosHTML = "";
while($linhaJogos = mysqli_fetch_assoc($jogosConsulta)) {
if((bool)$linhaJogos["ExibirNaHomePage"] == true){
$codigoJogosHTML .= '
<div style="width: auto; height: 80px; padding: 5px; display: grid; grid-template-columns: 80px auto 20%;">
<div style="height: 80px; width: auto;">
<img src="'.$linhaJogos["UrlIconeJogo"].'" width="100%" height="100%" style="border-radius: 50%;" />
<div style="width: 35px; height: 35px; position: relative; border-radius: 35px; top: -35px; left: 55px; background-color: #ffffff;">
<div style="width: auto; height: auto; padding: 8px;">
<img src="'.$linhaJogos["UrlIconePlataforma"].'" width="100%" height="100%" />
</div>
</div>
</div>
<div style="width: auto;">
<div style="position: relative; top: 50%; transform: translateY(-50%); font-size: 18px; font-weight: bolder; margin-left: 10px;">
'.$linhaJogos["Nome"].'
</div>
</div>
<div style="height: 80px;">
<div class="listaDeJogosBotaoBaixar">
<a href="'.$linhaJogos["LinkNaLoja"].'"><font style="vertical-align: middle; line-height: 40px;"><center>Baixar</center></font></a>
</div>
</div>
</div>
';
}
}
?>
<br/>
<center>Conheça mais projetos da Windsoft Games!</center>
<br/>
<?php echo($codigoJogosHTML); ?>
<?php
include("includes/rodape.inc");
?><file_sep>/global/sessoes/verificador-de-sessao.inc
<?php
/*
* Essa classe é responsável por verificar a validade da sessão do usuário, mostrar a mensagem de página carregada
* e retornar os dados atuais da sessão do usuário.
*/
//Este script deve ser incluído no topo dos scripts, na PRIMEIRA linha do script, para que todos os métodos funcionem.
function IgnorarSessaoImprimirMensagemDeConteudoCarregado(){
//Mostra a mensagem de arquivo carregado
echo("[Loaded Json Document]");
}
function VerificarSessao($pararScriptEmCasoDeSessaoInvalida, $imprimirMensagemSobreValidadeSessao){
//Obtem o Cookie enviado pelo usuário, verifica e válida a sessão referente a ele.
//Inicializa as sessões
if(session_status() == PHP_SESSION_NONE){
session_start();
}
//------------ Caso a sessão não seja válida --------------
//Verifica se todos os dados estão setados na sessão.
if(!isset($_SESSION["nick"]) || !isset($_SESSION["id"])){
//Destroi a sessão
session_destroy();
//Mostra a mensagem sobre a sessão caso seja desejado
if($imprimirMensagemSobreValidadeSessao == true){
echo("[Session Expired]");
}
//Para o script, caso seja desejado
if($pararScriptEmCasoDeSessaoInvalida == true){
exit();
}
//Retorna que a sessão é inválida caso a interrupção não seja desejada
if($pararScriptEmCasoDeSessaoInvalida == false){
return false;
}
}
//------------ Caso a sessão seja válida --------------
//Caso os dados estejam setados
if(isset($_SESSION["nick"]) && isset($_SESSION["id"])){
//Mostra a mensagem de arquivo carregado
if($imprimirMensagemSobreValidadeSessao == true){
echo("[Loaded Json Document]");
}
//Retorna que a sessão é válida
return true;
}
}
?><file_sep>/browser/microsite/painel/ajax-query/editar-asset.php
<?php
/*
* script que edita um asset no banco de dados
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$id = mysqli_real_escape_string($DB_Metadados, $_POST["id"]);
$nome = mysqli_real_escape_string($DB_Metadados, $_POST["nome"]);
$preco = mysqli_real_escape_string($DB_Metadados, $_POST["preco"]);
$descricao = mysqli_real_escape_string($DB_Metadados, $_POST["descricao"]);
$urlVideo = mysqli_real_escape_string($DB_Metadados, $_POST["urlVideo"]);
$urlAssetStore = mysqli_real_escape_string($DB_Metadados, $_POST["urlAssetStore"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Edita o asset
$consultaEdicao = mysqli_query($DB_Metadados, "UPDATE AssetStore SET Nome='$nome', PrecoAtual='$preco', Descricao='$descricao', UrlVideo='$urlVideo', UrlAssetStore='$urlAssetStore' WHERE ID=$id");
echo("".
'parent.mostrarNotificacao("'.$nome.' foi editado com sucesso!", "#117700", 2500);'
."");
}
?><file_sep>/browser/microsite/painel/ajax-query/aplicar-suspensao.php
<?php
/*
* script que remove o banimento de um usuario
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
include("../../../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$id = mysqli_real_escape_string($DB_Registros, $_POST["id"]);
$dias = mysqli_real_escape_string($DB_Registros, $_POST["diasSuspensao"]);
$motivo = mysqli_real_escape_string($DB_Registros, $_POST["motivoSuspensao"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Atualiza a versão do jogo no banco de dados
$consulta = mysqli_query($DB_Registros, "UPDATE Acesso SET SuspensaoDias=$dias, SuspensaoMotivo='$motivo' WHERE ID=$id");
echo("".
'parent.mostrarNotificacao("A conta foi suspensa com sucesso.", "#1E7200", 3000);'
."diasDeSuspensao = '".$dias."';"
."motivoDeSuspensao = '".$motivo."';"
."exibirPainelDeEdicao();"
."");
}
?><file_sep>/browser/sobre-nos.php
<?php
/*
* Essa página HTML contém as informações de Sobre a Windsoft Games.
*/
$tituloPagina = "Sobre Nós - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("includes/cabecalho.inc");
?>
<br/>
<center><b>Sobre nós</b></center>
<br/>
<br/>
A Windsoft Games é uma empresa Indie Brasileira que tem como objetivo, desenvolver jogos intuitivos e cativantes.
<br/>
<br/>
Fundada por <NAME> em 20 de maio de 2015 a Windsoft Games almeja alcançar mais e mais jogadores. Desejamos ver mais jogadores felizes com jogos
de qualidade!
<br/>
<br/>
Até o momento a equipe da Windsoft Games é integrada somente por <NAME>.
<br/>
<br/>
<?php
include("includes/rodape.inc");
?><file_sep>/browser/microsite/painel/ajax-query/salvar-edicao-publicar-noticia.php
<?php
/*
* script que recebe o conteúdo da edição e o salva em arquivos temporários,
* para persistir a edição
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$titulo = $_POST["titulo"];
$urlPagina = $_POST["urlPagina"];
$urlCapa = $_POST["urlCapa"];
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Configura a data
date_default_timezone_set('America/Sao_Paulo');
$ano = date('Y');
$mesNumero = date('m');
$dia = date('d');
$hora = date('H');
$minuto = date('i');
//Cria os arquivos temporários de texto da noticia
salvarArquivoTemporario($_SESSION["id"] . "_publicacao-titulo.tmp", $titulo);
salvarArquivoTemporario($_SESSION["id"] . "_publicacao-urlPagina.tmp", $urlPagina);
salvarArquivoTemporario($_SESSION["id"] . "_publicacao-urlCapa.tmp", $urlCapa);
salvarArquivoTemporario($_SESSION["id"] . "_publicacao-dataSalvamento.tmp", "Alterações salvas em " . $dia . "/" . $mesNumero . "/" . $ano . " às " . $hora . ":" . $minuto);
salvarArquivoTemporario($_SESSION["id"] . "_publicacao-existeEdicaoSalva.tmp", "true");
echo("".
'parent.mostrarNotificacao("Alterações salvas com sucesso.", "#117700", 2500);'.
'document.getElementById("alteracoes").innerHTML = "' . "Alterações salvas em " . $dia . "/" . $mesNumero . "/" . $ano . " às " . $hora . ":" . $minuto . '";'.
"");
}
function salvarArquivoTemporario($nome, $conteudo){
//Configura o diretorio para salvar os arquivos de texto da edição
$diretorioDosArquivosTemporarios = "../paginas/noticias/temp";
//Salva o arquivo, o escrevendo
$arquivo = fopen($diretorioDosArquivosTemporarios . "/" . $nome, 'w');
fwrite($arquivo, $conteudo);
fclose($arquivo);
}
?><file_sep>/browser/microsite/painel/paginas/php-info.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
phpinfo();
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/preferencias.php
<?php
/*
* Essa página é responsável por configurações de preferências da conta do usuário
*/
$tituloPagina = "Preferências - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("includes/cabecalho.inc");
RedirecionarParaLoginCasoNaoEstejaLogado();
include("../global/mysql/registros.inc");
?>
<center>
<h3>Preferências da Conta</h3>
<br>
<br>
<h3>Alteração de E-mail</h3>
Altere o e-mail vinculado a sua conta, inserindo o novo e-mail abaixo.<br><div id="emailAtual"><?php echo("Seu e-mail atual é \"" . $_SESSION["email"] . "\"."); ?></div>
<br>
<br>
<form autocomplete="off">
<input type="email" id="email" placeholder="Novo E-mail" onKeyUp="validarEmail(); validarRepetirEmail();">
<div id="emailStatus" class="statusCampo"></div>
<input type="email" id="repetirEmail" placeholder="Repita o E-mail" onKeyUp="validarRepetirEmail();">
<div id="repetirEmailStatus" class="statusCampo"></div>
<input type="button" value="Salvar" onclick="salvarAlteracaoEmail();">
</form>
<br>
<br>
<h3>Alteração de Senha</h3>
Altere a senha de sua conta, inserindo os dados abaixo.
<br>
<br>
<form autocomplete="off">
<input type="password" id="senhaAntiga" placeholder="Senha Atual" onKeyUp="validarSenha();">
<div id="senhaAntigaStatus" class="statusCampo"></div>
<input type="password" id="novaSenha" placeholder="Nova Senha" onKeyUp="validarNovaSenha(); validarRepetirSenhaNova();">
<div id="senhaNovaStatus" class="statusCampo"></div>
<input type="password" id="repetirSenha" placeholder="Repita a Nova Senha" onKeyUp="validarRepetirSenhaNova();">
<div id="senhaNovaRepetirStatus" class="statusCampo"></div>
<input type="button" value="Salvar" onclick="salvarAlteracaoSenha();">
</form>
</center>
<!-- Javascript da página -->
<script type"text/javascript">
//Inicio
campoEmail = document.getElementById("email");
statusEmail = document.getElementById("emailStatus");
campoRepetirEmail = document.getElementById("repetirEmail");
statusRepetirEmail = document.getElementById("repetirEmailStatus");
campoSenhaAntiga = document.getElementById("senhaAntiga");
statusSenhaAntiga = document.getElementById("senhaAntigaStatus");
campoSenhaNova = document.getElementById("novaSenha");
statusSenhaNova = document.getElementById("senhaNovaStatus");
campoSenhaNovaRepetir = document.getElementById("repetirSenha");
statusSenhaNovaRepetir = document.getElementById("senhaNovaRepetirStatus");
emailValido = false;
repetirEmailValido = false;
senhaAntigaValida = false;
senhaNovaValida = false;
senhaNovaRepetirValida = false;
function validarEmail(){
//Desvalida
campoEmail.style.borderColor = "#990000";
campoEmail.style.borderWidth = "1px";
statusEmail.style.color = "#990000";
emailValido = false;
if(campoEmail.value == ""){
statusEmail.innerHTML = "Por favor, preencha este campo.";
return;
}
if(pareceComEmail(campoEmail.value) == false){
statusEmail.innerHTML = "O conteúdo digitado não parece com um e-mail!";
return;
}
//Deixa como válido caso não haja nenhum problema
campoEmail.style.borderColor = "";
campoEmail.style.borderWidth = "";
statusEmail.innerHTML = "";
emailValido = true;
}
function validarRepetirEmail(){
//Desvalida
campoRepetirEmail.style.borderColor = "#990000";
campoRepetirEmail.style.borderWidth = "1px";
statusRepetirEmail.style.color = "#990000";
repetirEmailValido = false;
if(campoRepetirEmail.value == ""){
statusRepetirEmail.innerHTML = "Por favor, preencha este campo.";
return;
}
if(campoRepetirEmail.value != campoEmail.value){
statusRepetirEmail.innerHTML = "O e-mail digitado não bate com o de cima.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoRepetirEmail.style.borderColor = "";
campoRepetirEmail.style.borderWidth = "";
statusRepetirEmail.innerHTML = "";
repetirEmailValido = true;
}
//Salva a alteração do e-mail
function salvarAlteracaoEmail(){
//Verifica se os campos forão preenchidos
if(emailValido == false || repetirEmailValido == false){
mostrarNotificacao("Por favor, verifique e preencha cada campo.", "#750000", 2000);
return;
}
mostrarSpinner(true);
//Cria a conexão e inicia
var conexao = novaConexaoPost("ajax-query/alterar-email.php");
conexao.onreadystatechange = function(){
mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
definirFuncaoDeSucessoOuErro(conexao,
function()
{
mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(textoDaConexao(conexao));
});
};
iniciarConexaoPost(conexao, "email=" + campoEmail.value);
}
function exibirEmailEmUso(){
//Exibe a mensagem de email em uso
statusEmail.style.color = "#990000";
statusEmail.innerHTML = "Este e-mail já está em uso!";
mostrarNotificacao("Por favor, verifique cada campo em busca de erros.", "#750000", 2000);
emailValido = false;
}
function limparCamposDeEmailExibirNovoEmail(email){
//Limpa os campos de email
campoEmail.value = "";
campoRepetirEmail.value = "";
document.getElementById("emailAtual").innerHTML = "Seu e-mail atual é \"" + email + "\".";
emailValido = false;
repetirEmailValido = false;
}
function validarSenha(){
//Desvalida
campoSenhaAntiga.style.borderColor = "#990000";
campoSenhaAntiga.style.borderWidth = "1px";
statusSenhaAntiga.style.color = "#990000";
senhaAntigaValida = false;
if(campoSenhaAntiga.value == ""){
statusSenhaAntiga.innerHTML = "Por favor, preencha este campo.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoSenhaAntiga.style.borderColor = "";
campoSenhaAntiga.style.borderWidth = "";
statusSenhaAntiga.innerHTML = "";
senhaAntigaValida = true;
}
function validarNovaSenha(){
var pontuacao = 0;
if(campoSenhaNova.value.length >= 6){
pontuacao += 1;
}
if(campoSenhaNova.value.length >= 12){
pontuacao += 1;
}
if(contemNumeros(campoSenhaNova.value) == true && campoSenhaNova.value.length >= 6){
pontuacao += 1;
}
if(contemLetrasMaiusculas(campoSenhaNova.value) == true && campoSenhaNova.value.length >= 6){
pontuacao += 1;
}
if(contemCaracteresEspeciais(campoSenhaNova.value) == true && campoSenhaNova.value.length >= 6){
pontuacao += 1;
}
//Cria a barra de força
if(statusSenhaNova.innerHTML == ""){
statusSenhaNova.innerHTML = "<div style=\"border-radius: 2px; width: 100%; background-color: #DBDBDB; height: 4px;\"><div id=\"barraForca\" style=\"border-radius: 2px; transition: width 500ms; width: 0%; height: 100%;\"></div></div>";
}
if(pontuacao == 0){
document.getElementById("barraForca").style.width = "0%";
document.getElementById("barraForca").style.backgroundColor = "#770000";
campoSenhaNova.style.borderColor = "#990000";
campoSenhaNova.style.borderWidth = "1px";
senhaNovaValida = false;
}
if(pontuacao == 1){
document.getElementById("barraForca").style.width = "20%";
document.getElementById("barraForca").style.backgroundColor = "#770000";
campoSenhaNova.style.borderColor = "";
campoSenhaNova.style.borderWidth = "";
senhaNovaValida = true;
}
if(pontuacao == 2){
document.getElementById("barraForca").style.width = "40%";
document.getElementById("barraForca").style.backgroundColor = "#CE7800";
campoSenhaNova.style.borderColor = "";
campoSenhaNova.style.borderWidth = "";
senhaNovaValida = true;
}
if(pontuacao == 3){
document.getElementById("barraForca").style.width = "60%";
document.getElementById("barraForca").style.backgroundColor = "#B7B400";
campoSenhaNova.style.borderColor = "";
campoSenhaNova.style.borderWidth = "";
senhaNovaValida = true;
}
if(pontuacao == 4){
document.getElementById("barraForca").style.width = "80%";
document.getElementById("barraForca").style.backgroundColor = "#159100";
campoSenhaNova.style.borderColor = "";
campoSenhaNova.style.borderWidth = "";
senhaNovaValida = true;
}
if(pontuacao == 5){
document.getElementById("barraForca").style.width = "100%";
document.getElementById("barraForca").style.backgroundColor = "#0092BF";
campoSenhaNova.style.borderColor = "";
campoSenhaNova.style.borderWidth = "";
senhaNovaValida = true;
}
}
function validarRepetirSenhaNova(){
//Desvalida
campoSenhaNovaRepetir.style.borderColor = "#990000";
campoSenhaNovaRepetir.style.borderWidth = "1px";
statusSenhaNovaRepetir.style.color = "#990000";
senhaNovaRepetirValida = false;
if(campoSenhaNovaRepetir.value == ""){
statusSenhaNovaRepetir.innerHTML = "Por favor, preencha este campo.";
return;
}
if(campoSenhaNovaRepetir.value != campoSenhaNova.value){
statusSenhaNovaRepetir.innerHTML = "A senha não bate com a digitada acima.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoSenhaNovaRepetir.style.borderColor = "";
campoSenhaNovaRepetir.style.borderWidth = "";
statusSenhaNovaRepetir.innerHTML = "";
senhaNovaRepetirValida = true;
}
//Salva a alteração da senha
function salvarAlteracaoSenha(){
//Verifica se os campos forão preenchidos
if(senhaAntigaValida == false || senhaNovaValida == false || senhaNovaRepetirValida == false){
mostrarNotificacao("Por favor, verifique e preencha cada campo.", "#750000", 2000);
return;
}
mostrarSpinner(true);
//Cria a conexão e inicia
var conexao = novaConexaoPost("ajax-query/alterar-senha.php");
conexao.onreadystatechange = function(){
mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
definirFuncaoDeSucessoOuErro(conexao,
function()
{
mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(textoDaConexao(conexao));
});
};
iniciarConexaoPost(conexao, "senha=" + campoSenhaAntiga.value + "&senhaNova=" + campoSenhaNova.value);
}
function exibirSenhaErrada(){
//Exibe a mensagem de senha incorreta
statusSenhaAntiga.style.color = "#990000";
statusSenhaAntiga.innerHTML = "Senha informada não bate com a senha atual da conta.";
mostrarNotificacao("Por favor, verifique cada campo em busca de erros.", "#750000", 2000);
senhaAntigaValida = false;
}
function limparCamposDeSenha(){
//Limpa os campos de senha
campoSenhaAntiga.value = "";
campoSenhaNova.value = "";
campoSenhaNovaRepetir.value = "";
statusSenhaNova.innerHTML = "";
senhaNovaValida = false;
senhaNovaRepetirValida = false;
senhaAntigaValida = false;
}
</script>
<?php
include("includes/rodape.inc");
?><file_sep>/browser/microsite/painel/ajax-query/editar-slide.php
<?php
/*
* script que recebe o conteúdo da edição e o salva em arquivos temporários,
* para persistir a edição
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$id = mysqli_real_escape_string($DB_Metadados, $_POST["id"]);
$titulo = mysqli_real_escape_string($DB_Metadados, $_POST["titulo"]);
$urlPagina = mysqli_real_escape_string($DB_Metadados, $_POST["urlPagina"]);
$urlCapa = mysqli_real_escape_string($DB_Metadados, $_POST["urlCapa"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Edita o slide desejado
$consultaEditarSlide = mysqli_query($DB_Metadados, "UPDATE Noticias SET Titulo='$titulo', UrlDaPagina='$urlPagina', UrlDaCapa='$urlCapa' WHERE Noticia=$id");
echo("".
'parent.mostrarNotificacao("Slide '.$id.' editado com sucesso!", "#117700", 2500);'.
'exibirMensagemSlideEditado();'.
"");
}
?><file_sep>/browser/recuperar.php
<?php
/*
* Essa é a página de recuperação de conta da Windsoft Games
*/
$tituloPagina = "Recuperação de conta - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("includes/cabecalho.inc");
RedirecionarParaHomeCasoEstejaLogado();
?>
<center>
<h3>Esqueceu a senha da sua conta? Podemos te ajudar!</h3>
<div id="respostaConsulta">
Digite o e-mail vinculado a sua conta. Caso a encontremos, iremos lhe enviar um e-mail com um link
para que você possa gerar uma nova senha, ok?
<br>
<br>
<br>
<form autocomplete="off" id="formularioLogin">
<input type="text" id="email" placeholder="E-mail">
<input type="button" value="Recuperar" onclick="consultarLogin();">
</form>
</div>
</center>
<!-- Javascript da página -->
<script type"text/javascript">
//Inicio
campoEmail = document.getElementById("email");
respostaConsulta = document.getElementById("respostaConsulta");
function consultarLogin(){
campoEmail = document.getElementById("email");
//Verifica se os campos forão preenchidos
if(campoEmail.value == ""){
mostrarNotificacao("Por favor, preencha todos os campos.", "#750000", 2000);
return;
}
mostrarSpinner(true);
//Cria a conexão e inicia
var conexao = novaConexaoPost("ajax-query/consulta-recuperacao.php");
conexao.onreadystatechange = function(){
mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
definirFuncaoDeSucessoOuErro(conexao,
function()
{
mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
respostaConsulta.innerHTML = textoDaConexao(conexao);
eval(document.getElementById("scriptResposta").innerHTML);
});
};
iniciarConexaoPost(conexao, "email=" + campoEmail.value);
}
</script>
<?php
include("includes/rodape.inc");
?><file_sep>/browser/microsite/painel/ajax-query/editar-anuncio-intersticial.php
<?php
/*
* script que recebe o conteúdo da edição e o salva em arquivos temporários,
* para persistir a edição
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$ativarAnuncio = mysqli_real_escape_string($DB_Metadados, $_POST["ativarAnuncio"]);
$textoBotao = mysqli_real_escape_string($DB_Metadados, $_POST["textoBotao"]);
$urlImagem = mysqli_real_escape_string($DB_Metadados, $_POST["urlImagem"]);
$urlPagina = mysqli_real_escape_string($DB_Metadados, $_POST["urlPagina"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Obtem os dados do slide selecionado
$consultaAtualizarAnuncio = mysqli_query($DB_Metadados, "UPDATE AdIntersticial SET AtivarAnuncio=$ativarAnuncio, TextoBotao='$textoBotao', UrlImagem='$urlImagem', UrlDaPagina='$urlPagina' WHERE Anuncio='Global'");
echo("".
'parent.mostrarNotificacao("O Anúncio Intersticial, foi editar com sucesso!", "#117700", 2500);'
."");
}
?><file_sep>/browser/microsite/painel/ajax-query/receber-arquivo-expansao.php
<?php
/*
* script que recebe a imagem enviada através da função de carregar imagem
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$arquivo = $_FILES["arquivo"];
$plataforma = strtolower($_POST["plataforma"]);
$pacote = $_POST["pacote"];
$versao = $_POST["versao"];
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Obtem a extensão do arquivo
$extensaoDoArquivo = pathinfo($arquivo["name"], PATHINFO_EXTENSION);
//Cria o diretorio dos arquivos de expansão para este jogo, caso não exista
if(!is_dir("../../../../global/repositorio/arquivos-de-jogos/".$plataforma."/".$pacote)){
mkdir("../../../../global/repositorio/arquivos-de-jogos/".$plataforma."/".$pacote, 0777, true);
}
//Monta o nome do arquivo e diretorio
$diretorioFinal = "../../../../global/repositorio/arquivos-de-jogos/".$plataforma."/".$pacote."/".$arquivo["name"];
//Caso o upload ocorra bem
if(move_uploaded_file($arquivo["tmp_name"], $diretorioFinal)){
//Renomeia o arquivo enviado
rename($diretorioFinal, "../../../../global/repositorio/arquivos-de-jogos/".$plataforma."/".$pacote."/expansion(".$versao.").".$extensaoDoArquivo);
echo(""
."parent.mostrarNotificacao(\"Arquivo de expansão carregado com sucesso!\", \"#467200\", 3500);"
."exibirMensagemArquivoEnviado();"
."");
}
}
?><file_sep>/browser/microsite/mt-assets/home.php
<?php
/*
* Essa é a página inicial do portfolio MT Assets
*/
$TituloPagina = "Home - MT Assets";
include("includes/cabecalho.inc");
?>
<div class="titulo">
About MT Assets
</div>
<br/>
MT Assets is a developer of assets for Unity. MT Assets refers directly to me, <NAME>! I am an Indie programmer and game developer,
I always like to learn something new and I've been working with Unity since 2014. I'm at the Asset Store to provide useful and helpful tools for Unity Engine
developers. Get to know my assets, and visit my <a href="https://assetstore.unity.com/publishers/40306">Asset Store page!</a> If you need contact or support for my assets, please contact me at <EMAIL>.
<br/>
<br/>
<div class="titulo">
See My Assets
</div>
<br/>
<div class="grid-assets">
<?php
include("../../../global/mysql/metadados.inc");
//Consulta os assets
$assetsConsulta = mysqli_query($DB_Metadados, "SELECT Nome, PrecoAtual, Descricao, UrlImagem, UrlVideo, UrlAssetStore FROM AssetStore");
//Gera o HTML de items para a lista de assets
$codigoAssetsHtml = "";
while($linhaAssets = mysqli_fetch_assoc($assetsConsulta)) {
$codigoAssetsHtml .= '
<div>
<div class="grid-item">
<div class="grid-item-image" style="background-image: url('.$linhaAssets["UrlImagem"].');">
</div>
<div class="grid-item-title">
<center>'.$linhaAssets["Nome"].'</center>
</div>
<div class="grid-item-text">
'.$linhaAssets["Descricao"].'
</div>
<iframe width="100%" height="180" src="'.$linhaAssets["UrlVideo"].'" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a target="_blank" href="'.$linhaAssets["UrlAssetStore"].'">
<div class="grid-item-button">
<center>View In Asset Store</center>
</div>
</a>
<center><small>Available for US$ '.$linhaAssets["PrecoAtual"].'</small></center>
<br/>
</div>
</div>
';
}
echo($codigoAssetsHtml);
?>
</div>
<br/>
<br/>
<?php
include("includes/rodape.inc");
?><file_sep>/browser/ajax-query/alterar-email.php
<?php
/*
* script que faz consulta de email
*/
include("../../global/sessoes/verificador-de-sessao.inc");
include("../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Obtem as variaveis
$email = mysqli_real_escape_string($DB_Registros, $_POST["email"]);
//Verifica se é o mesmo e-mail da conta
if($email == $_SESSION["email"]){
echo("mostrarNotificacao(\"Sua conta já está usando este e-mail!\", \"#117700\", 5000);s");
exit();
}
//Verifica se já existe alguem usando este e-mail, caso exista para o script
$verificaEmail = mysqli_query($DB_Registros, "SELECT ID FROM Acesso WHERE Email='$email'");
if(mysqli_num_rows($verificaEmail) == 1){
echo("exibirEmailEmUso();");
exit();
}
//obtem o id do usuário
$id = $_SESSION["id"];
//Realiza a alteração do email
$consultaTroca = mysqli_query($DB_Registros, "UPDATE Acesso SET Email='$email' WHERE ID=$id");
$_SESSION["email"] = $email;
echo("".
"mostrarNotificacao('Seu e-mail foi alterado com sucesso para \"".$email."\".', \"#117700\", 5000);".
"limparCamposDeEmailExibirNovoEmail('".$email."');".
"");
?><file_sep>/browser/microsite/painel/ajax-query/receber-arte-asset.php
<?php
/*
* script que recebe a arte enviada através da página de edição de arte
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$arquivo = $_FILES["imagem"];
$nomeDoArquivoArte = $_POST["nomeDoArquivoArte"];
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
$podeContinuarComCarregamento = true;
//Verifica o tipo de arquivo
$extensoesPermitidas = array("png");
$extensaoDoArquivo = pathinfo($arquivo["name"], PATHINFO_EXTENSION);
if(in_array($extensaoDoArquivo, $extensoesPermitidas) == false && $podeContinuarComCarregamento == true){
echo("
parent.mostrarNotificacao('O arquivo enviado, não é do formato PNG.', \"#750000\", 5000);
redefinirInterface();
");
$podeContinuarComCarregamento = false;
}
//Verifica o tamanho maximo do arquivo
$tamanhoMaxEmKb = 512 * 1024;
if($arquivo["size"] > $tamanhoMaxEmKb && $podeContinuarComCarregamento == true){
echo("
parent.mostrarNotificacao('O arquivo enviado excede o tamanho limite de 512Kb.', \"#750000\", 5000);
redefinirInterface();
");
$podeContinuarComCarregamento = false;
}
//Verifica se o arquivo é uma imagem
if(!getimagesize($arquivo["tmp_name"]) && $podeContinuarComCarregamento == true){
echo("
parent.mostrarNotificacao('O arquivo enviado não é uma imagem, ou está corrompido.', \"#750000\", 5000);
redefinirInterface();
");
$podeContinuarComCarregamento = false;
}
//Inicia o upload do arquivo, caso seja possível
if($podeContinuarComCarregamento == true){
//Monta o nome do arquivo e diretorio
$diretorioFinal = "../../mt-assets/asset-images/".$arquivo["name"];
//Caso o upload ocorra bem
if(move_uploaded_file($arquivo["tmp_name"], $diretorioFinal)){
//Renomeia o arquivo enviado
rename($diretorioFinal, "../../mt-assets/asset-images/".$nomeDoArquivoArte);
echo("".
"parent.mostrarNotificacao(\"Arte carregada com sucesso!\", \"#467200\", 8000);".
"parent.carregarPagina('editar-arte-asset.php');"
."");
}
}
}
?><file_sep>/client/metadados/dados-do-jogo/obter-dados.php
<?php
/*
* Essa classe é responsável por obter a versão de um determinado jogo
* com base no nome do pacote informado
*/
include("../../../global/sessoes/verificador-de-sessao.inc");
include("../../../global/mysql/metadados.inc");
IgnorarSessaoImprimirMensagemDeConteudoCarregado();
$tempoInicio = microtime(true);
$jsonResposta = new stdClass();
//Variaveis base do json
$jsonResposta->ultimaVersao = "";
//Variaveis do script
$pacote = mysqli_real_escape_string($DB_Metadados, $_POST["pacote"]);
//<!---------------------- Inicio do Script ----------------------------->
//Inicia a consulta da obtenção da versão
$dadosDoJogoConsulta = mysqli_query($DB_Metadados, "SELECT UltimaVersao FROM JogosDaWindsoft WHERE PacoteOuNamespace = '$pacote'");
if(mysqli_num_rows($dadosDoJogoConsulta) == 1){
$dadosDoJogo = mysqli_fetch_array($dadosDoJogoConsulta);
//Insere as informações do anuncio no JSON resposta
$jsonResposta->ultimaVersao = $dadosDoJogo[0];
}
if(mysqli_num_rows($dadosDoJogoConsulta) == 0){
//Insere as variaveis vazias, para evitar crashs, no client
$jsonResposta->ultimaVersao = "0.0.1";
}
//Insere o tempo da duração da execução do script no JSON Resposta
$jsonResposta->tempoExecucaoDoScript = number_format(microtime(true) - $tempoInicio, 5) . "ms";
//Imprime o JSON resposta
echo("<pre>" . json_encode($jsonResposta, JSON_PRETTY_PRINT) . "</pre>");
?><file_sep>/browser/ajax-query/trocar-capa.php
<?php
/*
* script que faz consulta de alteração do icone
*/
include("../../global/sessoes/verificador-de-sessao.inc");
include("../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Obtem as variaveis
$novaCapa = mysqli_real_escape_string($DB_Registros, $_POST["capa"]);
//obtem o id do usuário
$id = $_SESSION["id"];
//Altera o icone
$consulta = mysqli_query($DB_Registros, "UPDATE Perfis SET IdCapa=$novaCapa WHERE ID=$id");
$_SESSION["idCapa"] = $novaCapa;
echo("".
"mostrarNotificacao(\"Capa de perfil alterado com sucesso!\", \"#117700\", 5000); ".
"document.getElementById(\"capaPagPerfil\").style.backgroundImage = \"url(https://windsoft.xyz/global/repositorio/arquivos-de-perfil/capas-de-perfil/capa_".$novaCapa.".png)\";".
"");
?><file_sep>/browser/microsite/painel/ajax-query/obter-dados-do-usuario.php
<?php
/*
* script que obtem os dados da conta de um determinado usuário
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
include("../../../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$nick = mysqli_real_escape_string($DB_Registros, $_POST["nick"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Atualiza a versão do jogo no banco de dados
$consultaAcesso = mysqli_query($DB_Registros, "SELECT ID, Email, Ativada, ConcordouContrato, DataCriacao_Millis, Banimento, SuspensaoDias, SuspensaoMotivo FROM Acesso WHERE Nick='$nick'");
//Caso encontre este usuário
if(mysqli_num_rows($consultaAcesso) == 1){
$dadosAcesso = mysqli_fetch_array($consultaAcesso);
$id = $dadosAcesso[0];
$email = $dadosAcesso[1];
$ativada = boolval($dadosAcesso[2]) ? 'true' : 'false';
$concordouContrato = boolval($dadosAcesso[3]) ? 'true' : 'false';
$dataCriacaoMillis = $dadosAcesso[4];
$banimento = $dadosAcesso[5];
$suspensaoDias = $dadosAcesso[6];
$suspensaoMotivo = $dadosAcesso[7];
$consultaPerfil = mysqli_query($DB_Registros, "SELECT IdIcone FROM Perfis WHERE ID=$id");
$dadosPerfil = mysqli_fetch_array($consultaPerfil);
$idIcone = $dadosPerfil[0];
$consultaStaff = mysqli_query($DB_Metadados, "SELECT Cargo, Autoridade FROM Staff WHERE Nick='$nick'");
$dadosStaff = mysqli_fetch_array($consultaStaff);
if(mysqli_num_rows($consultaStaff) == 0){
$staff = "false";
$cargo = "Membro";
$autoridade = 0;
}
if(mysqli_num_rows($consultaStaff) == 1){
$staff = "true";
$cargo = $dadosStaff[0];
$autoridade = $dadosStaff[1];
}
echo("".
'gravarDadosDesteUsuario('.$id.',"'.$email.'",'.$ativada.','.$concordouContrato.','.$dataCriacaoMillis.',"'.$banimento.'",'.$suspensaoDias.',"'.$suspensaoMotivo.'",'.$idIcone.','.$staff.',"'.$cargo.'",'.$autoridade.');'
.'exibirPainelDeEdicao();'
."");
}
//Caso não encontre o usuário
if(mysqli_num_rows($consultaAcesso) == 0){
echo("".
'parent.mostrarNotificacao("Nenhum usuário com este Nickname foi encontrado.", "#750000", 2500);'
."");
}
}
?><file_sep>/browser/microsite/painel/ajax-query/cadastrar-novo-jogo.php
<?php
/*
* script que insere o novo jogo no banco de dados
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$nome = mysqli_real_escape_string($DB_Metadados, $_POST["nome"]);
$ultimaVersao = mysqli_real_escape_string($DB_Metadados, $_POST["ultimaVersao"]);
$nomeDoPacote = mysqli_real_escape_string($DB_Metadados, $_POST["nomeDoPacote"]);
$plataforma = mysqli_real_escape_string($DB_Metadados, $_POST["plataforma"]);
$linkLoja = mysqli_real_escape_string($DB_Metadados, $_POST["linkLoja"]);
$exibirNoSite = mysqli_real_escape_string($DB_Metadados, $_POST["exibirNoSite"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Deixa o nome da plataforma em minusculo
$plataformaMinusculo = strtolower($plataforma);
//Insere o novo jogo no banco de dados
$consultaCadastrarJogo = mysqli_query($DB_Metadados, "INSERT INTO JogosDaWindsoft(Nome, UrlIconeJogo, UltimaVersao, PacoteOuNamespace, Plataforma, LinkNaLoja, UrlIconePlataforma, ExibirNaHomePage) VALUES('$nome', 'https://windsoft.xyz/global/repositorio/icones-de-jogos/$nomeDoPacote.png', '$ultimaVersao', '$nomeDoPacote', '$plataforma', '$linkLoja', 'https://windsoft.xyz/global/repositorio/icones-de-plataformas/$plataformaMinusculo.png', $exibirNoSite)");
echo("".
'parent.mostrarNotificacao("'.$nome.' foi cadastrado com sucesso!", "#117700", 2500);'.
'exibirMensagemJogoCadastrado();'
."");
}
?><file_sep>/browser/microsite/painel/paginas/graficos-vendas-assets.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<!-- Código PHP que processa o armazenamento de dados de vendas dos assets e carrega todos os dados dos assets -->
<?php include("includes/mt-assets-historico-de-vendas.inc"); ?>
<center>
<h3>Gráficos de Vendas</h3>
</center>
<div style="width: 100%; max-width: 100%; margin-left: auto; margin-right: auto; display: grid; grid-template-columns: 40% 40% 20%;">
<select id="selectAno" style="width: calc(100% - 6px);">
<?php
//Cria opções automaticamente, até o ano atual
$anoInicial = 2018;
$diferencaDeAnos = (int)(date("Y")) - $anoInicial;
echo('<option value="'.$anoInicial.'">Ano de '.$anoInicial.'</option>');
for($i = 0; $i < $diferencaDeAnos; $i++){
if((int)(date("Y")) == ($anoInicial + $i + 1)){
echo('<option value="'.($anoInicial + $i + 1).'" selected="selected">Ano de '.($anoInicial + $i + 1).'</option>');
}
if((int)(date("Y")) != ($anoInicial + $i + 1)){
echo('<option value="'.($anoInicial + $i + 1).'">Ano de '.($anoInicial + $i + 1).'</option>');
}
}
?>
</select>
<select id="selectMes" style="width: calc(100% - 6px);">
<?php
//Cria opções automaticamente, de todos os meses
for($i = 0; $i < 12; $i++){
if($i == "0"){ $mesExtenso = ("Janeiro"); }
if($i == "1"){ $mesExtenso = ("Fevereiro"); }
if($i == "2"){ $mesExtenso = ("Março"); }
if($i == "3"){ $mesExtenso = ("Abril"); }
if($i == "4"){ $mesExtenso = ("Maio"); }
if($i == "5"){ $mesExtenso = ("Junho"); }
if($i == "6"){ $mesExtenso = ("Julho"); }
if($i == "7"){ $mesExtenso = ("Agosto"); }
if($i == "8"){ $mesExtenso = ("Setembro"); }
if($i == "9"){ $mesExtenso = ("Outubro"); }
if($i == "10"){ $mesExtenso = ("Novembro"); }
if($i == "11"){ $mesExtenso = ("Dezembro"); }
if(((int)(date("n")) - 1) == $i){
echo('<option value="'.$i.'" selected="selected">'.$mesExtenso.'</option>');
}
if(((int)(date("n")) - 1) != $i){
echo('<option value="'.$i.'">'.$mesExtenso.'</option>');
}
}
?>
</select>
<input type="button" value="Filtrar" style="width: 100%;" onclick="filtrarGraficos();" />
</div>
<center><h3 style="margin-bottom: 0px;" id="receitasDoAnoTitulo">Receitas no Ano</h3></center>
<div id="receitasDoAnoGrafico" style="width: 100%; height: 300px;"></div>
<center><small>* A receita exibida no gráfico, é de 70% do valor total, pois 30% da receita é voltada para a Unity.</small></center>
<center><h3 style="margin-bottom: 0px;" id="vendasDoMesTitulo">Vendas do Mês</h3></center>
<div id="vendasDoMesGrafico" style="width: 100%; height: 300px;"></div>
<br>
<br>
<center>
Acesso Rápido a Vendas Diárias
<br>
<br>
<?php
echo('<a href="#vendasAsset1">'.$nome[1].'</a>');
for($x = 2; $x < count($nome) + 1; $x++){
echo(' - <a href="#vendasAsset'.$x.'">'.$nome[$x].'</a>');
}
?>
</center>
<br>
<br>
<?php
for($x = 1; $x < count($nome) + 1; $x++){
echo('
<center><h3 style="margin-bottom: 0px;" id="vendasAsset'.$x.'">Vendas diárias de '.$nome[$x].'</h3></center>
<div id="vendasAsset'.$x.'Grafico" style="width: 100%; height: 300px;"></div>
<center><small>* Estas vendas diárias são referentes ao mês atualmente selecionado no filtro.</small></center>
<br>
<br>
');
}
?>
<!-- código javascript desta página -->
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart', 'bar']});
google.charts.setOnLoadCallback(desenharTodosGraficos);
//dados de receitas do ano
receitasDoAnoDados = [['Mês', 'US$'], ['Carregando dados', 0]];
//dados de vendas do mês
vendasDoMesDados = [['Asset', 'Quantia'], ['Carregando dados', 1]];
//Dados de vendas diarias de cada asset
<?php
for($x = 1; $x < count($nome) + 1; $x++){
echo('
vendasDoAsset'.$x.'Dados = [["Dia", "Quantidade"], ["Carregando dados", 0]];
');
}
?>
//Função que desenha todos os gráficos
function desenharTodosGraficos(){
//Obtem o nome do mes atual
var mesAtualNome = "";
if(document.getElementById("selectMes").value == "0"){mesAtualNome = "Janeiro";}
if(document.getElementById("selectMes").value == "1"){mesAtualNome = "Fevereiro";}
if(document.getElementById("selectMes").value == "2"){mesAtualNome = "Março";}
if(document.getElementById("selectMes").value == "3"){mesAtualNome = "Abril";}
if(document.getElementById("selectMes").value == "4"){mesAtualNome = "Maio";}
if(document.getElementById("selectMes").value == "5"){mesAtualNome = "Junho";}
if(document.getElementById("selectMes").value == "6"){mesAtualNome = "Julho";}
if(document.getElementById("selectMes").value == "7"){mesAtualNome = "Agosto";}
if(document.getElementById("selectMes").value == "8"){mesAtualNome = "Setembro";}
if(document.getElementById("selectMes").value == "9"){mesAtualNome = "Outubro";}
if(document.getElementById("selectMes").value == "10"){mesAtualNome = "Novembro";}
if(document.getElementById("selectMes").value == "11"){mesAtualNome = "Dezembro";}
//Desenha o gráfico de receita deste ano
var receitasDesteAno = new google.visualization.BarChart(document.getElementById('receitasDoAnoGrafico'));
receitasDesteAno.draw(google.visualization.arrayToDataTable(receitasDoAnoDados), {legend: {position: 'none'}, 'chartArea': {'width': '65%', 'height': '300px'}});
document.getElementById("receitasDoAnoTitulo").innerHTML = "Receitas no Ano de " + document.getElementById("selectAno").value;
//Desenha o gráfico de vendas do mes
var vendasDoMes = new google.visualization.PieChart(document.getElementById('vendasDoMesGrafico'));
vendasDoMes.draw(google.visualization.arrayToDataTable(vendasDoMesDados), {pieHole: 0.4, legend: {position: 'bottom'}, 'chartArea': {'width': '100%', 'height': '300px'}});
document.getElementById("vendasDoMesTitulo").innerHTML = "Vendas de " + mesAtualNome;
//Desenha o gráfico de vendas diarias de cada asset
<?php
for($x = 1; $x < count($nome) + 1; $x++){
echo('
var vendasDoAsset'.$x.' = new google.visualization.ColumnChart(document.getElementById("vendasAsset'.$x.'Grafico"));
vendasDoAsset'.$x.'.draw(google.visualization.arrayToDataTable(vendasDoAsset'.$x.'Dados), {legend: {position: "none"}, "chartArea": {"width": "100%", "height": "300px"}});
');
}
?>
}
//Função que filtra os graficos para uma determinada data
function filtrarGraficos(){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/obter-graficos-desta-data.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
console.log(parent.textoDaConexao(conexao));
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"ano=" + document.getElementById("selectAno").value +
"&mes=" + document.getElementById("selectMes").value);
}
//Função que obtem os dados do ajax e os exibe nos graficos
function atualizarDadosDosGraficos(arrayReceitaDoAno, arrayVendasDoMes<?php
for($x = 1; $x < count($nome) + 1; $x++){
echo(', arrayVendasDiariasAsset'.$x);
}
?>){
receitasDoAnoDados = arrayReceitaDoAno;
vendasDoMesDados = arrayVendasDoMes;
<?php
for($x = 1; $x < count($nome) + 1; $x++){
echo("vendasDoAsset".$x."Dados = arrayVendasDiariasAsset".$x.";");
}
?>
desenharTodosGraficos();
}
//Inicia carregando os dados da data atual
filtrarGraficos();
</script>
<?php
$conteudoQuadroDeAviso = ('
• Estes são os gráficos gerados, usando o histórico de compras. Utilize os controles de filtro, no topo desta página para visualizar e comparar gráficos.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/mt-assets/includes/rodape.inc
<?php
/*
* Essa classe é responsável por fornecer o rodapé das páginas.
*/
?>
<br/>
<br/>
<hr/>
<br/>
<center>
<small>
<a href="https://windsoft.xyz/mtassets">Home</a>
•
<a href="https://www.youtube.com/channel/UCqAgiYBwAWajjFUqyJ6_xyw?view_as=subscriber">Youtube Channel</a>
•
<a href="mailto:<EMAIL>">Contact</a>
•
<a href="https://assetstore.unity.com/publishers/40306">Unity Asset Store</a>
•
<a href="https://windsoft.xyz/">Meet the Windsoft Games!</a>
</small>
</center>
<br/>
</div>
</body>
</html><file_sep>/browser/ajax-query/processar-registro.php
<?php
/*
* Script que faz registro no banco de dados
*/
//Processa a resposta do ReCaptcha
require_once "validador-recaptcha-2.0.php";
$secret = "<KEY>";
$response = null;
$reCaptcha = new ReCaptcha($secret);
if ($_POST["tokenCaptcha"]) {
$response = $reCaptcha->verifyResponse($_SERVER["REMOTE_ADDR"], $_POST["tokenCaptcha"]);
}
//Caso a resposta do reCaptcha tenha dado certo, processa o formulario e para o script
if ($response != null && $response->success) {
include("../../global/mysql/registros.inc");
//Obtem as variaveis
$nick = mysqli_real_escape_string($DB_Registros, $_POST["nick"]);
$senha = MD5($_POST["senha"]);
$email = mysqli_real_escape_string($DB_Registros, $_POST["email"]);
$nome = mysqli_real_escape_string($DB_Registros, $_POST["nome"]);
$genero = mysqli_real_escape_string($DB_Registros, $_POST["genero"]);
$idade = mysqli_real_escape_string($DB_Registros, $_POST["idade"]);
//Valida as variaveis. Ao encontrar qualquer problema, simplesmente interrompe tudo
if(strlen($nick) > 12 || strlen($nick) < 2){
exit();
}
if(strlen($nome) > 18){
exit();
}
if(strlen($genero) > 1){
exit();
}
if($idade < 13 || $idade > 999){
exit();
}
//Processa o registro
//Verifica se o nick já está sendo usado
$consultaUsandoNick = mysqli_query($DB_Registros, "SELECT ID FROM Acesso WHERE Nick='$nick'");
//Caso o nick já esteja sendo usado
if(mysqli_num_rows($consultaUsandoNick) == 1){
echo("exibirNickEmUso();");
exit();
}
//Verifica se o email já está sendo usado
$consultaUsandoEmail = mysqli_query($DB_Registros, "SELECT ID FROM Acesso WHERE Email='$email'");
//Caso o email já esteja sendo usado
if(mysqli_num_rows($consultaUsandoEmail) == 1){
echo("exibirEmailEmUso();");
exit();
}
//Caso esteja tudo certo
//Obtem a hora atual em millis
$dataAtual = round(microtime(true) * 1000);
//Insere os dados de acesso
$consultaInsercaoAcesso = mysqli_query($DB_Registros, "INSERT INTO Acesso (Nick, Senha, Email, Ativada, ConcordouContrato, DataCriacao_Millis) VALUES('$nick', '$senha', '$email', 0, 1, $dataAtual)");
//Obtem o ID do usuário
$consultaID = mysqli_query($DB_Registros, "SELECT ID FROM Acesso WHERE Nick='$nick'");
$dadosId = mysqli_fetch_array($consultaID);
//Obtem o ano de nascimento
$anoNascimento = date("Y") - $idade;
//Insere os dados de perfil
$consultaInsercaoAcesso = mysqli_query($DB_Registros, "INSERT INTO Perfis (ID, Nome, IdCapa, IdIcone, Genero, AnoNascimento, UltimoLogin_Millis) VALUES($dadosId[0], '$nome', 1, 1, '$genero', $anoNascimento, $dataAtual)");
//Imprime a mensagem de sucesso
echo("".
"mostrarSpinner(true); ".
"mostrarNotificacao(\"Sua conta foi criada com sucesso! Estamos lhe redirecionando para que possa fazer login.\", \"#1F7F00\", 15000);".
"setTimeout(function () { ".
"window.location.href = \"https://windsoft.xyz/browser/login.php\"; ".
"}, 10000);".
"");
exit();
}
//Caso tenha dado errado
echo("mostrarNotificacao(\"Verificação do reCaptcha está incorreta. Tente novamente.\", \"#750000\", 3500);");
?><file_sep>/browser/microsite/painel/paginas/contas-registradas.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem a contagem de contas registradas
$consulta = mysqli_query($DB_Registros, "SELECT TABLE_ROWS FROM information_schema.TABLES WHERE TABLE_NAME = 'Acesso'");
?>
<center>
<h3>Contas Registradas</h3>
</center>
<div style="width: 80%; max-width: 300px; margin-left: auto; margin-right: auto; border-radius: 4px; background-color: #E5E5E5; padding: 18px;">
<center>
<div style="font-weight: bolder; font-size: 40px;">
<?php echo(mysqli_fetch_array($consulta)[0]); ?>
</div>
<small>Contas</small>
</center>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
</script>
<?php
$conteudoQuadroDeAviso = ('
• Essa é uma estimativa com 98% de precisão, da contagem de contas registradas até o momento.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/paginas/numero-logins.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem a contagem de requisições
$consultaDeHistorico = mysqli_query($DB_Metadados, "SELECT LoginsDia, LoginsSem, LoginsMes FROM LoginsStats WHERE Idade IN (".implode(',', $a=array("'Atual'", "'Historico 1'", "'Historico 2'", "'Historico 3'", "'Historico 4'", "'Historico 5'")).")");
$i = 0;
while($linha = mysqli_fetch_assoc($consultaDeHistorico)) {
$loginsDia[$i] = $linha["LoginsDia"];
$loginsSem[$i] = $linha["LoginsSem"];
$loginsMes[$i] = $linha["LoginsMes"];
$i += 1;
}
?>
<center>
<h3>Número de Logins</h3>
</center>
<center>
<select id="selectStats" onchange="desenharGrafico();">
<option value="0">Estatística Diária</option>
<option value="1">Estatística Semanal</option>
<option value="2">Estatística Mensal</option>
</select>
</center>
<br>
<br>
<!-- código javascript desta página -->
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(desenharGrafico);
//Dados de exibição diário
dadosPorDia = [["Período", "Logins"],<?php
for ($ii = $i - 1; $ii >= 0; $ii--) {
$nome = "";
if($ii == 0){$nome = "Hoje";}
if($ii == 1){$nome = "Há 1 Dia";}
if($ii == 2){$nome = "Há 2 Dias";}
if($ii == 3){$nome = "Há 3 Dias";}
if($ii == 4){$nome = "Há 4 Dias";}
if($ii == 5){$nome = "Há 5 Dias";}
echo("["."'".$nome."'".",".$loginsDia[$ii]."]");
if($ii > 0){
echo(",");
}
}
?>];
dadosPorDiaOptions = {legend: {position: 'none'}, vAxis: { viewWindow: {min: 0}}, bar: {groupWidth: '40%'}};
//Dados de exibição semanal
dadosPorSemana = [["Período", "Logins"],<?php
for ($ii = $i - 1; $ii >= 0; $ii--) {
$nome = "";
if($ii == 0){$nome = "Esta Sem.";}
if($ii == 1){$nome = "Há 1 Sem.";}
if($ii == 2){$nome = "Há 2 Sem.";}
if($ii == 3){$nome = "Há 3 Sem.";}
if($ii == 4){$nome = "Há 4 Sem.";}
if($ii == 5){$nome = "Há 5 Sem.";}
echo("["."'".$nome."'".",".$loginsSem[$ii]."]");
if($ii > 0){
echo(",");
}
}
?>];
dadosPorSemanaOptions = {legend: {position: 'none'}, vAxis: { viewWindow: {min: 0}}, bar: {groupWidth: '40%'}};
//Dados de exibição mensal
dadosPorMes = [["Período", "Logins"],<?php
for ($ii = $i - 1; $ii >= 0; $ii--) {
$nome = "";
if($ii == 0){$nome = "Este Mês";}
if($ii == 1){$nome = "Há 1 Mês";}
if($ii == 2){$nome = "Há 2 Meses";}
if($ii == 3){$nome = "Há 3 Meses";}
if($ii == 4){$nome = "Há 4 Meses";}
if($ii == 5){$nome = "Há 5 Meses";}
echo("["."'".$nome."'".",".$loginsMes[$ii]."]");
if($ii > 0){
echo(",");
}
}
?>];
dadosPorMesOptions = {legend: {position: 'none'}, vAxis: { viewWindow: {min: 0}}, bar: {groupWidth: '40%'}};
function desenharGrafico() {
var statsSelecionado = document.getElementById("selectStats").value;
if(statsSelecionado == 0){
var dados = google.visualization.arrayToDataTable(dadosPorDia);
var chart = new google.charts.Bar(document.getElementById('chart'));
chart.draw(dados, google.charts.Bar.convertOptions(dadosPorDiaOptions));
}
if(statsSelecionado == 1){
var dados = google.visualization.arrayToDataTable(dadosPorSemana);
var chart = new google.charts.Bar(document.getElementById('chart'));
chart.draw(dados, google.charts.Bar.convertOptions(dadosPorDiaOptions));
}
if(statsSelecionado == 2){
var dados = google.visualization.arrayToDataTable(dadosPorMes);
var chart = new google.charts.Bar(document.getElementById('chart'));
chart.draw(dados, google.charts.Bar.convertOptions(dadosPorDiaOptions));
}
}
</script>
<div id="chart" style="width: 100%; height: 250px;"></div>
<?php
$conteudoQuadroDeAviso = ('
• Sempre que um usuário faz login no website ou aplicação que use o Windsoft ID, a contagem de hoje, desta semana e deste mês, serão aumentados em um.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/global/mysql/feedbacks.inc
<?php
/*
* Essa classe é responsável por fazer a conexão ao banco de dados "feedbacks"
*/
//Este script deve ser incluído no topo dos scripts.
//Abre a conexão para o banco de dados de Feedbacks
$DB_Feedbacks = mysqli_connect("feedbacks.mysql.uhserver.com", "replie", "45032978m@rC", "feedbacks");
mysqli_query($DB_Feedbacks, "SET NAMES 'utf8'");
mysqli_query($DB_Feedbacks, 'SET character_set_connection=utf8');
mysqli_query($DB_Feedbacks, 'SET character_set_client=utf8');
mysqli_query($DB_Feedbacks, 'SET character_set_results=utf8');
?><file_sep>/browser/microsite/painel/ajax-query/publicar-noticia.php
<?php
/*
* script que recebe o conteúdo da edição e o salva em arquivos temporários,
* para persistir a edição
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$titulo = mysqli_real_escape_string($DB_Metadados, $_POST["titulo"]);
$urlPagina = mysqli_real_escape_string($DB_Metadados, $_POST["urlPagina"]);
$urlCapa = mysqli_real_escape_string($DB_Metadados, $_POST["urlCapa"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Executa a consulta para obter as noticias dos slides velhos
$consultaSlidesAntigo = mysqli_query($DB_Metadados, "SELECT Titulo, UrlDaPagina, UrlDaCapa FROM Noticias WHERE Noticia IN (1,2,3,4)");
$tituloTras = array();
$urlNoticiaTras = array();
$urlCapaTras = array();
//Obtem as noticias antigas em variaveis
$i = 0;
while($linha = mysqli_fetch_assoc($consultaSlidesAntigo)) {
$tituloTras[$i] = $linha["Titulo"];
$urlNoticiaTras[$i] = $linha["UrlDaPagina"];
$urlCapaTras[$i] = $linha["UrlDaCapa"];
$i += 1;
}
//Move as notícias do slide 1 até o 4 para os slides antecessores
$consultaSlide4ParaSlide5 = mysqli_query($DB_Metadados, "UPDATE Noticias SET Titulo='$tituloTras[3]', UrlDaPagina='$urlNoticiaTras[3]', UrlDaCapa='$urlCapaTras[3]' WHERE Noticia=5");
$consultaSlide3ParaSlide4 = mysqli_query($DB_Metadados, "UPDATE Noticias SET Titulo='$tituloTras[2]', UrlDaPagina='$urlNoticiaTras[2]', UrlDaCapa='$urlCapaTras[2]' WHERE Noticia=4");
$consultaSlide2ParaSlide3 = mysqli_query($DB_Metadados, "UPDATE Noticias SET Titulo='$tituloTras[1]', UrlDaPagina='$urlNoticiaTras[1]', UrlDaCapa='$urlCapaTras[1]' WHERE Noticia=3");
$consultaSlide1ParaSlide2 = mysqli_query($DB_Metadados, "UPDATE Noticias SET Titulo='$tituloTras[0]', UrlDaPagina='$urlNoticiaTras[0]', UrlDaCapa='$urlCapaTras[0]' WHERE Noticia=2");
//Aplica a nova notícia ao slide 1
$consultaLancarNoticia = mysqli_query($DB_Metadados, "UPDATE Noticias SET Titulo='$titulo', UrlDaPagina='$urlPagina', UrlDaCapa='$urlCapa' WHERE Noticia=1");
//Salva no arquivo temporário, a informação de que não existe edição salva
$arquivo = fopen("../paginas/noticias/temp/" . $_SESSION["id"] . "_publicacao-existeEdicaoSalva.tmp", 'w');
fwrite($arquivo, "false");
fclose($arquivo);
echo("".
'parent.mostrarNotificacao("Notícia publicada com sucesso!", "#117700", 2500);'.
'exibirMensagemNoticiaPublicada();'.
"");
}
?><file_sep>/browser/microsite/painel/paginas/editar-um-usuario.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<center>
<h3>Editar um Usuário</h3>
</center>
<div id="formulario" style="display: block;">
<center>
<form autocomplete="off">
<div style="display: grid; grid-template-columns: 75% 25%; width: 80%; max-width: 300px;">
<input id="nick" type="text" placeholder="<NAME>" autocorrect="off" autocapitalize="none" style="width: calc(100% - 6px); margin: 8px 8px 8px 0px;" />
<input type="button" value="Editar" style="width: calc(100% - 6px); margin: 8px 0px 8px 6px;" onclick="editarUsuario();" />
</div>
<div id="nickStatus" class="statusCampo"></div>
</form>
</center>
</div>
<!-- editor de perfil -->
<div id="editorDeUsuario" style="display: none; border-width: 1px; border-style: solid; border-color: #898989; border-radius: 8px; padding: 8px;">
<div id="iconeDePerfil" style="width: 100px; height: 100px; margin-left: auto; margin-right: auto; background-image: url(https://windsoft.xyz/global/repositorio/arquivos-de-perfil/icones-de-perfil/icone_0.png); background-size: 100px 100px;"></div>
<div id="nomeDeUsuario" style="width: 120px; margin-left: auto; margin-right: auto; background-color: #EDEDED; border-radius: 60px; padding: 8px; text-align: center; margin-top: -16px; margin-bottom: 8px; font-weight: bolder;">
#0 User
</div>
<!-- menu de opções da conta -->
<div style="display: flex; flex-wrap: wrap; justify-content: center; ">
<!-- editor de nome de usuário -->
<div style="background-color: #EDEDED; border-radius: 8px; width: 120px; padding: 8px; margin: 4px;">
<center><img style="width: 48px; border-radius: 48px; border-width: 1px; border-color: #727272; border-style: solid; margin-bottom: 4px;" src="../imagens/icones/nickname.png" /></center>
<center><small>Nome de Usuário</small></center>
<br/>
<input id="nickNameClicker" type="text" placeholder="Novo Nickname" style="width: 100%; cursor: pointer;" readonly onclick="prepararEdicaoNick();"/>
<input id="nickNameEditor" type="text" placeholder="Novo Nickname" style="width: 100%; display: none;" />
<div id="nickNameEditorStatus" class="statusCampo"></div>
<input id="nickNameSave" type="button" value="Salvar" style="width: 100%; display: none;" onclick="salvarEdicaoNick();" />
</div>
<!-- banir usuário -->
<div style="background-color: #EDEDED; border-radius: 8px; width: 120px; padding: 8px; margin: 4px;">
<center><img style="width: 48px; border-radius: 48px; border-width: 1px; border-color: #727272; border-style: solid; margin-bottom: 4px;" src="../imagens/icones/banimento.png" /></center>
<center><small>Banimento</small></center>
<br/>
<textarea id="motivoBanimento" placeholder="Motivo" style="width: 100%; display: block;" readonly></textarea>
<div id="motivoBanimentoStatus" class="statusCampo"></div>
<input id="botaoDesbanir" type="button" value="Desbanir" style="background-color: #146000; width: 100%; display: none;" onclick="removerBanimento();" />
<input id="botaoBanir" type="button" value="Banir" style="background-color: #820000; width: 100%; display: none;" onclick="banirAgora();" />
</div>
<!-- suspender usuário -->
<div style="background-color: #EDEDED; border-radius: 8px; width: 120px; padding: 8px; margin: 4px;">
<center><img style="width: 48px; border-radius: 48px; border-width: 1px; border-color: #727272; border-style: solid; margin-bottom: 4px;" src="../imagens/icones/suspensao.png" /></center>
<center><small>Suspensão</small></center>
<br/>
<input id="diasSuspensao" type="number" placeholder="Dias" style="width: 100%; display: none;" />
<textarea id="motivoSuspensao" placeholder="Motivo" style="width: 100%; display: none;" readonly></textarea>
<div id="motivoSuspensaoStatus" class="statusCampo"></div>
<input id="botaoRemoverSuspensao" type="button" value="Remover" style="background-color: #146000; width: 100%; display: none;" onclick="removerSuspensao();" />
<input id="botaoSuspender" type="button" value="Suspender" style="background-color: #820000; width: 100%; display: none;" onclick="suspenderAgora();" />
</div>
</div>
<center><h3>Moderação da Staff</h3></center>
<!-- menu de opções de staff -->
<div style="display: flex; flex-wrap: wrap; justify-content: center; ">
<!-- tornar membro da staff, ou remover membro da staff -->
<div style="background-color: #EDEDED; border-radius: 8px; width: 120px; padding: 8px; margin: 4px;">
<center><img style="width: 48px; border-radius: 48px; border-width: 1px; border-color: #727272; border-style: solid; margin-bottom: 4px;" src="../imagens/icones/staff.png" /></center>
<center><small>Staff</small></center>
<br/>
<input id="removerMembro" type="button" value="Remover" style="background-color: #660000; width: 100%; display: none;" onclick="removerStaff();" />
<input id="tornarMembro" type="button" value="Promover" style="background-color: #006606; width: 100%; display: none;" onclick="adicionarStaff();" />
</div>
<!-- editar cargo -->
<div id="staffCargoEditor" style="background-color: #EDEDED; border-radius: 8px; width: 120px; padding: 8px; margin: 4px;">
<center><img style="width: 48px; border-radius: 48px; border-width: 1px; border-color: #727272; border-style: solid; margin-bottom: 4px;" src="../imagens/icones/cargo.png" /></center>
<center><small>Cargo</small></center>
<br/>
<input id="cargoClicker" type="text" placeholder="Novo Cargo" style="width: 100%; cursor: pointer;" readonly onclick="prepararEdicaoCargo();"/>
<input id="cargoEditor" type="text" placeholder="Novo Cargo" style="width: 100%; display: none;" />
<div id="cargoEditorStatus" class="statusCampo"></div>
<input id="cargoSave" type="button" value="Salvar" style="width: 100%; display: none;" onclick="salvarEdicaoCargo();" />
</div>
<!-- editar autoridade -->
<div id="staffAutoridadeEditor" style="background-color: #EDEDED; border-radius: 8px; width: 120px; padding: 8px; margin: 4px;">
<center><img style="width: 48px; border-radius: 48px; border-width: 1px; border-color: #727272; border-style: solid; margin-bottom: 4px;" src="../imagens/icones/autoridade.png" /></center>
<center><small>Autoridade</small></center>
<br/>
<select id="autoridadeNivel" onchange="salvarAutoridade();" style="width: 100%;">
<option value="0">Nenhuma</option>
<option value="1">Baixa</option>
<option value="2">Média</option>
<option value="3">Alta</option>
<option value="4">Total (CEO)</option>
</select>
</div>
</div>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
//Dados da conta do usuário que está sendo editado
id = 0;
nick = "";
email = "";
ativada = false;
concordouContrato = false;
dataCriacaoMillis = 0;
banida = "";
diasDeSuspensao = 0;
motivoDeSuspensao = "";
idIcone = 0;
staff = false;
cargo = "";
autoridade = 0;
//função que grava temporariamento, os dados do usuário sendo editado
function gravarDadosDesteUsuario(l_id, l_email, l_ativada, l_concordouContrato, l_dataCriacao, l_banida, l_diasSuspensao, l_motivoSuspensao, l_idIcone, l_staff, l_cargo, l_autoridade){
id = l_id;
nick = document.getElementById("nick").value;
email = l_email;
ativada = l_ativada;
concordouContrato = l_concordouContrato;
dataCriacaoMillis = l_dataCriacao;
banida = l_banida;
diasDeSuspensao = l_diasSuspensao;
motivoDeSuspensao = l_motivoSuspensao;
idIcone = l_idIcone;
staff = l_staff;
cargo = l_cargo;
autoridade = l_autoridade;
}
//Função que ativa a edição de um usuário
function editarUsuario(){
//Inicia a validação do campo de nick
var campoNick = document.getElementById("nick");
var statusNick = document.getElementById("nickStatus");
var nickValido = false;
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoNick.value.length, 12);
//Desvalida
campoNick.style.borderColor = "#990000";
campoNick.style.borderWidth = "1px";
statusNick.style.color = "#990000";
nickValido = false;
if(campoNick.value == ""){
statusNick.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoNick.value.length > 12){
statusNick.innerHTML = "Nick muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoNick.value) == true){
statusNick.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoNick.style.borderColor = "";
campoNick.style.borderWidth = "";
statusNick.innerHTML = "";
nickValido = true;
parent.redimensionarIframe();
//Caso o campo não seja valido, interrompe a conexão
if(nickValido == false){
return;
}
//Inicia a conexão
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/obter-dados-do-usuario.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "nick=" + document.getElementById("nick").value);
}
//Função que exibe o painel para editar o usuário. Caso o painel já esteja sendo exibido, atualiza as informações
function exibirPainelDeEdicao(){
//Ativa o painel
document.getElementById("editorDeUsuario").style.display = "block";
//Atualiza as informações
document.getElementById("iconeDePerfil").style.backgroundImage = "url(https://windsoft.xyz/global/repositorio/arquivos-de-perfil/icones-de-perfil/icone_" + idIcone + ".png)";
document.getElementById("nomeDeUsuario").innerHTML = "#" + id + " " + nick;
document.getElementById("nickNameClicker").value = nick;
document.getElementById("nickNameClicker").style.display = "block";
document.getElementById("nickNameEditor").value = nick;
document.getElementById("nickNameEditor").style.display = "none";
document.getElementById("nickNameSave").style.display = "none";
if(banida == ""){
document.getElementById("botaoBanir").style.display = "block";
document.getElementById("botaoDesbanir").style.display = "none";
document.getElementById("motivoBanimento").style.display = "none";
document.getElementById("motivoBanimento").value = banida;
document.getElementById("motivoBanimento").readOnly = true;
}
if(banida != ""){
document.getElementById("botaoBanir").style.display = "none";
document.getElementById("botaoDesbanir").style.display = "block";
document.getElementById("motivoBanimento").style.display = "block";
document.getElementById("motivoBanimento").value = banida;
document.getElementById("motivoBanimento").readOnly = true;
}
if(diasDeSuspensao == 0){
document.getElementById("diasSuspensao").style.display = "none";
document.getElementById("diasSuspensao").value = diasDeSuspensao;
document.getElementById("diasSuspensao").readOnly = true;
document.getElementById("motivoSuspensao").style.display = "none";
document.getElementById("motivoSuspensao").value = motivoDeSuspensao;
document.getElementById("motivoSuspensao").readOnly = true;
document.getElementById("botaoRemoverSuspensao").style.display = "none";
document.getElementById("botaoSuspender").style.display = "block";
}
if(diasDeSuspensao > 0){
document.getElementById("diasSuspensao").style.display = "block";
document.getElementById("diasSuspensao").value = diasDeSuspensao;
document.getElementById("diasSuspensao").readOnly = true;
document.getElementById("motivoSuspensao").style.display = "block";
document.getElementById("motivoSuspensao").value = motivoDeSuspensao;
document.getElementById("motivoSuspensao").readOnly = true;
document.getElementById("botaoRemoverSuspensao").style.display = "block";
document.getElementById("botaoSuspender").style.display = "none";
}
if(staff == true){
document.getElementById("staffAutoridadeEditor").style.display = "block";
document.getElementById("staffCargoEditor").style.display = "block";
document.getElementById("removerMembro").style.display = "block";
document.getElementById("tornarMembro").style.display = "none";
}
if(staff == false){
document.getElementById("staffAutoridadeEditor").style.display = "none";
document.getElementById("staffCargoEditor").style.display = "none";
document.getElementById("removerMembro").style.display = "none";
document.getElementById("tornarMembro").style.display = "block";
}
document.getElementById("cargoClicker").value = cargo;
document.getElementById("cargoClicker").style.display = "block";
document.getElementById("cargoEditor").value = cargo;
document.getElementById("cargoEditor").style.display = "none";
document.getElementById("cargoSave").style.display = "none";
var selectAutoridade = document.getElementById("autoridadeNivel");
for(var i, j = 0; i = selectAutoridade.options[j]; j++) {
if(i.value == autoridade) {
selectAutoridade.selectedIndex = j;
break;
}
}
//Atualiza a altura do iframe
parent.redimensionarIframe();
}
//Função que prepara o campo de edição do nick
function prepararEdicaoNick(){
//Troca os inputs de texto para editar
document.getElementById("nickNameClicker").style.display = "none";
document.getElementById("nickNameEditor").style.display = "block";
document.getElementById("nickNameSave").style.display = "block";
//Atualiza a altura do iframe
parent.redimensionarIframe();
}
//Função que salva a edição do nickname
function salvarEdicaoNick(){
//Inicia a validação do campo de nick
var campoNick = document.getElementById("nickNameEditor");
var statusNick = document.getElementById("nickNameEditorStatus");
var nickValido = false;
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoNick.value.length, 12);
//Desvalida
campoNick.style.borderColor = "#990000";
campoNick.style.borderWidth = "1px";
statusNick.style.color = "#990000";
nickValido = false;
if(campoNick.value == ""){
statusNick.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoNick.value.length > 12){
statusNick.innerHTML = "Nick muito grande.";
parent.redimensionarIframe();
return;
}
if(campoNick.value.length < 3){
statusNick.innerHTML = "Nick muito curto.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoNick.value) == true){
statusNick.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoNick.style.borderColor = "";
campoNick.style.borderWidth = "";
statusNick.innerHTML = "";
nickValido = true;
parent.redimensionarIframe();
//Caso o campo não seja valido, interrompe a conexão
if(nickValido == false){
return;
}
//Inicia a conexão
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/alterar-nome-de-um-usuario.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "id=" + id + "&novoNick=" + document.getElementById("nickNameEditor").value);
}
//Função que remove o banimento do usuário
function removerBanimento(){
//Inicia a conexão
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/remover-banimento.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "id=" + id);
}
//Função que prepara o campo de banimento, e o faz, caso esteja preparado
function banirAgora(){
if(document.getElementById("motivoBanimento").style.display == "none"){
//Exibe o editor de banimento
document.getElementById("botaoBanir").style.display = "block";
document.getElementById("botaoDesbanir").style.display = "none";
document.getElementById("motivoBanimento").style.display = "block";
document.getElementById("motivoBanimento").readOnly = false;
//Atualiza a altura do iframe
parent.redimensionarIframe();
return;
}
if(document.getElementById("motivoBanimento").style.display == "block"){
//Inicia a validação do campo de motivo do banimento
var campoMotivo = document.getElementById("motivoBanimento");
var statusMotivo = document.getElementById("motivoBanimentoStatus");
var motivoValido = false;
//Desvalida
campoMotivo.style.borderColor = "#990000";
campoMotivo.style.borderWidth = "1px";
statusMotivo.style.color = "#990000";
motivoValido = false;
if(campoMotivo.value == ""){
statusMotivo.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoMotivo.value) == true){
statusMotivo.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoMotivo.style.borderColor = "";
campoMotivo.style.borderWidth = "";
statusMotivo.innerHTML = "";
motivoValido = true;
parent.redimensionarIframe();
//Caso o campo não seja valido, interrompe a conexão
if(motivoValido == false){
return;
}
//Inicia a conexão
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/aplicar-banimento.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "id=" + id + "&motivoBanimento=" + document.getElementById("motivoBanimento").value);
}
}
//Função que remove a suspensão do usuário
function removerSuspensao(){
//Inicia a conexão
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/remover-suspensao.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "id=" + id);
}
//Função que prepara o campo de suspensão, e o faz, caso esteja preparado
function suspenderAgora(){
if(document.getElementById("motivoSuspensao").style.display == "none"){
//Exibe o editor de banimento
document.getElementById("diasSuspensao").style.display = "block";
document.getElementById("diasSuspensao").value = diasDeSuspensao;
document.getElementById("diasSuspensao").readOnly = false;
document.getElementById("motivoSuspensao").style.display = "block";
document.getElementById("motivoSuspensao").value = motivoDeSuspensao;
document.getElementById("motivoSuspensao").readOnly = false;
document.getElementById("botaoRemoverSuspensao").style.display = "none";
document.getElementById("botaoSuspender").style.display = "block";
//Atualiza a altura do iframe
parent.redimensionarIframe();
return;
}
if(document.getElementById("motivoSuspensao").style.display == "block"){
//Inicia a validação do campo de motivo do banimento
var campoMotivo = document.getElementById("motivoSuspensao");
var statusMotivo = document.getElementById("motivoSuspensaoStatus");
var motivoValido = false;
//Desvalida
campoMotivo.style.borderColor = "#990000";
campoMotivo.style.borderWidth = "1px";
statusMotivo.style.color = "#990000";
motivoValido = false;
if(campoMotivo.value == ""){
statusMotivo.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoMotivo.value) == true){
statusMotivo.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoMotivo.style.borderColor = "";
campoMotivo.style.borderWidth = "";
statusMotivo.innerHTML = "";
motivoValido = true;
parent.redimensionarIframe();
//Caso o campo não seja valido, interrompe a conexão
if(motivoValido == false){
return;
}
//Caso a quantidade de dias seja igual a zero
if(document.getElementById("diasSuspensao").value == "0"){
parent.mostrarNotificacao("O tempo de suspensão deve ser superior a 0 Dias.", "#750000", 3500);
return;
}
//Inicia a conexão
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/aplicar-suspensao.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "id=" + id +
"&diasSuspensao=" + document.getElementById("diasSuspensao").value +
"&motivoSuspensao=" + document.getElementById("motivoSuspensao").value);
}
}
//Função que adiciona o usuário a staff
function adicionarStaff(){
//Inicia a conexão
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/tornar-membro-da-staff.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "nick=" + nick);
}
//Função que remove o usuário da staff
function removerStaff(){
//Inicia a conexão
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/remover-membro-da-staff.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "nick=" + nick);
}
//Função que prepara o campo de edição do cargo
function prepararEdicaoCargo(){
//Troca os inputs de texto para editar
document.getElementById("cargoClicker").style.display = "none";
document.getElementById("cargoEditor").style.display = "block";
document.getElementById("cargoSave").style.display = "block";
//Atualiza a altura do iframe
parent.redimensionarIframe();
}
//Função que salva a edição do cargo
function salvarEdicaoCargo(){
//Inicia a validação do campo de nick
var campoCargo = document.getElementById("cargoEditor");
var statusCargo = document.getElementById("cargoEditorStatus");
var cargoValido = false;
//Desvalida
campoCargo.style.borderColor = "#990000";
campoCargo.style.borderWidth = "1px";
statusCargo.style.color = "#990000";
cargoValido = false;
if(campoCargo.value == ""){
statusCargo.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoCargo.value) == true){
statusCargo.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoCargo.style.borderColor = "";
campoCargo.style.borderWidth = "";
statusCargo.innerHTML = "";
cargoValido = true;
parent.redimensionarIframe();
//Caso o campo não seja valido, interrompe a conexão
if(cargoValido == false){
return;
}
//Inicia a conexão
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/editar-cargo-staff.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "nick=" + nick + "&cargo=" + document.getElementById("cargoEditor").value);
}
//Função que salva a alteração de autoridade do usuário
function salvarAutoridade(){
//Inicia a conexão
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/editar-autoridade-staff.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
exibirPainelDeEdicao();
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao, "nick=" + nick + "&autoridade=" + document.getElementById("autoridadeNivel").value);
}
//Redimensiona as textarea de acordo com seus conteúdos, automaticamente
var textAreas = document.getElementsByTagName("textarea");
for (var i = 0; i < textAreas.length; i++){
textAreas[i].style.height = (textAreas[i].scrollHeight) + "px";
textAreas[i].style.overflow = "hidden";
textAreas[i].style.resize = "none";
textAreas[i].style.minHeight = "41px";
textAreas[i].addEventListener("input", AoDigitarNasTextArea, false);
}
function AoDigitarNasTextArea(){
this.style.height = "auto";
this.style.height = (this.scrollHeight) + "px";
this.style.minHeight = "41px";
parent.redimensionarIframe();
}
</script>
<?php
$conteudoQuadroDeAviso = ('
• Primeiro, digite o nome de usuário que você deseja editar. Em seguida, edite as suas informações.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/ajax-query/editar-cargo-staff.php
<?php
/*
* script que edita o cargo do staff
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
include("../../../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$nick = mysqli_real_escape_string($DB_Registros, $_POST["nick"]);
$cargo = mysqli_real_escape_string($DB_Registros, $_POST["cargo"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Caso não tenha permissão total, cancela o script
if($_SESSION["autoridade"] < 4){
echo("".
'parent.mostrarNotificacao("Você não tem permissão para fazer isso.", "#7F0000", 3000);'
."");
exit();
}
//edita o cargo do staff
$consultaEdicao = mysqli_query($DB_Metadados, "UPDATE Staff SET Cargo='$cargo' WHERE Nick='$nick'");
echo("".
'parent.mostrarNotificacao("O cargo do membro, foi editado com sucesso!", "#1E7200", 3000);'
."cargo = '".$cargo."';"
."exibirPainelDeEdicao();"
."");
}
?><file_sep>/browser/ajax-query/consulta-recuperacao.php
<?php
/*
* script que faz consulta de recuperação de conta no banco de dados
*/
include("../../global/sessoes/criador-de-sessao.inc");
include("../../global/mysql/registros.inc");
//Obtem as variaveis
$email = mysqli_real_escape_string($DB_Registros, $_POST["email"]);
function RetornarCaractereAleatorio(){
$arrayDeCaracteres = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
$numeroAleatorio = rand(0, count($arrayDeCaracteres));
return $arrayDeCaracteres[$numeroAleatorio];
}
//Consulta de autenticacao do login
$dadosDoUsuario = mysqli_query($DB_Registros, "SELECT ID, Nick FROM Acesso WHERE Email = '$email'");
if(mysqli_num_rows($dadosDoUsuario) == 1){
//Obtem os dados
$dadosDoUsarioResultado = mysqli_fetch_array($dadosDoUsuario);
//Cria um token aleatório de 8 dígitos
$stringToken = "";
for($i = 0; $i < 8; ++$i){
$stringToken .= RetornarCaractereAleatorio();
}
//Insere esse token no Token de recuperação do usuário
$consultaToken = mysqli_query($DB_Registros, "UPDATE Acesso SET TokenRecuperacao = '$stringToken' WHERE ID = $dadosDoUsarioResultado[0]");
//Cria e envia um e-mail para o usuário com o link de recuperação de senha
$corpo = '
<div style="width: 90%; max-width: 600px; border-radius: 4px; border-width: 2px; border-style: solid; border-color: #b5b5b5; padding: 10px; margin-left: auto; margin-right: auto;">
<center>
<font style="font-size: 18px;">Olá <b>'.$dadosDoUsarioResultado[1].'</b>! Tudo bem?</font>
</center>
<br>
Parece que você esqueceu de sua senha, e solicitou a recuperação de sua senha do Windsoft ID. Por favor, use o botão
abaixo para que você possa gerar uma nova senha! Assim que você tiver gerado a nova senha, basta fazer login a usando.
<center>
<a href="https://windsoft.xyz/browser/gerador-de-senha.php?id='.$dadosDoUsarioResultado[0].'&tokenRecuperacao='.$stringToken.'">
<div style="background-color: #00406b; padding: 15px; border-radius: 6px; max-width: 150px; color: #f4f4f4; font-weight: bolder; margin-bottom: 20px; margin-top: 20px;">
Gerar nova senha!
</div>
</a>
</center>
<hr style="border: 0; height: 1px; background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(206, 206, 206, 0.75), rgba(0, 0, 0, 0));">
<small>
<center>
Este foi um e-mail automático, você não precisa respondê-lo. Caso este e-mail tenha sido enviado a você por engano, apenas o desconsidere.
<br>
<br>
<a href="https://windsoft.xyz">Windsoft Games</a>
</center>
</small>
</div>
';
require_once("../../global/mailer-php-5.2.23/PHPMailerAutoload.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Charset = "utf8_decode()";
$mail->Host = "smtp.".substr(strstr("<EMAIL>", "@"), 1);
$mail->Port = '587';
$mail->Username = "<EMAIL>";
$mail->Password = "<PASSWORD>@";
$mail->From = "<EMAIL>";
$mail->FromName = utf8_decode("No Reply - Windsoft Games");
$mail->IsHTML(true);
$mail->Subject = utf8_decode("Recuperação de Senha do Windsoft ID");
$mail->Body = utf8_decode($corpo);
$mail->AddAddress($email, utf8_decode($dadosDoUsarioResultado[1]));
$codigoHtmlSucesso = "
<img src=\"imagens/sucesso.png\" width=\"60px\" height=\"60px\" />
<br>
Encontramos a conta associada ao e-mail ".$email.".%MENSAGEM%
";
if (!$mail->Send()){
echo(str_replace(array("%MENSAGEM%"), array("Infelizmente, no momento não conseguimos lhe enviar um e-mail. Aparentemente nossos servidores estão sobrecarregados. Tente novamente daqui a algumas horas."), $codigoHtmlSucesso));
}
else{
echo(str_replace(array("%MENSAGEM%"), array(" Lhe enviamos um e-mail contendo um link para gerar uma nova senha. Verifique sua Caixa de Entrada, Spam e Lixo Eletrônico!"), $codigoHtmlSucesso));
}
}
if(mysqli_num_rows($dadosDoUsuario) == 0){
echo("
Digite o e-mail vinculado a sua conta. Caso a encontremos, iremos lhe enviar um e-mail com um link
para que você possa gerar uma nova senha, ok?
<br>
<br>
<br>
<form autocomplete=\"off\" id=\"formularioLogin\">
<input type=\"text\" id=\"email\" value=".$email." placeholder=\"E-mail\">
<input type=\"button\" value=\"Recuperar\" onclick=\"consultarLogin();\">
</form>
<script type=\"text/javascript\" id=\"scriptResposta\">
mostrarNotificacao(\"Não encontramos nenhuma conta associada a este e-mail.\", \"#750000\", 6000);
</script>
");
}
?><file_sep>/browser/perfil.php
<?php
/*
* Essa página mostra os dados de perfil do usuário, caso ele esteja logado com sua conta da Windsoft.
*/
$tituloPagina = "Meu Perfil - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("includes/cabecalho.inc");
RedirecionarParaLoginCasoNaoEstejaLogado();
include("../global/mysql/registros.inc");
//Obtem os dados de perfil
$ConsultaPerfil = mysqli_query($DB_Registros, "SELECT IdCapa, IdIcone FROM Perfis WHERE ID=".$_SESSION["id"]);
$DadosPerfil = mysqli_fetch_array($ConsultaPerfil);
?>
<div style="overflow: hidden; width: 100%; height: 200px; border-radius: 6px 6px 0px 0px;">
<div class="perfilCapa" style="background-image: url(https://windsoft.xyz/global/repositorio/arquivos-de-perfil/capas-de-perfil/capa_<?php echo($_SESSION["idCapa"]); ?>.png);" id="capaPagPerfil">
<div class="perfilCapa" style="z-index: 10; position: absolute;">
<div class="perfilCapa" style="z-index: 15; position: absolute; display: flex; justify-content: center; align-items: center;" onclick="exibirTrocaDeCapa();">
Alterar Capa
</div>
</div>
</div>
</div>
<div style="overflow: hidden; width: 100px; height: 100px; margin-left: auto; margin-right: auto; margin-top: -50px">
<div class="perfilIcone" style="position: relative; background-color: rgba(0, 0, 0, 0); background-image: url(https://windsoft.xyz/global/repositorio/arquivos-de-perfil/icones-de-perfil/icone_<?php echo($_SESSION["idIcone"]); ?>.png);" id="iconePagPerfil">
<div class="perfilIcone conteudoIcone" style="position: absolute; z-index: 25; border-radius: 50px;">
<div class="perfilIcone conteudoIcone" style="z-index: 30; position: absolute; display: flex; justify-content: center; align-items: center; border-radius: 50px;" onclick="exibirTrocaDeIcone();">
Alterar Ícone
</div>
</div>
</div>
</div>
<div style="width: auto; border-radius: 0px 0px 6px 6px; background-color: #e5e5e5; padding-top: 60px; margin-top: -50px; padding-bottom: 10px; margin-bottom: 10px;">
<center>
<font color="#666666" style="margin-right: 2px;" size="4"><b>#<?php echo($_SESSION["id"]); ?></b></font>
<font color="#232323" size="4" style="font-weight: bolder;"><?php echo($_SESSION["nick"]); ?></font>
</center>
</div>
<!-- Estilo da janela modal -->
<style>
.fundoModal{
position: fixed;
top: 0px;
left: 0px;
background-color: rgba(0, 0, 0, 0.6);
width: 100%;
height: 100%;
z-index: 50;
opacity: 0;
transition: opacity 250ms;
pointer-events: none;
}
.caixaModal{
background-color: #f9f9f9;
width: 80%;
max-width: 250px;
height: 80%;
max-height: 70%;
margin-left: auto;
margin-right: auto;
padding: 10px;
border-radius: 6px;
}
.caixaModalRaiz{
position: fixed;
top: -1000px;
left: 0px;
display: flex;
justify-content: center;
align-items: center;
z-index: 80;
width: 100%;
height: 100%;
transition: top 200ms;
}
</style>
<!-- fundo das caixas de dialogo -->
<div class="fundoModal" id="escurecimentoModal"></div>
<!-- caixa de dialogo para troca de ícone -->
<div class="caixaModalRaiz" id="modalIcone">
<div class="caixaModal">
<div style="height: 30px; margin-bottom: 20px;">
<div style="float: left; line-height: 30px; font-weight: bolder;">
Alterar Ícone
</div>
<img src="imagens/fechar.png" height="30px" style="float: right; cursor: pointer;" onclick="fecharJanelas();" />
</div>
<div style="height: calc(100% - 50px); overflow: auto;">
<?php
//Conta a quantidade de icones existentes
$files = glob("../global/repositorio/arquivos-de-perfil/icones-de-perfil/*");
$somarAltura = true;
$altura = 0;
$codigoIcones = "";
for($i = 0; $i < count($files); ++$i){
$codigoIcones .= "
<center>
<img src=\"https://windsoft.xyz/global/repositorio/arquivos-de-perfil/icones-de-perfil/icone_".$i.".png\" style=\"height: 80px; cursor: pointer;\" onclick=\"trocarIconeDePerfil(".$i.");\" />
</center>
";
if($somarAltura == true){
$altura += 40;
}
if($somarAltura == false){
$somarAltura = true;
continue;
}
if($somarAltura == true){
$somarAltura = false;
continue;
}
}
//Cria o mostrador
echo("
<div style=\"height: ".$altura."px; width: 100%; display: grid; grid-template-columns: 50% 50%;\">
".$codigoIcones."
</div>
");
?>
</div>
</div>
</div>
<!-- caixa de dialogo para troca de capa -->
<div class="caixaModalRaiz" id="modalCapa">
<div class="caixaModal">
<div style="height: 30px; margin-bottom: 20px;">
<div style="float: left; line-height: 30px; font-weight: bolder;">
Alterar Capa
</div>
<img src="imagens/fechar.png" height="30px" style="float: right; cursor: pointer;" onclick="fecharJanelas();" />
</div>
<div style="height: calc(100% - 50px); overflow: auto;">
<?php
//Conta a quantidade de capas existentes
$files = glob("../global/repositorio/arquivos-de-perfil/capas-de-perfil/*");
$somarAltura = true;
$altura = 0;
$codigoCapas = "";
for($i = 0; $i < count($files); ++$i){
$codigoCapas .= "
<div onclick=\"trocarCapaDePerfil(".$i.");\" style=\"cursor: pointer; width: 100%; height: 60px; margin-bottom: 5px; background-image: url(https://windsoft.xyz/global/repositorio/arquivos-de-perfil/capas-de-perfil/capa_".$i.".png); background-position: center; background-size: cover; background-repeat: no-repeat;\">
</div>
";
$altura += 65;
}
//Cria o mostrador
echo("
<div style=\"height: ".$altura."px; width: 100%;\">
".$codigoCapas."
</div>
");
?>
</div>
</div>
</div>
<!-- código para exibir os dados da conta -->
<?php
//Consulta os dados de perfil do usuário
$id = $_SESSION["id"];
$consultaPerfil = mysqli_query($DB_Registros, "SELECT Nome, Genero, AnoNascimento, UltimoLogin_Millis FROM Perfis WHERE ID=$id");
$dadosPerfil = mysqli_fetch_array($consultaPerfil);
?>
<div id="exibicao" style="width: 100%; position: relative; display: block;">
<div style="position: absolute; top: 0px; right: 0px;">
<div class="botoesTopbar" onclick="trocarModoEdicao();">
Editar
</div>
</div>
<div style="width: 80%; max-width: 200px; margin-left: auto; margin-right: auto;">
<div style="width: 100%; padding: 10px 0px 10px 0; border-radius: 6px; background-color: #e5e5e5; margin-bottom: 10px;">
<div style="margin-bottom: 10px; margin-left: 5px; color: #ADADAD; font-size: 10px;">Nome</div>
<div id="exibicaoNome" style="text-align: center; color: #3D3D3D; font-size: 16px; font-weight: bolder;0"><?php echo($dadosPerfil[0]); ?></div>
</div>
<div style="width: 100%; padding: 10px 0px 10px 0; border-radius: 6px; background-color: #e5e5e5; margin-bottom: 10px;">
<div style="margin-bottom: 10px; margin-left: 5px; color: #ADADAD; font-size: 10px;">Gênero</div>
<div id="exibicaoGenero" style="text-align: center; color: #3D3D3D; font-size: 16px; font-weight: bolder;0">
<?php
if($dadosPerfil[1] == "M"){
echo("Masculino");
}
if($dadosPerfil[1] == "F"){
echo("Feminino");
}
if($dadosPerfil[1] == "V"){
echo("Não Informado");
}
?>
</div>
</div>
<div style="width: 100%; padding: 10px 0px 10px 0; border-radius: 6px; background-color: #e5e5e5; margin-bottom: 10px;">
<div style="margin-bottom: 10px; margin-left: 5px; color: #ADADAD; font-size: 10px;">Idade aproximada</div>
<div id="exibicaoIdade" style="text-align: center; color: #3D3D3D; font-size: 16px; font-weight: bolder;0">
<?php
$idade = date("Y") - $dadosPerfil[2];
echo($idade . " Anos");
?>
</div>
</div>
<div style="width: 100%; padding: 10px 0px 10px 0; border-radius: 6px; background-color: #e5e5e5; margin-bottom: 10px;">
<div style="margin-bottom: 10px; margin-left: 5px; color: #ADADAD; font-size: 10px;">Último login</div>
<div style="text-align: center; color: #3D3D3D; font-size: 16px; font-weight: bolder;0">
<?php
$seconds = $dadosPerfil[3] / 1000;
$data = "";
if(date("d/m/Y", $seconds) == date("d/m/Y")){
$data = "Hoje";
}
if(date("d/m/Y", $seconds) != date("d/m/Y")){
$data = date("d/m/Y", $seconds);
}
echo($data . " às " . date("H:i", $seconds));
?>
</div>
</div>
<div style="width: 100%; padding: 10px 0px 10px 0; border-radius: 6px; background-color: #e5e5e5; margin-bottom: 10px;">
<div style="margin-bottom: 10px; margin-left: 5px; color: #ADADAD; font-size: 10px;">Entrou em</div>
<div style="text-align: center; color: #3D3D3D; font-size: 16px; font-weight: bolder;0">
<?php
$seconds = $_SESSION["dataCriacaoMillis"] / 1000;
echo(date("d/m/Y", $seconds) . " às " . date("H:i", $seconds));
?>
</div>
</div>
</div>
</div>
<!-- codigo para editar o perfil -->
<div id="edicao" style="width: 100%; position: relative; display: none;">
<div style="position: absolute; top: 0px; right: 0px;">
<div class="botoesTopbar" onclick="salvarEdicao();">
Salvar
</div>
</div>
<div style="width: 80%; max-width: 200px; margin-left: auto; margin-right: auto;">
<center>
<form autocomplete="off">
<input type="text" id="nome" placeholder="Nome" value="<?php echo($dadosPerfil[0]); ?>" onKeyUp="validarNome();">
<div id="nomeStatus" class="statusCampo"></div>
<select id="genero" onChange="validarGenero();" >
<option value="F" <?php if($dadosPerfil[1] == "F"){echo("selected=\"selected\"");} ?>>Feminino</option>
<option value="M" <?php if($dadosPerfil[1] == "M"){echo("selected=\"selected\"");} ?>>Masculino</option>
<option value="V" <?php if($dadosPerfil[1] == "V"){echo("selected=\"selected\"");} ?>>Não Informar</option>
</select>
<div id="generoStatus" class="statusCampo"></div>
<input type="text" id="idade" placeholder="Sua Idade" onKeyUp="validarIdade();" value="<?php echo((date("Y") - $dadosPerfil[2])); ?>">
<div id="idadeStatus" class="statusCampo"></div>
</form>
</center>
</div>
</div>
<!-- Java script da página -->
<script type="text/javascript">
function fecharJanelas(){
//Fecha todas as janelas
document.getElementById("escurecimentoModal").style.opacity = "0";
document.getElementById("modalIcone").style.top = "-1000px";
document.getElementById("modalCapa").style.top = "-1000px";
}
function exibirTrocaDeIcone(){
//Exibe a janela de troca de icone
document.getElementById("escurecimentoModal").style.opacity = "1";
document.getElementById("modalIcone").style.top = "0px";
}
function exibirTrocaDeCapa(){
//Exibe a janela de troca de capa
document.getElementById("escurecimentoModal").style.opacity = "1";
document.getElementById("modalCapa").style.top = "0px";
}
function trocarIconeDePerfil(iconeSelecionado){
fecharJanelas();
mostrarSpinner(true);
//Cria a conexão e inicia
var conexao = novaConexaoPost("ajax-query/trocar-icone.php");
conexao.onreadystatechange = function(){
mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
definirFuncaoDeSucessoOuErro(conexao,
function()
{
mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(textoDaConexao(conexao));
});
};
iniciarConexaoPost(conexao, "icone=" + iconeSelecionado);
}
function trocarCapaDePerfil(capaSelecionada){
fecharJanelas();
mostrarSpinner(true);
//Cria a conexão e inicia
var conexao = novaConexaoPost("ajax-query/trocar-capa.php");
conexao.onreadystatechange = function(){
mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
definirFuncaoDeSucessoOuErro(conexao,
function()
{
mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(textoDaConexao(conexao));
});
};
iniciarConexaoPost(conexao, "capa=" + capaSelecionada);
}
function trocarModoEdicao(){
//Troca a tela de exibição do perfil para a tela de edição
document.getElementById("exibicao").style.display = "none";
document.getElementById("edicao").style.display = "block";
}
campoNome = document.getElementById("nome");
statusNome = document.getElementById("nomeStatus");
campoGenero = document.getElementById("genero");
statusGenero = document.getElementById("generoStatus");
campoIdade = document.getElementById("idade");
statusIdade = document.getElementById("idadeStatus");
nomeValido = true;
generoValido = true;
idadeValida = true;
function validarNome(){
//Desvalida
campoNome.style.borderColor = "#990000";
campoNome.style.borderWidth = "1px";
statusNome.style.color = "#990000";
nomeValido = false;
if(campoNome.value == ""){
statusNome.innerHTML = "Por favor, preencha este campo.";
return;
}
if(campoNome.value.length > 18){
statusNome.innerHTML = "Nome muito longo.";
return;
}
if(somenteLetras(campoNome.value) == false){
statusNome.innerHTML = "O nome só pode conter letras.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoNome.style.borderColor = "";
campoNome.style.borderWidth = "";
statusNome.innerHTML = "";
nomeValido = true;
}
function validarGenero(){
//Desvalida
campoGenero.style.borderColor = "#990000";
campoGenero.style.borderWidth = "1px";
statusGenero.style.color = "#990000";
generoValido = false;
if(campoGenero.options[campoGenero.selectedIndex].value == ""){
statusGenero.innerHTML = "Por favor, escolha uma opção.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoGenero.style.borderColor = "";
campoGenero.style.borderWidth = "";
statusGenero.innerHTML = "";
generoValido = true;
}
function validarIdade(){
//Desvalida
campoIdade.style.borderColor = "#990000";
campoIdade.style.borderWidth = "1px";
statusIdade.style.color = "#990000";
idadeValida = false;
if(campoIdade.value == ""){
statusIdade.innerHTML = "Por favor, preencha este campo.";
return;
}
if(campoIdade.value.lenght > 3 ){
statusIdade.innerHTML = "Idade inválida.";
return;
}
if(campoIdade.value < 13 ){
statusIdade.innerHTML = "Você precisa ter 13 anos ou mais para se registrar.";
return;
}
if(somenteNumeros(campoIdade.value) == false){
statusIdade.innerHTML = "A idade só pode conter números.";
return;
}
//Deixa como válido caso não haja nenhum problema
campoIdade.style.borderColor = "";
campoIdade.style.borderWidth = "";
statusIdade.innerHTML = "";
idadeValida = true;
}
function salvarEdicao(){
//Verifica se os campos forão preenchidos
if(nomeValido == false || idadeValida == false){
mostrarNotificacao("Por favor, preencha e verifique cada campo em busca de erros.", "#750000", 2000);
return;
}
if(generoValido == false){
mostrarNotificacao("Por favor, selecione uma opção de gênero.", "#750000", 2000);
return;
}
mostrarSpinner(true);
//Cria a conexão e inicia
var conexao = novaConexaoPost("ajax-query/editar-perfil.php");
conexao.onreadystatechange = function(){
mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
definirFuncaoDeSucessoOuErro(conexao,
function()
{
mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(textoDaConexao(conexao));
});
};
iniciarConexaoPost(conexao, "nome=" + campoNome.value + "&genero=" + campoGenero.options[campoGenero.selectedIndex].value + "&idade=" + campoIdade.value);
}
function trocarModoExibicao(){
//Troca a tela de edição do perfil para a tela de exibição
document.getElementById("exibicao").style.display = "block";
document.getElementById("edicao").style.display = "none";
//Atualiza a exibição e troca a tela
document.getElementById("exibicaoNome").innerHTML = campoNome.value;
if(campoGenero.options[campoGenero.selectedIndex].value == "M"){
document.getElementById("exibicaoGenero").innerHTML = "Masculino";
}
if(campoGenero.options[campoGenero.selectedIndex].value == "F"){
document.getElementById("exibicaoGenero").innerHTML = "Feminino";
}
if(campoGenero.options[campoGenero.selectedIndex].value == "V"){
document.getElementById("exibicaoGenero").innerHTML = "Não Informado";
}
document.getElementById("exibicaoIdade").innerHTML = campoIdade.value + " Anos";
}
</script>
<?php
include("includes/rodape.inc");
?><file_sep>/browser/microsite/painel/ajax-query/buscar-arquivos-expansao.php
<?php
/*
* script que recebe o conteúdo da edição e o salva em arquivos temporários,
* para persistir a edição
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$plataforma = strtolower($_POST["plataforma"]);
$pacote = $_POST["pacote"];
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Obtem o diretório alvo
$diretorioAlvoString = ("../../../../global/repositorio/arquivos-de-jogos/".$plataforma."/".$pacote);
//Verifica se o diretório existe ou não
if(is_dir($diretorioAlvoString) == false){
echo("<br/><center>Nenhum arquivo de expansão foi encontrado para o jogo selecionado</center><br/>");
}
if(is_dir($diretorioAlvoString) == true){
//Escaneia o diretório alvo
$listaDeArquivos = scandir($diretorioAlvoString);
//Conta a quantidade de arquivos no diretorio
if(count($listaDeArquivos) <= 2){
echo("<br/><center>A pasta referente a data de ".$dataParaPesquisar.", está vazia.</center><br/>");
}
if(count($listaDeArquivos) > 2){
echo("<center>Listando arquivos de expansão para o jogo selecionado...</center><br/>");
//Rastreia os arquivos do diretório
foreach($listaDeArquivos as $arquivo){
//Verifica se o arquivo é apenas um ponto, ou dois pontos
if($arquivo != "." && $arquivo != ".."){
//Obtem a extensão do arquivo
$extensao = pathinfo($diretorioAlvoString . "/" . $arquivo, PATHINFO_EXTENSION);
//Gera o código do ícone
if($extensao == "zip"){
$codigoIcone = '<img src="../imagens/zip.png" width="16px" />';
}
if($extensao == "obb"){
$codigoIcone = '<img src="../imagens/obb.png" width="16px" />';
}
if($extensao != "obb" && $extensao != "zip"){
$codigoIcone = '<img src="../imagens/bin.png" width="16px" />';
}
//Imprime o código HTML para representar este arquivo
echo('<div class="arquivo">
<div class="iconeArquivo" style="justify-content: flex-start;">
'.$codigoIcone.'
</div>
<div>'.$arquivo.'</div>
<div style="display: flex; justify-content: flex-end;">'.number_format((filesize($diretorioAlvoString . "/" . $arquivo) / 1048576), 1).' MiB</div>
</div>');
}
}
}
}
}
?><file_sep>/client/metadados/anuncio-intersticial/intersticial-metadados.php
<?php
/*
* Essa classe é responsável por fornecer os dados atuais do anúncio intersticial
* da Windsoft Games
*/
include("../../../global/sessoes/verificador-de-sessao.inc");
include("../../../global/mysql/metadados.inc");
IgnorarSessaoImprimirMensagemDeConteudoCarregado();
$tempoInicio = microtime(true);
$jsonResposta = new stdClass();
//<!---------------------- Inicio do Script ----------------------------->
//Inicia a consulta do anuncio intersticial
$anuncioConsulta = mysqli_query($DB_Metadados, "SELECT AtivarAnuncio, TextoBotao, UrlImagem, UrlDaPagina FROM AdIntersticial WHERE Anuncio = 'Global'");
$dadosDoAnuncio = mysqli_fetch_array($anuncioConsulta);
//Inicia a consulta de informar exibição do anuncio
$informarEstatisticaConsulta = mysqli_query($DB_Metadados, "UPDATE AdIntersticialStats SET AdsExibidosDia = AdsExibidosDia + 1, AdsExibidosSem = AdsExibidosSem + 1, AdsExibidosMes = AdsExibidosMes + 1 WHERE Idade = 'Atual'");
//Insere as informações do anuncio no JSON resposta
$jsonResposta->anuncioAtivadoNoMomento = $dadosDoAnuncio[0];
$jsonResposta->textoDoBotao = $dadosDoAnuncio[1];
$jsonResposta->urlDaImagem = $dadosDoAnuncio[2];
$jsonResposta->urlDaPagina = $dadosDoAnuncio[3];
//Insere o tempo da duração da execução do script no JSON Resposta
$jsonResposta->tempoExecucaoDoScript = number_format(microtime(true) - $TempoInicio, 5) . "ms";
//Imprime o JSON resposta
echo("<pre>" . json_encode($jsonResposta, JSON_PRETTY_PRINT) . "</pre>");
?><file_sep>/browser/microsite/painel/ajax-query/gerar-arquivo-noticia.php
<?php
/*
* script que recebe o conteúdo da edição e o salva em arquivos temporários,
* para persistir a edição
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$titulo = $_POST["titulo"];
$urlCapa = $_POST["urlCapa"];
$descricao = $_POST["descricao"];
$introducao = $_POST["introducao"];
$subtitulo1 = $_POST["subtitulo1"];
$texto1 = $_POST["texto1"];
$subtitulo2 = $_POST["subtitulo2"];
$texto2 = $_POST["texto2"];
$subtitulo3 = $_POST["subtitulo3"];
$texto3 = $_POST["texto3"];
$subtitulo4 = $_POST["subtitulo4"];
$texto4 = $_POST["texto4"];
$subtitulo5 = $_POST["subtitulo5"];
$texto5 = $_POST["texto5"];
$modoPrevia = $_POST["modoPrevia"];
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Configura a data
date_default_timezone_set('America/Sao_Paulo');
$ano = date('Y');
$mesNumero = date('m');
$dia = date('d');
$hora = date('H');
$minuto = date('i');
//Da um nome ao mês obtido
if($mesNumero == "01"){ $mesExtenso = ("Jan"); }
if($mesNumero == "02"){ $mesExtenso = ("Fev"); }
if($mesNumero == "03"){ $mesExtenso = ("Mar"); }
if($mesNumero == "04"){ $mesExtenso = ("Abr"); }
if($mesNumero == "05"){ $mesExtenso = ("Mai"); }
if($mesNumero == "06"){ $mesExtenso = ("Jun"); }
if($mesNumero == "07"){ $mesExtenso = ("Jul"); }
if($mesNumero == "08"){ $mesExtenso = ("Ago"); }
if($mesNumero == "09"){ $mesExtenso = ("Set"); }
if($mesNumero == "10"){ $mesExtenso = ("Out"); }
if($mesNumero == "11"){ $mesExtenso = ("Nov"); }
if($mesNumero == "12"){ $mesExtenso = ("Dez"); }
//Dados para o preenchimento da notícia
$variaveisSeremPreenchidas = array("%TITULO%", "%CAPA_URL%", "%BREVE_DESCRICAO%", "%ANO%", "%MES_NUMERO%", "%MES_EXTENSO%", "%DIA_NUMERO%", "%HORA%", "%MINUTO%", "%AUTOR_NICK%", "%CARGO%", "%INTRODUCAO%", "%SUBTITULO1%", "%TEXTO1%", "%SUBTITULO2%", "%TEXTO2%", "%SUBTITULO3%", "%TEXTO3%", "%SUBTITULO4%", "%TEXTO4%", "%SUBTITULO5%", "%TEXTO5%");
$stringsParaPreenchimento = array(strFormatd($titulo), $urlCapa, strFormatd($breveDescricao), $ano, $mesNumero, $mesExtenso, $dia, $hora, $minuto, $_SESSION["nick"], $_SESSION["cargo"], strFormatd($introducao), strFormatd($subtitulo1), strFormatd($texto1), strFormatd($subtitulo2), strFormatd($texto2), strFormatd($subtitulo3), strFormatd($texto3), strFormatd($subtitulo4), strFormatd($texto4), strFormatd($subtitulo5), strFormatd($texto5));
//Abre o arquivo base das notícias para obter o código PHP base, e preenche a notícia
$codigoBaseNoticia = file_get_contents("../paginas/noticias/codigo-base-noticia.php");
$codigoFinalNoticia = str_replace($variaveisSeremPreenchidas, $stringsParaPreenchimento, $codigoBaseNoticia);
//Caso seja o modo prévia, gera uma página temporária somente para visualização
if($modoPrevia === "true"){
//Código de selo final
$seloFinal = '
<div style="background-color: #DB6D00; color: #FFFFFF; text-align: center; position: fixed; top: 5%; right: -40%; transform: rotate(45deg); width: 100%; z-index: 15; height: 25px; line-height: 25px; font-size: 90%; pointer-events: none; box-shadow: 0px 0px 9px -1px rgba(0,0,0,0.75);">
Visualização
</div>
';
//Termina de preencher o documento de notícia, com os dados CASO seja uma previa
$varParaPreencher = array("%DIRETORIO_CABECALHO%", "%DIRETORIO_RODAPE%", "%SELO_FINAL%");
$strParaPreencher = array("../../../../../includes/cabecalho.inc", "../../../../../includes/rodape.inc", $seloFinal);
//Cria o arquivo final para exibir a previa
$codigoParaPrevia = str_replace($varParaPreencher, $strParaPreencher, $codigoFinalNoticia);
//Cria o arquivo temporário da notícia, somente para visualização
$noticiaTemp = fopen("../paginas/noticias/temp/" . $_SESSION["id"] . "_noticia-preview.php", 'w');
fwrite($noticiaTemp, $codigoParaPrevia);
fclose($noticiaTemp);
//Abre a nova aba para visualização
echo('window.open("https://windsoft.xyz/browser/microsite/painel/paginas/noticias/temp/' . $_SESSION["id"] . '_noticia-preview.php" + "?previa=" + (new Date()).getTime());');
}
//Caso não seja o modo prévia, gera uma página permanente
if($modoPrevia === "false"){
//Termina de preencher o documento de notícia, com os dados CASO não seja uma previa
$varParaPreencher = array("%DIRETORIO_CABECALHO%", "%DIRETORIO_RODAPE%", "%SELO_FINAL%");
$strParaPreencher = array("../../../../../includes/cabecalho.inc", "../../../../../includes/rodape.inc", "");
//Cria o arquivo final
$codigo = str_replace($varParaPreencher, $strParaPreencher, $codigoFinalNoticia);
//Filtra o titulo da noticia para gerar o URL sem caracteres especiais, e minusculo
$tituloRemoverEspacos = str_replace(" ", "-", $titulo);
$tituloParaUrl = strtolower(preg_replace("/[^A-Za-z0-9\-]/", "", $tituloRemoverEspacos));
//Configura o diretorio da noticia
$diretorioDaNoticia = "../../../noticias/por-data/".$ano."/".$mesNumero."/".$dia;
//Cria o diretorio da noticia de acordo com a data, caso não exista um
if(!is_dir($diretorioDaNoticia)){
mkdir($diretorioDaNoticia, 0777, true);
}
//Cria o arquivo permanente da notícia, para ser acessível
$noticia = fopen($diretorioDaNoticia . "/" . $tituloParaUrl . ".php", 'w');
fwrite($noticia, $codigo);
fclose($noticia);
//Salva no arquivo temporário, a informação de que não existe edição salva
$arquivo = fopen("../paginas/noticias/temp/" . $_SESSION["id"] . "_noticia-existeEdicaoSalva.tmp", 'w');
fwrite($arquivo, "false");
fclose($arquivo);
//Exibe a mensagem de sucesso
echo("exibirMensagemArquivoCriado('https://windsoft.xyz/browser/noticias/por-data/".$ano."/".$mesNumero."/".$dia."/".$tituloParaUrl.".php'); parent.exibirIconeEmote(false);");
}
}
//Método que formata o texto, substituindo algumas partes por outros caracteres ou tags de HTML.
function strFormatd($texto){
$TextoFinal = str_replace(
array("\n", '"', "'"),
array("<br/>", """, "'"),
$texto);
return $TextoFinal;
}
?><file_sep>/browser/includes/rodape.inc
<?php
/*
* Essa classe é responsável por fornecer o rodapé das páginas.
*/
?>
<br/>
</div>
<div class="content" style="margin-top: 10px;">
<br/>
<center style="opacity: 0.85;">
<a href="https://windsoft.xyz"><small>Ínicio</small></a>
-
<a href="https://windsoft.xyz/gplay"><small>Play Store</small></a>
-
<a href="https://windsoft.xyz/fb"><small>Facebook</small></a>
-
<a href="https://windsoft.xyz/yt"><small>Youtube</small></a>
-
<a href="https://windsoft.xyz/terms"><small>Termos</small></a>
-
<a href="https://windsoft.xyz/privacy"><small>Privacidade</small></a>
-
<a href="https://windsoft.xyz/sobre"><small>Sobre</small></a>
<br/>
<br/>
<small>
Windsoft Games (2015 - <?php echo(date("Y")); ?>)
</small>
</center>
<br/>
<script type="text/javascript">
function myFunction() {
document.getElementById("menuLogadoId").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.botaoMenuLogado')) {
var dropdowns = document.getElementsByClassName("menuLogadoConteudo");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
};
</script>
</div>
</body>
</html><file_sep>/browser/microsite/painel/paginas/includes/cabecalho.inc
<html>
<head>
<link rel="stylesheet" href="<?php echo(__DIR__); ?>/../../../../estilos/estilo-base.css" />
<link rel="stylesheet" href="<?php echo(__DIR__); ?>/../../../../estilos/estilo-inputs.css"/>
<link rel="stylesheet" href="<?php echo(__DIR__); ?>/../../../../estilos/estilo-divs.css"/>
<link rel="stylesheet" href="<?php echo(__DIR__); ?>/../../../../estilos/estilo-pag-noticia.css" />
<link rel="stylesheet" href="<?php echo(__DIR__); ?>/../../../../estilos/estilo-animations.css" />
<style>
body{
background-color: #ffffff;
padding: auto;
margin: auto;
}
</style>
<!-- script para gerar gráficos -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<?php
/*
* Essa classe é responsável por fornecer o cabeçalho das páginas. É o conteúdo básico e verificador para cada página do painel.
*/
//Connecta aos banco de dados
include __DIR__ . ("/../../../../../global/mysql/feedbacks.inc");
include __DIR__ . ("/../../../../../global/mysql/metadados.inc");
include __DIR__ . ("/../../../../../global/mysql/registros.inc");
include __DIR__ . ("/../../../../../global/sessoes/verificador-de-sessao.inc");
//Verifica se a sessão do usuário não está ativa. Caso não esteja, ativa o aviso
if(VerificarSessao(false, false) == false){
echo('
<div style="display: grid; background-color: #FFCECE; padding: 10px; text-left: center; border-radius: 6px; grid-template-columns: 20% 80%;">
<div style="display: flex; align-items: center;">
<img src="' . __DIR__ .'/../../imagens/alerta.png" style="width: 40%; margin-left: auto; margin-right: auto;" />
</div>
<div style="display: flex; align-items: center;">
Não foi possível carregar o conteúdo desejado. Sua sessão encontra-se expirada, ou é incorreta, pois pode ter ocorrido uma alteração na sua rede. Por favor, re-faça login para continuar.
</div>
</div>
');
}
//Verifica a sessão atual, e a valida, caso esteja invalida, não carrega o conteúdo
VerificarSessao(true, false);
//Obtem a permissão necessária para este script
$consultaPermissao = mysqli_query($DB_Metadados, "SELECT AutoridadeMinima FROM StaffPaginas WHERE Pagina='$estaPagina'");
$dadosPermissao = mysqli_fetch_array($consultaPermissao);
//Interrompe o script caso a autoridade do usuário não seja suficiente
if($dadosPermissao[0] > $_SESSION["autoridade"] || mysqli_num_rows($consultaPermissao) == 0){
echo('
<div style="display: grid; background-color: #FFCECE; padding: 10px; text-left: center; border-radius: 6px; grid-template-columns: 20% 80%;">
<div style="display: flex; align-items: center;">
<img src="' . __DIR__ .'/../../imagens/alerta.png" style="width: 40%; margin-left: auto; margin-right: auto;" />
</div>
<div style="display: flex; align-items: center;">
Você não tem permissão o suficiente para acessar está página.
</div>
</div>
<center>
<input type="button" value="Ínicio" onclick="parent.carregarPagina(\'home.php\');" style="max-width: 100px; margin-top: 40px; margin-bottom: 40px;" />
</center>
<br>
');
exit();
}
?><file_sep>/global/repositorio/arquivos-de-jogos/obter-url-para-arquivo.php
<?php
/*
* Esta classe é chamada pelo launcher windsoft, quando o mesmo precisa baixar
* um arquivo de expansão para o jogo. Essa classe é responsável por retornar
* a ele, a URL para o arquivo de expansão correspondente a versão e pacotes informados.
*/
include("../../sessoes/verificador-de-sessao.inc");
IgnorarSessaoImprimirMensagemDeConteudoCarregado();
$tempoInicio = microtime(true);
$jsonResposta = new stdClass();
//Variaveis da solicitação
$plataforma = $_POST["plataforma"];
//Caso seja para plataforma Android
if($plataforma == "Android"){
//Variaveis da solicitação
$pacote = $_POST["pacote"];
$versao = $_POST["versao"];
//Monta o diretório da OBB solicitada
$diretorioOBB = "android/".$pacote."/expansion(".$versao.").obb";
//Verifica se o arquivo OBB existe
if(file_exists($diretorioOBB) == true){
$tamanhoArquivoBytes = filesize($diretorioOBB);
$tamanhoArquivoMebibytes = $tamanhoArquivoBytes / 1048576;
$encontrou = "true";
}
if(file_exists($diretorioOBB) == false){
$encontrou = "false";
}
//Carrega os resultados para a JSON resposta
$jsonResposta->arquivoEncontrado = $encontrou;
$jsonResposta->linkParaArquivo = "https://windsoft.xyz/global/repositorio/arquivos-de-jogos/android/".$pacote."/expansion(".$versao.").obb";
$jsonResposta->tamanhoEmBytes = $tamanhoArquivoBytes;
$jsonResposta->tamanhoEmMebiBytes = number_format($tamanhoArquivoMebibytes, 1);
}
//Caso seja para plataforma Fuchsia
if($plataforma == "Fuchsia"){
}
//Caso seja para plataforma Windows
if($plataforma == "Windows"){
}
//Insere o tempo da duração das contas no JSON Resposta
$jsonResposta->tempoExecucaoDoScript = number_format(microtime(true) - $tempoInicio, 5) . "ms";
//Imprime o JSON resposta
echo ("<pre>" . json_encode($jsonResposta, JSON_PRETTY_PRINT) . "</pre>");
?><file_sep>/client/mtassets-patcher/get-current-patcher-code.php
<?php
//Inicia um comentário, pois caso o php gere alguma mensagem de erro, a mensagem ficará comentada, para evitar erros de compilação
echo("/*");
//Esse código é responsável por receber a requisição do MT Assets Patcher
include("../../global/mysql/metadados.inc");
//Carrega a estatistica atual, caso não exista, cria o JSON para armazenar
$consultaEstatistica = mysqli_query($DB_Metadados, "SELECT DadosDestaEstatistica FROM AssetStoreStats WHERE TipoDeEstatistica='MTAssets-PatcherUpdater-Requisicoes'");
$jsonEstatisticaArray = mysqli_fetch_array($consultaEstatistica);
if($jsonEstatisticaArray[0] == ""){
//Cria uma array de objetos "Dia"
$arrayObjetosDia = array();
for ($x = 0; $x < 31; $x++) {
$objetoDia = new stdClass;
$objetoDia->requisicoes = 0;
array_push($arrayObjetosDia, $objetoDia);
}
//Cria o JSON para armazenar as estatisticas
$objetoMes = new stdClass;
$objetoMes->diasDoMes = $arrayObjetosDia;
$jsonEstatisticaArray[0] = json_encode($objetoMes);
$consultaCriarArmazenamento = mysqli_query($DB_Metadados, "UPDATE AssetStoreStats SET DadosDestaEstatistica='$jsonEstatisticaArray[0]' WHERE TipoDeEstatistica='MTAssets-PatcherUpdater-Requisicoes'");
}
//Incrementa a requisição atual, no dia de hoje, nas estatisticas
$armazenamentoEstatisticas = json_decode($jsonEstatisticaArray[0]);
$diasDoMesArray = $armazenamentoEstatisticas->diasDoMes;
$diaDeHoje = (int)(date("j")) - 1;
for($i = 0; $i < 31; $i++){
//Caso o indice seja igual o dia de hoje, incrementa a estatistica
if($i == $diaDeHoje){
$diasDoMesArray[$i]->requisicoes += 1;
}
//Caso o indice seja maior que o dia de hoje, zera os dias posteriores
if($i > $diaDeHoje){
$diasDoMesArray[$i]->requisicoes = 0;
}
}
//Salva as estatísticas
$jsonRequisicoesDesteMesAtualizado = json_encode($armazenamentoEstatisticas);
$consultaAtualizarEstatisticas = mysqli_query($DB_Metadados, "UPDATE AssetStoreStats SET DadosDestaEstatistica='$jsonRequisicoesDesteMesAtualizado' WHERE TipoDeEstatistica='MTAssets-PatcherUpdater-Requisicoes'");
//Lê o arquivo de script
$codigoCSharpDoPatcher = file_get_contents("Patcher.cs");
//Finaliza o comentário
echo("This is version ".date("Y")."/".date("m")."/".date("d")." of \"Patcher.cs\".*/\r\n\r\n");
//Imprime o código para que o Patcher Updater o atualize no projeto do cliente
echo($codigoCSharpDoPatcher);
?><file_sep>/browser/logout.php
<?php
/*
* Essa página apaga a sessão do usuário e o redireciona para a página inicial
*/
//Finaliza a sessão e redireciona o usuario
session_start();
session_destroy();
header("Location:"."https://windsoft.xyz");
?><file_sep>/browser/microsite/painel/paginas/editar-anuncio-intersticial.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem os dados do anúncio intersticial
$consultaAnuncio = mysqli_query($DB_Metadados, "SELECT AtivarAnuncio, TextoBotao, UrlImagem, UrlDaPagina FROM AdIntersticial WHERE Anuncio='Global'");
$dadosAnuncio = mysqli_fetch_array($consultaAnuncio);
?>
<center>
<h3>Editar Anúncio Intersticial</h3>
</center>
<div id="formulario">
<center>
<form autocomplete="off">
<input id="textoBotao" type="text" placeholder="Texto do Botão" onkeyup="validarTitulo();"
value="<?php echo($dadosAnuncio[1]); ?>"/>
<div id="textoBotaoStatus" class="statusCampo"></div>
<input id="urlImagem" type="text" placeholder="URL da Imagem" onkeyup="validarUrlImagem();" onblur="trocarImagemAnuncio();"
value="<?php echo($dadosAnuncio[2]); ?>"/>
<div id="urlImagemStatus" class="statusCampo"></div>
<input id="urlPagina" type="text" placeholder="URL da Página" onkeyup="validarUrlPagina();"
value="<?php echo($dadosAnuncio[3]); ?>"/>
<div id="urlPaginaStatus" class="statusCampo"></div>
<div class="checkboxMainContainer">
<label class="container">
<div>
Exibir Anúncio Intersticial
</div>
<input type="checkbox" id="exibir" onchange="validarCheckboxAnuncioIntersticial();" <?php if((boolean)$dadosAnuncio[0] == true){echo("checked");} ?>>
<span class="checkmark"></span>
</label>
</div>
<input type="button" value="Aplicar" onclick="salvarEdicao();" />
</form>
</center>
</div>
<!-- pré visualização do anúncio intersticial -->
<center>
<h3 id="tituloVisualizacao">Pré Visualização</h3>
</center>
<div id="preVisualizar" style="width: 80%; max-width: 300px; border-radius: 6px; background-color: #E0E0E0; height: 300px; margin-left: auto; margin-right: auto; background-image: url(<?php echo($dadosAnuncio[2]); ?>); background-position: center; background-size: cover; background-repeat: no-repeat; display: flex; align-items: flex-end;">
<a id="link" href="<?php echo($dadosAnuncio[3]); ?>" target="_blank" style="width: auto; margin-top: calc(100% - 53px); margin-left: auto; margin-right: auto; position;">
<input id="botao" type="button" value="<?php echo($dadosAnuncio[1]); ?>" style="width: auto;" />
</a>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
campoTitulo = document.getElementById("textoBotao");
statusTitulo = document.getElementById("textoBotaoStatus");
tituloValido = false;
function validarTitulo(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoTitulo.value.length, 40);
//Desvalida
campoTitulo.style.borderColor = "#990000";
campoTitulo.style.borderWidth = "1px";
statusTitulo.style.color = "#990000";
tituloValido = false;
if(campoTitulo.value == ""){
statusTitulo.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoTitulo.value.length > 40){
statusTitulo.innerHTML = "Título muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoTitulo.value) == true){
statusTitulo.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoTitulo.style.borderColor = "";
campoTitulo.style.borderWidth = "";
statusTitulo.innerHTML = "";
tituloValido = true;
//Caso o titulo seja válido, exibe a pré-visualização
if(tituloValido == true){
document.getElementById("botao").value = campoTitulo.value;
}
parent.redimensionarIframe();
}
campoUrlImagem = document.getElementById("urlImagem");
statusUrlImage = document.getElementById("urlImagemStatus");
urlImagemValida = false;
function validarUrlImagem(){
//Desvalida
campoUrlImagem.style.borderColor = "#990000";
campoUrlImagem.style.borderWidth = "1px";
statusUrlImage.style.color = "#990000";
urlImagemValida = false;
if(campoUrlImagem.value == ""){
statusUrlImage.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComUrl(campoUrlImagem.value) == false){
statusUrlImage.innerHTML = "O conteúdo digitado não é uma URL.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoUrlImagem.style.borderColor = "";
campoUrlImagem.style.borderWidth = "";
statusUrlImage.innerHTML = "";
urlImagemValida = true;
parent.redimensionarIframe();
}
function trocarImagemAnuncio(){
//Atualiza a imagem do anúncio, quando o usuário sair do campo de texto da image
if(urlImagemValida == true){
document.getElementById("preVisualizar").style.backgroundImage = "url(" + campoUrlImagem.value + ")";
}
}
campoUrlPagina = document.getElementById("urlPagina");
statusUrlPagina = document.getElementById("urlPaginaStatus");
urlPaginaValida = false;
function validarUrlPagina(){
//Desvalida
campoUrlPagina.style.borderColor = "#990000";
campoUrlPagina.style.borderWidth = "1px";
statusUrlPagina.style.color = "#990000";
urlPaginaValida = false;
if(campoUrlPagina.value == ""){
statusUrlPagina.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComUrl(campoUrlPagina.value) == false){
statusUrlPagina.innerHTML = "O conteúdo digitado não é uma URL.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoUrlPagina.style.borderColor = "";
campoUrlPagina.style.borderWidth = "";
statusUrlPagina.innerHTML = "";
urlPaginaValida = true;
//Caso o link da pagina seja válido, exibe a pré-visualização
if(urlPaginaValida == true){
document.getElementById("link").href = campoUrlPagina.value;
}
parent.redimensionarIframe();
}
//Ao ativar/desativar anuncio
checkbox = document.getElementById("exibir");
checkboxExibir = "0";
function validarCheckboxAnuncioIntersticial(){
if(checkbox.checked == true){
checkboxExibir = "1";
document.getElementById("preVisualizar").style.display = "flex";
document.getElementById("tituloVisualizacao").innerHTML = "Pré-Visualização";
}
if(checkbox.checked == false){
checkboxExibir = "0";
document.getElementById("preVisualizar").style.display = "none";
document.getElementById("tituloVisualizacao").innerHTML = "Anúncio Desativado";
}
parent.redimensionarIframe();
}
//Função que verifica se todos os campos estão válidos
function todosOsCamposEstaoValidos(){
validarTitulo();
validarUrlPagina();
validarUrlImagem();
validarCheckboxAnuncioIntersticial();
if(tituloValido == true && urlPaginaValida == true && urlImagemValida == true){
return true;
}
if(tituloValido == false || urlPaginaValida == false || urlImagemValida == false){
parent.mostrarNotificacao("Verifique o formulário em busca de erros e tente novamente.", "#750000", 3000);
return false;
}
}
//Função que salva as alterações
function salvarEdicao(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/editar-anuncio-intersticial.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"ativarAnuncio=" + checkboxExibir +
"&textoBotao=" + document.getElementById("textoBotao").value +
"&urlImagem=" + document.getElementById("urlImagem").value +
"&urlPagina=" + document.getElementById("urlPagina").value);
}
}
todosOsCamposEstaoValidos();
</script>
<?php
$conteudoQuadroDeAviso = ('
• Utilize uma imagem de 400x400 para o anúncio.
<br>
• O Anúncio Intersticial é exibido nos jogos da Windsoft, quando o jogador acessa o menu principal, quando o mesmo se encontra habilitado.
<br>
• O Anúncio Intersticial pode ser usado para anúnciar jogos da Windsoft Games.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/ajax-query/receber-imagem.php
<?php
/*
* script que recebe a imagem enviada através da função de carregar imagem
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$arquivo = $_FILES["imagem"];
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Configura a data
date_default_timezone_set('America/Sao_Paulo');
$ano = date('Y');
$mesNumero = date('m');
$dia = date('d');
$hora = date('H');
$minuto = date('i');
$segundos = date('s');
//Configura o diretorio do upload
$diretorioDoArquivo = "../../../noticias/por-data/".$ano."/".$mesNumero."/".$dia;
//Cria o diretorio da noticia de acordo com a data, caso não exista um
if(!is_dir($diretorioDoArquivo)){
mkdir($diretorioDoArquivo, 0777, true);
}
$podeContinuarComCarregamento = true;
//Verifica o tipo de arquivo
$extensoesPermitidas = array("jpeg", "jpg");
$extensaoDoArquivo = pathinfo($arquivo["name"], PATHINFO_EXTENSION);
if(in_array($extensaoDoArquivo, $extensoesPermitidas) == false && $podeContinuarComCarregamento == true){
echo("
parent.mostrarNotificacao('O arquivo enviado, não é do formato JPG/JPEG.', \"#750000\", 5000);
redefinirInterface();
");
$podeContinuarComCarregamento = false;
}
//Verifica o tamanho maximo do arquivo
$tamanhoMaxEmKb = 100 * 1024;
if($arquivo["size"] > $tamanhoMaxEmKb && $podeContinuarComCarregamento == true){
echo("
parent.mostrarNotificacao('O arquivo enviado excede o tamanho limite de 100Kb.', \"#750000\", 5000);
redefinirInterface();
");
$podeContinuarComCarregamento = false;
}
//Verifica se o arquivo é uma imagem
if(!getimagesize($arquivo["tmp_name"]) && $podeContinuarComCarregamento == true){
echo("
parent.mostrarNotificacao('O arquivo enviado não é uma imagem, ou está corrompido.', \"#750000\", 5000);
redefinirInterface();
");
$podeContinuarComCarregamento = false;
}
//Inicia o upload do arquivo, caso seja possível
if($podeContinuarComCarregamento == true){
//Monta o nome do arquivo e diretorio
$novoNome = $diretorioDoArquivo."/"."IMG-".$hora.$minuto.$segundos.".jpg";
$diretorioFinal = $diretorioDoArquivo."/".$arquivo["name"];
//Caso o upload ocorra bem
if(move_uploaded_file($arquivo["tmp_name"], $diretorioFinal)){
//Renomeia o arquivo enviado
rename($diretorioFinal, $novoNome);
//Calcula a URL da imagem
echo(""
."parent.mostrarNotificacao(\"Imagem carregada com sucesso!\", \"#467200\", 3500); "
."setTimeout(function(){ exibirInterfaceDeConclusao('"
."https://windsoft.xyz/browser/noticias/por-data/".$ano."/".$mesNumero."/".$dia."/"."IMG-".$hora.$minuto.$segundos.".jpg"
."');"
."}, 1500);");
}
}
}
?><file_sep>/browser/microsite/painel/paginas/recebimentos-notificacao.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem a contagem de recebimentos da atual notificação
$consulta = mysqli_query($DB_Metadados, "SELECT Recebimentos FROM NotificacaoStats WHERE Canal = 'Global'");
?>
<center>
<h3>Recebimentos da Notificação Atual</h3>
</center>
<div style="width: 80%; max-width: 300px; margin-left: auto; margin-right: auto; border-radius: 4px; background-color: #E5E5E5; padding: 18px;">
<center>
<div style="font-weight: bolder; font-size: 40px;">
<?php echo(mysqli_fetch_array($consulta)[0]); ?>
</div>
<small>Recebimentos</small>
</center>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
</script>
<?php
$conteudoQuadroDeAviso = ('
• Sempre que algum client solicitar uma notificação, ele irá contatar o servidor para informar que recebeu a notificação. Sempre que o servidor for informado do recebimento, esta contagem aumentará em um.
<br>
• Esse dado é uma aproximação.
<br>
• Sempre que uma nova notificação for emitida, a contagem será redefinida a zero.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/ajax-query/trocar-icone.php
<?php
/*
* script que faz consulta de alteração do icone
*/
include("../../global/sessoes/verificador-de-sessao.inc");
include("../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Obtem as variaveis
$novoIcone = mysqli_real_escape_string($DB_Registros, $_POST["icone"]);
//obtem o id do usuário
$id = $_SESSION["id"];
//Altera o icone
$consulta = mysqli_query($DB_Registros, "UPDATE Perfis SET IdIcone=$novoIcone WHERE ID=$id");
$_SESSION["idIcone"] = $novoIcone;
echo("".
"mostrarNotificacao(\"Ícone de perfil alterado com sucesso!\", \"#117700\", 5000);".
"document.getElementById(\"iconeTopbar\").src = \"https://windsoft.xyz/global/repositorio/arquivos-de-perfil/icones-de-perfil/icone_".$_SESSION["idIcone"].".png\";".
"document.getElementById(\"iconePagPerfil\").style.backgroundImage = \"url(https://windsoft.xyz/global/repositorio/arquivos-de-perfil/icones-de-perfil/icone_".$novoIcone.".png)\";".
"");
?><file_sep>/browser/microsite/painel/paginas/editar-versao-de-jogo.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem os dados de todos os jogos cadastrados
$consultaDeJogos = mysqli_query($DB_Metadados, "SELECT JogoID, Nome, UltimaVersao, Plataforma FROM JogosDaWindsoft WHERE JogoID > 0");
$i = 0;
while($linha = mysqli_fetch_assoc($consultaDeJogos)) {
$jogoId[$i] = $linha["JogoID"];
$nome[$i] = $linha["Nome"];
$plataforma[$i] = $linha["Plataforma"];
$ultimaVersao[$i] = $linha["UltimaVersao"];
$i += 1;
}
?>
<center>
<h3>Editar Versão de Jogo</h3>
</center>
<div id="formulario" style="display: block;">
<center>
<form autocomplete="off">
<select id="selectSlide" onchange="aoTrocarJogo();">
<?php
for ($ii = 0; $ii < $i; $ii++) {
echo('<option value="'.$jogoId[$ii].'">'.$nome[$ii].' ('.$plataforma[$ii].')</option>');
}
?>
</select>
<input id="versao" type="text" placeholder="Versão do Jogo" onkeyup="validarVersao();"/>
<div id="versaoStatus" class="statusCampo"></div>
<input type="button" value="Salvar" onclick="salvarEdicao();" />
</form>
</center>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
//Função que preenche o campo de versão, ao trocar o jogo
versoesDosJogos = ["", <?php
for ($iii = 0; $iii < $i; $iii++) {
echo('"'.$ultimaVersao[$iii].'"');
if($iii != $i){
echo(",");
}
}
?>];
jogoSelect = document.getElementById("selectSlide");
jogoSelecionadoId = 1;
function aoTrocarJogo(){
jogoSelecionadoId = jogoSelect.value;
document.getElementById("versao").value = versoesDosJogos[parseInt(jogoSelecionadoId)];
todosOsCamposEstaoValidos();
}
campoVersao = document.getElementById("versao");
statusVersao = document.getElementById("versaoStatus");
versaoValido = false;
function validarVersao(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoVersao.value.length, 8);
//Desvalida
campoVersao.style.borderColor = "#990000";
campoVersao.style.borderWidth = "1px";
statusVersao.style.color = "#990000";
versaoValido = false;
if(campoVersao.value == ""){
statusVersao.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoVersao.value.length > 8){
statusVersao.innerHTML = "Nome de versão, muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoVersao.value) == true){
statusVersao.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoVersao.style.borderColor = "";
campoVersao.style.borderWidth = "";
statusVersao.innerHTML = "";
versaoValido = true;
parent.redimensionarIframe();
}
//Função que verifica se todos os campos estão válidos
function todosOsCamposEstaoValidos(){
validarVersao();
if(versaoValido == true){
return true;
}
if(versaoValido == false){
parent.mostrarNotificacao("Verifique o formulário em busca de erros e tente novamente.", "#750000", 3000);
return false;
}
}
//Função que publica o jogo
function salvarEdicao(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/editar-versao-jogo.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
//Atualiza a versão, na array de versões
versoesDosJogos[parseInt(jogoSelecionadoId)] = document.getElementById("versao").value;
});
};
parent.iniciarConexaoPost(conexao,
"id=" + jogoSelecionadoId +
"&ultimaVersao=" + document.getElementById("versao").value);
}
}
aoTrocarJogo();
</script>
<?php
$conteudoQuadroDeAviso = ('
• O Windsoft Launcher, usará a versão informada aqui, para identificar se o jogo no dispositivo do cliente, está atualizado.
<br/>
• As versões devem ter a seguinte organização "major.minor.patch", exemplo 1.7.23 (Sendo que o "Patch" é uma correção aplicada a atualização "Minor", e "Minor" são adições ou melhorias feitas ao jogo. "Major" updates, são atualizações onde muita coisa é alterada).
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/paginas/enviar-arquivo-expansao.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem os dados de todos os jogos cadastrados
$consultaDeJogos = mysqli_query($DB_Metadados, "SELECT JogoID, Nome, UltimaVersao, PacoteOuNamespace, Plataforma FROM JogosDaWindsoft WHERE JogoID > 0");
$i = 0;
while($linha = mysqli_fetch_assoc($consultaDeJogos)) {
$jogoId[$i] = $linha["JogoID"];
$nome[$i] = $linha["Nome"];
$ultimaVersao[$i] = $linha["UltimaVersao"];
$pacote[$i] = $linha["PacoteOuNamespace"];
$plataforma[$i] = $linha["Plataforma"];
$i += 1;
}
?>
<center>
<h3>Enviar Arquivo de Expansão</h3>
</center>
<!-- envio do arquivo -->
<form method="post" id="formularioUpload" enctype="multipart/form-data" autocomplete="off">
<center>
<select id="selectSlide" onchange="aoTrocarJogo();" style="max-width: 270px;">
<?php
for ($ii = 0; $ii < $i; $ii++) {
echo('<option value="'.$jogoId[$ii].'">'.$nome[$ii].' (v'.$ultimaVersao[$ii].') ('.$plataforma[$ii].')</option>');
}
?>
</select>
</center>
<input type="file" name="imagem" id="imagemUpload" style="display: none;" onchange="selecionarArquivo();" />
<div style="display: grid; grid-template-rows: 60% 20% 20%; height: 250px; width: 250px; margin-left: auto; margin-right: auto; background-color: #EDEDED; padding: 10px; border-radius: 4px;">
<div id="preVisualizacao" onclick="clickNoSeletorDeArquivos();" style="background-image: url(../imagens/upload1.png); background-position: center; background-size: cover; background-repeat: no-repeat; border-radius: 100%; width: 100%; max-width: 60%; margin-left: auto; margin-right: auto; cursor: pointer;">
</div>
<div style="display: flex; justify-content: center; align-items: center; font-weight: bolder; text-align: center;">
<div id="nomeDoArquivo">
Selecione um arquivo...
</div>
</div>
<div style="display: flex; justify-content: center; align-items: center;">
<button id="botaoCarregar" style="width: 100%; height: 100%; border-radius: 4px; background-color: #356B00; color: #F4F4F4; border-style: none; cursor: pointer; display: none;">Carregar</button>
<div id="progressoBg" style="width: 100%; height: 6px; background-color: #BFBFBF; border-radius: 4px; display: none;">
<div id="progressoFill" style="transition: 0.25s; height: 100%; width: 1%; background-color: #00A4E0; float: left; border-radius: 4px;"></div>
</div>
</div>
</div>
</form>
<div id="arquivoEnviado" style="display: none;">
<center>
<img src="../imagens/sucesso.png" width="128px" />
<br>
<br>
O arquivo de expansão foi enviado com sucesso para o jogo selecionado!
<br>
<br>
</center>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
//Função que obtem os dados, ao trocar de jogo selecionado
nomesDosJogos = ["", <?php
for ($iii = 0; $iii < $i; $iii++) {
echo('"'.$nome[$iii].'"');
if($iii != $i){
echo(",");
}
}
?>];
plataformaDosJogos = ["", <?php
for ($iii = 0; $iii < $i; $iii++) {
echo('"'.$plataforma[$iii].'"');
if($iii != $i){
echo(",");
}
}
?>];
pacoteDosJogos = ["", <?php
for ($iii = 0; $iii < $i; $iii++) {
echo('"'.$pacote[$iii].'"');
if($iii != $i){
echo(",");
}
}
?>];
versoesDosJogos = ["", <?php
for ($iii = 0; $iii < $i; $iii++) {
echo('"'.$ultimaVersao[$iii].'"');
if($iii != $i){
echo(",");
}
}
?>];
jogoSelect = document.getElementById("selectSlide");
jogoSelecionadoId = 1;
function aoTrocarJogo(){
jogoSelecionadoId = jogoSelect.value;
parent.mostrarNotificacao('Atenção: "' + nomesDosJogos[parseInt(jogoSelecionadoId)] + '" foi escolhido para receber este arquivo de expansão.', '#AA6300', 3000);
}
//Inicializa o formulario
document.getElementById("formularioUpload").addEventListener("submit", function(evt){
evt.preventDefault();
}, false);
document.getElementById("botaoCarregar").addEventListener("click", function(){
var inputFile = document.getElementById("imagemUpload");
carregarArquivo(inputFile.files[0]);
}, false);
//Função que abre o seletor de arquivos e exibe seu nome e dados
function selecionarArquivo(){
var uploader = document.getElementById("imagemUpload");
if(uploader.value != ""){
document.getElementById("botaoCarregar").style.display = "block";
document.getElementById("nomeDoArquivo").innerHTML = uploader.value.split(/\\|\//).pop() + "<br>(" + (uploader.files[0].size / 1000).toFixed(1) + " Kb)";
}
if(uploader.value == ""){
redefinirInterface();
}
}
//Função que clica no seletor de arquivos verdadeiro (que está invisivel)
function clickNoSeletorDeArquivos(){
document.getElementById("imagemUpload").click();
}
//Função que redefine a interface para o padrão, de inicio
function redefinirInterface(){
var data = new Date();
document.getElementById("botaoCarregar").style.display = "none";
document.getElementById("progressoBg").style.display = "none";
document.getElementById("progressoFill").style.width = "1%";
document.getElementById("nomeDoArquivo").innerHTML = "Selecione um arquivo...";
document.getElementById("preVisualizacao").style.cursor = "pointer";
document.getElementById("preVisualizacao").onclick = function(){ clickNoSeletorDeArquivos(); };
}
//Função que efetua o envio enquanto exibe o progresso
function carregarArquivo(file){
document.getElementById("botaoCarregar").style.display = "none";
document.getElementById("progressoBg").style.display = "block";
document.getElementById("preVisualizacao").onclick = null;
document.getElementById("preVisualizacao").style.cursor = "not-allowed";
document.getElementById("nomeDoArquivo").innerHTML = "Carregando arquivo...";
var preenchimentoProgresso = document.getElementById("progressoFill");
var request = new XMLHttpRequest();
var formData = new FormData();
formData.append("arquivo", file);
formData.append("plataforma", plataformaDosJogos[parseInt(jogoSelecionadoId)]);
formData.append("pacote", pacoteDosJogos[parseInt(jogoSelecionadoId)]);
formData.append("versao", versoesDosJogos[parseInt(jogoSelecionadoId)]);
request.open("POST", "../ajax-query/receber-arquivo-expansao.php");
request.upload.addEventListener("progress", function(evt){
if(evt.lengthComputable){
preenchimentoProgresso.style.width = ((evt.loaded / evt.total) * 100) + "%";
}
else{
redefinirInterface();
document.getElementById("nomeDoArquivo").innerHTML = "Erro no upload";
}
}, false);
request.send(formData);
request.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status === 200){
eval(this.responseText);
}
else{
parent.mostrarNotificacao('Ocorreu um erro de conexão durante o Upload.', '#750000', 5000);
redefinirInterface();
}
}
};
}
//Função que exibe a mensagem de sucesso após criar arquivo de notícia
function exibirMensagemArquivoEnviado(){
document.getElementById("arquivoEnviado").style.display = "block";
document.getElementById("formularioUpload").style.display = "none";
document.getElementById("quadroDeAvisos").style.display = "none";
parent.redimensionarIframe();
}
aoTrocarJogo();
</script>
<?php
$conteudoQuadroDeAviso = ('
• Selecione o jogo ao qual, vai receber este arquivo de expansão, e faça o envio.
<br/>
• O arquivo de expansão enviado aqui, será associado a Última Versão informada, no cadastro desse jogo, automaticamente.
<br/>
• Caso um jogo de um cliente esteja sem os arquivos de expansão, o Windsoft Launcher irá buscar no servidor, o arquivo de expansão correspondente a versão instalada no dispositivo do cliente.
<br/>
• Verifique se a Última Versão informada no cadastro do jogo, é a correta, antes de enviar.
<br/>
• Os arquivos de expansão devem ter o formato de OBB ou ZIP. Caso o upload dê erro, em arquivos grandes, faça o carregamento usando FTP.
<br/>
• Caso já exista um arquivo de expansão, para esta versão do jogo selecionado, o arquivo existente será sobrescrevido.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/client.php
<?php
/*
* Essa página é responsável pela pagina inicial client do painal de administração
*/
$tituloPagina = "Admin Painel - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("../../includes/cabecalho.inc");
RedirecionarParaLoginCasoNaoEstejaLogado();
include("../../../global/mysql/feedbacks.inc");
include("../../../global/mysql/registros.inc");
include("../../../global/mysql/metadados.inc");
//Redireciona para o inicio caso não tenha permissão
if($_SESSION["autoridade"] == 0){
header('Location: http://windsoft.xyz');
}
?>
<!-- Estilo da janela modal -->
<style>
.fundoModal{
position: fixed;
top: 0px;
left: 0px;
background-color: rgba(0, 0, 0, 0.6);
width: 100%;
height: 100%;
z-index: 50;
opacity: 0;
transition: opacity 250ms;
pointer-events: none;
}
.caixaModal{
background-color: #E8E8E8;
width: 80%;
max-width: 250px;
height: 80%;
max-height: 70%;
margin-left: auto;
margin-right: auto;
padding: 10px;
border-radius: 6px;
}
.caixaModalRaiz{
position: fixed;
top: -1000px;
left: 0px;
display: flex;
justify-content: center;
align-items: center;
z-index: 80;
width: 100%;
height: 100%;
transition: top 200ms;
}
.itemMenu{
cursor: pointer;
border-radius: 4px;
padding: 5px;
transition: 250ms;
}
.itemMenu:hover{
background-color: #D8D8D8;
}
</style>
<!-- fundo das caixas de dialogo -->
<div class="fundoModal" id="escurecimento"></div>
<!-- caixa de dialogo para o menu -->
<div class="caixaModalRaiz" id="menu">
<div class="caixaModal">
<div style="height: 30px; background-color: #FFFFFF; border-radius: 4px 4px 0px 0px; height: 30px; margin: -10px -10px 10px -10px; padding: 10px;">
<div style="float: left; line-height: 30px; font-weight: bolder;">
Menu do Painel
</div>
<img src="imagens/fechar.png" height="30px" style="float: right; cursor: pointer;" onclick="abrirMenu(false);" />
</div>
<div style="height: calc(100% - 50px); overflow: auto;">
<?php
$altura = 1300;
if($_SESSION["autoridade"] >= 4){
$altura = $altura + 200;
}
?>
<div style="height: <?php echo($altura); ?>px; width: 100%;">
<?php include("menu-itens.inc"); ?>
<?php if($_SESSION["autoridade"] >= 4){ include("menu-itens-mt-assets.inc"); } ?>
</div>
</div>
</div>
</div>
<!-- cria topbar que exibe as informações de staff -->
<div style="background-color: #E2E2E2; border-radius: 4px; width: calc(100% - 20px); padding: 10px; margin-bottom: 10px; overflow: auto; display: grid; grid-template-columns: 33.3% 33.3% 33.3%;">
<div align="left">
<div style="color: #b2b2b2; font-size: 10px;">
<?php
echo($_SESSION["cargo"]);
?>
</div>
<div style="font-weight: bolder;">
<?php
$id = $_SESSION["id"];
$consultaPerfil = mysqli_query($DB_Registros, "SELECT Nome FROM Perfis WHERE ID=$id");
$dadosPerfil = mysqli_fetch_array($consultaPerfil);
echo($dadosPerfil[0]);
?>
</div>
</div>
<div align="center">
<div style="color: #b2b2b2; font-size: 10px;">
Autoridade
</div>
<div align="left" style="background-color: #BABABA; border-radius: 4px; width: 60px; height: 6px; margin-top: 6px;">
<?php
if($_SESSION["autoridade"] == 1){
echo("<div style=\"background-color: #AD913C; border-radius: 4px; width: 25%; height: 100%;\"></div>");
}
if($_SESSION["autoridade"] == 2){
echo("<div style=\"background-color: #73A013; border-radius: 4px; width: 50%; height: 100%;\"></div>");
}
if($_SESSION["autoridade"] == 3){
echo("<div style=\"background-color: #0EAD00; border-radius: 4px; width: 75%; height: 100%;\"></div>");
}
if($_SESSION["autoridade"] == 4){
echo("<div style=\"background-color: #007FCE; border-radius: 4px; width: 100%; height: 100%;\"></div>");
}
?>
</div>
</div>
<div align="right">
<img src="imagens/menu.png" height="27px" style="float: right; cursor: pointer;" onclick="abrirMenu(true);" />
</div>
</div>
<!-- iframe que exibe as páginas desejadas -->
<iframe id="iframe" onload="concluirCarregamento();" scrolling="no" style="width: 100%; border: none; background-repeat: no-repeat; background-position: center; background-image: url(imagens/load.gif); background-size: 32px 32px; overflow: hidden;">
</iframe>
<!-- código java script do client -->
<script type="text/javascript">
function abrirMenu(abrir){
//Abre ou fecha o menu
if(abrir == true){
document.getElementById("menu").style.top = "0px";
document.getElementById("escurecimento").style.opacity = "1";
}
if(abrir == false){
document.getElementById("menu").style.top = "-1000px";
document.getElementById("escurecimento").style.opacity = "0";
}
}
function carregarPagina(pagina){
//esconde o ícone de emote
exibirIconeEmote(false);
//Carrega uma página desejada
mostrarSpinner(true);
abrirMenu(false);
//Carrega a página desejada dentro do iframe após um tempo
setTimeout(function(){
var iframe = document.getElementById("iframe");
iframe.src = "paginas/" + pagina;
}, 1000);
}
function abrirNovaAba(pagina){
//Abre a página desejada em uma nova aba
window.open(pagina, '_blank');
}
//método que conclui o carregamento do iframe
function concluirCarregamento() {
//redimensiona a altura do iframe conforme o conteúdo
redimensionarIframe();
//remove o carregamento
document.getElementById('iframe').style.backgroundImage = "";
setTimeout(function(){
mostrarSpinner(false);
}, 500);
}
//método que redimensiona o iframe de conteúdo de acordo com o que possui dentro, mantendo a mesma posição da tela
function redimensionarIframe() {
var iframe = document.getElementById('iframe');
var posicaoAntesDoRedimensionamento = document.documentElement.scrollTop;
iframe.height = "";
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
document.documentElement.scrollTop = posicaoAntesDoRedimensionamento;
}
//Carrega a página inicial
setTimeout(function(){
document.getElementById('iframe').style.backgroundImage = "url(imagens/load.gif)";
carregarPagina("home.php");
}, 25);
</script>
<?php
include("../../includes/rodape.inc");
?><file_sep>/browser/microsite/mt-assets/includes/cabecalho.inc
<?php
/*
* Essa classe é responsável por fornecer o cabeçalho das páginas.
*/
?>
<html>
<head>
<title><?php echo($TituloPagina); ?></title>
<link rel="stylesheet" href="estilos/estilo-padrao.css" />
<link rel="icon" href="favicons/favicon.ico" type="image/x-icon" />
<link rel="shortcut/icon" href="favicons/favicon.ico" type="image/x-icon" />
</head>
<body>
<div class="topBar">
<div style="float: left; height: 45px; margin: 3px;">
<img src="images/mtw.png" height="40px" />
</div>
<div style="float: left; height: 45px;">
<div style="line-height: 33px; vertical-align: middle; margin-left: 3px; color: #ffffff; font-weight: bold; font-size: 22px;">
MT Assets
</div>
<div style="line-height: 8px; vertical-align: middle; margin-left: 3px; color: #d3d3d3; font-size: 10px;">
for Unity Engine
</div>
</div>
<div style="float: right; height: 45px;">
<div style="line-height: 16px; vertical-align: middle; margin-right: 10px; color: #d3d3d3; font-size: 10px; text-align: right;">
for support and contact
</div>
<div style="line-height: 25px; vertical-align: middle; margin-right: 10px; color: #ffffff; font-weight: bold; font-size: 16px;">
<EMAIL>
</div>
</div>
</div>
<a href="https://windsoft.xyz/mtassets">
<div class="bannerMT" style="background-image: url(images/banner-mt.png);">
</div>
</a>
<div class="subBody">
<br/><file_sep>/global/sessoes/criador-de-sessao.inc
<?php
/*
* Essa classe é responsável por criar sessões no servidor e fornecer o Cookie de acesso ao usuário.
*/
//Este script deve ser incluído no topo dos scripts.
function CriarNovaSessao($id, $nick){
//Cria uma sessão nova com os dados do usuário e fornece o Cookie referente a essa sessão, para o usuário.
session_start();
$_SESSION["id"] = $id;
$_SESSION["nick"] = $nick;
}
?><file_sep>/browser/microsite/painel/ajax-query/atualizar-post-it.php
<?php
/*
* script que atualiza o conteudo do post-it
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Obtem as variaveis
$texto = mysqli_real_escape_string($DB_Metadados, $_POST["texto"]);
$corDeFundo = mysqli_real_escape_string($DB_Metadados, $_POST["corDeFundo"]);
//Realiza a atualização do post it
$consultaAtualizacao = mysqli_query($DB_Metadados, "UPDATE StaffPostIt SET Texto='$texto', CorPostIt='$corDeFundo' WHERE ID=0");
echo("".
'parent.mostrarNotificacao("O Post-It foi atualizado com sucesso.", "#117700", 2500);'
."");
?><file_sep>/browser/microsite/painel/paginas/listar-assets.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem os assets cadastrados
$assetsConsulta = mysqli_query($DB_Metadados, "SELECT Nome, PrecoAtual, UrlImagem FROM AssetStore");
$i = 0;
while($linha = mysqli_fetch_assoc($assetsConsulta)) {
$nome[$i] = $linha["Nome"];
$precoAtual[$i] = $linha["PrecoAtual"];
$urlImagem[$i] = $linha["UrlImagem"];
$i += 1;
}
?>
<center>
<h3>Listar Assets Cadastrados</h3>
</center>
<table style="width: 100%; border-collapse: collapse; font-size: 14px;">
<tr>
<th style="border: 1px solid #ddd; padding: 4px; text-align: left;">Asset</th>
<th style="border: 1px solid #ddd; padding: 4px;">Preço Atual</th>
</tr>
<?php
for ($ii = 0; $ii < $i; $ii++) {
//Imprime o código HTML para representar este usuário
echo('
<tr>
<td style="border: 1px solid #ddd; padding: 4px;">
<div style="display: grid; grid-template-columns: 32px auto;">
<img src="'.$urlImagem[$ii].'" style="width: 24px; border-radius: 24px; margin-right: 8px;"/> <div style="line-height: 24px;">'.$nome[$ii].'</div>
</div>
</td>
<td style="text-align: right; border: 1px solid #ddd; padding: 4px;">
US$ '.$precoAtual[$ii].'
</td>
</tr>');
}
?>
</table>
<!-- código javascript desta página -->
<script type="text/javascript">
</script>
<?php
$conteudoQuadroDeAviso = ('
• Estes são todos os assets cadastrados no Banco de Dados até o momento.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/ajax-query/reportar-venda-asset.php
<?php
/*
* script que adiciona a venda ao historico de vendas do asset
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Código PHP que processa o armazenamento de dados de vendas dos assets e carrega todos os dados dos assets
include("../paginas/includes/mt-assets-historico-de-vendas.inc");
//Variaveis do script
$id = mysqli_real_escape_string($DB_Metadados, $_POST["id"]);
$copiasVendidas = mysqli_real_escape_string($DB_Metadados, $_POST["copiasVendidas"]);
$precoVenda = mysqli_real_escape_string($DB_Metadados, $_POST["precoAsset"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Incrementa na quantidade de vendas do respectivo asset, na data de hoje
$armazenamento = json_decode($vendasPorDataJson[$id]);
$arrayObjetosAno = $armazenamento->anosArmazenados;
for ($x = 0; $x < count($arrayObjetosAno); $x++) {
if($arrayObjetosAno[$x]->numeroAno == date("Y")){
$anoSelecionado = $arrayObjetosAno[$x];
}
}
$mesSelecionado = $anoSelecionado->mesesDoAno[(int)(date("n")) - 1];
$diaSelecionado = $mesSelecionado->diasDoMes[(int)(date("j")) - 1];
$diaSelecionado->quantiaDeVendas += $copiasVendidas;
$diaSelecionado->receitaDoDia += $precoVenda * $copiasVendidas;
$codigoJson = json_encode($armazenamento);
//Aplica as alterações
$consultaReporte = mysqli_query($DB_Metadados, "UPDATE AssetStore SET VendasPorData_Json='$codigoJson' WHERE ID=$id");
echo("".
'parent.mostrarNotificacao("A venda foi reportada com sucesso!", "#117700", 2500);'.
'AtualizarDadosNaTela('.$id.', '.$copiasVendidas.', '.($precoVenda * $copiasVendidas).')'
."");
}
?><file_sep>/browser/microsite/painel/paginas/editar-um-slide.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem os dados de todos os slides
$slidesConsulta = mysqli_query($DB_Metadados, "SELECT Titulo, UrlDaPagina, UrlDaCapa FROM Noticias WHERE Noticia IN (".implode(',', $a=array(1, 2, 3, 4, 5)).")");
$i = 0;
while($linha = mysqli_fetch_assoc($slidesConsulta)) {
$titulo[$i] = $linha["Titulo"];
$urlPagina[$i] = $linha["UrlDaPagina"];
$urlCapa[$i] = $linha["UrlDaCapa"];
$i += 1;
}
?>
<center>
<h3>Editar um Slide de Notícia</h3>
</center>
<div id="formulario" style="display: block;">
<center>
<form autocomplete="off">
<select id="selectSlide" onchange="trocarSlide();">
<option value="1">Slide 1</option>
<option value="2">Slide 2</option>
<option value="3">Slide 3</option>
<option value="4">Slide 4</option>
<option value="5">Slide 5</option>
</select>
<input id="titulo" type="text" placeholder="Título da Notícia" onkeyup="validarTitulo();"
value="<?php echo($titulo[0]); ?>"/>
<div id="tituloStatus" class="statusCampo"></div>
<input id="urlPagina" type="text" placeholder="URL da Página" onkeyup="validarUrlPagina();"
value="<?php echo($urlPagina[0]); ?>"/>
<div id="urlPaginaStatus" class="statusCampo"></div>
<input id="urlCapa" type="text" placeholder="URL da Capa" onkeyup="validarUrlCapa();"
value="<?php echo($urlCapa[0]); ?>"/>
<div id="urlCapaStatus" class="statusCampo"></div>
<input type="button" value="Salvar" onclick="salvarEdicao();" />
</form>
</center>
</div>
<div id="slideEditado" style="display: none;">
<center>
<img src="../imagens/sucesso.png" width="128px" />
<br>
<br>
O Slide foi editado com sucesso!
<br>
Acesse a página inicial da Windsoft Games para ver a alteração.
<br>
<br>
<a href="https://windsoft.xyz" target="_blank">
<input type="button" value="Visualizar" />
</a>
<br>
</center>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
campoTitulo = document.getElementById("titulo");
statusTitulo = document.getElementById("tituloStatus");
tituloValido = false;
function validarTitulo(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoTitulo.value.length, 40);
//Desvalida
campoTitulo.style.borderColor = "#990000";
campoTitulo.style.borderWidth = "1px";
statusTitulo.style.color = "#990000";
tituloValido = false;
if(campoTitulo.value == ""){
statusTitulo.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoTitulo.value.length > 40){
statusTitulo.innerHTML = "Título muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoTitulo.value) == true){
statusTitulo.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoTitulo.style.borderColor = "";
campoTitulo.style.borderWidth = "";
statusTitulo.innerHTML = "";
tituloValido = true;
parent.redimensionarIframe();
}
campoUrlPagina = document.getElementById("urlPagina");
statusUrlPagina = document.getElementById("urlPaginaStatus");
urlPaginaValida = false;
function validarUrlPagina(){
//Desvalida
campoUrlPagina.style.borderColor = "#990000";
campoUrlPagina.style.borderWidth = "1px";
statusUrlPagina.style.color = "#990000";
urlPaginaValida = false;
if(campoUrlPagina.value == ""){
statusUrlPagina.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComUrl(campoUrlPagina.value) == false){
statusUrlPagina.innerHTML = "O conteúdo digitado não é uma URL.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoUrlPagina.style.borderColor = "";
campoUrlPagina.style.borderWidth = "";
statusUrlPagina.innerHTML = "";
urlPaginaValida = true;
parent.redimensionarIframe();
}
campoUrlCapa = document.getElementById("urlCapa");
statusUrlCapa = document.getElementById("urlCapaStatus");
urlCapaValido = false;
function validarUrlCapa(){
//Desvalida
campoUrlCapa.style.borderColor = "#990000";
campoUrlCapa.style.borderWidth = "1px";
statusUrlCapa.style.color = "#990000";
urlCapaValido = false;
if(campoUrlCapa.value == ""){
statusUrlCapa.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComUrl(campoUrlCapa.value) == false){
statusUrlCapa.innerHTML = "O conteúdo digitado não é uma URL.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoUrlCapa.style.borderColor = "";
campoUrlCapa.style.borderWidth = "";
statusUrlCapa.innerHTML = "";
urlCapaValido = true;
parent.redimensionarIframe();
}
//Função que verifica se todos os campos estão válidos
function todosOsCamposEstaoValidos(){
validarTitulo();
validarUrlPagina();
validarUrlCapa();
if(tituloValido == true && urlPaginaValida == true && urlCapaValido == true){
return true;
}
if(tituloValido == false || urlPaginaValida == false || urlCapaValido == false){
parent.mostrarNotificacao("Verifique o formulário em busca de erros e tente novamente.", "#750000", 3000);
return false;
}
}
//Função que troca o conteudo dos campos de acordo com o slide selecionado
tituloSlide = ["<?php echo($titulo[0]); ?>", "<?php echo($titulo[1]); ?>", "<?php echo($titulo[2]); ?>", "<?php echo($titulo[3]); ?>", "<?php echo($titulo[4]); ?>"];
urlPaginaSlide = ["<?php echo($urlPagina[0]); ?>", "<?php echo($urlPagina[1]); ?>", "<?php echo($urlPagina[2]); ?>", "<?php echo($urlPagina[3]); ?>", "<?php echo($urlPagina[4]); ?>"];
urlCapaSlide = ["<?php echo($urlCapa[0]); ?>", "<?php echo($urlCapa[1]); ?>", "<?php echo($urlCapa[2]); ?>", "<?php echo($urlCapa[3]); ?>", "<?php echo($urlCapa[4]); ?>"];
function trocarSlide(){
var slideSelecionado = parseInt(document.getElementById("selectSlide").value) - 1;
campoTitulo.value = tituloSlide[slideSelecionado];
campoUrlPagina.value = urlPaginaSlide[slideSelecionado];
campoUrlCapa.value = urlCapaSlide[slideSelecionado];
todosOsCamposEstaoValidos();
}
//Função que publica a noticia
function salvarEdicao(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/editar-slide.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"id=" + document.getElementById("selectSlide").value +
"&titulo=" + document.getElementById("titulo").value +
"&urlPagina=" + document.getElementById("urlPagina").value +
"&urlCapa=" + document.getElementById("urlCapa").value);
}
}
//Função que exibe a mensagem de sucesso após criar arquivo de notícia
function exibirMensagemSlideEditado(){
document.getElementById("slideEditado").style.display = "block";
document.getElementById("formulario").style.display = "none";
document.getElementById("quadroDeAvisos").style.display = "none";
parent.redimensionarIframe();
}
todosOsCamposEstaoValidos();
</script>
<?php
$conteudoQuadroDeAviso = ('
• Selecione o slide de notícia que você deseja editar, faça suas alterações e basta salvar.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/ajax-query/salvar-edicao-criar-noticia.php
<?php
/*
* script que recebe o conteúdo da edição e o salva em arquivos temporários,
* para persistir a edição
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$titulo = $_POST["titulo"];
$urlCapa = $_POST["urlCapa"];
$descricao = $_POST["descricao"];
$introducao = $_POST["introducao"];
$subtitulo1 = $_POST["subtitulo1"];
$texto1 = $_POST["texto1"];
$subtitulo2 = $_POST["subtitulo2"];
$texto2 = $_POST["texto2"];
$subtitulo3 = $_POST["subtitulo3"];
$texto3 = $_POST["texto3"];
$subtitulo4 = $_POST["subtitulo4"];
$texto4 = $_POST["texto4"];
$subtitulo5 = $_POST["subtitulo5"];
$texto5 = $_POST["texto5"];
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Configura a data
date_default_timezone_set('America/Sao_Paulo');
$ano = date('Y');
$mesNumero = date('m');
$dia = date('d');
$hora = date('H');
$minuto = date('i');
//Cria os arquivos temporários de texto da noticia
salvarArquivoTemporario($_SESSION["id"] . "_noticia-titulo.tmp", $titulo);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-urlCapa.tmp", $urlCapa);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-descricao.tmp", $descricao);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-introducao.tmp", $introducao);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-subtitulo1.tmp", $subtitulo1);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-texto1.tmp", $texto1);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-subtitulo2.tmp", $subtitulo2);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-texto2.tmp", $texto2);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-subtitulo3.tmp", $subtitulo3);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-texto3.tmp", $texto3);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-subtitulo4.tmp", $subtitulo4);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-texto4.tmp", $texto4);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-subtitulo5.tmp", $subtitulo5);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-texto5.tmp", $texto5);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-dataSalvamento.tmp", "Alterações salvas em " . $dia . "/" . $mesNumero . "/" . $ano . " às " . $hora . ":" . $minuto);
salvarArquivoTemporario($_SESSION["id"] . "_noticia-existeEdicaoSalva.tmp", "true");
echo("".
'parent.mostrarNotificacao("Alterações salvas com sucesso.", "#117700", 2500);'.
'document.getElementById("alteracoes").innerHTML = "' . "Alterações salvas em " . $dia . "/" . $mesNumero . "/" . $ano . " às " . $hora . ":" . $minuto . '";'.
"");
}
function salvarArquivoTemporario($nome, $conteudo){
//Configura o diretorio para salvar os arquivos de texto da edição
$diretorioDosArquivosTemporarios = "../paginas/noticias/temp";
//Salva o arquivo, o escrevendo
$arquivo = fopen($diretorioDosArquivosTemporarios . "/" . $nome, 'w');
fwrite($arquivo, $conteudo);
fclose($arquivo);
}
?><file_sep>/browser/microsite/painel/ajax-query/alterar-nome-de-um-usuario.php
<?php
/*
* script que edita o nickname de um usuário
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
include("../../../../global/mysql/registros.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$id = mysqli_real_escape_string($DB_Registros, $_POST["id"]);
$novoNick = mysqli_real_escape_string($DB_Registros, $_POST["novoNick"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Atualiza a versão do jogo no banco de dados
$consultaNick = mysqli_query($DB_Registros, "SELECT ID FROM Acesso WHERE Nick='$novoNick'");
//Caso esse nick já exista
if(mysqli_num_rows($consultaNick) == 1){
echo("".
'parent.mostrarNotificacao("Este nome de usuário já está a ser utilizado.", "#750000", 2500);'
."");
}
//Caso esse nick não exista
if(mysqli_num_rows($consultaNick) == 0){
$alteracaoNick = mysqli_query($DB_Registros, "UPDATE Acesso SET Nick='$novoNick' WHERE ID=$id");
echo("".
'parent.mostrarNotificacao("O nome de usuário foi aplicado com sucesso!", "#1E7200", 3000);'
."document.getElementById('nick').value = '".$novoNick."';"
."editarUsuario();"
."");
}
}
?><file_sep>/browser/microsite/painel/paginas/listar-staffs.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Obtem os dados de membros cadastrados como Staff
$staffConsulta = mysqli_query($DB_Metadados, "SELECT Nick, Cargo, Autoridade FROM Staff");
$i = 0;
while($linha = mysqli_fetch_assoc($staffConsulta)) {
$nick[$i] = $linha["Nick"];
$cargo[$i] = $linha["Cargo"];
$autoridade[$i] = $linha["Autoridade"];
$i += 1;
}
?>
<center>
<h3>Listar Membros da Staff</h3>
</center>
<table style="width: 100%; border-collapse: collapse; font-size: 14px;">
<tr>
<th style="border: 1px solid #ddd; padding: 4px; text-align: left;">Nome de Usuário</th>
<th style="border: 1px solid #ddd; padding: 4px;">Cargo</th>
<th style="border: 1px solid #ddd; padding: 4px; text-align: right;">Autoridade</th>
</tr>
<?php
for ($ii = 0; $ii < $i; $ii++) {
$autoridadeTexto = "";
if($autoridade[$ii] == 0){
$autoridadeTexto = "Nenhuma";
}
if($autoridade[$ii] == 1){
$autoridadeTexto = "Baixa";
}
if($autoridade[$ii] == 2){
$autoridadeTexto = "Média";
}
if($autoridade[$ii] == 3){
$autoridadeTexto = "Alta";
}
if($autoridade[$ii] == 4){
$autoridadeTexto = "Total (CEO)";
}
//Imprime o código HTML para representar este usuário
echo('
<tr>
<td style="border: 1px solid #ddd; padding: 4px;">
'.$nick[$ii].'
</td>
<td style="text-align: center; border: 1px solid #ddd; padding: 4px;">
'.$cargo[$ii].'
</td>
<td style="text-align: right; border: 1px solid #ddd; padding: 4px;">
'.$autoridadeTexto.'
</td>
</tr>');
}
?>
</table>
<!-- código javascript desta página -->
<script type="text/javascript">
</script>
<?php
$conteudoQuadroDeAviso = ('
• Estes são todos os membros cadastrados como Staff, no banco de dados.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/paginas/cadastrar-novo-jogo.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<center>
<h3>Cadastrar Novo Jogo</h3>
</center>
<div id="formulario">
<center>
<form autocomplete="off">
<input id="titulo" type="text" placeholder="Nome do Jogo" onkeyup="validarTitulo();" />
<div id="tituloStatus" class="statusCampo"></div>
<input id="versao" type="text" placeholder="Última Versão" onkeyup="validarVersao();" />
<div id="versaoStatus" class="statusCampo"></div>
<input id="pacote" type="text" placeholder="Nome do Pacote" onkeyup="validarPacote();" />
<div id="pacoteStatus" class="statusCampo"></div>
<select id="plataforma" onchange="">
<option value="Android">Android</option>
<option value="Fuchsia">Fuchsia</option>
<option value="Windows">Windows</option>
</select>
<input id="link" type="text" placeholder="Link na Loja" onkeyup="validarLinkLoja();" />
<div id="linkStatus" class="statusCampo"></div>
<div class="checkboxMainContainer">
<label class="container">
<div>
Exibir este jogo, na página inicial do site da Windsoft.
</div>
<input type="checkbox" id="exibir" onchange="validarExibir();">
<span class="checkmark"></span>
</label>
</div>
<input type="button" value="Cadastrar" onclick="salvarEdicao();" />
</form>
</center>
</div>
<div id="jogoCadastrado" style="display: none;">
<center>
<img src="../imagens/sucesso.png" width="128px" />
<br>
<br>
O novo jogo foi cadastrado com sucesso, no banco de dados!
<br>
<br>
</center>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
campoTitulo = document.getElementById("titulo");
statusTitulo = document.getElementById("tituloStatus");
tituloValido = false;
function validarTitulo(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoTitulo.value.length, 30);
//Desvalida
campoTitulo.style.borderColor = "#990000";
campoTitulo.style.borderWidth = "1px";
statusTitulo.style.color = "#990000";
tituloValido = false;
if(campoTitulo.value == ""){
statusTitulo.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoTitulo.value.length > 30){
statusTitulo.innerHTML = "Nome muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoTitulo.value) == true){
statusTitulo.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoTitulo.style.borderColor = "";
campoTitulo.style.borderWidth = "";
statusTitulo.innerHTML = "";
tituloValido = true;
parent.redimensionarIframe();
}
campoVersao = document.getElementById("versao");
statusVersao = document.getElementById("versaoStatus");
versaoValido = false;
function validarVersao(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoVersao.value.length, 8);
//Desvalida
campoVersao.style.borderColor = "#990000";
campoVersao.style.borderWidth = "1px";
statusVersao.style.color = "#990000";
versaoValido = false;
if(campoVersao.value == ""){
statusVersao.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoVersao.value.length > 8){
statusVersao.innerHTML = "Nome de versão, muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoVersao.value) == true){
statusVersao.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoVersao.style.borderColor = "";
campoVersao.style.borderWidth = "";
statusVersao.innerHTML = "";
versaoValido = true;
parent.redimensionarIframe();
}
campoPacote = document.getElementById("pacote");
statusPacote = document.getElementById("pacoteStatus");
pacoteValido = false;
function validarPacote(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoPacote.value.length, 30);
//Desvalida
campoPacote.style.borderColor = "#990000";
campoPacote.style.borderWidth = "1px";
statusPacote.style.color = "#990000";
pacoteValido = false;
if(campoPacote.value == ""){
statusPacote.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoPacote.value.length > 30){
statusPacote.innerHTML = "Nome do pacote, muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoPacote.value) == true){
statusPacote.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoPacote.style.borderColor = "";
campoPacote.style.borderWidth = "";
statusPacote.innerHTML = "";
pacoteValido = true;
parent.redimensionarIframe();
}
campoLink = document.getElementById("link");
statusLink = document.getElementById("linkStatus");
linkValido = false;
function validarLinkLoja(){
//Desvalida
campoLink.style.borderColor = "#990000";
campoLink.style.borderWidth = "1px";
statusLink.style.color = "#990000";
linkValido = false;
if(campoLink.value == ""){
statusLink.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComUrl(campoLink.value) == false){
statusLink.innerHTML = "O conteúdo digitado não é uma URL.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoLink.style.borderColor = "";
campoLink.style.borderWidth = "";
statusLink.innerHTML = "";
linkValido = true;
parent.redimensionarIframe();
}
//Ao ativar/desativar exibição do jogo na home page
checkbox = document.getElementById("exibir");
checkboxExibir = "0";
function validarExibir(){
if(checkbox.checked == true){
checkboxExibir = "1";
}
if(checkbox.checked == false){
checkboxExibir = "0";
}
}
//Função que verifica se todos os campos estão válidos
function todosOsCamposEstaoValidos(){
validarTitulo();
validarPacote();
validarExibir();
validarVersao();
validarLinkLoja();
if(tituloValido == true && pacoteValido == true && versaoValido == true && linkValido == true){
return true;
}
if(tituloValido == false || pacoteValido == false || versaoValido == false || linkValido == false){
parent.mostrarNotificacao("Verifique o formulário em busca de erros e tente novamente.", "#750000", 3000);
return false;
}
}
//Função que publica o jogo
function salvarEdicao(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/cadastrar-novo-jogo.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"nome=" + document.getElementById("titulo").value +
"&ultimaVersao=" + document.getElementById("versao").value +
"&nomeDoPacote=" + document.getElementById("pacote").value +
"&plataforma=" + document.getElementById("plataforma").value +
"&linkLoja=" + document.getElementById("link").value +
"&exibirNoSite=" + checkboxExibir);
}
}
//Função que exibe a mensagem de sucesso após cadastrar jogo
function exibirMensagemJogoCadastrado(){
document.getElementById("jogoCadastrado").style.display = "block";
document.getElementById("formulario").style.display = "none";
document.getElementById("quadroDeAvisos").style.display = "none";
parent.redimensionarIframe();
}
</script>
<?php
$conteudoQuadroDeAviso = ('
• Caso o jogo não utilize nome de pacote, use o namespace do jogo.
<br/>
• Em "Última Versão", insira a última versão em que o jogo se encontra. O Windsoft Launcher usará este dado para se orientar sobre novas versões.
<br/>
• Caso o jogo seja multiplataforma, você deverá cadastra-lo uma vez para cada plataforma.
<br/>
• Após cadastrar o jogo nessa página, faça o upload do seu ícone.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/microsite/painel/paginas/publicar-noticia.php
<?php
//Obtem o nome da página atual e adiciona o cabeçalho
$estaPagina = basename(__FILE__, ".php") . ".php";
include("includes/cabecalho.inc");
?>
<?php
//Função que verifica se o arquivo temporário de edição, existe, caso exista, retorna o seu conteúdo, se não retorna uma string vazia
function arquivoExiste($nome){
//Configura o diretorio
$diretorioDoArquivo = "noticias/temp/" . $nome;
//Verifica sua existência
if(file_exists($diretorioDoArquivo) == false){
return "";
}
if(file_exists($diretorioDoArquivo) == true){
return file_get_contents($diretorioDoArquivo);
}
}
//Função que verifica se existe uma edição salva
$existeEdicaoSalva = false;
if(arquivoExiste($_SESSION["id"] . "_publicacao-existeEdicaoSalva.tmp") == true){
if(arquivoExiste($_SESSION["id"] . "_publicacao-existeEdicaoSalva.tmp") == "true"){
$existeEdicaoSalva = true;
}
}
?>
<center>
<h3>Publicar Nova Notícia</h3>
</center>
<div id="formulario" style="display: block;">
<center>
<form autocomplete="false">
<input id="titulo" type="text" placeholder="Título da Notícia" onkeyup="validarTitulo();"
value="<?php
$nome = $_SESSION["id"] . "_publicacao-titulo.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?>"/>
<div id="tituloStatus" class="statusCampo"></div>
<input id="urlPagina" type="text" placeholder="URL da Página" onkeyup="validarUrlPagina();"
value="<?php
$nome = $_SESSION["id"] . "_publicacao-urlPagina.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?>"/>
<div id="urlPaginaStatus" class="statusCampo"></div>
<input id="urlCapa" type="text" placeholder="URL da Capa" onkeyup="validarUrlCapa();"
value="<?php
$nome = $_SESSION["id"] . "_publicacao-urlCapa.tmp";
if(arquivoExiste($nome) == true && $existeEdicaoSalva == true){
echo(arquivoExiste($nome));
}
?>"/>
<div id="urlCapaStatus" class="statusCampo"></div>
<br>
<br>
<div id="alteracoes" style="text-align: center;">
<?php
if($existeEdicaoSalva == false){
echo("Nenhuma alteração salva.");
}
if($existeEdicaoSalva == true){
echo(arquivoExiste($_SESSION["id"] . "_publicacao-dataSalvamento.tmp"));
}
?>
</div>
<br>
<br>
<div style="display: grid; grid-template-columns: 50% 50%; width: 80%; max-width: 300px;">
<input type="button" value="Salvar" style="width: calc(100% - 8px); margin: 8px 8px 8px 0px;" onclick="salvarEdicao();" />
<input type="button" value="Publicar" style="width: calc(100% - 8px); margin: 8px 0px 8px 8px;" onclick="publicarNoticia();" />
</div>
</form>
</center>
</div>
<div id="noticiaPublicada" style="display: none;">
<center>
<img src="../imagens/sucesso.png" width="128px" />
<br>
<br>
A notícia foi publicada com sucesso!
<br>
Acesse a página inicial da Windsoft Games para ver a publicação.
<br>
<br>
<a href="https://windsoft.xyz" target="_blank">
<input type="button" value="Visualizar" />
</a>
<br>
</center>
</div>
<!-- código javascript desta página -->
<script type="text/javascript">
campoTitulo = document.getElementById("titulo");
statusTitulo = document.getElementById("tituloStatus");
tituloValido = false;
function validarTitulo(){
//Exibe a contagem
parent.exibirContadorDeCaracteres(campoTitulo.value.length, 40);
//Desvalida
campoTitulo.style.borderColor = "#990000";
campoTitulo.style.borderWidth = "1px";
statusTitulo.style.color = "#990000";
tituloValido = false;
if(campoTitulo.value == ""){
statusTitulo.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(campoTitulo.value.length > 40){
statusTitulo.innerHTML = "Título muito grande.";
parent.redimensionarIframe();
return;
}
if(parent.contemHtml(campoTitulo.value) == true){
statusTitulo.innerHTML = "Este campo não pode conter código HTML.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoTitulo.style.borderColor = "";
campoTitulo.style.borderWidth = "";
statusTitulo.innerHTML = "";
tituloValido = true;
parent.redimensionarIframe();
}
campoUrlPagina = document.getElementById("urlPagina");
statusUrlPagina = document.getElementById("urlPaginaStatus");
urlPaginaValida = false;
function validarUrlPagina(){
//Desvalida
campoUrlPagina.style.borderColor = "#990000";
campoUrlPagina.style.borderWidth = "1px";
statusUrlPagina.style.color = "#990000";
urlPaginaValida = false;
if(campoUrlPagina.value == ""){
statusUrlPagina.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComUrl(campoUrlPagina.value) == false){
statusUrlPagina.innerHTML = "O conteúdo digitado não é uma URL.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoUrlPagina.style.borderColor = "";
campoUrlPagina.style.borderWidth = "";
statusUrlPagina.innerHTML = "";
urlPaginaValida = true;
parent.redimensionarIframe();
}
campoUrlCapa = document.getElementById("urlCapa");
statusUrlCapa = document.getElementById("urlCapaStatus");
urlCapaValido = false;
function validarUrlCapa(){
//Desvalida
campoUrlCapa.style.borderColor = "#990000";
campoUrlCapa.style.borderWidth = "1px";
statusUrlCapa.style.color = "#990000";
urlCapaValido = false;
if(campoUrlCapa.value == ""){
statusUrlCapa.innerHTML = "Por favor, preencha este campo.";
parent.redimensionarIframe();
return;
}
if(parent.pareceComUrl(campoUrlCapa.value) == false){
statusUrlCapa.innerHTML = "O conteúdo digitado não é uma URL.";
parent.redimensionarIframe();
return;
}
//Deixa como válido caso não haja nenhum problema
campoUrlCapa.style.borderColor = "";
campoUrlCapa.style.borderWidth = "";
statusUrlCapa.innerHTML = "";
urlCapaValido = true;
parent.redimensionarIframe();
}
//Função que verifica se todos os campos estão válidos
function todosOsCamposEstaoValidos(){
validarTitulo();
validarUrlPagina();
validarUrlCapa();
if(tituloValido == true && urlPaginaValida == true && urlCapaValido == true){
return true;
}
if(tituloValido == false || urlPaginaValida == false || urlCapaValido == false){
parent.mostrarNotificacao("Verifique o formulário em busca de erros e tente novamente.", "#750000", 3000);
return false;
}
}
//Função que salva o conteúdo digitado, no servidor, através do ajax
function salvarEdicao(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/salvar-edicao-publicar-noticia.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"titulo=" + document.getElementById("titulo").value +
"&urlPagina=" + document.getElementById("urlPagina").value +
"&urlCapa=" + document.getElementById("urlCapa").value);
}
}
//Função que publica a noticia
function publicarNoticia(){
if(todosOsCamposEstaoValidos() == false){
return;
}
if(todosOsCamposEstaoValidos() == true){
parent.mostrarSpinner(true);
//Cria a conexão para salvar os dados
var conexao = parent.novaConexaoPost("ajax-query/publicar-noticia.php");
conexao.onreadystatechange = function(){
parent.mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
parent.definirFuncaoDeSucessoOuErro(conexao,
function()
{
parent.mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
eval(parent.textoDaConexao(conexao));
});
};
parent.iniciarConexaoPost(conexao,
"titulo=" + document.getElementById("titulo").value +
"&urlPagina=" + document.getElementById("urlPagina").value +
"&urlCapa=" + document.getElementById("urlCapa").value);
}
}
//Função que exibe a mensagem de sucesso após criar arquivo de notícia
function exibirMensagemNoticiaPublicada(){
document.getElementById("noticiaPublicada").style.display = "block";
document.getElementById("formulario").style.display = "none";
document.getElementById("quadroDeAvisos").style.display = "none";
parent.redimensionarIframe();
}
</script>
<?php
$conteudoQuadroDeAviso = ('
• Ao publicar esta noticia, a mesma será colocada no primeiro slide, em primeiro lugar. A noticia que estava em primeiro irá ocupar o segundo lugar, e assim sucessivamente.
<br/>
• A imagem de capa deve ter uma resolução de 400x400 para melhor posicionamento e exibição no browser e apps.
');
?>
<!-- Código do rodapé -->
<?php include("includes/rodape.inc"); ?><file_sep>/browser/noticias/por-data/2018/08/24/Envie-sua-opinio.php
<!DOCTYPE html>
<html>
<head>
<!-- Meta tags do Facebook, Google e LinkedIn -->
<meta property="og:title" content="Windsoft Notícias: Envie sua opinião!" />
<meta property="og:type" content="article" />
<meta property="og:image" content="https://windsoft.xyz/Club/Noticias/PorData/2018/08/24/IMG-101223.jpg" />
<meta property="og:image:width" content="400px" />
<meta property="og:image:height" content="400px" />
<meta property="og:url" content="https://windsoft.xyz/Club/Noticias/PorData/2018/08/24/<?php echo basename($_SERVER['PHP_SELF']); ?>?b" />
<meta property="og:description" content="Utilize o app do Windsoft Club e envie sua opinião!" />
<meta property="fb:app_id" content="1100512010112474" />
<link media="screen and (min-width: 128px)">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#1E90FF">
<link rel="icon" href="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/favicon.ico" type="image/x-icon" />
<title>Envie sua opinião! - Windsoft Notícias</title>
<style>
html, body {
height: 100%;
}
body {
padding: 0;
background-color: #d6d6d6;
margin: 0 auto !important;
background-repeat: no-repeat;
background-size: 100% 100%;
font-family: gotham, arial, helvetica, sans-serif;
font-size: 12px;
}
hr {
border: 0;
height: 1px;
background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(206, 206, 206, 0.75), rgba(0, 0, 0, 0));
}
a {
text-decoration: none;
color: #3068c1;
}
a:link {
text-decoration: none;
color: #3068c1;
}
a:hover {
color: #404144;
}
a:visited {
color: #3068c1;
text-decoration:none;
}
.card{
margin-top: 10px;
margin-bottom: 10px;
background-color: #f9f9f9;
max-width: 500px;
width: 95%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
border-radius: 6px;
display: block;
margin-left: auto;
margin-right: auto;
}
.cardConteudo{
padding: 8px 8px 8px 8px;
overflow: auto;
}
.capaFundo{
width: auto;
height: 200px;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
background-image: url(https://windsoft.xyz/Club/Noticias/PorData/2018/08/24/IMG-101223.jpg);
margin: -8px;
background-size: cover;
background-position: center center;
}
.capaEscurecimento{
background-color: rgba(0, 0, 0, 0.7);
width: 100%;
height: 100%;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
}
.capaConteudo{
color: white;
text-align: center;
position: relative;
top: 50%;
transform: translateY(-50%);
margin-left: 10px;
margin-right: 10px;
font-size: 18px;
font-weight: bolder;
}
.dadosPostagem{
display: inline-block;
}
.iconsRedeSocial{
display: inline-block;
cursor: pointer;
}
.redesSociaisCaixa{
border-color: #375584;
border-width: 1px;
border-style: solid;
border-radius: 5px;
width: 250px;
height: 150px;
}
.redesSociaisCaixaShare{
display: inline-block;
width: 124px;
height: 100%;
float: left;
}
.redesSociaisCaixaLike{
display: inline-block;
width: 124px;
height: 100%;
float: left;
}
.redesSociaisSeparador{
background-color: #375584;
display: inline-block;
width: 1px;
height: 100%;
float: left;
}
.botaoBaixarApp{
background-color: #d16830;
border-radius: 5px;
width: 120px;
height: 40px;
text-align: center;
text-weight: bolder;
color: white;
cursor: pointer;
padding-left: 7px;
padding-right: 10px;
}
.botaoBaixarApp:hover{
background-color: #1a5b1e;
background-size: 100%;
border-radius: 5px;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}
.botaoDireita{
float: right;
display: inline-block;
cursor: pointer;
}
.botaoDireita:hover{
background-color: #9b9b9b;
border-radius: 32px;
}
.conteudoExclusivoBrowsers{
display: <?php if(isset($_GET["b"])){ echo("block"); } else{ echo("none"); } ?>;
}
</style>
</head>
<body>
<!-- Toolbar e Logotipo. SÓ SÃO EXIBIDAS COM A VARIAVEL b SETADA NA URL -->
<div class="conteudoExclusivoBrowsers">
<center>
<img src="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/Logo.png" width="250" height="46" style="margin-top: 10px;"/>
</center>
<div class="card">
<div class="cardConteudo">
<div style="float: left; display: inline-block;">
<a href="https://windsoft.xyz">
<div class="botaoBaixarApp">
<div style="position: relative; top: 50%; transform: translateY(-45%); float: left;">
<img src="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/DownloadApp.png" width="20px" height="20px" />
</div>
<div style="position: relative; top: 50%; transform: translateY(-50%); float: right;">
Baixe nosso App!
</div>
</div>
</a>
</div>
<div class="botaoDireita">
<a href="https://windsoft.xyz">
<img src="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/Home.png" width="32px" height="32px" style="margin: 2px;" />
</a>
</div>
</div>
</div>
</div>
<!-- Corpo da notícia -->
<div class="card">
<div class="cardConteudo">
<div class="capaFundo">
<div class="capaEscurecimento">
<div class="capaConteudo">
Envie sua opinião!
</div>
</div>
</div>
<center>
<br/>
<div class="dadosPostagem">
<img src="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/Data.png" width="25px" height="25px" style="opacity: 0.6;" />
</div>
<div class="dadosPostagem">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
24 de Ago de 2018 ás 12:53
</div>
</div>
<div class="dadosPostagem">
<img src="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/Autor.png" width="25px" height="25px" style="opacity: 0.6;" />
</div>
<div class="dadosPostagem">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
marcos4503 (CEO)
</div>
</div>
</center>
<br/>
<br/>
<center>
Utilize o app do Windsoft Club e envie sua opinião!
</center>
<br/>
<br/>
<center>
<h2>Nós valorizamos a sua opinião</h2>
</center>
Sua opinião é muito importante para nós, afinal fazemos jogos para você! Se você tem uma sugestão ou opinião sobre nossos produtos, por gentileza, utilize o botão de enviar opinião que fica no canto inferiro do app do Windsoft Club!
<br/>
<br/>Enviando sua opinião, nós saberemos onde devemos melhorar e onde devemos investir para continuar agradando a todos os nossos fãs. Obrigado por estar com a gente! ❤
<center>
<h2></h2>
</center>
<center>
<h2></h2>
</center>
<br/>
<br/>
<br/>
<center>
<div class="redesSociaisCaixa">
<div class="redesSociaisCaixaLike">
<br/>
<b>Curta a Windsoft Games!</b>
<div style="position: relative; top: 50%; transform: translateY(-85%);">
<!-- Botão de curtir -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = 'https://connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v3.1&appId=1100512010112474&autoLogAppEvents=1';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="https://www.facebook.com/windsoft.games/" data-width="100" data-layout="box_count" data-action="like" data-size="large" data-show-faces="false" data-share="false"></div>
</div>
</div>
<div class="redesSociaisSeparador"></div>
<div class="redesSociaisCaixaShare">
<br/>
<b>Compartilhe esta Notícia!</b>
<div style="position: relative; top: 50%; transform: translateY(-70%); width: 100px;">
<!-- Botao Facebook -->
<img class="iconsRedeSocial" src="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/Facebook.png" width="40px" height="40px" style="margin-right: 5px;"
onclick="AbrirPopUp('https://www.facebook.com/sharer/sharer.php?u=https://windsoft.xyz/Club/Noticias/PorData/2018/08/24/<?php echo basename($_SERVER['PHP_SELF']); ?>%3Fb')"/>
<!-- Botao Google+ -->
<img class="iconsRedeSocial" src="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/Google+.png" width="40px" height="40px" style="margin-right: 5px;"
onclick="AbrirPopUp('https://plus.google.com/share?url=https://windsoft.xyz/Club/Noticias/PorData/2018/08/24/<?php echo basename($_SERVER['PHP_SELF']); ?>%3Fb')" />
<!-- Botao LinkedIn -->
<img class="iconsRedeSocial" src="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/LinkedIn.png" width="40px" height="40px" style="margin-right: 5px; margin-top: 5px;"
onclick="AbrirPopUp('https://www.linkedin.com/shareArticle?mini=true&url=https://windsoft.xyz/Club/Noticias/PorData/2018/08/24/<?php echo basename($_SERVER['PHP_SELF']); ?>%3Fb&title=Veja%20esta%20notícia%20do%20Windsoft%20Notícias!')" />
<!-- Botao Twitter -->
<img class="iconsRedeSocial" src="https://windsoft.xyz/Club/Noticias/ArquivosGlobais/Twitter.png" width="40px" height="40px"
onclick="AbrirPopUp('https://twitter.com/intent/tweet?text=Veja%20esta%20notícia%20do%20Windsoft%20Notícias!%20https://windsoft.xyz/Club/Noticias/PorData/2018/08/24/<?php echo basename($_SERVER['PHP_SELF']); ?>?b')" />
</div>
</div>
</div>
<!-- Abrir popup -->
<script>
function AbrirPopUp(URL){
window.open(URL, 'targetWindow', 'toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=450px, height=450px')
}
</script>
</center>
<br/>
<br/>
<br/>
<br/>
<br/>
</div>
</div>
<!-- Rodapé da notícia. SÓ SÃO EXIBIDAS COM A VARIAVEL b SETADA NA URL -->
<div class="conteudoExclusivoBrowsers">
<div class="card">
<div class="cardConteudo">
<center>
<a href="https://windsoft.xyz/">Nosso Site</a>
•
<a href="https://windsoft.xyz/link/termos">Termos de Uso</a>
•
<a href="https://windsoft.xyz/link/privacidade">Política de Privacidade</a>
•
<a href="https://windsoft.xyz/link/sobre">Sobre Nós</a>
<br/>
<br/>
Windsoft Games - 2018
<center>
</div>
</div>
</div>
<?php
//Registra a estatística de notícia aberta. Fica no fim para não influenciar a renderição do documento e suas META TAGS
include("../../../../../ConexoesMySQL/ClubMainAbrir.php");
$ConsultaDeIncrementacaoEstatistica = mysqli_query($ConexaoMain, "UPDATE ClubNoticiasEstatisticas SET NoticiasAbertas24Hrs = NoticiasAbertas24Hrs + 1, NoticiasAbertasSemana = NoticiasAbertasSemana + 1, NoticiasAbertasMes = NoticiasAbertasMes + 1 WHERE Idade='Atual'");
include("../../../../../ConexoesMySQL/ClubMainFechar.php");
?>
</body>
</html><file_sep>/browser/ajax-query/efetuar-login.php
<?php
/*
* script que faz consulta de login ao banco de dados
*/
include("../../global/sessoes/criador-de-sessao.inc");
include("../../global/mysql/registros.inc");
include("../../global/mysql/metadados.inc");
//Obtem as variaveis
$nick = mysqli_real_escape_string($DB_Registros, $_POST["nick"]);
$senha = MD5($_POST["senha"]);
//Consulta de autenticacao do login
$consultaDeAutenticacao = mysqli_query($DB_Registros, "SELECT ID, Senha, Email, Banimento, SuspensaoDias, SuspensaoMotivo, DataCriacao_Millis FROM Acesso WHERE Nick = '$nick'");
$dadosAutenticacao = mysqli_fetch_array($consultaDeAutenticacao);
$htmlMensagem = "
<div style=\"width: 80%; padding-top: 20px; padding-bottom: 20px; border-radius: 6px; margin-left: auto; margin-right: auto; max-width: 300px; background-color: #AD0000; color: #F4F4F4; animation-name: tremerDiv; animation-duration: 600ms;\">
%MENSAGEM%
</div>
<br>
";
//Realiza a autenticação
if(mysqli_num_rows($consultaDeAutenticacao) == 0){
echo(str_replace(array("%MENSAGEM%"), array("Usuário ou senha inválidos"), $htmlMensagem));
}
if(mysqli_num_rows($consultaDeAutenticacao) == 1){
//Caso a senha não bata
if($dadosAutenticacao[1] != $senha){
echo(str_replace(array("%MENSAGEM%"), array("Usuário ou senha inválidos"), $htmlMensagem));
}
//Caso a senha bata
if($dadosAutenticacao[1] == $senha){
//Verifica se existe alguma punição na conta
if($dadosAutenticacao[3] != ""){
echo(str_replace(array("%MENSAGEM%"), array("Sua conta foi banida pelo motivo abaixo<br><br>" . $dadosAutenticacao[3]), $htmlMensagem));
exit();
}
if($dadosAutenticacao[4] > 0){
echo(str_replace(array("%MENSAGEM%"), array("Sua conta foi suspensa por ".$dadosAutenticacao[4]." dias pelo motivo abaixo<br><br>" . $dadosAutenticacao[5]), $htmlMensagem));
exit();
}
//Obtem a hora atual em millis
$dataAtual = round(microtime(true) * 1000);
//Obtem os dados de perfil da conta
$consultaPerfil = mysqli_query($DB_Registros, "SELECT IdCapa, IdIcone FROM Perfis WHERE ID=$dadosAutenticacao[0]");
$dadosPerfil = mysqli_fetch_array($consultaPerfil);
//Obtem os dados de permissão
$consultaPermissao = mysqli_query($DB_Metadados, "SELECT Cargo, Autoridade FROM Staff WHERE Nick='$nick'");
$dadosPermissao = mysqli_fetch_array($consultaPermissao);
//Atualiza a data de ultimo login
$atualizaUltimoLogin = mysqli_query($DB_Registros, "UPDATE Perfis SET UltimoLogin_Millis=$dataAtual WHERE ID=$dadosAutenticacao[0]");
//Cria a sessão
CriarNovaSessao($dadosAutenticacao[0], $nick);
//Passa os dados para o cache
$_SESSION["email"] = $dadosAutenticacao[2];
$_SESSION["idIcone"] = $dadosPerfil[1];
$_SESSION["idCapa"] = $dadosPerfil[0];
$_SESSION["dataCriacaoMillis"] = $dadosAutenticacao[6];
//Grava os dados de permissão no cache
if(mysqli_num_rows($consultaPermissao) == 0){
$_SESSION["cargo"] = "Usuário";
$_SESSION["autoridade"] = 0;
}
if(mysqli_num_rows($consultaPermissao) == 1){
$_SESSION["cargo"] = $dadosPermissao[0];
$_SESSION["autoridade"] = $dadosPermissao[1];
}
//Executa a consulta para incrementar as estatisticas
$consultaEstatistica = mysqli_query($DB_Metadados, "UPDATE LoginsStats SET LoginsDia = LoginsDia + 1, LoginsSem = LoginsSem + 1, LoginsMes = LoginsMes + 1 WHERE Idade='Atual'");
echo("
<script type=\"text/javascript\" id=\"scriptRetornado\">
window.location.href = \"https://windsoft.xyz\";
</script>
");
}
}
?><file_sep>/browser/microsite/painel/ajax-query/lancar-nova-notificacao.php
<?php
/*
* script que lança uma nova notificação
*/
include("../../../../global/sessoes/verificador-de-sessao.inc");
include("../../../../global/mysql/metadados.inc");
//Verifica a sessão
VerificarSessao(true, false);
//Variaveis do script
$texto = mysqli_real_escape_string($DB_Metadados, $_POST["texto"]);
//Verificar se o usuário é da staff
if($_SESSION["autoridade"] > 0){
//Configura a data
date_default_timezone_set('America/Sao_Paulo');
$Date = date('Y-m-d H:i:s', time());
$Data = date('Y-m-d', time());
$Hora = date('H:i:s', time());
//Obtem a data atual em millis
$dataAtual = strtotime($Date) * 1000;
//Publica a notificação
$consultaLancamento = mysqli_query($DB_Metadados, "UPDATE Notificacao SET Texto='$texto', DataDeEnvio_Millis=$dataAtual WHERE Canal='Global'");
//Redefine a contagem de recebimentos da atual notificação para zero
$consultaRedefinirStats = mysqli_query($DB_Metadados, "UPDATE NotificacaoStats SET Recebimentos=0 WHERE Canal='Global'");
echo("".
'parent.mostrarNotificacao("A notificação foi publicada com êxito!", "#117700", 5000);'.
"");
}
?><file_sep>/browser/microsite/painel/paginas/includes/mt-assets-historico-de-vendas.inc
<?php
//Obtem os dados de todos os assets cadastrados
$consultaDeAssets = mysqli_query($DB_Metadados, "SELECT ID, Nome, PrecoAtual, VendasPorData_Json, DataPublicacao FROM AssetStore");
$i = 1;
while($linha = mysqli_fetch_assoc($consultaDeAssets)) {
$id[$i] = $linha["ID"];
$nome[$i] = $linha["Nome"];
$precoAtual[$i] = $linha["PrecoAtual"];
$vendasPorDataJson[$i] = $linha["VendasPorData_Json"];
$dataPublicacao[$i] = $linha["DataPublicacao"];
$i += 1;
}
//Faz uma varredura em cada asset
for ($x = 1; $x < $i; $x++) {
//Caso esse armazenamento esteja vazio, cria o armazenamento
if($vendasPorDataJson[$x] == ""){
$vendasPorDataJson[$x] = json_encode(CriarArmazenamento());
$consultaCriacao = mysqli_query($DB_Metadados, "UPDATE AssetStore SET VendasPorData_Json='$vendasPorDataJson[$x]' WHERE ID=$x");
}
//Caso esse armazenamento não tenha esse ano, adiciona este ano a ele
if(ObterAnoApartirDoArmazenamento($vendasPorDataJson[$x], date("Y")) == ""){
$vendasPorDataJson[$x] = json_encode(AdicionarAnoAoArmazenamento($vendasPorDataJson[$x]));
$consultaAdicaoAno = mysqli_query($DB_Metadados, "UPDATE AssetStore SET VendasPorData_Json='$vendasPorDataJson[$x]' WHERE ID=$x");
}
}
//-------- Métodos de Leitura ------------
//Método que obtem as vendas deste mes, de um determinado asset
function ObterVendasDesteMes($armazenamento){
$arrayObjetosAno = json_decode($armazenamento)->anosArmazenados;
for ($x = 0; $x < count($arrayObjetosAno); $x++) {
if($arrayObjetosAno[$x]->numeroAno == date("Y")){
$anoSelecionado = $arrayObjetosAno[$x];
}
}
$mesSelecionado = $anoSelecionado->mesesDoAno[(int)(date("n")) - 1];
$diasDesteMes = $mesSelecionado->diasDoMes;
$vendasDesteMes = 0;
for ($x = 0; $x < count($diasDesteMes); $x++) {
$vendasDesteMes += $diasDesteMes[$x]->quantiaDeVendas;
}
return $vendasDesteMes;
}
//Método que obtem as vendas de hoje, de um determinado asset
function ObterVendasDeHoje($armazenamento){
$arrayObjetosAno = json_decode($armazenamento)->anosArmazenados;
for ($x = 0; $x < count($arrayObjetosAno); $x++) {
if($arrayObjetosAno[$x]->numeroAno == date("Y")){
$anoSelecionado = $arrayObjetosAno[$x];
}
}
$mesSelecionado = $anoSelecionado->mesesDoAno[(int)(date("n")) - 1];
$diaSelecionado = $mesSelecionado->diasDoMes[(int)(date("j")) - 1];
return $diaSelecionado->quantiaDeVendas;
}
//Método que obtem a receita gerada hoje, de um determinado asset
function ObterReceitaDeHoje($armazenamento){
$arrayObjetosAno = json_decode($armazenamento)->anosArmazenados;
for ($x = 0; $x < count($arrayObjetosAno); $x++) {
if($arrayObjetosAno[$x]->numeroAno == date("Y")){
$anoSelecionado = $arrayObjetosAno[$x];
}
}
$mesSelecionado = $anoSelecionado->mesesDoAno[(int)(date("n")) - 1];
$diaSelecionado = $mesSelecionado->diasDoMes[(int)(date("j")) - 1];
return $diaSelecionado->receitaDoDia;
}
//Método que obtem um objeto "Ano" a partir do armazenamento
function ObterAnoApartirDoArmazenamento($armazenamento, $anoDesejado){
$arrayObjetosAno = json_decode($armazenamento)->anosArmazenados;
for ($x = 0; $x < count($arrayObjetosAno); $x++) {
if($arrayObjetosAno[$x]->numeroAno == $anoDesejado){
return $arrayObjetosAno[$x];
}
}
$vazio = "";
return $vazio;
}
//-------- Métodos de Escrita ------------
//Metodo que adiciona mais um objeto "Ano" a um armazenamento já existente
function AdicionarAnoAoArmazenamento($armazenamentoJson){
//Cria uma array de objetos "Dia"
$arrayObjetosDia = array();
for ($x = 0; $x < 31; $x++) {
$objetoDia = new stdClass;
$objetoDia->receitaDoDia = 0;
$objetoDia->quantiaDeVendas = 0;
array_push($arrayObjetosDia, $objetoDia);
}
//Cria uma array de objetos "Mes" para que seja armazenados 31 objetos "Dia"
$arrayObjetosMes = array();
for ($x = 0; $x < 12; $x++) {
$objetoMes = new stdClass;
$objetoMes->diasDoMes = $arrayObjetosDia;
array_push($arrayObjetosMes, $objetoMes);
}
//Cria um objeto "Ano" para que sejam armazenados 12 objetos "Mes"
$objetoAno = new stdClass;
$objetoAno->numeroAno = date("Y");
$objetoAno->mesesDoAno = $arrayObjetosMes;
//Lê o objeto "Armazenamento", adiciona o ano atual e retorna o "Armazenamento" atualizado
$armazenamento = json_decode($armazenamentoJson);
$arrayObjetosAno = $armazenamento->anosArmazenados;
array_push($arrayObjetosAno, $objetoAno);
$armazenamento->anosArmazenados = $arrayObjetosAno;
return $armazenamento;
}
//Metodo que cria o armazenamento para guardar objetos "Ano"
function CriarArmazenamento(){
//Cria uma array de objetos "Dia"
$arrayObjetosDia = array();
for ($x = 0; $x < 31; $x++) {
$objetoDia = new stdClass;
$objetoDia->receitaDoDia = 0;
$objetoDia->quantiaDeVendas = 0;
array_push($arrayObjetosDia, $objetoDia);
}
//Cria uma array de objetos "Mes" para que seja armazenados 31 objetos "Dia"
$arrayObjetosMes = array();
for ($x = 0; $x < 12; $x++) {
$objetoMes = new stdClass;
$objetoMes->diasDoMes = $arrayObjetosDia;
array_push($arrayObjetosMes, $objetoMes);
}
//Cria um objeto "Ano" para que sejam armazenados 12 objetos "Mes"
$objetoAno = new stdClass;
$objetoAno->numeroAno = date("Y");
$objetoAno->mesesDoAno = $arrayObjetosMes;
//Cria o objeto de "Armazenamento" (armazenando primeiramente, o ano atual) e o retorna
$arrayObjetosAno = array();
array_push($arrayObjetosAno, $objetoAno);
$objetoArmazenamento = new stdClass;
$objetoArmazenamento->anosArmazenados = $arrayObjetosAno;
return $objetoArmazenamento;
}
?><file_sep>/browser/login.php
<?php
/*
* Essa é a página de login do site da Windsoft Games
*/
$tituloPagina = "Login - Windsoft Games";
$exibirLogsDeDepuracaoDoPHP = false;
include("includes/cabecalho.inc");
RedirecionarParaHomeCasoEstejaLogado();
?>
<center>
<br/>
<h3>Entrar com sua conta da Windsoft</h3>
<br/>
<div id="respostaLogin">
</div>
<form autocomplete="off" id="formularioLogin">
<input type="text" id="nick" placeholder="Nome de usuário" autocorrect="off" autocapitalize="none">
<br/>
<input type="password" id="senha" placeholder="<PASSWORD>">
<br/>
<div class="checkboxMainContainer">
<label class="container">
<div>
Mantenha meu nome de usuário salvo para futuros logins.
</div>
<input type="checkbox" id="manterNick">
<span class="checkmark"></span>
</label>
</div>
<br/>
<br>
<input type="button" value="Entrar" onclick="consultarLogin();">
</form>
<br>
<small>
<a href="https://windsoft.xyz/browser/recuperar.php">Esqueceu sua senha?</a>
-
<a href="https://windsoft.xyz/browser/registrar.php">Crie sua conta!</a>
</small>
</center>
<!-- Javascript da página -->
<script type"text/javascript">
//Inicio
campoNick = document.getElementById("nick");
campoSenha = document.getElementById("senha");
respostaLogin = document.getElementById("respostaLogin");
//Caso tenha um nickname salvo no navegador, o restaura
if(localStorage.getItem("nick") != null){
campoNick.value = localStorage.getItem("nick");
document.getElementById("manterNick").checked = true;
}
function consultarLogin(){
//Salva o nick caso seja desejado
if(document.getElementById("manterNick").checked == true){
localStorage.setItem("nick", campoNick.value);
}
//Remove o nick caso não seja necessário
if(document.getElementById("manterNick").checked == false){
localStorage.removeItem("nick");
}
//Verifica se os campos forão preenchidos
if(campoNick.value == "" || campoSenha.value == ""){
mostrarNotificacao("Por favor, preencha todos os campos.", "#750000", 2000);
return;
}
respostaLogin.innerHTML = "";
mostrarSpinner(true);
//Cria a conexão e inicia
var conexao = novaConexaoPost("ajax-query/efetuar-login.php");
conexao.onreadystatechange = function(){
mostrarSpinner(false);
//Processa o resultado (1º erro, 2º sucesso)
definirFuncaoDeSucessoOuErro(conexao,
function()
{
mostrarNotificacao("Erro de conexão, tente novamente.", "#750000", 3500);
},
function()
{
respostaLogin.innerHTML = textoDaConexao(conexao);
eval(document.getElementById("scriptRetornado").innerHTML);
});
};
iniciarConexaoPost(conexao, "nick=" + campoNick.value + "&senha=" + campoSenha.value);
}
</script>
<?php
include("includes/rodape.inc");
?> | fb3c612a6e30457a7013c9be5522be04546572cf | [
"JavaScript",
"C#",
"PHP"
] | 94 | PHP | marcos4503/windsoft-site | 3076cc87594098b3c7eb6c23355d9243e09a9ab1 | bd71c1f4d4bf416670934175d66607e4748b3ced | |
refs/heads/master | <file_sep>#include "server.h"
using std::unordered_map;
using std::string;
using std::queue;
using std::vector;
pthread_t workers[NUM_WORKERS];
pthread_attr_t worker_attr;
pthread_mutex_t locks[NUM_WORKERS];
unordered_map<int, string> db; //DataBase
//op is the structure of single operation in the transaction.
struct op {
xxop code;
int key;
int key2;
string value;
op() {
}
op(xxop c, int k, string v = "") {
code = c;
key = k;
key2 = 0;
value = v;
}
op(xxop c, int k, int k2) {
code = c;
key = k;
key2 = k2;
value = "";
}
void show() {
printf("code = %d, key = %d, key2 = %d, value = %s\n", code, key, key2, value.c_str());
}
};
// ret is the structure of single key-value pair
struct ret {
int key;
string value;
ret() {
}
ret(int k, string v) {
key = k;
value = v;
}
void show() {
printf("key = %d, Value = %s\n", key, value.c_str());
}
};
// Init DB, for test only.
void initDB() {
for (int i = 1; i <= NUM_PARTITION * NUM_WORKERS; i++) {
db[i] = "Initial Data";
}
}
// Map key to the partition #
int getParti(int key) {
if (key < 1) {
return 1;
}
if (key > NUM_WORKERS * NUM_PARTITION) {
return NUM_WORKERS;
}
return (key % NUM_PARTITION == 0 ? key / NUM_PARTITION : key / NUM_PARTITION + 1);
}
// The worker.
void *worker_start(void *arg) {
queue<struct op> *myops = (queue<struct op> *)arg;
queue<struct ret> *tmp = new queue<struct ret>();
op cur;
// Worker accesses the Database.
while (!myops->empty()) {
cur = myops->front();
if (cur.code == GET) {
if (db.count(cur.key) > 0) {
tmp->push(ret(cur.key, db[cur.key]));
}
}
else if (cur.code == PUT) {
db[cur.key] = cur.value;
}
else if (cur.code == GETRANGE) {
for (int i = cur.key; i <= cur.key2; i++) {
if (db.count(i) > 0) {
tmp->push(ret(i, db[i]));
}
}
}
myops->pop();
}
pthread_exit((void*)tmp);
}
// The coordinator
gpb *dbaccess_1_svc(gpb *buf, struct svc_req *req) {
string tmpstr (buf->data, buf->size);
InMemDB::TransRequest tr;
tr.ParseFromString(tmpstr);
queue<struct op> *myops = new queue<struct op>();
for (int i = 0; i < tr.op_size(); i++) {
const InMemDB::TransRequest::Op& iter = tr.op(i);
switch (iter.code()) {
case InMemDB::TransRequest_Op_Code_GET:
myops->push(op(GET, iter.key()));
break;
case InMemDB::TransRequest_Op_Code_PUT:
myops->push(op(PUT, iter.key(), iter.value()));
break;
case InMemDB::TransRequest_Op_Code_GETRANGE:
myops->push(op(GETRANGE, iter.key(), iter.key2()));
break;
default:
break;
}
}
queue<struct op> *packs = new queue<struct op>[NUM_WORKERS]; //Decompose the transaction into small parts, and store into the corresponding position in packs.
vector<int> reg; //Remember which workers shall be used.
void *worker_result;
queue<struct ret> *tmp;
queue<struct ret> info; //Store the result of each worker into this variable.
InMemDB::TransResponse trsp;
InMemDB::TransResponse::Ret *trsp_ret;
op cur;
ret aret;
while (!myops->empty()) {
cur = myops->front();
if (cur.code == GETRANGE) { //GetRange may involve more than one partition.
while (getParti(cur.key) < getParti(cur.key2)) {
packs[getParti(cur.key) - 1].push(op(GETRANGE, cur.key, getParti(cur.key) * NUM_PARTITION));
cur.key = getParti(cur.key) * NUM_PARTITION + 1;
}
packs[getParti(cur.key) - 1].push(op(GETRANGE, cur.key, cur.key2));
}
else {
packs[getParti(cur.key) - 1].push(op(cur.code, cur.key, cur.value));
}
myops->pop();
}
int rc;
//Phase 1: Get all locks.
for (int i = 0; i < NUM_WORKERS; i++) {
if (!packs[i].empty()) {
pthread_mutex_lock(&locks[i]);
reg.push_back(i);
}
}
//Phase 2: Start workers.
for (size_t i = 0; i < reg.size(); i++) {
rc = pthread_create(&workers[reg[i]], &worker_attr, worker_start, (void *)(packs + reg[i]));
if (rc) {
printf("ERROR: worker init failed. %s\n", strerror(rc));
}
}
//Phase 3: Collect the results.
for (size_t i = 0; i < reg.size(); i++) {
rc = pthread_join(workers[reg[i]], &worker_result);
if (rc) {
printf("Worker fail to end.\n");
}
pthread_mutex_unlock(&locks[reg[i]]);
tmp = (queue<struct ret> *)worker_result;
while (!tmp->empty()) {
trsp_ret = trsp.add_ret();
aret = tmp->front();
trsp_ret->set_key(aret.key);
trsp_ret->set_value(aret.value);
tmp->pop();
}
delete tmp;
}
delete myops;
delete[] packs;
string str_trsp;
trsp.SerializeToString(&str_trsp);
gpb *buf_ret = new gpb();
buf_ret->size = str_trsp.size();
buf_ret->data = (char*)malloc(str_trsp.size());
memcpy(buf_ret->data, str_trsp.c_str(), str_trsp.size());
return buf_ret;
}
//int main(int argc, char *argv[]) {
// initDB();
// int rc; //Store any return value about pthread
// int fifo_max_prio, fifo_min_prio;
// struct sched_param fifo_param;
//
// //initialize and set worker thread joinable and FIFO...
// pthread_attr_init(&worker_attr);
// pthread_attr_setdetachstate(&worker_attr, PTHREAD_CREATE_JOINABLE);
//
// pthread_attr_init(&handle_attr);
// pthread_attr_setinheritsched(&handle_attr, PTHREAD_EXPLICIT_SCHED);
// pthread_attr_setschedpolicy(&handle_attr, SCHED_FIFO);
// fifo_max_prio = sched_get_priority_max(SCHED_FIFO);
// fifo_min_prio = sched_get_priority_min(SCHED_FIFO);
// fifo_param.sched_priority = (fifo_max_prio + fifo_min_prio) / 2;
// pthread_attr_setschedparam(&handle_attr, &fifo_param);
//
// //Construct a transaction, for test only.
// queue<struct op> *trans = new queue<struct op>();
// trans->push(op(PUT, 1, "0000"));
// trans->push(op(PUT, 51, "5151"));
// trans->push(op(GETRANGE, 1, 51));
//
// //Coordinator handle this transaction.
// rc = pthread_create(&handles[0], &handle_attr, handle_start, (void *)trans);
// if (rc) {
// printf("ERROR: handle create fail.\n");
// exit(-1);
// }
// rc = pthread_join(handles[0], NULL);
// pthread_exit(NULL);
//}
<file_sep>#include <iostream>
#include <string>
#include "TransMessage.h"
#include "TransMessage.pb.h"
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main(int argc, char *argv[]) {
if (argc < 2) {
cout << "You should specify the server address." << endl;
return 1;
}
gpb *buf = new gpb();
gpb *result;
InMemDB::TransRequest trans;
InMemDB::TransRequest::Op *op;
CLIENT *cl;
cl = clnt_create(argv[1], DBTRANS, DBTRANS_V1, "tcp");
if (cl == NULL) {
cout << "Could not connect to server" << endl;
return 1;
}
string tmp;
int key, key2;
while (true) {
cout << "Enter an operation code (or leave blank to finish): ";
getline(cin, tmp);
if (tmp.compare("put") == 0 || tmp.compare("get") == 0) {
op = trans.add_op();
if (tmp.compare("put") == 0) {
op->set_code(InMemDB::TransRequest_Op_Code_PUT);
}
else {
op->set_code(InMemDB::TransRequest_Op_Code_GET);
}
cout << "Enter a key: ";
cin >> key;
op->set_key(key);
cin.ignore(256, '\n');
if (tmp.compare("put") == 0) {
cout << "Enter a value: ";
getline(cin, *op->mutable_value());
}
}
else if (tmp.compare("getrange") == 0) {
op = trans.add_op();
op->set_code(InMemDB::TransRequest_Op_Code_GETRANGE);
cout << "Enter a start position: ";
cin >> key;
op->set_key(key);
cin.ignore(256, '\n');
cout << "Enter an end position: ";
cin >> key2;
op->set_key2(key2);
cin.ignore(256, '\n');
}
else {
break;
}
}
if (trans.op_size() < 1) {
cout << "No operation, exit now." << endl;
return 1;
}
tmp.clear();
trans.SerializeToString(&tmp);
buf->size = tmp.size();
buf->data = (char*)malloc(tmp.size());
memcpy(buf->data, tmp.c_str(), tmp.size());
result = dbaccess_1(buf, cl);
if (result == NULL) {
cout << "error:RPC failed" << endl;
return 1;
}
string tmp_rsp (result->data, result->size);
InMemDB::TransResponse trans_rsp;
trans_rsp.ParseFromString(tmp_rsp);
for (int i = 0; i < trans_rsp.ret_size(); i++) {
const InMemDB::TransResponse::Ret &ret = trans_rsp.ret(i);
cout << "Key: " << ret.key() << ", value: " << ret.value() << endl;
}
return 0;
}
<file_sep>#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <queue>
#include <vector>
#include <unordered_map>
#include "TransMessage.pb.h"
#include "TransMessage.h"
#define NUM_WORKERS 8
#define NUM_PARTITION 50
enum xxop {
GET,
PUT,
GETRANGE
};
<file_sep>InMemDB
=======
Usage:
Open a terminal & run
sudo ./server
Open another terminal & run
./client localhost
You will be asked to input one or more code(put, get, getrange) and some information.
Enter a blank to finish the input and send transaction to server.
<file_sep>.PHONY: all clean
CC = g++
CFLAGS = -std=c++11 -g -Wall `pkg-config --cflags protobuf`
all: protoc_middleman xdr_middleman server client
protoc_middleman: TransMessage.proto
protoc --cpp_out=. TransMessage.proto
@touch protoc_middleman
xdr_middleman: TransMessage.x
rpcgen TransMessage.x
@touch xdr_middleman
server.o: server.c
pkg-config --cflags protobuf
$(CC) -c -o server.o $(CFLAGS) server.c
client.o: client.c
$(CC) -c -o client.o $(CFLAGS) client.c
TransMessage.pb.o: TransMessage.pb.cc
pkg-config --cflags protobuf
$(CC) -c -o TransMessage.pb.o $(CFLAGS) TransMessage.pb.cc
TransMessage_svc.o: TransMessage_svc.c
$(CC) -c -o TransMessage_svc.o $(CFLAGS) TransMessage_svc.c
TransMessage_clnt.o: TransMessage_clnt.c
$(CC) -c -o TransMessage_clnt.o $(CFLAGS) TransMessage_clnt.c
TransMessage_xdr.o: TransMessage_xdr.c
$(CC) -c -o TransMessage_xdr.o $(CFLAGS) TransMessage_xdr.c
server: server.o TransMessage.pb.o TransMessage_svc.o TransMessage_xdr.o
$(CC) -o server server.o TransMessage.pb.o TransMessage_svc.o TransMessage_xdr.o -lpthread `pkg-config --libs protobuf`
client: client.o TransMessage.pb.o TransMessage_clnt.o TransMessage_xdr.o
$(CC) -o client client.o TransMessage.pb.o TransMessage_clnt.o TransMessage_xdr.o `pkg-config --libs protobuf`
clean:
rm -f server client
rm -f *.o
rm -f protoc_middleman TransMessage.pb.h TransMessage.pb.cc
rm -f xdr_middleman TransMessage.h TransMessage_svc.c TransMessage_xdr.c TransMessage_clnt.c
| 619e1588bee62319c6432839961cff4e24d950ba | [
"Markdown",
"C",
"Makefile",
"C++"
] | 5 | C | yuzhangqu/InMemDB | 30e930011969955ec0c7e6ee1e1726c976c1ecfe | 46f6a44d62b9c1b61cd3e8ca16f69e18c3326b02 | |
refs/heads/master | <repo_name>dwxero/Immoscout<file_sep>/src/main/java/com/dwxero/crawl/immoscout/repository/PropertyRepository.java
package com.dwxero.crawl.immoscout.repository;
import com.dwxero.crawl.immoscout.entity.Property;
import com.dwxero.crawl.immoscout.entity.PropertyState;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface PropertyRepository extends MongoRepository<Property, String> {
Property findById(String id);
Property findByUrl(String url);
Property findByExposeId(String exposeId);
List<Property> findByState(PropertyState state);
List<Property> findByState(PropertyState state, Pageable pageable);
}
<file_sep>/readme.md
# start mongo db
sudo ./dev/db/mongodb-osx-x86_64-2.6.5/bin/mongod
# connect to mongo db via terminal
./dev/db/mongodb-osx-x86_64-2.6.5/bin/mongo
# useful commands
show dbs;
show collections;
db.property.find().pretty()
db.property.remove({})<file_sep>/src/test/java/com/dwxero/crawl/immoscout/helper/DataExtractorHelperTest.java
package com.dwxero.crawl.immoscout.helper;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class DataExtractorHelperTest {
private String html;
@Before
public void loadExampleHtmlFile() throws Exception {
this.html = IOUtils.toString(this.getClass().getResourceAsStream("exampleRawHtml.html"),
"UTF-8"
);
}
@Test
public void testThatTitleExtractionWorks() {
// given
String title;
DataExtractorHelper helper = new DataExtractorHelper();
// when
title = helper.getTitleFromHtml(html);
// then
assertNotNull(title);
assertTrue("Wohntraum auf großem Eckgrundstück im noblen Junkersdorf".equals(title));
}
@Test
public void testThatAddressExtractionWorks() {
// given
String address;
DataExtractorHelper helper = new DataExtractorHelper();
// when
address = helper.getAddressFromHtml(html);
// then
assertNotNull(address);
assertTrue("Amselstraße 19, 50858 Köln, Junkersdorf".equals(address));
}
@Test
public void testThatPriceExtractionWorks() {
// given
double price;
DataExtractorHelper helper = new DataExtractorHelper();
// when
price = helper.getPriceFromHtml(html);
// then
assertEquals(1275000.00d, price, 0.001d);
}
@Test
public void testThatRoomsExtractionWorks() {
// given
double rooms;
DataExtractorHelper helper = new DataExtractorHelper();
// when
rooms = helper.getRoomsFromHtml(html);
// then
assertEquals(5.0d, rooms, 0.01d);
}
@Test
public void testThatBedroomsExtractionWorks() {
// given
double bedrooms;
DataExtractorHelper helper = new DataExtractorHelper();
// when
bedrooms = helper.getBedroomsFromHtml(html);
// then
assertEquals(4.0d, bedrooms, 0.01d);
}
@Test
public void testThatBathroomsExtractionWorks() {
// given
double bathrooms;
DataExtractorHelper helper = new DataExtractorHelper();
// when
bathrooms = helper.getBathroomsFromHtml(html);
// then
assertEquals(1.0d, bathrooms, 0.01d);
}
@Test
public void testThatSquareMetersLivingExtractionWorks() {
// given
double squareMetersLiving;
DataExtractorHelper helper = new DataExtractorHelper();
// when
squareMetersLiving = helper.getSquareMetersLivingFromHtml(html);
// then
assertEquals(172.0d, squareMetersLiving, 0.001d);
}
@Test
public void testThatSquareMetersLandExtractionWorks() {
// given
double squareMetersLand;
DataExtractorHelper helper = new DataExtractorHelper();
// when
squareMetersLand = helper.getSquareMetersLandFromHtml(html);
// then
assertEquals(539.0d, squareMetersLand, 0.001d);
}
@Test
public void testThatCommissionNoteExtractionWorks() {
// given
String commissionNote;
DataExtractorHelper helper = new DataExtractorHelper();
// when
commissionNote = helper.getCommissionNoteFromHtml(html);
// then
assertTrue("Nein".equals(commissionNote));
}
}<file_sep>/src/main/java/com/dwxero/crawl/immoscout/DetailsCrawler.java
package com.dwxero.crawl.immoscout;
import com.dwxero.crawl.immoscout.entity.Property;
import com.dwxero.crawl.immoscout.entity.PropertyState;
import com.dwxero.crawl.immoscout.service.PropertyService;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
/**
* this class crawls the detail information pages for the given properties in the database.
* the crawler only stores the raw html code in the property.
*/
@Component
public class DetailsCrawler implements Crawler {
private static final Logger LOG = LoggerFactory.getLogger(ListCreationCrawler.class);
private PropertyService propertyService;
@Autowired
public DetailsCrawler(PropertyService propertyService) {
this.propertyService = propertyService;
}
@Override
@Scheduled(fixedDelay = 10 * 1000)
public void crawl() {
LOG.info("------------------------------------");
LOG.info("Start of DetailsCrawler");
LOG.info("------------------------------------");
List<Property> listOfProperties = propertyService.getNewProperties();
for (Property property : listOfProperties) {
property = getInformationFromDetailsPage(property);
propertyService.updateProperty(property);
}
LOG.info("------------------------------------");
LOG.info("Finish of DetailsCrawler");
LOG.info("------------------------------------");
}
private Property getInformationFromDetailsPage(Property property) {
try {
LOG.info("Fetching information for property:" + property);
Connection.Response response = Jsoup.connect(property.getUrl()).method(Connection.Method.GET).execute();
if (response.statusCode() == 200) {
Document detailsPage = response.parse();
property.setRawHtml(detailsPage.html());
property.setState(PropertyState.DOWNLOADED);
return property;
} else {
property.setState(PropertyState.OFFLINE);
return property;
}
} catch (IOException e) {
LOG.error(e.getMessage());
return property;
}
}
}
| 88e87c15970e7b504348312b00bf59d0d026c09b | [
"Markdown",
"Java"
] | 4 | Java | dwxero/Immoscout | 869c74a4a5aba25f6aebedaf60a70b433c516bda | 090ebfad878f797d2866079105f86fb1a6b043e9 | |
refs/heads/master | <file_sep>app.controller('nodeJSController', function($scope, $http){
$scope.displayResults = function() {
$scope.venueList={};
$scope.params={
"location":$scope.location,
"search":$scope.search
};
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
var req = $http.post('http://127.0.0.1:8083/display',$scope.params);
req.then(function(data, status, headers, config) {
$scope.message = data;
console.log(JSON.stringify(data.data.response.groups[0].items.length));
for (var i = 0; i < data.data.response.groups[0].items.length;) {
$scope.venueList[i] = {
"name": data.data.response.groups[0].items[i].venue.name,
"location": data.data.response.groups[0].items[i].venue.location.address
};
i++;
}
});
}
});
// app.controller('searchctrl', function($scope, $http) {
// console.log("hi");
// $scope.getSearchResult = function() {
//
// $http.get('http://127.0.0.1:8082/getData?searchkey='+$scope.searchitem).then(function(data)
// {
//
// console.log(data.data);
// $scope.searchDescription = data.data.itemListElement[0].result.detailedDescription.articleBody;
// $scope.description = "Description:";
// $scope.searchimage = data.data.itemListElement[0].result.image.contentUrl;
//
//
//
// },function(err)
// {
// }
// )
// }
// })
<file_sep>var cors = require('cors');
var request= require('request');
var express = require('express');
var app = express();
var port = process.env.PORT || 8083;
app.use(express.static(__dirname + '/public'));
app.use(cors());
app.get('/', function(req, res) {
res.render('index');
})
app.post('/display', function (req, res) {
console.log(req.query.searchkey);
//console.log(req.query.searchkey2);
var searchKeyword = req.query.searchkey;
request("https://api.foursquare.com/v2/venues/explore?client_id=UI4R30BP32O2W3TNNZ4KUQVSXSNFHWATY3MK1XT0SDGRVY0V&client_secret=<KEY>&v=20180323&limit=3&near=" + "Kansas City"+ "&query=" + "Hospitals", function (error, data, body) {
//Check for error
if (error) {
return console.log('Error:', error);
}
console.log(data.body);
res.send(JSON.parse(data.body));
//Check for right status code
if (data.statusCode !== 200) {
return console.log('Invalid Status Code Returned:', data.statusCode);
}
});
});
// app.get('/getData', function (req, res) {
// var searchKeyword = req.query.searchkey;
// request("https://kgsearch.googleapis.com/v1/entities:search?query="+searchKeyword+"&key=<KEY>&limit=1&indent=True", function (error, response, body) {
// res.send(body);
// });
//
//
//
// });
app.listen(port, function() {
console.log('app running')
})
| c7acc9217bc3b37184309231336bcbb9bd1a7cc2 | [
"JavaScript"
] | 2 | JavaScript | VineethDvv/ICP_10 | 507a6588d20590f4f377c0aac705d2c640d3d607 | 761ffcfea8d5a7738b4bae53fbadb613630c30f3 | |
refs/heads/main | <file_sep># A3-String-Interpolation | 93f84c728828701cad4c06d981ff47baa87adc6f | [
"Markdown"
] | 1 | Markdown | epeppinWCTC/A3-String-Interpolation | a1d68a2f1b517b6e732dc3c02e3d8da74ccb17c4 | 070f5a5f4f776678a5e89bae36285e4716c4a22e | |
refs/heads/main | <file_sep>class Ball {
constructor(x,y){
var options={'frictionAir':0.005,'density':1}
this.body=Bodies.rectangle(x,y,50,50,options)
this.width=30
this.height=50
World.add(wld,this.body)
}
display(){
var posx=this.body.position.x
var posy=this.body.position.y
var angle=this.body.angle
push();
translate(posx,posy)
rotate(angle)
ellipseMode(RADIUS)
stroke("red")
strokeWeight(4)
fill("blue")
ellipse(0,0,this.width)
pop();
}
} | 3a3724862cc8baa02eb42ae11a8d4bd41a7f1d56 | [
"JavaScript"
] | 1 | JavaScript | 9890920686/C34 | 986503cd78a0a4993cc10c027b24b8925c312825 | bb573d43a87fc10fedbe7a2f19d4be7df970f23b | |
refs/heads/master | <repo_name>Sal-Ali/SMS-Polling<file_sep>/django_polling/application/models.py
from django.db import models
class BaseModel(models.Model):
class Meta:
abstract = True
date_created = models.DateTimeField(auto_now_add=True)
class Poll(BaseModel):
question = models.CharField(max_length=500)
@classmethod
def get_current(cls):
try:
return cls.objects.all().order_by('-id')[0]
except IndexError, e:
return None
def total_responses(self):
return self.response_set.all().count()
class Answer(BaseModel):
poll = models.ForeignKey(Poll)
answer_text = models.CharField(max_length=100)
def get_total_responses(self):
return self.response_set.all().count()
class Response(BaseModel):
class InvalidAnswerIndexException(Exception): pass
poll = models.ForeignKey(Poll)
mobile_number = models.CharField(max_length=25, blank=True, null=True)
answer = models.ForeignKey(Answer)<file_sep>/django_polling/views.py
from application.models import Poll
from django.shortcuts import render, HttpResponse, get_object_or_404
import simplejson
import time
def admin(request):
if request.method == "POST":
question = request.POST.get('question')
answers = request.POST.get('answers')
if len(question) and len(answers):
poll = Poll.objects.create(
question = question
)
for answer_text in answers.split("\n"):
poll.answer_set.create(
answer_text = answer_text
)
return render(request, 'admin.html')
def home(request):
return render(request, 'home.html', {
'recent_polls' : Poll.objects.all().order_by('-id')[:5]
})
def new_poll_listener(request):
running_poll = Poll.get_current()
new_poll = None
while True:
time.sleep(1)
new_poll = Poll.get_current()
if new_poll != running_poll:
break
return HttpResponse(simplejson.dumps({
'new_poll' : True
}), content_type="application/json")
def new_response_listener(request, poll_id):
poll = get_object_or_404(Poll, id=poll_id)
try:
recent_response = poll.response_set.all().order_by('-id')[0]
except IndexError, e:
recent_response = None
new_response = recent_response
while True:
time.sleep(1)
try:
new_response = poll.response_set.all().order_by('-id')[0]
except IndexError, e:
pass
if new_response != recent_response:
break
return HttpResponse(simplejson.dumps({
'new_response' : True
}), content_type="application/json")
def polls_create(request):
return render(request, 'polls/create.html')
def polls_current(request):
return render(request, 'polls/current.html', {
'poll' : Poll.get_current()
})
def telapi_inbound_sms(request):
running_poll = Poll.get_current()
if running_poll:
answers = running_poll.answer_set.all()
try:
answer_index = int(request.REQUEST.get('Body')) - 1
answer = answers[answer_index]
running_poll.response_set.create(
mobile_number = request.REQUEST.get('From'),
answer = answer
)
except (TypeError, IndexError), e:
print e
pass
return HttpResponse("Saved response")<file_sep>/django_polling/urls.py
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/create$', 'views.polls_create'),
url(r'^polls/current$', 'views.polls_current'),
url(r'^new-poll-listener$', 'views.new_poll_listener'),
url(r'^poll/(?P<poll_id>\d+)/new-response-listener$', 'views.new_response_listener'),
url(r'^telapi/inbound/sms$', 'views.telapi_inbound_sms'),
url(r'^admin$', 'views.admin'),
url(r'^$', 'views.home'),
)
| d21411ffbaf219cfb20db8df6f1c7f7b14e8be85 | [
"Python"
] | 3 | Python | Sal-Ali/SMS-Polling | c5e7c62351b4b09dad6bc411b4e2642e6cb63ccf | 408d54ef937ae96099d9d4761de5bc87bbc5fa84 | |
refs/heads/master | <file_sep>package com.domain.celticcelery.optcstaminacalculator;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class StaminaToTime extends AppCompatActivity {
private Calendar time;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private Button calculateBtn, desiredBtn, alarmBtn;
private EditText currentStaminaText, desiredStaminaText;
private TextView currentTimeEditText, expectedTimeEditText;
private String emptyDisplay = "";
private SimpleDateFormat df = new SimpleDateFormat("MMMM dd, yyyy \t HH:mm:ss");
private String error = "Please enter inputs for Current Stamina and Desired Stamina";
private int neededStam, currentNeededStam, rechargeTime = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stamina_to_time);
currentTimeEditText = (TextView) findViewById(R.id.currentTimeEditText);
expectedTimeEditText = (TextView) findViewById(R.id.expectedTimeEditText);
currentStaminaText = (EditText) findViewById(R.id.currentStaminaText);
desiredStaminaText = (EditText) findViewById(R.id.desiredStaminaText);
alarmBtn = (Button) findViewById(R.id.alarmBtn);
}
public int getNeededStamina() {
int currentStam = Integer.parseInt(currentStaminaText.getText().toString());
int desiredStam = Integer.parseInt(desiredStaminaText.getText().toString());
return ((desiredStam - currentStam) * rechargeTime);
}
public void clearScreen() {
currentStaminaText.setText(emptyDisplay);
desiredStaminaText.setText(emptyDisplay);
currentTimeEditText.setText(emptyDisplay);
expectedTimeEditText.setText(emptyDisplay);
neededStam = 0;
time = null;
alarmBtn.setEnabled(true);
}
public void onClickCalculate(View view) {
try {
neededStam = getNeededStamina();
currentNeededStam = neededStam;
}
catch(IllegalStateException | NumberFormatException nfex){
Toast.makeText(this,error,Toast.LENGTH_SHORT).show();
}
if (neededStam < 0 ) {
Toast.makeText(this,"Invalid input",Toast.LENGTH_SHORT).show();
clearScreen();
}
else if(neededStam > 0){
time = Calendar.getInstance();
String currentTime = df.format(time.getTime());
currentTimeEditText.setText(currentTime);
time.add(Calendar.MINUTE, neededStam);
String desiredTime = df.format(time.getTime());
expectedTimeEditText.setText(desiredTime);
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
public void onClickAlarm(View view){
try {
Toast.makeText(this, "Alarm set for " + df.format(time.getTime()), Toast.LENGTH_SHORT).show();
setAlarm(neededStam * 60 * 1000);
alarmBtn.setEnabled(false);
}
catch(IllegalStateException | NullPointerException | NumberFormatException nfex) {
Toast.makeText(this, "No alarm. Please press calculate for a desired time first", Toast.LENGTH_LONG).show();
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void setAlarm(long timeInMillis) {
alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmMgr.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + timeInMillis, alarmIntent);
}
public void onClickReset(View view) {
clearScreen();
if(alarmMgr != null) {
alarmMgr.cancel(alarmIntent);
}
}
}
<file_sep>package com.domain.celticcelery.optcstaminacalculator;
public class Storage {
}
<file_sep>package com.domain.celticcelery.optcstaminacalculator;
import android.view.View;
import android.widget.Toast;
import java.util.Calendar;
//public class Calculate {
// public int getNeededStamina() {
//
// int currentStam = Integer.parseInt(currentStaminaText.getText().toString());
// int desiredStam = Integer.parseInt(desiredStaminaText.getText().toString());
// return ((desiredStam - currentStam) * 5);
//
//
// }
//
// public void onClickCalculate(View view) {
//
// try {
// neededStam = getNeededStamina();
// }
// catch(IllegalStateException | NumberFormatException nfex){
// Toast.makeText(this,error,Toast.LENGTH_SHORT).show();
// }
//
// if (neededStam < 0 ) {
// Toast.makeText(this,"Invalid input",Toast.LENGTH_SHORT).show();
// clearScreen();
// }
// else if(neededStam > 0){
// time = Calendar.getInstance();
// String currentTime = df.format(time.getTime());
// currentTimeEditText.setText(currentTime);
//
// time.add(Calendar.MINUTE, neededStam);
// String desiredTime = df.format(time.getTime());
// expectedTimeEditText.setText(desiredTime);
// }
//
//// }
//
//}
| 336df0240d91a9c3a5e3042b0ab068c4a1ac1f21 | [
"Java"
] | 3 | Java | celticcelery/OPTCStaminaCalculatorV2 | 217ecb39c5de0ead2325226b76d9cc0caab50e3c | 2bb08de35fb5ff29eb93cab9bb876c4006a0d814 | |
refs/heads/master | <file_sep>compile.on.save=true
user.properties.file=C:\\Users\\frepa\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
<file_sep>/**
* Class Heroi - ...
*
* ...
* ...
* ...
*
* @author <NAME> e <NAME>
* @version 2019.07.07
*/
package jogorpg.world_of_zuul;
import java.util.Map;
public class Heroi extends Personagem {
private int limiteDePeso;
private int pesoAtual;
private int qntdItens;
private int moedas;
private Map<String, Item> inventario;
public Heroi(String nome, int energia) {
super(nome, energia);
}
public void alimentar(String comida){ // Passar como parametro um int de quanto incrementar; Facilitaria para comida/poção;
Item aux = null;
if(inventario.get(comida)!= null){
aux = inventario.get(comida);
incremento(aux.getAtributo());
}
System.out.println("Item inexistente");
}
public void lutar(Personagem inimigo){ // Método de luta deveria mesmo ser dentro da classe Heroi?
Item aux;
Item auxI;
int auxDano = 0;
//Vitoria Heroi
if(sorte() > inimigo.sorte()){
incremento(1);
if(inimigo.getDefesa() != null){
aux = getAtaque();
auxI = inimigo.getDefesa();
auxDano = aux.getAtributo() - auxI.getAtributo();
inimigo.decremento(auxDano);
}
}
//Vitoria inimiga
if(sorte() < inimigo.sorte()){
if(getDefesa() != null){
aux = getDefesa();
auxI = inimigo.getAtaque();
auxDano = auxI.getAtributo() - aux.getAtributo();
decremento(auxDano);
}
inimigo.incremento(1);
}
// Empate na Sorte
if(sorte() == inimigo.sorte()){
if(getDefesa() != null){
aux = getDefesa();
auxI = inimigo.getAtaque();
auxDano = auxI.getAtributo() - aux.getAtributo();
decremento(auxDano);
}
else{
auxI = inimigo.getAtaque();
decremento(auxI.getAtributo());
}
if(inimigo.getDefesa() != null){
aux = getAtaque();
auxI = inimigo.getDefesa();
auxDano = aux.getAtributo() - auxI.getAtributo();
inimigo.decremento(auxDano);
}
else{
aux = getAtaque();
inimigo.decremento(aux.getAtributo());
}
}
}
public void inserirItem(Item item){ // Modificar para tipo Boolean para poder retornar se
if(pesoAtual < limiteDePeso){
inventario.put(item.getNomeDoItem(), item);
pesoAtual = pesoAtual + item.getPesoDoItem();
qntdItens++;
}
else
System.out.println("Inventário cheio!");
}
public void remover(String nome){ // Modifiquei/Modificar nome do método de "Remover" para "RemoverItem"; Tbm modificar para tipo Item para pdoer retornar
if(inventario.get(nome) != null){
inventario.remove(nome);
qntdItens--;
System.out.println("Item removido");
}
else
System.out.println("Item não existe no seu inventário");
}
public void equiparItem(String eqp){
Item aux = null;
aux = inventario.get(eqp);
if(aux.getTipoIP().equals("A")){
setAtaque(aux);
System.out.println("Equipado arma");
}
if(aux.getTipoIP().equals("D")){
setDefesa(aux);
System.out.println("Equipado Escudo");
}
}
public int getPesoAtual() {
return pesoAtual;
}
public void adionarMoedas(int qtd){
int p = 1;
moedas += qtd;
if(inventario.get("Moedas") == null){
Item m = new Item("Moedas", p, moedas, "M");
inserirItem(m);
}
else{
p = moedas/1000;
Item auxM = null;
auxM = inventario.get("Moedas");
auxM.setPesoDoItem(p);
auxM.setAtributo(moedas);
}
if((moedas%1000) != 0){
Item auxM = null;
p =+ 1 ;
auxM = inventario.get("Moedas");
auxM.setPesoDoItem(p);
}
}
}
<file_sep>/**
* Class Item - ...
*
* ...
* ...
* ...
*
* @author <NAME> e <NAME>
* @version 2019.06.30
*/
package jogorpg.world_of_zuul;
public class Item {
private String NomeDoItem;
private int PesoDoItem;
private int atributo;
private String tipoIP; //C = consumivel A = ataque D = defesa B = Buffer M = moeda
public Item(String NomeDoItem, int PesoDoItem, int atributo, String tipoIP) {
this.NomeDoItem = NomeDoItem;
this.PesoDoItem = PesoDoItem;
this.atributo = atributo;
this.tipoIP = tipoIP;
}
public void setPesoDoItem(int PesoDoItem) {
this.PesoDoItem = PesoDoItem;
}
public String getNomeDoItem() {
return NomeDoItem;
}
public int getPesoDoItem() {
return PesoDoItem;
}
public int getAtributo() {
return atributo;
}
public String getTipoIP() {
return tipoIP;
}
public void setAtributo(int atributo) {
this.atributo = atributo;
}
}
| 3a7713d44b2b7915602cee935c30a15bd5684d1b | [
"Java",
"INI"
] | 3 | INI | hpfred/JogoRPG-POO | 960c6ff1b6457681db806002ac4e10417a987612 | 38e1f10cd77b44d76ae608f8609528b4ecd3ef17 | |
refs/heads/master | <file_sep>//1st function
function feetToMile(feet){
if(feet< 0){
console.log("Invalid Input");
}
else{
var mile = feet/ 5280;
var remainingFeet = feet % 5280;
var mileNo = parseInt(mile);
return mileNo , remainingFeet;
}
}
//2nd function
function woodCalculator(chair, table, bed){
var totalWood = chair + (table*3) + (bed*5);
return totalWood;
}
//3rd function
function brickCalculator(floorNo){
if(floorNo<=0){
console.log("Invalid Input");
}
else if(floorNo <11){
var feet = floorNo*15;
}
else if(floorNo<21){
feet = ((floorNo-10)*12)+150;
}
else{
feet= ((floorNo-20)*10)+270;
}
var brick = feet*1000;
return brick;
}
//4th function
function tinyFriend(names){
var tiny = names[0];
for(var i=0; i<names.length;i++){
if(names[i].length<tiny.length){
tiny = names[i];
}
}
return tiny;
}
| 8a7eda830f3974858d9f40a4eacbe6d208ea1879 | [
"JavaScript"
] | 1 | JavaScript | Neaz-Mahmood/Js-assignment | 89afb26baf42bac62c81d5f20fb2e594c91b7a72 | da9ba49d2c543d132576cc92caaa70966db8e052 | |
refs/heads/master | <repo_name>johnantoni/simple_form_ext<file_sep>/lib/simple_form_ext.rb
require "simple_form_ext/version"
require 'find'
dir = File.expand_path("simple_form_ext/ext", File.dirname(__FILE__))
Find.find(dir) do |path|
next if File.extname(path) != ".rb"
require path
end
<file_sep>/lib/simple_form_ext/ext/radio_buttons_left_label_input.rb
# example
# <%= form.input :gender, :as => :radio_buttons_left_label, :collection => %w[Female Male] %>
class RadioButtonsLeftLabelInput < SimpleForm::Inputs::CollectionRadioButtonsInput
def input
label_method, value_method = detect_collection_methods
@builder.send("collection_radio_buttons",
attribute_name, collection, value_method, label_method,
input_options, input_html_options, &collection_block_for_nested_boolean_style
)
end
protected
def build_nested_boolean_style_item_tag(collection_builder)
collection_builder.text.html_safe + collection_builder.radio_button.html_safe
end
end
| 0e19a5f7c56ffce15bc68b9ebad26daa19608817 | [
"Ruby"
] | 2 | Ruby | johnantoni/simple_form_ext | 999a9f531ea4ab91b212175adf7262abe51c9839 | 504f268d9a3db510771bf30a38a5e8ef15fe1cb6 | |
refs/heads/master | <file_sep>export class ItemDetails {
description: string;
name: string;
price: DoubleRange;
}<file_sep>import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import { ItemDetails } from '../itemdetails';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {
menuDetails: AngularFireList<any[]>;
menu: Observable<any[]>;
subMenuItems: Array<{ name: string, items: ItemDetails[] }>;
constructor(private db: AngularFireDatabase) {
this.menuDetails = db.list('menu_details');
this.menu = this.menuDetails.snapshotChanges();
this.menu.subscribe(data => {
this.subMenuItems = [];
data.forEach(snapshot => {
var key = snapshot.key;
var itemDetails = this.extractBody(snapshot.payload.val());
this.subMenuItems.push({ name : key, items : itemDetails});
});
console.log(this.subMenuItems);
});
}
extractBody(data) : ItemDetails[] { //converting object to array
var items = [];
var itemDetails = ItemDetails;
for(let i in data) {
itemDetails = data[i];
items.push(itemDetails);
}
return items;
}
ngOnInit() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-orderonline',
templateUrl: './orderonline.component.html',
styleUrls: ['./orderonline.component.css']
})
export class OrderonlineComponent implements OnInit {
sidenavList: Array<{ name: string, subMenu: any }>;
subMenuItems: Array<{ name: string, items: any }>;
selectedSubMenu: any;
selectsubitems : any;
constructor() {
this.selectedSubMenu = "Soups"; //if no menu is selected by default display soup content
this.sidenavList = [
{
name: "Menu",
subMenu: [
{ name: "Soups" },
{ name: "Appetizers" },
{ name: "Rotis/Paratas" },
{ name: "Curries" },
{ name: "Desserts" }]
},
{
name: "Drinks",
subMenu: [
{ name: "Coffe/Tea" },
{ name: "Beer" },
{ name: "Wine" },
{ name: "Juices/Milk shakes" }]
}
]
this.subMenuItems = [
{
name: "Soups",
items: [
{ name: "Corn Soup", price: 3.50, id:1 },
{ name: "Tomato Soup", price: 4.50, id:2 }
]
},
{
name: "Appetizers",
items: [
{ name: "Gobi manchurian", price: 6.50, id:3 },
{ name: "chicken pepper dry", price: 7.50, id:4 }
]
},
{
name: "Rotis/Paratas",
items: [
{ name: "Aloo parata", price: 4.00, id:5 },
{ name: "Tandoori roti", price: 1.50, id:6 }
]
},
{
name: "Curries",
items: [
{ name: "Bendi Masala", price: 9.50, id:7 },
{ name: "Ch<NAME>", price: 8.50, id:8 }
]
},
{
name: "Desserts",
items: [
{ name: "Jamoon(2)", price: 3.00, id:9 },
{ name: "GudBud", price: 5.00 , id:10 }
]
}
]
}
onSelect(submenuname: any): void {
this.selectedSubMenu = submenuname;
this.fetchSubMenuItems(this.subMenuItems, submenuname);
}
fetchSubMenuItems(arr, val) {
this.selectsubitems = arr.filter(function(arrVal) {
console.log(arrVal.name, val);
return arrVal.name === val;
});
console.log(this.selectsubitems);
}
ngOnInit() {
this.onSelect(this.selectedSubMenu);
}
}
| df486e4d69068e308e903d373bb6c6cc21dd83e3 | [
"TypeScript"
] | 3 | TypeScript | Preethi-V-3/sad2018-resturant-management | c769db3cb57043a38e72e92c5a9df09b9eec1bc5 | d5d517d9c471f5cf6d7cfeab757c5dee024a5825 | |
refs/heads/master | <repo_name>rsuth/gentle<file_sep>/install_binaries.sh
#!/bin/bash
# THIS DOWNLOADS BINARIES COMPILED FOR UBUNTU 20.04
set -e
download_bin() {
echo "Getting k3"
local k3filename="k3"
local k3url="https://www.dropbox.com/s/zx9qkch3yrizieg/k3?dl=0"
wget --no-check-certificate -O $k3filename $k3url
echo "Getting m3"
local m3filename="m3"
local m3url="https://www.dropbox.com/s/3tm4e23xhcrq0v4/m3?dl=0"
wget --no-check-certificate -O $m3filename $m3url
}
echo "Downloading binaries..."
cd ext && download_bin
<file_sep>/install_models.sh
#!/bin/bash
set -e
download_models() {
local filename="kaldi-models-0.03.zip"
local url="https://www.dropbox.com/s/u5dgawwyl0totow/kaldi-models-0.03.zip?dl=0"
wget --no-check-certificate -O $filename $url
unzip $filename
rm $filename
}
echo "Downloading models..."
download_models
| 36af2d6ab7ba04c50d45683f01c763380a0ea8e5 | [
"Shell"
] | 2 | Shell | rsuth/gentle | 23f41f8ad9539c1208bff8e487ec640c3a23167d | 95d1460c1807e40867bb75b1401d14db315cd6a0 |