branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>kd01gh/CoreDataTest<file_sep>/DataManager.xctemplate/___FILEBASENAME___.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import UIKit import Foundation import CoreData @objc(___FILEBASENAMEASIDENTIFIER___) class ___FILEBASENAMEASIDENTIFIER___{ let managedContext: NSManagedObjectContext // Init init() { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let applicationDocumentsDirectory = urls[urls.endIndex-1] as NSURL let storeURL = applicationDocumentsDirectory.URLByAppendingPathComponent("___FILEBASENAMEASIDENTIFIER___.sqlite") let managedModel = NSManagedObjectModel.mergedModelFromBundles(nil) let storeCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedModel) func addStore() -> NSError?{ var error: NSError? = nil let result = storeCoordinator.addPersistentStoreWithType( NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) if !result { println("Create persistent store error occurred: \(error?.userInfo)") } return error } var error = addStore() if error { println("Store scheme error. Will remove store and try again.") NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil) error = addStore() if error { println("Unresolved critical error with persistent store: \(error?.userInfo)") abort() } } managedContext = NSManagedObjectContext() managedContext.persistentStoreCoordinator = storeCoordinator NSNotificationCenter .defaultCenter() .addObserver(self, selector: "saveContext", name: UIApplicationDidEnterBackgroundNotification, object: nil) } //Save context @objc(saveContext) func saveContext() -> NSError? { var error: NSError? = nil if managedContext.hasChanges { managedContext.save(&error) } if error != nil{ println("Application did not save data with reason: \(error?.userInfo)") } return error } //Singleton Instance class var instance: ___FILEBASENAMEASIDENTIFIER___ { struct Shared { static var instance: ___FILEBASENAMEASIDENTIFIER___? = nil static var token: dispatch_once_t = 0 } dispatch_once(&Shared.token) { Shared.instance = ___FILEBASENAMEASIDENTIFIER___() } return Shared.instance! } } <file_sep>/CoreDataTest/AppDelegate.swift // // AppDelegate.swift // CoreDataTest // // Created by <NAME> on 09.06.14. // Copyright (c) 2014 Novilab Mobile. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { //Get manager let manager = CSDataManager.instance //Testing insert new objects let newDepartment : CSDepartment = NSEntityDescription.insertNewObjectForEntityForName("CSDepartment", inManagedObjectContext: manager.managedContext) as CSDepartment let newEmployee: CSEmployee = NSEntityDescription.insertNewObjectForEntityForName("CSEmployee", inManagedObjectContext: manager.managedContext) as CSEmployee let newEmployee2: CSEmployee = NSEntityDescription.insertNewObjectForEntityForName("CSEmployee", inManagedObjectContext: manager.managedContext) as CSEmployee newEmployee.department = newDepartment newDepartment.addEmployeesObject(newEmployee2) manager.saveContext() //Get and print all departments println("\n//////////////////////////////////////////////////////////") println("Have add one department and two employees") println("Departments: \(manager.departments())") println("Employees: \(manager.employees())") //Testing remove child object //TODO: Working bad(((( - child pointer to department is not changed // newDepartment.removeEmployeesObject(newEmployee2) // manager.saveContext() // println("\n//////////////////////////////////////////////////////////") // println("Have delete one employee") // println("Departments: \(manager.departments())") //Testing cascade remove // manager.managedContext.deleteObject(newDepartment) // manager.saveContext() // println("\n//////////////////////////////////////////////////////////") // println("Have delete department") // println("Departments: \(manager.departments())") // println("Employees: \(manager.employees())") //Testing remove without delete newDepartment.removeEmployeesObject(newEmployee) println("\n//////////////////////////////////////////////////////////") println("Have remove furst employee without delete") println("Department: \(manager.departments())") println("Employees: \(manager.employees())") //Testing remove with delete // newDepartment.removeEmployees(NSSet(object: newEmployee2), delete: true) newDepartment.removeEmployeesObject(newEmployee2, delete: true) // newDepartment.removeEmployeesAndDelete(NSSet(object: newEmployee2)) println("\n//////////////////////////////////////////////////////////") println("Have remove second employee with delete") println("Department: \(manager.departments())") println("Employees: \(manager.employees())") // Uncomment to remove all records let departments = manager.departments() for i in 0..departments.count{ let dep = departments[i] as CSDepartment manager.managedContext.deleteObject(dep) } let employees = manager.employees() for i in 0..employees.count{ let emp = employees[i] as CSEmployee manager.managedContext.deleteObject(emp) } manager.saveContext() println("\n//////////////////////////////////////////////////////////") println("Have delete all data") println("Departments: \(manager.departments())") println("Employees: \(manager.employees())") return true } } <file_sep>/CoreDataTest/CSEmployee.swift // // CSEmployee.swift // CoreDataTest // // Created by <NAME> on 09.06.14. // Copyright (c) 2014 Novilab Mobile. All rights reserved. // import Foundation import CoreData let st_fNames = ["John", "David", "Michael", "Bob"] let st_lNames = ["Lim", "Jobs", "Kyler"] @objc(CSEmployee) class CSEmployee:NSManagedObject{ @NSManaged var firstName: NSString @NSManaged var lastName: NSString @NSManaged var age: NSNumber? @NSManaged var department: CSDepartment override func awakeFromInsert() { super.awakeFromInsert() self.firstName = st_fNames[Int(arc4random_uniform(UInt32(st_fNames.count)))] self.lastName = st_lNames[Int(arc4random_uniform(UInt32(st_lNames.count)))] } func description() -> NSString{ return "Employee: name= \(self.firstName) \(self.lastName), age=\(self.age) years" } }<file_sep>/CoreDataTest/CSDepartment.swift // // CSDepartment.swift // CoreDataTest // // Created by <NAME> on 09.06.14. // Copyright (c) 2014 Novilab Mobile. All rights reserved. // import Foundation import CoreData @objc(CSDepartment) class CSDepartment : NSManagedObject{ @NSManaged var title: NSString @NSManaged var internalID: NSNumber @NSManaged var phone: NSString? @NSManaged var employees: NSSet override func awakeFromInsert() { self.title = "New department" self.internalID = 0 } func description() -> NSString{ let employeesDescription = self.employees.allObjects.map({employee in employee.description()}) return "Department: title=\(self.title), id=[\(self.internalID)], phone=\(self.phone) and employees = \(employeesDescription)" } //Working with Employees func addEmployeesObject(employee: CSEmployee?){ let set:NSSet = NSSet(object: employee) self.addEmployees(set) } func removeEmployeesObject(employee: CSEmployee?, delete: Bool = false){ let set:NSSet = NSSet(object: employee) self.removeEmployees(set, delete: delete) } func addEmployees(employees: NSSet?){ self.willChangeValueForKey("employees", withSetMutation: NSKeyValueSetMutationKind.UnionSetMutation, usingObjects: employees) self.primitiveValueForKey("employees").unionSet(employees) self.didChangeValueForKey("employees", withSetMutation: NSKeyValueSetMutationKind.UnionSetMutation, usingObjects: employees) } func removeEmployees(employees: NSSet?, delete: Bool = false){ self.willChangeValueForKey("employees", withSetMutation: .MinusSetMutation, usingObjects: employees) self.primitiveValueForKey("employees").minusSet(employees) if delete{ func delete(obj: AnyObject!, stop: CMutablePointer<ObjCBool>)-> Void{ let employee: CSEmployee = obj as CSEmployee self.managedObjectContext.deleteObject(employee) } employees!.enumerateObjectsUsingBlock(delete) } self.didChangeValueForKey("employees", withSetMutation: .MinusSetMutation, usingObjects: employees) } } <file_sep>/README.md CoreDataTest ============ CoreData using with modern language Swift
c909a385af0494bc545b4b287bd85fd46618781d
[ "Swift", "Markdown" ]
5
Swift
kd01gh/CoreDataTest
e1dbca6f0675a99c29d6ab1773ba54600dcd2c20
e2bee7a138f574d4f1cc0e751701a81cbca2731e
refs/heads/main
<repo_name>vshalt/pomodoro-clock<file_sep>/README.md # Pomodoro Clock ![pomodoro clock](./assets/demo_main.gif) > A pomodoro clock app to make you more productive. > hosted project: https://vshalt.github.io/pomodoro-clock --- ## Table of Contents - [Description](#description) - [Technologies](#technologies) - [How To Use](#how-to-use) - [Installation](#installation) - [License](#license) --- ## Description - This is a simple but effective way to monitor your productivity. - You work when the session is active, there are breaks after every session. - The session is originally 25 minutes long and the breaks 5 minutes. - The user can play around with the session and break time. - The page is responsive, configured for mobile view too. - At the end of every session/break there is a audio response for the user to know the timer has ended. ![pomodoro-clock](./assets/demo.png) --- ### Technologies - React - JavaScript - HTML - CSS --- ## How To Use You can view the hosted project [here](https://vshalt.github.io/pomodoro-clock) or https://vshalt.github.io/pomodoro-clock --- ## Installation - Clone the repository with `git clone https://github.com/vshalt/pomodoro-clock` - Then change directory into the newly cloned repository. - Run `npm install` to install the dependencies - Once the dependencies are installed run the project locally with `npm start` - Happy productivity! --- ## License MIT License [Read here](./LICENSE) [Back To The Top](#pomodoro-clock) <file_sep>/src/App.js import React from 'react'; import ReactDOM from 'react-dom'; import './App.css'; class App extends React.Component{ constructor(props){ super(props); this.interval = undefined; this.state = { clockName: 'Session', sessionTimer: 25, clockCount: 25 * 60, breakTimer: 5, isRunning: false, } this.handleBreakPlus = this.handleBreakPlus.bind(this); this.handleBreakMinus = this.handleBreakMinus.bind(this); this.handleSessionPlus = this.handleSessionPlus.bind(this); this.handleSessionMinus = this.handleSessionMinus.bind(this); this.handleReset = this.handleReset.bind(this); this.handlePlayPause = this.handlePlayPause.bind(this); } handleBreakPlus() { if (this.state.breakTimer < 60) this.setState({ breakTimer: this.state.breakTimer+ 1 }) } handleBreakMinus() { if (this.state.breakTimer > 1) this.setState({ breakTimer: this.state.breakTimer - 1 }) } handleSessionPlus() { if (this.state.sessionTimer < 60) this.setState({ sessionTimer: this.state.sessionTimer +1, clockCount: (this.state.sessionTimer +1) * 60, }) } handleSessionMinus() { if (this.state.sessionTimer > 1) this.setState({ sessionTimer: this.state.sessionTimer - 1, clockCount: (this.state.sessionTimer -1) * 60, }) } getTime(count){ let minutes = Math.floor(count / 60); let seconds = count % 60; minutes = minutes < 10? '0'+minutes: minutes; seconds = seconds < 10? '0'+ seconds: seconds; return `${minutes}:${seconds}` } handlePlayPause() { const { isRunning } = this.state; if (isRunning) { clearInterval(this.interval) this.setState({ isRunning: false, }) } else { this.setState({ isRunning: true, }) this.interval = setInterval(() => { const { clockCount, clockName } = this.state; if (clockCount === 0){ if (clockName === 'Session') { document.querySelector('audio').play(); this.setState({ clockName: 'Break', clockCount: this.state.breakTimer * 60, }) } else { document.querySelector('audio').play(); this.setState({ clockName: 'Session', clockCount: this.state.sessionTimer * 60, }) } } else { this.setState({ clockCount: clockCount - 1, }) } }, 1000) } } handleReset() { document.querySelector('audio').pause(); document.querySelector('audio').currentTime = 0; clearInterval(this.interval); this.interval = undefined; this.setState({ clockName: 'Session', clockCount: 25 * 60, breakTimer: 5, sessionTimer: 25, isRunning: false, }) } render() { const { breakTimer, sessionTimer, clockCount, clockName, isRunning } = this.state; return( <div className="container"> <h1>Pomodoro Clock</h1> <div className="btn-container"> <Timer timerId="break-length" incrementId="break-increment" decrementId="break-decrement" titleId="break-label" title='Break' timer={breakTimer} onPlusClick={this.handleBreakPlus} onMinusClick={this.handleBreakMinus}/> <Timer timerId="session-length" incrementId="session-increment" decrementId="session-decrement" titleId="session-label" title='Session' timer={sessionTimer} onPlusClick={this.handleSessionPlus} onMinusClick={this.handleSessionMinus}/> </div> <p id="timer-label">{clockName}</p> <div id="time-left" className="clock"> {this.getTime(clockCount)} </div> <div className="controls"> <button id="start_stop" onClick={this.handlePlayPause}><i className={`fa fa-${isRunning? `pause`: `play`} fa-2x`}></i></button> <button id="reset" onClick={this.handleReset}><i className="fa fa-sync-alt fa-2x"></i></button> </div> </div> )} } const Timer = (props) => { const { title, onMinusClick, onPlusClick, timer, titleId, incrementId, decrementId, timerId, } = props; return ( <div className="timer-container"> <span id={titleId}>{title}</span> <div className="timer"> <button id={decrementId} onClick={onMinusClick}><i className="fa fa-minus fa-2x"></i></button> <span id={timerId}>{timer}</span> <button id={incrementId} onClick={onPlusClick}><i className="fa fa-plus fa-2x"></i></button> </div> </div> )} ReactDOM.render(<App />, document.getElementById('app')) export default App;
d03eb4118d5b04e5a6dd5013723100f472ce254d
[ "Markdown", "JavaScript" ]
2
Markdown
vshalt/pomodoro-clock
040cc83a4fae72e561629c322aed333263067783
a4417ff13ec4eb1392137f27f6f3a672661409b4
refs/heads/master
<repo_name>dmonitha/RoboFriends<file_sep>/robots.js export const robots = [ { id: 1, name: '<NAME>', username: 'BossMan', email: '<EMAIL>' }, { id: 2, name: '<NAME>', username: 'Big Tuna', email: '<EMAIL>' }, { id: 3, name: '<NAME>', username: 'D', email: '<EMAIL>' }, { id: 4, name: '<NAME>', username: 'Nard Dog', email: '<EMAIL>' }, { id: 5, name: '<NAME>', username: 'Pamalama', email: '<EMAIL>' }, { id: 6, name: '<NAME>', username: 'Temp Guy', email: '<EMAIL>' }, { id: 7, name: '<NAME>', username: 'Monkey', email: '<EMAIL>' }, { id: 8, name: '<NAME>', username: 'The Antichrist', email: '<EMAIL>' }, { id: 9, name: '<NAME>', username: '<NAME>', email: '<EMAIL>' }, { id: 10, name: '<NAME>', username: 'Fire Girl', email: '<EMAIL>' } ];<file_sep>/README.md # RoboFriends A simple App to list my RoboFriends from The Office.
6cb2a3788896ec081d3c33381e7a81e2c92bd699
[ "JavaScript", "Markdown" ]
2
JavaScript
dmonitha/RoboFriends
2fcb7421eb140bbd876eef888effd09fa5b67459
8c2b99d9d7daa57bccfd0dffd8ce7c2af6865307
refs/heads/main
<repo_name>LoopGlitch26/Twitter-Bot-Custom<file_sep>/bot.py import tweepy as twitter # Basically that's all you need to pip install import secrets import datetime import time auth = twitter.OAuthHandler(secrets.API_KEY,secrets.API_SECRET_KEY) auth.set_access_token(secrets.ACCESS_TOKEN,secrets.SECRET_ACCESS_TOKEN) api = twitter.API(auth) def bot(hashtags): while True: # Infinite Loop print(datetime.datetime.now()) # Print the date time for hashtag in hashtags: for tweet in twitter.Cursor(api.search, q = hashtag, rpp = 10).items(5): # Fetch queries as hashtags try: id = dict(tweet._json)['id'] text = dict(tweet._json)['text'] api.retweet(id) api.create_favorite(id) print("Tweet ID:", id) print("Tweet Text:", text) except twitter.TweepError as e: print(e.reason) time.sleep(10) # To avoid spam bot(['']) # List the hashtags to be liked and retweeted<file_sep>/secrets.py API_KEY = '' API_SECRET_KEY = '' BEARER_TOKEN = '' ACCESS_TOKEN = '' SECRET_ACCESS_TOKEN = ''<file_sep>/README.md # Twitter-Bot-Custom ### Demo Live Bot: https://twitter.com/bot_resources ## Steps to follow: 1) Create a `twitter account` for your twitter bot 2) Apply for `twitter developer` account 3) Pass all the necessary `verifications` by Twitter 4) Create a `new app` 5) Change to `read and write` mode and regenerate the `Tokens` 6) Put the tokens in the [secrets.py](https://github.com/LoopGlitch26/Twitter-Bot-Custom/blob/main/secrets.py) file 7) Create a virtual environment `virtualenv <venv>` and activate it `source <venv>/bin/activate` 8) Run the [requirements.txt](https://github.com/LoopGlitch26/Twitter-Bot-Custom/blob/main/requirements.txt) 9) Enter the hashtags in the list [bot](https://github.com/LoopGlitch26/Twitter-Bot-Custom/blob/0661212e9c41f5c0831ec3568b26fe8d1ead027d/bot.py#L26) 10) Run the [bot.py](https://github.com/LoopGlitch26/Twitter-Bot-Custom/blob/main/bot.py) ###### P.S: Don't try it with your own twitter account (because it'll get spammed with retweets) XD I know the consequences so I'm warning you beforehand
0eb5e64d4d9d49c36b92f310481877262ff2e430
[ "Markdown", "Python" ]
3
Python
LoopGlitch26/Twitter-Bot-Custom
e36797ef7fc06f71de239d5f55997a90d3ed4b9a
9e9cf6fd7a392178446dc46ceaf9565503d545f9
refs/heads/master
<repo_name>TaricaTarica/vacunasuy-backend<file_sep>/comp-cent-ejb/src/main/java/datos/ReservaDatoLocal.java package datos; import java.time.LocalDate; import java.util.List; import javax.ejb.Local; import entidades.Reserva; @Local public interface ReservaDatoLocal { public List<Reserva> obtenerReservas(); public void crearReserva(Reserva res); public Reserva obtenerReserva(long id); public void editarReserva(Reserva res); public Boolean existeReserva(long idAgenda); public List<Reserva> obtenerReservasAgenda(LocalDate fecha, long id); public List<Reserva> obtenerReservasPorUbicacion(long id); public Reserva obtenerUltimaReserva(long id, LocalDate fecha); public int obtenerCantidadUltimaHora(long id, LocalDate fecha, int hora); public int obtenerCantidadReservasDia(long id, LocalDate fecha); } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTRegistroVacuna.java package datatypes; public class DTRegistroVacuna { private int cedula; private long idVacuna; private long idVacunatorio; private long idReserva; private String fecha; public DTRegistroVacuna() { // TODO Auto-generated constructor stub } public DTRegistroVacuna(int cedula, long idVacuna, long idVacunatorio, long idReserva, String fecha) { super(); this.cedula = cedula; this.idVacuna = idVacuna; this.idVacunatorio = idVacunatorio; this.idReserva = idReserva; this.fecha = fecha; } public int getCedula() { return cedula; } public void setCedula(int cedula) { this.cedula = cedula; } public long getIdVacuna() { return idVacuna; } public void setIdVacuna(long idVacuna) { this.idVacuna = idVacuna; } public long getIdVacunatorio() { return idVacunatorio; } public void setIdVacunatorio(long idVacunatorio) { this.idVacunatorio = idVacunatorio; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public long getIdReserva() { return idReserva; } public void setIdReserva(long idReserva) { this.idReserva = idReserva; } } <file_sep>/comp-cent-ejb/src/main/java/datos/VacunatorioDatoLocal.java package datos; import java.util.List; import javax.ejb.Local; import entidades.Vacunatorio; @Local public interface VacunatorioDatoLocal { public void agregarVacunatorio(Vacunatorio vacunatorio); public List<Vacunatorio> listarVacunatorio(); public Vacunatorio obtenerVacunatorio(long id); public Vacunatorio obtenerVacunatorioPorCodigo(String codigo); public Boolean existeVacunatorio(String codigo); public void editarVacunatorio(Vacunatorio vac); public void eliminarVacunatorio(Vacunatorio vac); } <file_sep>/comp-cent-ejb/src/main/java/datos/RegistroVacunaDato.java package datos; import java.time.LocalDate; import java.time.Period; import java.util.ArrayList; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import entidades.RegistroVacuna; import entidades.Vacuna; import enumeradores.Sexo; /** * Session Bean implementation class RegistroVacunaDato */ @Stateless @LocalBean public class RegistroVacunaDato implements RegistroVacunaDatoLocal { @PersistenceContext(name = "comp-centPersistenceUnit") private EntityManager em; /** * Default constructor. */ public RegistroVacunaDato() { // TODO Auto-generated constructor stub } @Override public void agregarRegistroVacuna(RegistroVacuna regVac) { em.persist(regVac); } @Override public List<RegistroVacuna> obtenerRegistroPorCi (int ci) { List<RegistroVacuna> listRegVac = new ArrayList<RegistroVacuna>(); for (RegistroVacuna rv :em.createQuery("Select rv from RegistroVacuna rv where rv.ciudadano.ci = :ci",RegistroVacuna.class).setParameter("ci", ci).getResultList()) { listRegVac.add(rv); } return listRegVac; } @Override public List<RegistroVacuna> obtenerRegistro(){ ArrayList<RegistroVacuna> lista = new ArrayList<RegistroVacuna>(); for(Object obj : em.createQuery("Select r from RegistroVacuna r").getResultList()) { RegistroVacuna r = (RegistroVacuna) obj; lista.add(r); } return lista; } @Override public int cantRegistroPorMes(Vacuna vacuna, int mes, int anio){ LocalDate fechaIni = LocalDate.of(anio, mes, 1); LocalDate fechaFin = LocalDate.now(); if (mes == 12) { fechaFin = LocalDate.of(anio + 1, 1, 1); } else { fechaFin = LocalDate.of(anio, mes + 1, 1); } List<RegistroVacuna> listRegistros = em.createQuery("Select rv from RegistroVacuna rv where rv.vacuna.id = :id and rv.fecha between :fechaIni and :fechaFin",RegistroVacuna.class) .setParameter("id", vacuna.getId()) .setParameter("fechaIni",fechaIni) .setParameter("fechaFin",fechaFin).getResultList(); if (listRegistros == null) { return 0; } else { return listRegistros.size(); } } @Override public int cantRegistroPorSexo(Vacuna vacuna, Sexo sexo, int anio) { LocalDate fechaIni = LocalDate.of(anio, 1, 1); LocalDate fechaFin = LocalDate.of(anio, 12, 31); List<RegistroVacuna> listRegistros = em.createQuery("Select rv from RegistroVacuna rv where rv.vacuna.id = :id and rv.fecha between :fechaIni and :fechaFin",RegistroVacuna.class) .setParameter("id", vacuna.getId()) .setParameter("fechaIni",fechaIni) .setParameter("fechaFin",fechaFin).getResultList(); int cant = 0; for (RegistroVacuna rv : listRegistros) { if (rv.getCiudadano().getSexo() == sexo) { cant ++; } } return cant; } @Override public int cantRegistroPorEdad(Vacuna vacuna, int edadMin, int edadMax, int anio) { LocalDate fechaIni = LocalDate.of(anio, 1, 1); LocalDate fechaFin = LocalDate.of(anio, 12, 31); List<RegistroVacuna> listRegistros = em.createQuery("Select rv from RegistroVacuna rv where rv.vacuna.id = :id and rv.fecha between :fechaIni and :fechaFin",RegistroVacuna.class) .setParameter("id", vacuna.getId()) .setParameter("fechaIni",fechaIni) .setParameter("fechaFin",fechaFin).getResultList(); int cant = 0; LocalDate ahora = LocalDate.now(); for (RegistroVacuna rv : listRegistros) { Period edad = Period.between(rv.getCiudadano().getFnac(), ahora); if (edad.getYears() >= edadMin && edad.getYears() <= edadMax) { cant ++; } } return cant; } @Override public RegistroVacuna obtenerCertificadoReserva(long idReserva) { List<RegistroVacuna> registros = this.obtenerRegistro(); RegistroVacuna retorno = null; for(RegistroVacuna r: registros) { if(r.getReserva().getId() == idReserva) { retorno = r; } } return retorno; } @Override public int cantVacHastaFecha(long vacunaId, LocalDate fecha) { long cant = (long) em.createQuery("Select count(rv) from RegistroVacuna rv where rv.vacuna.id = :id and rv.fecha <= :fecha") .setParameter("id", vacunaId) .setParameter("fecha", fecha).getSingleResult(); return (int) cant; } } <file_sep>/comp-cent-ejb/src/main/java/datos/CiudadanoDatoLocal.java package datos; import java.util.List; import javax.ejb.Local; import entidades.Ciudadano; @Local public interface CiudadanoDatoLocal { public void agregarCiudadano(Ciudadano ciudadano); public Ciudadano obtenerCiudadano(int ci); public List<Ciudadano> obtenerCiudadanos(); public void editarCiudadano(Ciudadano ciudadano); public boolean existeCiudadano(int ci); } <file_sep>/comp-cent-ejb/src/main/java/datos/VacunaDato.java package datos; import java.util.ArrayList; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import entidades.Enfermedad; import entidades.Proveedor; import entidades.Vacuna; /** * Session Bean implementation class vacunaDato */ @Stateless @LocalBean public class VacunaDato implements VacunaDatoLocal { @PersistenceContext(name = "comp-centPersistenceUnit") private EntityManager em; /** * Default constructor. */ public VacunaDato() { // TODO Auto-generated constructor stub } @Override public void agregarVacuna(Vacuna vac) { em.persist(vac); } @Override public Vacuna obtenerVacuna (String nombre) { Vacuna vacuna =(Vacuna) em.createQuery("Select v from Vacuna v where v.nombre = :nombre").setParameter("nombre", nombre).getSingleResult(); return vacuna; } public Vacuna obtenerVacuna(long id) { Vacuna vac = new Vacuna(); vac = em.find(Vacuna.class, id); return vac; } public void agregarVacunas() { // Vacuna vac1 = new Vacuna("Vacuna1","XC1","LosPepes"); // Vacuna vac2 = new Vacuna("Vacuna2","JK2","LosPedros"); // Vacuna vac3 = new Vacuna("Vacuna3","PL4","LosRodo"); // Vacuna vac4 = new Vacuna("Vacuna4","JK5","LosClavos"); // Vacuna vac5 = new Vacuna("Vacuna5","YT7","LosMemes"); // em.persist(vac1); // em.persist(vac2); // em.persist(vac3); // em.persist(vac4); // em.persist(vac5); } @Override public List<Vacuna> obtenerVacunas() { // TODO Auto-generated method stub ArrayList<Vacuna> lista = new ArrayList<Vacuna>(); for (Object obj : em.createQuery("Select v from Vacuna v").getResultList()) { Vacuna v = (Vacuna) obj; lista.add(v); } return lista; } public Boolean existeVacuna(String nombre) { Boolean existe = (em.createQuery("Select v from Vacuna v where v.nombre = :nombre").setParameter("nombre", nombre).getResultList().size() > 0); return existe; } @Override public void editarVacuna(Vacuna vacuna) { em.merge(vacuna); } @Override public void eliminarVacuna(Vacuna vacuna) { em.remove(vacuna); } @Override public Proveedor obtenerProveedorDeVacuna(String nomVac) { try { Vacuna vac = this.obtenerVacuna(nomVac); return vac.getProveedor(); } catch (Exception e){ return null; } } @Override public Enfermedad obtenerEnfermedadDeVacuna(String nomVac) { try { Vacuna vac = this.obtenerVacuna(nomVac); return vac.getEnfermedad(); } catch (Exception e){ return null; } } @Override public Vacuna obtenerVacunaPorId(long id) { Vacuna vac = em.find(Vacuna.class, id); return vac; } }<file_sep>/iniciarBD.sql INSERT INTO departamento VALUES (1, 'Artigas'); INSERT INTO departamento VALUES (2, 'Canelones'); INSERT INTO departamento VALUES (3, 'Cerro Largo'); INSERT INTO departamento VALUES (4, 'Colonia'); INSERT INTO departamento VALUES (5, 'Durazno'); INSERT INTO departamento VALUES (6, 'Flores'); INSERT INTO departamento VALUES (7, 'Florida'); INSERT INTO departamento VALUES (8, 'Lavalleja'); INSERT INTO departamento VALUES (9, 'Maldonado'); INSERT INTO departamento VALUES (10, 'Montevideo'); INSERT INTO departamento VALUES (11, 'Paysandú'); INSERT INTO departamento VALUES (12, 'Río Negro'); INSERT INTO departamento VALUES (13, 'Rivera'); INSERT INTO departamento VALUES (14, 'Rocha'); INSERT INTO departamento VALUES (15, 'Salto'); INSERT INTO departamento VALUES (16, 'San José'); INSERT INTO departamento VALUES (17, 'Soriano'); INSERT INTO departamento VALUES (18, 'Tacuarembó'); INSERT INTO departamento VALUES (19, 'Treinta y Tres'); --Agregamos enfermedad para caso de uso gestion de plan de vacuna INSERT INTO public.enfermedad(id, fechacreacion, nombre) VALUES (1, '31-10-2020', 'Enfermedad1'); INSERT INTO public.enfermedad(id, fechacreacion, nombre) VALUES (2, '20-10-1993', 'Enfermedad2'); INSERT INTO public.enfermedad(id, fechacreacion, nombre) VALUES (3, '25-3-2019', 'Enfermedad3'); --Agregamos vacunas para caso de uso gestion de plan de vacuna INSERT INTO public.vacuna(id, codigo, laboratorio, nombre, enfermedad_id, proveedor_id) VALUES (1, 'JK1', 'LoDePepe', '<NAME>.', 1, null); INSERT INTO public.vacuna(id, codigo, laboratorio, nombre, enfermedad_id, proveedor_id) VALUES (2, 'JK2', 'Jhosepha', '<NAME>.', 1, null); INSERT INTO public.vacuna(id, codigo, laboratorio, nombre, enfermedad_id, proveedor_id) VALUES (3, 'JK3', '<NAME>', '<NAME>.', 2, null); INSERT INTO public.vacuna(id, codigo, laboratorio, nombre, enfermedad_id, proveedor_id) VALUES (4, 'JK4', 'Herby', '<NAME>.', 3, null); -- Agregamos ubicaciones para vincularlos a los departamentos INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (1, 'Sur de artigas ', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (2, 'Norte de artigas ', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (3, 'Este de artigas ', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (4, 'Oeste de artigas ', null); -- Vinculamos la Tabla departamentos de Artigas con la ubicacion INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (1, 1); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (1, 2); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (1, 3); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (1, 4); -- Agregamos ubicaciones para vincularlos a los departamentos INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (5, 'Sur de Florida', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (6, 'Norte de Florida ', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (7, 'Este de Florida ', null); -- Vinculamos la Tabla departamentos de Florida con la ubicacion INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (7, 5); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (7, 6); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (7, 7); --Ubicaciones de Canelones INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (8, 'Sur de Canelones', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (9, 'Norte de Canelones', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (10, 'Este de Canelones', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (11, 'Oeste de Canelones', null); --Ubicaciones de Cerro Largo INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (12, 'Sur de Cerro Largo', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (13, 'Norte de Cerro Largo', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (14, 'Este de Cerro Largo', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (15, 'Oeste de Cerro Largo', null); --Ubicaciones de Colonia INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (16, 'Sur de Colonia', null); INSERT INTO public.ubicacion(id, descripcion, vacunatorio_id) VALUES (17, 'Norte de Colonia', null); --Vinculamos las ubicaciones al departamentos Canelones INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (2, 8); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (2, 9); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (2, 10); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (2, 11); --Vinculamos las ubicaciones al departamentos Cerro Largo INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (3, 12); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (3, 13); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (3, 14); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (3, 15); --Vinculamos las ubicaciones al departamentos Colonia INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (4, 16); INSERT INTO public.departamento_ubicacion(departamento_id, ubicaciones_id) VALUES (4, 17); --Agregamos planes de vacunacion INSERT INTO public.planvacunacion(id, edadmaxima, edadminima, nombre, poblacionobjetivo, enfermedad_id) VALUES (1, 30, 10, 'Plan COVID', 'Adolescentes', 1); INSERT INTO public.planvacunacion(id, edadmaxima, edadminima, nombre, poblacionobjetivo, enfermedad_id) VALUES (2, 50, 30, 'Plan GRIPE', 'Adultos', 2); INSERT INTO public.planvacunacion(id, edadmaxima, edadminima, nombre, poblacionobjetivo, enfermedad_id) VALUES (3, 80, 50, 'Plan COVID Mayores', 'Mayores', 2); --Agregamos vacunatorios INSERT INTO public.vacunatorio(id, codigo, nombre) VALUES (1000, 'V-ART', 'Vacunatorio Artigas'); INSERT INTO public.vacunatorio(id, codigo, nombre) VALUES (1001, 'V-FLO', 'Vacunatorio Florida'); INSERT INTO public.vacunatorio(id, codigo, nombre) VALUES (1002, 'V-CAN', 'Vacunatorio Canelones'); --Agregamos vacunatorios a las ubicaciones update ubicacion set vacunatorio_id = 1000 where id = 1; update ubicacion set vacunatorio_id = 1001 where id = 2; update ubicacion set vacunatorio_id = 1002 where id = 3; --Agregamos agendas INSERT INTO public.agenda(id, fin, horafin, horainicio, inicio, vacunatorio_id) VALUES (1124, '2020-01-01', '2000', '0800', '2020-02-10', 1000); INSERT INTO public.agenda(id, fin, horafin, horainicio, inicio, vacunatorio_id) VALUES (1123, '2023-06-11', '2000', '0800', '2022-01-01 ', 1001); INSERT INTO public.agenda(id, fin, horafin, horainicio, inicio, vacunatorio_id) VALUES (1125, '2021-10-01', '2000', '0800', '2021-05-01', 1001); --Agregamos ciudadanos INSERT INTO public.usuario(tipo, ci, email, primerapellido, primernombre, segundoapellido, segundonombre, telefono, contrasenia) VALUES ('ciudadano', 12345678, '<EMAIL>', 'Perez', 'Juan', 'Perez', 'Juan', 099654123, null); INSERT INTO public.usuario(tipo, ci, email, primerapellido, primernombre, segundoapellido, segundonombre, telefono, contrasenia) VALUES ('ciudadano', 12345679, '<EMAIL>', 'Lopez', 'Juana', 'Perez', 'Juana', 099654123, null); --Agregamos relacion agenda_planvacunacion INSERT INTO public.agenda_planvacunacion(agendas_id, planes_id) VALUES (1125, 1); INSERT INTO public.agenda_planvacunacion(agendas_id, planes_id) VALUES (1125, 2); INSERT INTO public.agenda_planvacunacion(agendas_id, planes_id) VALUES (1123, 1); INSERT INTO public.agenda_planvacunacion(agendas_id, planes_id) VALUES (1123, 3); <file_sep>/comp-cent-web/src/main/java/servicios/ServicioAgesic.java package servicios; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.3.2 * Generated source version: 2.2 * */ @WebService(name = "ServicioAgesic", targetNamespace = "http://servicios/") @XmlSeeAlso({ ObjectFactory.class }) public interface ServicioAgesic { /** * * @param arg0 * @return * returns servicios.DtPersona */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "obtenerPersona", targetNamespace = "http://servicios/", className = "servicios.ObtenerPersona") @ResponseWrapper(localName = "obtenerPersonaResponse", targetNamespace = "http://servicios/", className = "servicios.ObtenerPersonaResponse") public DtPersona obtenerPersona( @WebParam(name = "arg0", targetNamespace = "") int arg0); } <file_sep>/comp-cent-ejb/src/main/java/negocio/SessionBeanLocal.java package negocio; import javax.ejb.Local; @Local public interface SessionBeanLocal { public boolean iniciarSesion(int ci, String pass); } <file_sep>/comp-cent-ejb/src/main/java/entidades/Autoridad.java package entidades; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("autoridad") public class Autoridad extends Usuario{ public Autoridad() { super(); // TODO Auto-generated constructor stub } public Autoridad(int ci, String primerNombre, String segundoNombre, String primerApellido, String segundoApellido, int telefono, String email, String usuario, String contrasenia) { super(ci, primerNombre, segundoNombre, primerApellido, segundoApellido, telefono, email, contrasenia); // TODO Auto-generated constructor stub } } <file_sep>/comp-cent-ejb/src/main/java/datos/AutoridadDato.java package datos; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import entidades.Autoridad; /** * Session Bean implementation class AutoridadDato */ @Stateless @LocalBean public class AutoridadDato implements AutoridadDatoLocal { @PersistenceContext(name = "comp-centPersistenceUnit") private EntityManager em; /** * Default constructor. */ public AutoridadDato() { // TODO Auto-generated constructor stub } @Override public void guardarAutoridad(Autoridad autoridad) { em.persist(autoridad); } @Override public void editarAutoridad(Autoridad autoridad) { em.merge(autoridad); } @Override public List<Autoridad> obtenerAutoridades() { return em.createQuery("SELECT a FROM Autoridad a", Autoridad.class).getResultList(); } @Override public Autoridad obtenerAutoridadPorCI(int ci) { return em.find(Autoridad.class, ci); } } <file_sep>/comp-cent-ejb/src/main/java/enumeradores/Horario.java package enumeradores; public enum Horario { Mañana, Tarde } <file_sep>/comp-cent-ejb/src/main/java/negocio/NotificacionTokenNegocio.java package negocio; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import datatypes.DTNotificacionToken; import datos.NotificacionTokenDatoLocal; import datos.UsuarioDatoLocal; import entidades.NotificacionToken; import entidades.Usuario; /** * Session Bean implementation class NotificacionTokenNegocio */ @Stateless @LocalBean public class NotificacionTokenNegocio implements NotificacionTokenNegocioLocal { @EJB private NotificacionTokenDatoLocal notificacionTokenDato; @EJB private UsuarioDatoLocal usuariosDato; /** * Default constructor. */ public NotificacionTokenNegocio() { // TODO Auto-generated constructor stub } @Override public void saveUserToken(DTNotificacionToken dTnotificacionToken) { // TODO Auto-generated method stub NotificacionToken notificacionToken = new NotificacionToken(); notificacionToken.setToken(dTnotificacionToken.getToken()); Usuario usuario = usuariosDato.obtenerUsuarioPorCI(dTnotificacionToken.getCedula()); if ( usuario == null ) { throw new RuntimeException("Usuario no existe"); } notificacionToken.setUsuario(usuario); if (!notificacionTokenDato.existeNoficacionToken(notificacionToken)) { notificacionTokenDato.saveUserToken(notificacionToken); } } @Override public List<String> getUserTokens(int ci) { // TODO Auto-generated method stub List<String> tokensList = new ArrayList<String>(); List<NotificacionToken> list = notificacionTokenDato.getUserTokens(usuariosDato.obtenerUsuarioPorCI(ci)); for (NotificacionToken nt : list) { tokensList.add(nt.getToken()); } return tokensList; } } <file_sep>/comp-cent-web/src/main/java/beans/ReportesActosVacunalesBean.java package beans; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.view.ViewScoped; import javax.inject.Named; import org.primefaces.model.charts.ChartData; import org.primefaces.model.charts.axes.cartesian.CartesianScales; import org.primefaces.model.charts.axes.cartesian.linear.CartesianLinearAxes; import org.primefaces.model.charts.axes.cartesian.linear.CartesianLinearTicks; import org.primefaces.model.charts.bar.BarChartDataSet; import org.primefaces.model.charts.bar.BarChartModel; import org.primefaces.model.charts.bar.BarChartOptions; import org.primefaces.model.charts.line.LineChartDataSet; import org.primefaces.model.charts.line.LineChartModel; import org.primefaces.model.charts.line.LineChartOptions; import org.primefaces.model.charts.optionconfig.animation.Animation; import org.primefaces.model.charts.optionconfig.legend.Legend; import org.primefaces.model.charts.optionconfig.legend.LegendLabel; import org.primefaces.model.charts.optionconfig.title.Title; import org.primefaces.model.charts.pie.PieChartDataSet; import org.primefaces.model.charts.pie.PieChartModel; import datatypes.DTVacuna; import negocio.RegistroVacunaNegocioLocal; import negocio.VacunaNegocioLocal; @Named("reportesACBean") @ViewScoped public class ReportesActosVacunalesBean implements Serializable{ private static final long serialVersionUID = 1L; @EJB private RegistroVacunaNegocioLocal registroLocal; @EJB private VacunaNegocioLocal vacunaLocal; private List<Integer> cantidadVacunados; private int anio; private DTVacuna vacuna; private List<DTVacuna> listaVacunas; private List<String> nombreVacunas; private String vac; private List<Integer> cantidadVacunadosPorSexo; private List<Integer> cantidadVacunadosPorEdad; private int totalVacunados; private Boolean visible; private LineChartModel lineModel; private PieChartModel pieModel; private BarChartModel barModel; public ReportesActosVacunalesBean() { // TODO Auto-generated constructor stub } @PostConstruct public void init() { this.cantidadVacunados = new ArrayList<Integer>(); this.cantidadVacunadosPorSexo = new ArrayList<Integer>(); this.cantidadVacunadosPorEdad = new ArrayList<Integer>(); this.listaVacunas = vacunaLocal.obtenerVacunas(); this.nombreVacunas = vacunaLocal.nombresVacunas(); this.totalVacunados = 0; this.visible = false; createLineModel(); createPieModel(); createBarModel(); } public void createLineModel() { lineModel = new LineChartModel(); ChartData data = new ChartData(); LineChartDataSet dataSet = new LineChartDataSet(); List<Object> values = new ArrayList<>(); if (cantidadVacunados != null) { for (int cant : cantidadVacunados) { values.add(cant); } } else { values.add(0); } dataSet.setData(values); dataSet.setFill(false); if (vacuna != null) { dataSet.setLabel(vacuna.getNombre()); } else { dataSet.setLabel(""); } dataSet.setBorderColor("rgb(75, 192, 192)"); dataSet.setLineTension(0.1); data.addChartDataSet(dataSet); List<String> labels = new ArrayList<>(); labels.add("Enero"); labels.add("Febrero"); labels.add("Marzo"); labels.add("Abril"); labels.add("Mayo"); labels.add("Junio"); labels.add("Julio"); labels.add("Agosto"); labels.add("Septiembre"); labels.add("Octubre"); labels.add("Noviembre"); labels.add("Diciembre"); data.setLabels(labels); //Options LineChartOptions options = new LineChartOptions(); Title title = new Title(); title.setDisplay(true); title.setText("Vacunados"); options.setTitle(title); lineModel.setOptions(options); lineModel.setData(data); } public LineChartModel getLineModel() { return lineModel; } public void setLineModel(LineChartModel lineModel) { this.lineModel = lineModel; } private void createPieModel() { pieModel = new PieChartModel(); ChartData data = new ChartData(); PieChartDataSet dataSet = new PieChartDataSet(); List<Number> values = new ArrayList<>(); if (cantidadVacunadosPorSexo != null) { for (Integer cantPorSexo: cantidadVacunadosPorSexo) { values.add(cantPorSexo); } } else { values.add(0); } dataSet.setData(values); List<String> bgColors = new ArrayList<>(); bgColors.add("rgb(255, 99, 132)"); bgColors.add("rgb(54, 162, 235)"); dataSet.setBackgroundColor(bgColors); data.addChartDataSet(dataSet); List<String> labels = new ArrayList<>(); labels.add("Mujeres"); labels.add("Hombres"); data.setLabels(labels); pieModel.setData(data); } public PieChartModel getPieModel() { return pieModel; } public void setPieModel(PieChartModel pieModel) { this.pieModel = pieModel; } public void createBarModel() { barModel = new BarChartModel(); ChartData data = new ChartData(); BarChartDataSet barDataSet = new BarChartDataSet(); barDataSet.setLabel("Vacunados"); List<Number> values = new ArrayList<>(); if (cantidadVacunadosPorEdad != null) { for (Integer cantXEdad :cantidadVacunadosPorEdad) { values.add(cantXEdad); } } else { values.add(0); } barDataSet.setData(values); List<String> bgColor = new ArrayList<>(); bgColor.add("rgba(255, 99, 132, 0.2)"); bgColor.add("rgba(255, 159, 64, 0.2)"); bgColor.add("rgba(255, 205, 86, 0.2)"); bgColor.add("rgba(75, 192, 192, 0.2)"); bgColor.add("rgba(54, 162, 235, 0.2)"); bgColor.add("rgba(153, 102, 255, 0.2)"); bgColor.add("rgba(201, 203, 207, 0.2)"); barDataSet.setBackgroundColor(bgColor); List<String> borderColor = new ArrayList<>(); borderColor.add("rgb(255, 99, 132)"); borderColor.add("rgb(255, 159, 64)"); borderColor.add("rgb(255, 205, 86)"); borderColor.add("rgb(75, 192, 192)"); borderColor.add("rgb(54, 162, 235)"); borderColor.add("rgb(153, 102, 255)"); borderColor.add("rgb(201, 203, 207)"); barDataSet.setBorderColor(borderColor); barDataSet.setBorderWidth(1); data.addChartDataSet(barDataSet); List<String> labels = new ArrayList<>(); labels.add("0 - 11"); labels.add("12 - 17"); labels.add("18 - 25"); labels.add("26 - 40"); labels.add("41 - 60"); labels.add("61 - 75"); labels.add("Mayores de 76"); data.setLabels(labels); barModel.setData(data); //Options BarChartOptions options = new BarChartOptions(); CartesianScales cScales = new CartesianScales(); CartesianLinearAxes linearAxes = new CartesianLinearAxes(); linearAxes.setOffset(true); CartesianLinearTicks ticks = new CartesianLinearTicks(); ticks.setBeginAtZero(true); linearAxes.setTicks(ticks); cScales.addYAxesData(linearAxes); options.setScales(cScales); Title title = new Title(); title.setDisplay(true); title.setText("Por rango de edades"); options.setTitle(title); Legend legend = new Legend(); legend.setDisplay(true); legend.setPosition("top"); LegendLabel legendLabels = new LegendLabel(); legendLabels.setFontStyle("bold"); legendLabels.setFontColor("#2980B9"); legendLabels.setFontSize(24); legend.setLabels(legendLabels); options.setLegend(legend); // disable animation Animation animation = new Animation(); animation.setDuration(0); options.setAnimation(animation); barModel.setOptions(options); } public BarChartModel getBarModel() { return barModel; } public void setBarModel(BarChartModel barModel) { this.barModel = barModel; } public List<Integer> getCantidadVacunados() { return cantidadVacunados; } public void setCantidadVacunados(List<Integer> cantidadVacunados) { this.cantidadVacunados = cantidadVacunados; } public int getAnio() { return anio; } public void setAnio(int anio) { this.anio = anio; } public DTVacuna getVacuna() { return vacuna; } public void setVacuna(DTVacuna vacuna) { this.vacuna = vacuna; } public List<DTVacuna> getListaVacunas() { return listaVacunas; } public void setListaVacunas(List<DTVacuna> listaVacunas) { this.listaVacunas = listaVacunas; } public List<String> getNombreVacunas() { return nombreVacunas; } public void setNombreVacunas(List<String> nombreVacunas) { this.nombreVacunas = nombreVacunas; } public String getVac() { return vac; } public void setVac(String vac) { this.vac = vac; } public List<Integer> getCantidadVacunadosPorSexo() { return cantidadVacunadosPorSexo; } public void setCantidadVacunadosPorSexo(List<Integer> cantidadVacunadosPorSexo) { this.cantidadVacunadosPorSexo = cantidadVacunadosPorSexo; } public List<Integer> getCantidadVacunadosPorEdad() { return cantidadVacunadosPorEdad; } public void setCantidadVacunadosPorEdad(List<Integer> cantidadVacunadosPorEdad) { this.cantidadVacunadosPorEdad = cantidadVacunadosPorEdad; } public int getTotalVacunados() { return totalVacunados; } public void setTotalVacunados(int totalVacunados) { this.totalVacunados = totalVacunados; } public Boolean getVisible() { return visible; } public void setVisible(Boolean visible) { this.visible = visible; } public void obtenerVacunadosXAnio() { this.visible = true; this.vacuna = new DTVacuna(); for (DTVacuna dtVacuna : listaVacunas) { if (dtVacuna.getNombre().equals(vac)) { this.vacuna = dtVacuna; } } this.cantidadVacunados = registroLocal.obtenerCantVac(vacuna, anio); for (int cant: cantidadVacunados) { this.totalVacunados += cant; } createLineModel(); this.cantidadVacunadosPorSexo = registroLocal.cantRegistroPorSexo(vacuna, anio); createPieModel(); this.cantidadVacunadosPorEdad = registroLocal.cantRegistroPorEdad(vacuna, anio); createBarModel(); this.vacuna = new DTVacuna(); this.anio = 0; this.totalVacunados = 0; } } <file_sep>/comp-cent-ejb/src/main/java/datatypes/Horario.java package datatypes; public enum Horario { Mañana, Tarde } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTConsultaReservaCiudadano.java package datatypes; import java.io.Serializable; import entidades.Reserva; public class DTConsultaReservaCiudadano implements Serializable{ private static final long serialVersionUID = 1L; private long id; private int hora; private String fecha; private String enfermedad; private String vacunatorio; private String estado; public DTConsultaReservaCiudadano() { super(); // TODO Auto-generated constructor stub } public DTConsultaReservaCiudadano(Reserva res){ this.id = res.getId(); this.hora = res.getHora(); if(res.getFecha() == null) { this.fecha = "N/A"; } else { this.fecha = res.getFecha().toString(); } this.estado = res.getEstado().name(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getHora() { return hora; } public void setHora(int hora) { this.hora = hora; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public String getEnfermedad() { return enfermedad; } public void setEnfermedad(String enfermedad) { this.enfermedad = enfermedad; } public String getVacunatorio() { return vacunatorio; } public void setVacunatorio(String vacunatorio) { this.vacunatorio = vacunatorio; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } } <file_sep>/comp-cent-web/src/main/java/rest/RegistroVacunaREST.java package rest; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.naming.NamingException; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import datatypes.DTCertificado; import negocio.RegistroVacunaNegocioLocal; @RequestScoped @Path("/certificado") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class RegistroVacunaREST { @EJB RegistroVacunaNegocioLocal regVacLocal; public RegistroVacunaREST() throws NamingException { } @GET @Path("/ciudadano/{ci}") public Response getCertificadosPorCi(@PathParam("ci") String ci) { if (ci != null && !ci.equals("")) { List<DTCertificado> listDTCert = regVacLocal.obtenerCertificados(ci); if (!listDTCert.isEmpty()) { return Response .status(Response.Status.OK) .entity(listDTCert) .build(); } else { return Response .status(Response.Status.NOT_FOUND) .entity("No se encontraron certificados para la ci.") .build(); } } else { return Response .status(Response.Status.BAD_REQUEST) .entity("Falta paramentro ci.") .build(); } } @GET @Path("count-registros/{id}") public Response countVacunadosHoy(@PathParam("id") long vacunaId) { try { return Response .status(Response.Status.OK) .entity(regVacLocal.countVacunadosHoy(vacunaId)) .build(); } catch(Exception e) { return Response .status(Response.Status.BAD_REQUEST) .entity("Error") .build(); } } @GET @Path("count-vacunados-mes/{id}/{ano}") public Response countVacunadosPorMes(@PathParam("id") long vacunaId, @PathParam("ano") int ano) { try { return Response .status(Response.Status.OK) .entity(regVacLocal.countVacunadosPorMes(vacunaId, ano)) .build(); } catch(Exception e){ return Response .status(Response.Status.INTERNAL_SERVER_ERROR) .build(); } } @GET @Path("count-vacunados-departamento/{id}/{ano}") public Response countVacunadosPorDepartamento(@PathParam("id") long vacunaId, @PathParam("ano") int ano) { try { return Response .status(Response.Status.OK) .entity(regVacLocal.countVacunadosPorDepartamento(vacunaId, ano)) .build(); } catch(Exception e){ return Response .status(Response.Status.INTERNAL_SERVER_ERROR) .build(); } } @GET @Path("obtener-certificado-reserva/{id}") public Response obtenerCertificadoReserva(@PathParam("id") long idReserva) { try { return Response .status(Response.Status.OK) .entity(regVacLocal.obtenerCertificadoReserva(idReserva)) .build(); } catch(Exception e){ return Response .status(Response.Status.INTERNAL_SERVER_ERROR) .build(); } } } <file_sep>/comp-cent-ejb/src/main/java/datos/VacunatorioGeomDatoLocal.java package datos; import java.util.List; import javax.ejb.Local; import datatypes.DTVacunatorioGeom; @Local public interface VacunatorioGeomDatoLocal { public void agregarCoordenadas(long idVacunatorio, String lat, String lon); public List<DTVacunatorioGeom> vacunatoriosCercanos(String lat, String lon); } <file_sep>/comp-cent-ejb/src/main/java/entidades/Departamento.java package entidades; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; @Entity @NamedQueries ({ @NamedQuery(name="Departamento.obtenerDepartamentos", query="Select d from Departamento d ORDER BY d.descripcion") }) public class Departamento { @Id @GeneratedValue private long id; private String descripcion; @OneToMany(cascade=CascadeType.ALL,orphanRemoval=true) private List<Ubicacion> ubicaciones = new ArrayList<>(); public Departamento() { super(); // TODO Auto-generated constructor stub } public Departamento(long id, String descripcion) { super(); this.id = id; this.descripcion = descripcion; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public List<Ubicacion> getUbicaciones() { return ubicaciones; } public void setUbicaciones(List<Ubicacion> ubicaciones) { this.ubicaciones = ubicaciones; } } <file_sep>/comp-cent-ejb/src/main/java/negocio/VacunaNegocio.java package negocio; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.inject.Inject; import datatypes.DTEnfermedad; import datatypes.DTProveedor; import datatypes.DTVacuna; import datos.EnfermedadDatoLocal; import datos.ProveedorDatoLocal; import datos.VacunaDato; import entidades.Enfermedad; import entidades.Proveedor; import entidades.Vacuna; /** * Session Bean implementation class vacunaNegocio */ @Stateless @LocalBean public class VacunaNegocio implements VacunaNegocioLocal { @SuppressWarnings("unused") private static final long serialVersionUID = 1L; @Inject private VacunaDato puenteDatos; @EJB private EnfermedadDatoLocal enfermedadDatoLocal; @EJB private ProveedorDatoLocal proveedorDatoLocal; /** * Default constructor. */ public VacunaNegocio() { // TODO Auto-generated constructor stub } @Override public void agregarVacuna(String nombre, String codigo, String laboratorio, Enfermedad enf, Proveedor pro, int dosis, int periodoInmune) { Vacuna vac= new Vacuna(); vac.setNombre(nombre); vac.setCodigo(codigo); vac.setLaboratorio(laboratorio); vac.setDosis(dosis); vac.setPeriodoInmune(periodoInmune); puenteDatos.agregarVacuna(vac); } @Override public DTVacuna obtenerVacuna(long id) { Vacuna vac = puenteDatos.obtenerVacuna(id); return new DTVacuna(vac); } @Override public List<DTVacuna> obtenerVacunas(){ ArrayList<Vacuna> vacs = (ArrayList<Vacuna>)puenteDatos.obtenerVacunas(); ArrayList<DTVacuna> dtVacs = new ArrayList<DTVacuna>(); for(Vacuna vac : vacs) { dtVacs.add(new DTVacuna(vac)); } return dtVacs; } @Override public void agregarVacunas() { puenteDatos.agregarVacunas(); } @Override public void agregarVacuna(DTVacuna dtvacuna) throws Exception { if(puenteDatos.existeVacuna(dtvacuna.getNombre())) { throw new Exception("\nYa existe una Vacuna con el nombre ingresado"); }else { Vacuna vac = new Vacuna(dtvacuna); Enfermedad enf = enfermedadDatoLocal.buscarEnfermedad(dtvacuna.getEnfermedad().getNombre()); vac.setEnfermedad(enf); Proveedor pro = proveedorDatoLocal.obtenerProveedorPorNombre(dtvacuna.getProveedor().getNombre()); vac.setProveedor(pro); vac.setDosis(dtvacuna.getDosis()); vac.setPeriodoInmune(dtvacuna.getPeriodoInmune()); // System.out.println(enf.getNombre() + enf.getId()); // System.out.println(pro.getNombre() + pro.getId()); this.puenteDatos.agregarVacuna(vac); } } public void editarVacuna(DTVacuna dtvacuna) throws Exception { Vacuna vacuna = puenteDatos.obtenerVacunaPorId(dtvacuna.getId()); if(vacuna != null) { System.out.println(dtvacuna.getEnfermedad().getNombre()); Enfermedad enf = enfermedadDatoLocal.buscarEnfermedad(dtvacuna.getEnfermedad().getNombre()); vacuna.setEnfermedad(enf); Proveedor pro = proveedorDatoLocal.obtenerProveedorPorNombre(dtvacuna.getProveedor().getNombre()); vacuna.setProveedor(pro); vacuna.setNombre(dtvacuna.getNombre()); vacuna.setCodigo(dtvacuna.getCodigo()); vacuna.setLaboratorio(dtvacuna.getLaboratorio()); vacuna.setDosis(dtvacuna.getDosis()); vacuna.setPeriodoInmune(dtvacuna.getPeriodoInmune()); puenteDatos.editarVacuna(vacuna); }else { throw new Exception("\nNo se encontro una Vacuna con el id ingresado"); } } public DTProveedor obtenerProveedorDeVacuna(String nombre) { Vacuna vac = puenteDatos.obtenerVacuna(nombre); DTProveedor dtPro = new DTProveedor(vac.getProveedor()); return dtPro; } public DTEnfermedad obtenerEnfermedadDeVacuna(String nombre) { Vacuna vac = puenteDatos.obtenerVacuna(nombre); DTEnfermedad dtEnf = new DTEnfermedad(vac.getEnfermedad()); return dtEnf; } @Override public void eliminarVacuna(String nombre) throws Exception{ Vacuna vac = puenteDatos.obtenerVacuna(nombre); if(vac != null) { puenteDatos.eliminarVacuna(vac); }else { throw new Exception("\nNo se encontro un plan con el id ingresado"); } } @Override public List<String> nombresVacunas() { List<DTVacuna> vacunas = obtenerVacunas(); List<String> nombres = new ArrayList<String>(); vacunas.forEach((v)->{nombres.add(v.getNombre());}); return nombres; } }<file_sep>/comp-cent-ejb/src/main/java/datos/NotificacionTokenDatoLocal.java package datos; import java.util.List; import javax.ejb.Local; import entidades.NotificacionToken; import entidades.Usuario; @Local public interface NotificacionTokenDatoLocal { public void saveUserToken(NotificacionToken notificacionToken); public List<NotificacionToken> getUserTokens(Usuario usuario); Boolean existeNoficacionToken(NotificacionToken notificacionToken); } <file_sep>/comp-cent-ejb/src/main/java/entidades/Usuario.java package entidades; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import enumeradores.Sexo; @Entity @DiscriminatorColumn(name="tipo") public abstract class Usuario { @Id private int ci; private String primerNombre; private String segundoNombre; private String primerApellido; private String segundoApellido; private int telefono; private String email; private String contrasenia; @Enumerated(value = EnumType.STRING) private Sexo sexo; public Usuario() { super(); } public Usuario(int ci, String primerNombre, String segundoNombre, String primerApellido, String segundoApellido, int telefono, String email, String contrasenia) { super(); this.ci = ci; this.primerNombre = primerNombre; this.segundoNombre = segundoNombre; this.primerApellido = primerApellido; this.segundoApellido = segundoApellido; this.telefono = telefono; this.email = email; this.contrasenia = contrasenia; } public Usuario(int ci, String primerNombre, String segundoNombre, String primerApellido, String segundoApellido, int telefono, String email) { super(); this.ci = ci; this.primerNombre = primerNombre; this.segundoNombre = segundoNombre; this.primerApellido = primerApellido; this.segundoApellido = segundoApellido; this.telefono = telefono; this.email = email; } public int getCi() { return ci; } public void setCi(int ci) { this.ci = ci; } public String getPrimerNombre() { return primerNombre; } public void setPrimerNombre(String primerNombre) { this.primerNombre = primerNombre; } public String getSegundoNombre() { return segundoNombre; } public void setSegundoNombre(String segundoNombre) { this.segundoNombre = segundoNombre; } public String getPrimerApellido() { return primerApellido; } public void setPrimerApellido(String primerApellido) { this.primerApellido = primerApellido; } public String getSegundoApellido() { return segundoApellido; } public void setSegundoApellido(String segundoApellido) { this.segundoApellido = segundoApellido; } public int getTelefono() { return telefono; } public void setTelefono(int telefono) { this.telefono = telefono; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getContrasenia() { return contrasenia; } public void setContrasenia(String contrasenia) { this.contrasenia = contrasenia; } public Sexo getSexo() { return sexo; } public void setSexo(Sexo sexo) { this.sexo = sexo; } @Override public String toString() { return "Usuario [ci=" + ci + ", primerNombre=" + primerNombre + ", segundoNombre=" + segundoNombre + ", primerApellido=" + primerApellido + ", segundoApellido=" + segundoApellido + ", telefono=" + telefono + ", email=" + email + ", contrasenia=" + contrasenia + "]"; } } <file_sep>/comp-cent-ejb/src/main/java/notificacionesFirebase/NotificationResponseResults.java package notificacionesFirebase; import java.io.Serializable; public class NotificationResponseResults implements Serializable { private static final long serialVersionUID = -7985038301520373106L; private String message_id; public NotificationResponseResults() { super(); } public NotificationResponseResults(String message_id) { super(); this.message_id = message_id; } public String getMessage_id() { return message_id; } public void setMessage_id(String message_id) { this.message_id = message_id; } @Override public String toString() { return "{\"message_id\":\"" + message_id + "\"}"; } }<file_sep>/comp-cent-ejb/src/main/java/negocio/AutoridadNegocioLocal.java package negocio; import javax.ejb.Local; import entidades.Autoridad; @Local public interface AutoridadNegocioLocal { public Autoridad obtenerAutoridadPorCi (int ci); } <file_sep>/comp-cent-ejb/src/main/java/negocio/EnfermedadNegocioLocal.java package negocio; import java.util.List; import javax.ejb.Local; import datatypes.DTEnfermedad; import datatypes.DTVacuna; @Local public interface EnfermedadNegocioLocal { public List<DTEnfermedad> listarEnfermedades (); public void agregarEnfermedad(String nombre) throws Exception; public DTEnfermedad buscarEnfermedad(String nombre) throws Exception; public List<DTVacuna> listarVacunasPorEnfermedad (String nombreEnfermedad) throws Exception; public List<String> listarPoblacionObjetivo(); public void eliminarEnfermedad(String nombre) throws Exception; public DTEnfermedad obtenerEnfermedadPorId(long id); public void editarEnfermedad(DTEnfermedad dtEnf) throws Exception; } <file_sep>/comp-cent-ejb/src/main/java/datos/ProveedorDatoLocal.java package datos; import java.util.List; import javax.ejb.Local; import entidades.Proveedor; @Local public interface ProveedorDatoLocal { public List<Proveedor> obtenerProveedores(); public Proveedor obtenerProveedorPorNombre(String nombre); public Boolean existeProveedor(String nombre); public void agregarProveedor(Proveedor proveedor); public Proveedor obtenerProveedorPorId(long id); public void editarProveedor(Proveedor pro); public void eliminarProveedor(Proveedor pro); } <file_sep>/comp-cent-ejb/src/main/java/negocio/RegistroVacunaNegocioLocal.java package negocio; import java.time.LocalDate; import java.util.List; import javax.ejb.Local; import datatypes.DTCertificado; import datatypes.DTRegistroVacuna; import datatypes.DTVacuna; import entidades.RegistroVacuna; @Local public interface RegistroVacunaNegocioLocal { public List<DTCertificado> obtenerCertificados(String ci); public List<RegistroVacuna> listarRegistros(); public void altaRegistroVacuna (List<DTRegistroVacuna> regVacuna); public List<Integer> obtenerCantVac(DTVacuna vacuna, int anio); public List<Integer> cantRegistroPorSexo(DTVacuna vacuna, int anio); public List<Integer> cantRegistroPorEdad(DTVacuna vacuna, int anio); public int countVacunadosHoy(long vacunaId); public int[] countVacunadosPorMes(long vacunaId, int ano); public int[] countVacunadosPorDepartamento(long vacunaId, int ano); public DTCertificado obtenerCertificadoReserva(long idReserva); public int cantVacHastaFecha(long vacunaId, LocalDate fecha); } <file_sep>/comp-cent-ejb/src/test/java/negocio/ProveedorNegocioTest.java package negocio; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import datatypes.DTProveedor; import static org.mockito.ArgumentMatchers.any; import java.util.ArrayList; import java.util.List; import datos.ProveedorDatoLocal; import entidades.PlanVacunacion; import entidades.Proveedor; public class ProveedorNegocioTest { @Mock private ProveedorDatoLocal pdl; @InjectMocks private ProveedorNegocio pn; private static Proveedor proveedor; private static DTProveedor dtProveedor; private static List<Proveedor> proveedores; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); proveedor = Mockito.mock(Proveedor.class); dtProveedor = Mockito.mock(DTProveedor.class); proveedores = new ArrayList<Proveedor>(); proveedores.add(proveedor); } @Test public void testAgregarProveedor() throws Exception { Mockito.when(pdl.existeProveedor(any(String.class))).thenReturn(false); Mockito.doNothing().when(pdl).agregarProveedor(any(Proveedor.class)); pn.agregarProveedor("prueba", 11111); Mockito.verify(pdl ,Mockito.times(1)).agregarProveedor(any(Proveedor.class)); } @Test(expected = Exception.class) public void testAgregarProveedorException() throws Exception { Mockito.when(pdl.existeProveedor(any(String.class))).thenReturn(true); pn.agregarProveedor("prueba", 11111); } @Test public void testObtenerProveedores() { Mockito.when(pdl.obtenerProveedores()).thenReturn(proveedores); assert(pn.obtenerProveedores()!= null); } @Test public void testObtenerProveedorPorId() { Mockito.when(pdl.obtenerProveedorPorId(any(Long.class))).thenReturn(proveedor); assert(pn.obtenerProveedorPorId(any(Long.class))!=null); } @Test public void testEditarProveedor() throws Exception { Mockito.when(pdl.obtenerProveedorPorId(any(Long.class))).thenReturn(proveedor); Mockito.doNothing().when(pdl).editarProveedor(any(Proveedor.class)); pn.editarProveedor(dtProveedor); Mockito.verify(pdl ,Mockito.times(1)).editarProveedor(any(Proveedor.class)); } @Test(expected = Exception.class) public void testEditarProveedorException() throws Exception { Mockito.when(pdl.obtenerProveedorPorId(any(Long.class))).thenReturn(null); pn.editarProveedor(dtProveedor); } @Test public void testEliminarProveedor() throws Exception { Mockito.when(pdl.obtenerProveedorPorId(any(Long.class))).thenReturn(proveedor); Mockito.doNothing().when(pdl).eliminarProveedor(any(Proveedor.class)); pn.eliminarProveedor(dtProveedor); Mockito.verify(pdl ,Mockito.times(1)).eliminarProveedor(any(Proveedor.class)); } @Test(expected = Exception.class) public void testEliminarProveedorException() throws Exception { Mockito.when(pdl.obtenerProveedorPorId(any(Long.class))).thenReturn(null); pn.eliminarProveedor(dtProveedor); } @Test public void testObtenerProveedor() throws Exception { Mockito.when(pdl.existeProveedor(any(String.class))).thenReturn(true); Mockito.when(pdl.obtenerProveedorPorNombre(any(String.class))).thenReturn(proveedor); pn.obtenerProveedor("prueba"); } @Test(expected = Exception.class) public void testObtenerProveedorException() throws Exception { Mockito.when(pdl.existeProveedor(any(String.class))).thenReturn(false); pn.obtenerProveedor("prueba"); } } <file_sep>/comp-cent-ejb/src/main/java/negocio/AutoridadNegocio.java package negocio; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import datos.AutoridadDatoLocal; import entidades.Autoridad; /** * Session Bean implementation class AutoridadNegocio */ @Stateless @LocalBean public class AutoridadNegocio implements AutoridadNegocioLocal { @EJB private AutoridadDatoLocal datoLocal ; public AutoridadNegocio() { // TODO Auto-generated constructor stub } public Autoridad obtenerAutoridadPorCi (int ci) { return datoLocal.obtenerAutoridadPorCI(ci); } } <file_sep>/comp-cent-ejb/src/main/java/datos/AdministradorDato.java package datos; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import entidades.Administrador; /** * Session Bean implementation class AdministradorDato */ @Stateless @LocalBean public class AdministradorDato implements AdministradorDatoLocal { @PersistenceContext(name = "comp-centPersistenceUnit") private EntityManager em; /** * Default constructor. */ public AdministradorDato() { // TODO Auto-generated constructor stub } @Override public void guardarAdministrador(Administrador administrador) { em.persist(administrador); } @Override public void editarAdministrador(Administrador administrador) { em.merge(administrador); } @Override public List<Administrador> obtenerAdministradores() { return em.createQuery("SELECT r FROM Administrador r", Administrador.class).getResultList(); } @Override public Administrador obtenerAdministradorPorCI(int ci) { return em.find(Administrador.class, ci); } } <file_sep>/comp-cent-web/src/main/java/rest/ReservaREST.java package rest; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.naming.NamingException; import javax.ws.rs.Consumes; 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 javax.ws.rs.core.Response; import com.google.gson.Gson; import datatypes.DTCiudadano; import datatypes.DTConsultaReservaCiudadano; import datatypes.DTDepartamento; import datatypes.DTPlanVacunacion; import datatypes.DTReserva; import datatypes.DTReservaWS; import datatypes.DTUbicacion; import negocio.CiudadanoNegocioLocal; import negocio.DepartamentoNegocioLocal; import negocio.PlanVacunacionNegocioLocal; import negocio.ReservaNegocioLocal; @RequestScoped @Path("/reserva") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class ReservaREST { @Inject private ReservaNegocioLocal rnl; @Inject private CiudadanoNegocioLocal cnl; @Inject private PlanVacunacionNegocioLocal pvnl; @Inject private DepartamentoNegocioLocal dnl; public ReservaREST() throws NamingException { } @POST public Response crearReserva(DTReservaWS dtrws) { DTReserva dtReserva = new DTReserva(); try{ int numeroCi = Integer.parseInt(dtrws.getCi()); DTCiudadano dtCiudadano = cnl.obtenerCiudadano(numeroCi); if(dtCiudadano == null) { return Response .status(Response.Status.NOT_FOUND) .entity(new Gson().toJson("ERROR: no existe el ciudadano")) .build(); } else { dtReserva.setCiudadano(dtCiudadano); } } catch (NumberFormatException ex){ return Response .status(Response.Status.BAD_REQUEST) .entity(new Gson().toJson("ERROR: la cedula debe ser numerica")) .build(); } DTPlanVacunacion dtPlanVacunacion; try { dtPlanVacunacion = pvnl.obtenerPlanVacunacion(dtrws.getPlanVacunacion()); dtReserva.setPlanVacunacion(dtPlanVacunacion); } catch (Exception e) { return Response .status(Response.Status.NOT_FOUND) .entity(new Gson().toJson("ERROR: Plan de vacunacion no encontrado")) .build(); } DTUbicacion dtUbicacion = dnl.obtenerDepartamentoUbicacion(dtrws.getDepartamento(), dtrws.getUbicacion()); DTDepartamento dtDepartamento = new DTDepartamento(dtrws.getDepartamento()); if(dtUbicacion == null || dtDepartamento == null) { return Response .status(Response.Status.NOT_FOUND) .entity(new Gson().toJson("ERROR: Ubicacion o departamento no encontrado")) .build(); } else { dtReserva.setUbicacion(dtUbicacion); dtReserva.setDepartamento(dtDepartamento); } rnl.crearReserva(dtReserva); return Response .status(Response.Status.OK) .entity(new Gson().toJson("INFO: Reserva creada!")) .build(); } @GET @Path("/{ci}") public Response consultaReservas(@PathParam("ci") String ci) { try{ int numeroCi = Integer.parseInt(ci); List<DTConsultaReservaCiudadano> dtReservas = rnl.ciudadanoReservas(numeroCi); if(!dtReservas.isEmpty()) { return Response .status(Response.Status.OK) .entity(dtReservas) .build(); } else { return Response .status(Response.Status.NOT_FOUND) .entity("El ciudadano no tiene reservas") .build(); } } catch (NumberFormatException ex){ return Response .status(Response.Status.BAD_REQUEST) .entity("Ha ocurrido un error procesando la cedula") .build(); } } @PUT @Path("/cancelar") public Response cancelarReserva(String idReserva) { try { rnl.cancelarReserva(idReserva); return Response .status(Response.Status.OK) .entity(new Gson().toJson("INFO: Reserva cancelada")) .build(); } catch (Exception e) { return Response .status(Response.Status.INTERNAL_SERVER_ERROR) .build(); } } @GET @Path("/count-agendados/{id}") public Response countAgendadosHoy(@PathParam("id") long vacunaId) { try { return Response .status(Response.Status.OK) .entity(rnl.countAgendadosHoy(vacunaId)) .build(); } catch(Exception e){ return Response .status(Response.Status.INTERNAL_SERVER_ERROR) .build(); } } } <file_sep>/comp-cent-ejb/src/main/java/negocio/VacunatorioNegocio.java package negocio; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Schedule; import javax.ejb.Stateless; import javax.ejb.Timer; import javax.ejb.TimerService; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import datatypes.DTAgenda; import datatypes.DTAsignarVacunadores; import datatypes.DTUbicacion; import datatypes.DTVacunatorio; import datos.UbicacionDatoLocal; import datos.VacunatorioDatoLocal; import datos.VacunatorioVacunadorDatoLocal; import entidades.Agenda; import entidades.Ubicacion; import entidades.Vacunador; import entidades.Vacunatorio; /** * Session Bean implementation class VacunatorioNegocio */ @Stateless @LocalBean public class VacunatorioNegocio implements VacunatorioNegocioLocal { @Resource TimerService timerService; @EJB private VacunatorioDatoLocal vacunatorioLocal; @EJB private UbicacionDatoLocal ubicacionLocal; @EJB private VacunatorioVacunadorDatoLocal vvLocal; /** * Default constructor. */ public VacunatorioNegocio() { // TODO Auto-generated constructor stub } public void agregarVacunatorio(DTVacunatorio dtVacunatorio) throws Exception{ if (vacunatorioLocal.existeVacunatorio(dtVacunatorio.getCodigo())) throw new Exception("\nYa existe un vacunatorio con el codigo ingresado"); else if (ubicacionLocal.obtenerUbicacionPorId(dtVacunatorio.getUbicacion().getId()).getVacunatorio() != null) { throw new Exception("\nYa existe un vacunatorio en la ubicacion seleccionada"); } else { Vacunatorio vacunatorio = new Vacunatorio(dtVacunatorio); Ubicacion ubi = this.ubicacionLocal.obtenerUbicacionPorId(dtVacunatorio.getUbicacion().getId()); vacunatorio.agregarUbicacion(ubi); this.vacunatorioLocal.agregarVacunatorio(vacunatorio); ubi.setVacunatorio(vacunatorio); this.ubicacionLocal.actualizarVacunatorio(ubi); } } public List<DTVacunatorio> listarVacunatorio(){ List <Vacunatorio> vacunatorio = (ArrayList<Vacunatorio>)(this.vacunatorioLocal.listarVacunatorio()); List <DTVacunatorio> dtVacunatorio = new ArrayList<DTVacunatorio>(); vacunatorio.forEach((v)->{DTVacunatorio dtVac = new DTVacunatorio(v); dtVac.setUbicacion(new DTUbicacion(ubicacionLocal.obtenerUbicacionVacunatorio(v.getId())));dtVacunatorio.add(dtVac);}); return dtVacunatorio; } @Override public List<String> nombresVacunatorios() { List<DTVacunatorio> vacunatorio = listarVacunatorio(); List<String> nombres = new ArrayList<String>(); vacunatorio.forEach((v)->{nombres.add(v.getNombre());}); return nombres; } @Override public DTAgenda obtenerAgendaActiva(long idVacunatorio) { Vacunatorio vacunatorio = vacunatorioLocal.obtenerVacunatorio(idVacunatorio); if(vacunatorio != null) { DTAgenda retorno = null; List<Agenda> agendas = vacunatorio.getAgendas(); LocalDate fechaActual = LocalDate.now(); for(Agenda a: agendas) { if((fechaActual.isAfter(a.getInicio()) || fechaActual.isEqual(a.getInicio())) && (fechaActual.isBefore(a.getFin()) || fechaActual.isEqual(a.getFin()))) { retorno = new DTAgenda(a); } else{ if(fechaActual.isBefore(a.getFin())) { retorno = new DTAgenda(a); } } } return retorno; } else { return null; } } @Override public DTVacunatorio obtenerVacunatorioPorCodigo(String codigo) throws Exception { if (vacunatorioLocal.existeVacunatorio(codigo)) { Vacunatorio vacunatorio = vacunatorioLocal.obtenerVacunatorioPorCodigo(codigo); DTVacunatorio dtVacunatorio = new DTVacunatorio(vacunatorio); return dtVacunatorio; } else { throw new Exception("\nNo existe un Vacunatorio con el codigo ingresado"); } } @Override public void editarVacunatorio(DTVacunatorio vacunatorioSeleccionado) throws Exception { int cantVacunadoresAsignados = vvLocal.obtenerVacunatoriosVacunadores(vacunatorioSeleccionado.getId()).size(); if (cantVacunadoresAsignados>vacunatorioSeleccionado.getCantidadPuestos()) { throw new Exception("\nLa cantidad de puestos no puede ser menor a la cantidad de vacunadores asignados actualmente: " + cantVacunadoresAsignados); }else { Vacunatorio vac = vacunatorioLocal.obtenerVacunatorio(vacunatorioSeleccionado.getId()); vac.setCantidadPuestos(vacunatorioSeleccionado.getCantidadPuestos()); vac.setCodigo(vacunatorioSeleccionado.getCodigo()); vac.setNombre(vacunatorioSeleccionado.getNombre()); vac.setDominio(vacunatorioSeleccionado.getDominio()); vacunatorioLocal.editarVacunatorio(vac); } } @Override public void eliminarVacunatorio(DTVacunatorio vacunatorio) throws Exception { Vacunatorio vac = vacunatorioLocal.obtenerVacunatorio(vacunatorio.getId()); if (vac != null) { if (vac.getAgendas().isEmpty()) { //vac.eliminarUbicacion(); //ubicacionLocal.eliminarVacunatorio(vac.getId()); // Ubicacion ubi = this.ubicacionLocal.obtenerUbicacionPorId(vacunatorio.getUbicacion().getId()); // ubi.setVacunatorio(new Vacunatorio()); // this.ubicacionLocal.actualizarVacunatorio(ubi); vacunatorioLocal.eliminarVacunatorio(vac); }else throw new Exception("\nNo se puede eliminar el vacunatorio, porque tiene agendas asociadas"); }else { throw new Exception("\nNo se encontro un vacunatorio con el id ingresado"); } } public void setTimer(long interval) { timerService.createTimer(interval, "Seteando timer"); } } <file_sep>/comp-cent-ejb/src/main/java/negocio/SocioLogisticoNegocio.java package negocio; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import datatypes.DTSocioLogistico; import datos.SocioLogisticoDatoLocal; import entidades.SocioLogistico; /** * Session Bean implementation class SocioLogisticoNegocio */ @Stateless @LocalBean public class SocioLogisticoNegocio implements SocioLogisticoNegocioLocal { @EJB SocioLogisticoDatoLocal socioDato; /** * Default constructor. */ public SocioLogisticoNegocio() { // TODO Auto-generated constructor stub } public void agregarSocioLogistico(DTSocioLogistico dtSocio) throws Exception { if (socioDato.existeSocioLogistico(dtSocio.getCodigo())) { throw new Exception("\nYa existe ese socio logistico"); } else { socioDato.agregarSocioLogistico(new SocioLogistico(dtSocio)); } } public void editarSocioLogistico(DTSocioLogistico dtSocio) throws Exception { if (socioDato.existeSocioLogistico(dtSocio.getCodigo())){ SocioLogistico socio = socioDato.obtenerSocioLogistico(dtSocio.getCodigo()); if (socio.getId() != dtSocio.getId()) { throw new Exception("\nYa existe un socio con ese codigo"); } socio.setCodigo(dtSocio.getCodigo()); socio.setNombre(dtSocio.getNombre()); socioDato.editarSocioLogistico(socio); } else { SocioLogistico socio = socioDato.obtenerSocioLogisticoPorId(dtSocio.getId()); if ( socio == null) { throw new Exception("\nNo existe el socio logistico"); } socio.setCodigo(dtSocio.getCodigo()); socio.setNombre(dtSocio.getNombre()); socioDato.editarSocioLogistico(socio); } } public void eliminarSocioLosgistico(DTSocioLogistico dtSocio) throws Exception { SocioLogistico socio = socioDato.obtenerSocioLogistico(dtSocio.getCodigo()); if (socio != null) { socioDato.eliminarSocioLosgistico(socio);; } else { throw new Exception("\nNo existe el socio logistico"); } } public Boolean existeSocioLogistico(String codigo) { return socioDato.existeSocioLogistico(codigo); } public DTSocioLogistico obtenerSocioLogistico(String codigo) throws Exception { if (socioDato.existeSocioLogistico(codigo)) { return new DTSocioLogistico(socioDato.obtenerSocioLogistico(codigo)); } else { throw new Exception("\nNo se encontro un socio logistico con el codigo ingresado"); } } public List<DTSocioLogistico> listarSocioLogistico(){ List<SocioLogistico> listaSocios = socioDato.listarSocioLogistico(); List<DTSocioLogistico> listaDtSocios = new ArrayList<DTSocioLogistico>(); for (SocioLogistico socio : listaSocios) { listaDtSocios.add(new DTSocioLogistico(socio)); } return listaDtSocios; } } <file_sep>/comp-cent-web/src/main/java/beans/PlanVacunacionBean.java package beans; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.view.ViewScoped; import javax.inject.Named; import org.primefaces.PrimeFaces; import datatypes.DTEnfermedad; import datatypes.DTPlanVacunacion; import datatypes.DTVacuna; import negocio.EnfermedadNegocioLocal; import negocio.PlanVacunacionNegocioLocal; import negocio.VacunaNegocioLocal; @Named("planVacunacionBean") @ViewScoped public class PlanVacunacionBean implements Serializable { private static final long serialVersionUID = 1L; @EJB private EnfermedadNegocioLocal enfermedadLocal; @EJB private VacunaNegocioLocal vacunaLocal; @EJB private PlanVacunacionNegocioLocal planLocal; private DTEnfermedad enfermedad; private List<DTEnfermedad> enfermedades; private List<DTPlanVacunacion> planesVacunaciones; private DTVacuna vacuna; private DTPlanVacunacion planVacunacion; private List<DTVacuna> vacunas; private List<DTVacuna> vacunasEnPlan; private String nombreEnfermedad; private String nombrePlan; private String[] nombreVacuna; private String poblacion; private List<String> poblaciones; private String nombreBoton; private String estiloBoton; private Boolean editar; @PostConstruct public void init() { enfermedades = enfermedadLocal.listarEnfermedades(); planesVacunaciones = planLocal.listarPlanesDeVacunacion(); enfermedad = new DTEnfermedad(); vacuna = new DTVacuna(); planVacunacion = new DTPlanVacunacion(); poblaciones = enfermedadLocal.listarPoblacionObjetivo(); } public String getNombreEnfermedad() { return nombreEnfermedad; } public void setNombreEnfermedad(String nombreEnfermedad) { this.nombreEnfermedad = nombreEnfermedad; } public String[] getNombreVacuna() { return nombreVacuna; } public void setNombreVacuna(String[] nombreVacuna) { this.nombreVacuna = nombreVacuna; } public List<DTEnfermedad> getEnfermedades(){ return enfermedades; } public List<DTVacuna> getVacunas() { return vacunas; } public DTEnfermedad getEnfermedad() { return this.enfermedad; } public DTVacuna getVacuna() { return vacuna; } public String getPoblacion() { return poblacion; } public void setPoblacion(String poblacion) { this.poblacion = poblacion; } public List<String> getPoblaciones() { return poblaciones; } public void setPoblaciones(List<String> poblaciones) { this.poblaciones = poblaciones; } public DTPlanVacunacion getPlanVacunacion() { return planVacunacion; } public void setPlanVacunacion(DTPlanVacunacion planVacunacion) { this.planVacunacion = planVacunacion; } public List<DTPlanVacunacion> getPlanesVacunaciones() { return planesVacunaciones; } public void setPlanesVacunaciones(List<DTPlanVacunacion> planesVacunaciones) { this.planesVacunaciones = planesVacunaciones; } public List<DTVacuna> getVacunasEnPlan() { return vacunasEnPlan; } public void setVacunasEnPlan(List<DTVacuna> vacunasEnPlan) { this.vacunasEnPlan = vacunasEnPlan; } public String getNombrePlan() { return nombrePlan; } public void setNombrePlan(String nombrePlan) { this.nombrePlan = nombrePlan; } public String getnombreBoton() { return nombreBoton; } public void setnombreBoton(String nombreBoton) { this.nombreBoton = nombreBoton; } public String getEstiloBoton() { return estiloBoton; } public void setEstiloBoton(String estiloBoton) { this.estiloBoton = estiloBoton; } public void cargarVacunasPlan(DTPlanVacunacion planVac) { vacunasEnPlan = planVac.getVacunas(); } public void editarPlan(DTPlanVacunacion planVac) throws Exception { this.editar = true; this.nombreBoton="Editar Plan"; this.estiloBoton="pi pi-pencil"; setPlanVacunacion(planVac); //nombreVacuna = null; nombreEnfermedad = planVac.getEnfermedad().getNombre(); cargarVacunas(); vacunasEnPlan = planVac.getVacunas(); String[] arr = new String[vacunasEnPlan.size()]; int i = 0; for (DTVacuna vacuna : vacunasEnPlan) { arr[i] = vacuna.getNombre(); i++; } nombreVacuna = arr; } public void eliminarPlanSeleccionado(DTPlanVacunacion planVacunacion) throws Exception { try { planLocal.eliminarPlanVacunacion(planVacunacion); this.planesVacunaciones.remove(planVacunacion); planVacunacion = null; FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Confirmado", "Plan eliminado Correctamente"); FacesContext.getCurrentInstance().addMessage(null, message); } catch (Exception e) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, message); } } public void cargarVacunas() throws Exception { if (nombreEnfermedad != null && !nombreEnfermedad.equals("")) { vacunas = enfermedadLocal.listarVacunasPorEnfermedad(nombreEnfermedad); }else { vacunas = new ArrayList<DTVacuna>(); } } public void addMessage(FacesMessage.Severity severity, String summary, String detail) { FacesContext.getCurrentInstance(). addMessage(null, new FacesMessage(severity, summary, detail)); } public void buscarPlan () { try { planVacunacion = planLocal.obtenerPlanVacunacion(nombrePlan); } catch (Exception e) { this.planVacunacion = null; } } public void agregarEditarPlanVacunacion () throws Exception { DTEnfermedad enfAux = new DTEnfermedad(); List<DTVacuna> vacAux = new ArrayList<DTVacuna>(); if (planVacunacion.getEdadMinima() > planVacunacion.getEdadMaxima()) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Edad Minima no puede ser mayor a Edad Maxima", "")); } else { for (DTEnfermedad enf: enfermedades) { if (enf.getNombre().equals(nombreEnfermedad)) enfAux = enf; } planVacunacion.setEnfermedad(enfAux); for (DTVacuna vac: vacunas) { for (String nombreV: nombreVacuna) { if (vac.getNombre().equals(nombreV)) { vacAux.add(vac); } } } planVacunacion.setVacunas(vacAux); try { if (editar) { planLocal.editarPlanVacunacion(planVacunacion); this.planVacunacion = null; PrimeFaces.current().executeScript("PF('planDialog').hide()"); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Plan editado correctamente","" )); } else { planLocal.agregarPlanVacunacion(planVacunacion); planVacunacion.setId(planLocal.obtenerPlanVacunacion(planVacunacion.getNombre()).getId()); planesVacunaciones.add(planVacunacion); this.planVacunacion = null; PrimeFaces.current().executeScript("PF('planDialog').hide()"); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Plan agregado correctamente","" )); } } catch (Exception e){ FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(),"" )); } } } public void reiniciarPlan(){ this.planVacunacion = new DTPlanVacunacion(); this.nombrePlan = null; this.nombreEnfermedad = null; this.nombreVacuna = null; this.vacunas = new ArrayList<DTVacuna>(); this.nombreBoton="Agregar Plan"; this.estiloBoton="pi pi-check"; this.editar= false; } } <file_sep>/comp-cent-web/src/main/java/beans/VacunaBean.java package beans; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import org.primefaces.PrimeFaces; import datatypes.DTEnfermedad; import datatypes.DTPlanVacunacion; import datatypes.DTProveedor; import datatypes.DTVacuna; import negocio.EnfermedadNegocioLocal; import negocio.ProveedorNegocioLocal; import negocio.VacunaNegocioLocal; @Named("vacunaBean") @ViewScoped public class VacunaBean implements Serializable{ private static final long serialVersionUID = 1L; @Inject private VacunaNegocioLocal vacunaLocal; @Inject private EnfermedadNegocioLocal enfermedadLocal; @Inject private ProveedorNegocioLocal proveedorLocal; private DTVacuna vacuna; private List<DTVacuna> vacunas; private DTProveedor proveedor; private List<DTProveedor> proveedores; private DTEnfermedad enfermedad; private List<DTEnfermedad> enfermedades; private String nombreEnfermedad; private String nombreProveedor; //Agrego String para saber el estado del botón private String nombreBoton; private String estiloBoton; private Boolean editar; @PostConstruct public void init() { this.setEnfermedades(enfermedadLocal.listarEnfermedades()); this.setVacunas(vacunaLocal.obtenerVacunas()); this.vacunas = vacunaLocal.obtenerVacunas(); this.proveedores = proveedorLocal.obtenerProveedores(); proveedor = new DTProveedor(); setEnfermedad(new DTEnfermedad()); vacuna = new DTVacuna(); } public DTVacuna getVacuna() { return vacuna; } public void setVacuna(DTVacuna vacuna) { this.vacuna = vacuna; } public List<DTVacuna> getVacunas() { return vacunas; } public void setVacunas(List<DTVacuna> vacunas) { this.vacunas = vacunas; } public DTProveedor getProveedor() { return proveedor; } public void setProveedor(DTProveedor proveedor) { this.proveedor = proveedor; } public List<DTProveedor> getProveedores() { return proveedores; } public void setProveedores(List<DTProveedor> proveedores) { this.proveedores = proveedores; } public DTEnfermedad getEnfermedad() { return enfermedad; } public void setEnfermedad(DTEnfermedad enfermedad) { this.enfermedad = enfermedad; } public List<DTEnfermedad> getEnfermedades() { return enfermedades; } public void setEnfermedades(List<DTEnfermedad> enfermedades) { this.enfermedades = enfermedades; } public String getNombreEnfermedad() { return nombreEnfermedad; } public void setNombreEnfermedad(String nombreEnfermedad) { this.nombreEnfermedad = nombreEnfermedad; } public String getNombreProveedor() { return nombreProveedor; } public void setNombreProveedor(String nombreProveedor) { this.nombreProveedor = nombreProveedor; } //Me cargo la vacuna seleccionada para modificarla public void editarVacunaBean(DTVacuna dtVacuna) { this.editar = true; this.nombreBoton = "Editar Vacuna"; this.estiloBoton = "pi pi-pencil"; setVacuna(dtVacuna); //nombreEnfermedad = dtVacuna.getEnfermedad().getNombre(); DTProveedor dtpro = vacunaLocal.obtenerProveedorDeVacuna(dtVacuna.getNombre()); nombreProveedor = dtpro.getNombre(); DTEnfermedad dtenf = vacunaLocal.obtenerEnfermedadDeVacuna(dtVacuna.getNombre()); nombreEnfermedad = dtenf.getNombre(); } public void eliminarVacuna(DTVacuna vacuna) throws Exception { System.out.println("Entre en el eliminarVacuna"); try { vacunaLocal.eliminarVacuna(vacuna.getNombre()); this.vacunas.remove(vacuna); vacuna = null; }catch (Exception e){ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, message); } } public void agregarVacuna() throws Exception { DTProveedor proAux = new DTProveedor(); DTEnfermedad enfAux = new DTEnfermedad(); for (DTEnfermedad enf: enfermedades) { if (enf.getNombre().equals(nombreEnfermedad)) { enfAux = enf; } } vacuna.setEnfermedad(enfAux); for (DTProveedor pro: proveedores) { if (pro.getNombre().equals(nombreProveedor)) { proAux = pro; } } vacuna.setProveedor(proAux); try { if(editar) { System.out.println("Estoy en el if del editar"); vacunaLocal.editarVacuna(vacuna); // this.vacuna=null; this.init(); PrimeFaces.current().executeScript("PF('VacunaDialog').hide()"); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Vacuna editado correctamente","" )); }else { System.out.println("Estoy en el else agregando vacuna"); vacunaLocal.agregarVacuna(vacuna); // vacunas.add(vacuna); // this.vacuna=null; this.init(); } } catch (Exception e){ FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(),"" )); } } public String getNombreBoton() { return nombreBoton; } public void setNombreBoton(String nombreBoton) { this.nombreBoton = nombreBoton; } public String getEstiloBoton() { return estiloBoton; } public void setEstiloBoton(String estiloBoton) { this.estiloBoton = estiloBoton; } public void reiniciarVacuna(){ this.vacuna = new DTVacuna(); this.nombreEnfermedad = null; this.nombreProveedor = null; this.nombreBoton="Agregar Vacuna"; this.estiloBoton="pi pi-check"; this.editar= false; } } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTAsignarVacunadores.java package datatypes; import java.util.List; public class DTAsignarVacunadores { private String fecha; private List<Integer> cedulas; public DTAsignarVacunadores() { } public DTAsignarVacunadores(String fecha, List<Integer> cedulas) { super(); this.fecha = fecha; this.cedulas = cedulas; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public List<Integer> getCedulas() { return cedulas; } public void setCedulas(List<Integer> cedulas) { this.cedulas = cedulas; } } <file_sep>/comp-cent-ejb/src/test/java/negocio/EnfermedadNegocioTest.java package negocio; import static org.junit.Assert.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import datatypes.DTAgenda; import datatypes.DTEnfermedad; import datatypes.DTVacuna; import datos.EnfermedadDatoLocal; import entidades.Enfermedad; import entidades.Vacuna; import entidades.Vacunatorio; import enumeradores.PoblacionObjetivo; import static org.mockito.ArgumentMatchers.any; public class EnfermedadNegocioTest { @Mock private EnfermedadDatoLocal datoLocal; @Mock private EnfermedadNegocioLocal nLocal; @InjectMocks private EnfermedadNegocio en; private static List<Enfermedad> enfermedades; private static List<Vacuna> vacunas; private static Enfermedad enfermedad; private static List<String> enumeradores; private static DTEnfermedad dtEnfermedad; private static Vacuna vacuna; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); enfermedad = new Enfermedad(); enfermedad.setFechaCreacion(LocalDate.now()); vacuna = Mockito.mock(Vacuna.class); vacunas = new ArrayList<Vacuna>(); vacunas.add(vacuna); enfermedad.setVacunas(vacunas); enfermedades = new ArrayList<Enfermedad>(); enfermedades.add(enfermedad); enumeradores = Stream.of(PoblacionObjetivo.values()) .map(Enum::name) .collect(Collectors.toList()); } @Test public void testListarEnfermedades() { Mockito.when(datoLocal.listarEnfermedades()).thenReturn(enfermedades); List<DTEnfermedad> dtEnfermedades = en.listarEnfermedades(); assertEquals(enfermedades.size(), dtEnfermedades.size()); } @Test public void testAgregarEnfermedad() throws Exception { Mockito.doNothing().when(datoLocal).agregarEnfermedad(Mockito.isA(Enfermedad.class)); datoLocal.agregarEnfermedad(Mockito.isA(Enfermedad.class)); en.agregarEnfermedad("prueba"); Mockito.verify(datoLocal ,Mockito.times(1)).agregarEnfermedad(Mockito.isA(Enfermedad.class)); } @Test(expected = Exception.class) public void testAgregarEnfermedadException() throws Exception { Mockito.when(datoLocal.existeEnfermedad("prueba")).thenReturn(true); en.agregarEnfermedad("prueba"); } @Test public void testBuscarEnfermedad() throws Exception { Mockito.when(datoLocal.existeEnfermedad("prueba")).thenReturn(true); Mockito.when(datoLocal.buscarEnfermedad("prueba")).thenReturn(enfermedad); DTEnfermedad dtEnf = en.buscarEnfermedad("prueba"); assertTrue(dtEnf!=null); } @Test(expected = Exception.class) public void testBuscarEnfermedadTrowException() throws Exception { Mockito.when(datoLocal.existeEnfermedad("prueba")).thenReturn(false); DTEnfermedad enf = en.buscarEnfermedad("prueba"); //assertTrue(dtEnf==null); } @Test public void testListarVacunasPorEnfermedad() throws Exception { Mockito.when(datoLocal.existeEnfermedad("prueba")).thenReturn(true); Mockito.when(datoLocal.buscarEnfermedad("prueba")).thenReturn(enfermedad); List<DTVacuna> vac = en.listarVacunasPorEnfermedad("prueba"); assertTrue(vac!=null); } @Test(expected = Exception.class) public void testListarVacunasPorEnfermedadException() throws Exception { Mockito.when(datoLocal.existeEnfermedad("prueba")).thenReturn(false); List<DTVacuna> vac = en.listarVacunasPorEnfermedad("prueba"); //assertTrue(vac!=null); } @Test public void testListarPoblacionObjetivo() { Mockito.when(nLocal.listarPoblacionObjetivo()).thenReturn(enumeradores); List<String> result = en.listarPoblacionObjetivo(); assertEquals(enumeradores,result); } @Test public void testEliminarEnfermedad() throws Exception { Mockito.when(datoLocal.buscarEnfermedad("prueba")).thenReturn(enfermedad); Mockito.doNothing().when(datoLocal).eliminarEnfermedad(enfermedad); en.eliminarEnfermedad("prueba"); Mockito.verify(datoLocal ,Mockito.times(1)).eliminarEnfermedad(enfermedad); } @Test(expected = Exception.class) public void testEliminarEnfermedadException() throws Exception { Mockito.when(datoLocal.buscarEnfermedad("prueba")).thenReturn(null); en.eliminarEnfermedad("prueba"); } @Test public void testObtenerEnfermedadPorId() { Mockito.when(datoLocal.obtenerEnfermedadPorId(any(Long.class))).thenReturn(enfermedad); DTEnfermedad enf = en.obtenerEnfermedadPorId(any(Long.class)); assertEquals(enfermedad.getFechaCreacion().toString(), enf.getFechaCreacion()); } @Test public void testEditarEnfermedad() throws Exception { Mockito.when(datoLocal.obtenerEnfermedadPorId(any(Long.class))).thenReturn(enfermedad); Mockito.doNothing().when(datoLocal).editarEnfermedad(enfermedad); dtEnfermedad = new DTEnfermedad(enfermedad); en.editarEnfermedad(dtEnfermedad); Mockito.verify(datoLocal ,Mockito.times(1)).editarEnfermedad(enfermedad); } @Test(expected = Exception.class) public void testEditarEnfermedadException() throws Exception { Mockito.when(datoLocal.obtenerEnfermedadPorId(any(Long.class))).thenReturn(null); dtEnfermedad = new DTEnfermedad(enfermedad); en.editarEnfermedad(dtEnfermedad); } } <file_sep>/comp-cent-ejb/src/main/java/datos/PlanVacunacionDato.java package datos; import java.time.LocalDate; import java.time.Period; import java.util.ArrayList; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import entidades.PlanVacunacion; /** * Session Bean implementation class PlanVacunacionDato */ @Stateless @LocalBean public class PlanVacunacionDato implements PlanVacunacionDatoLocal { @PersistenceContext(name = "comp-centPersistenceUnit") private EntityManager em; public PlanVacunacionDato() { // TODO Auto-generated constructor stub } @Override public void agregarPlanVacunacion(PlanVacunacion plan) { em.persist(plan); } @Override public void editarPlanVacunacion(PlanVacunacion plan) { em.merge(plan); } @Override public void eliminarPlanVacunacion(PlanVacunacion plan) { em.remove(plan); } @Override public List<PlanVacunacion> listarPlanesDeVacunacion (){ ArrayList<PlanVacunacion> lista = new ArrayList<PlanVacunacion>(); for (Object obj : em.createQuery("Select p from PlanVacunacion p").getResultList()) { PlanVacunacion p = (PlanVacunacion) obj; lista.add(p); } return lista; } @Override public Boolean existePlanVacunacion(String nombre) { Boolean existe = (em.createQuery("Select p from PlanVacunacion p where p.nombre = :nombre").setParameter("nombre", nombre).getResultList().size() > 0); return existe; } @Override public PlanVacunacion obtenerPlanVacunacionPorId(long id) { PlanVacunacion planVacunacion = em.find(PlanVacunacion.class, id); return planVacunacion; } @Override public PlanVacunacion obtenerPlanVacunacion(String nombre) { PlanVacunacion planVacunacion = (em.createQuery("Select p from PlanVacunacion p where p.nombre = :nombre", PlanVacunacion.class).setParameter("nombre", nombre).getSingleResult()); return planVacunacion; } @Override public List<PlanVacunacion> obtenerPlanesVacunacionObjetivoEdad(String poblacionObjetivo, String fnac){ List<PlanVacunacion> planesVacunacion = this.listarPlanesDeVacunacion(); List<PlanVacunacion> retorno = new ArrayList<>(); int edad = Period.between(LocalDate.parse(fnac), LocalDate.now()).getYears(); for(PlanVacunacion p: planesVacunacion) { if( p.getPoblacionObjetivo().toString().equals(poblacionObjetivo) && (p.getEdadMinima() < edad && edad < p.getEdadMaxima()) ){ retorno.add(p); } } return retorno; } } <file_sep>/comp-cent-ejb/src/main/java/negocio/EnvioNegocioLocal.java package negocio; import java.time.LocalDate; import java.util.List; import javax.ejb.Local; import datatypes.DTEnvio; import datatypes.DTLote; import datatypes.DTSocioLogistico; import datatypes.DTStockVacuna; import datatypes.DTVacunatorio; import enumeradores.EstadoEnvio; @Local public interface EnvioNegocioLocal { public List<DTEnvio> listarEnvios(); public List<DTEnvio> listarEnviosPorSocioLogistico(String cod); public void cambiarEstadoEnvio(EstadoEnvio estado, long idEnvio); public void AgregarEnvio(DTEnvio envio, DTLote lote, DTVacunatorio vacunatorio, DTSocioLogistico dtSocio ) throws Exception; public List<String> listarEstado (); public List<DTLote> listarLotePendientesDeEnviar (); public List<DTStockVacuna> stockEnviado(long idVacunatorio, LocalDate fecha); } <file_sep>/comp-cent-web/src/main/java/rest/VacunatorioREST.java package rest; import java.time.LocalDate; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.naming.NamingException; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import datatypes.DTRegistroVacuna; import datatypes.DTReservaVacunatorio; import negocio.RegistroVacunaNegocioLocal; import negocio.ReservaNegocioLocal; import negocio.VacunatorioGeomNegocioLocal; @RequestScoped @Path("/vacunatorio") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class VacunatorioREST { @EJB private ReservaNegocioLocal reservaNegocio; @EJB private RegistroVacunaNegocioLocal registroNegocio; @EJB private VacunatorioGeomNegocioLocal vgnl; public VacunatorioREST() throws NamingException { } @POST @Path("/obtenerRegistroVacuna") public void altaRegistroVacuna(List<DTRegistroVacuna> regVacuna) { registroNegocio.altaRegistroVacuna(regVacuna); } @GET @Path("/obtenerAgenda") public List<DTReservaVacunatorio> obtenerReservasVacunatorio (@QueryParam("id") long id, @QueryParam("fecha") String fecha){ return reservaNegocio.obtenerReservasVacunatorio(LocalDate.parse(fecha), id); } @GET @Path("/cercanos/{lat}/{lon}") public Response vacunatoriosCercanos(@PathParam("lat") String lat, @PathParam("lon") String lon){ try { return Response.status(Status.OK).entity(vgnl.vacunatoriosCercanos(lat, lon)).build(); } catch(Exception e) { return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } }<file_sep>/comp-cent-ejb/src/main/java/datos/EnvioDatoLocal.java package datos; import java.time.LocalDate; import java.util.List; import javax.ejb.Local; import datatypes.DTVistaEnvio; import entidades.Envio; import entidades.Lote; @Local public interface EnvioDatoLocal { public void guardarEnvio(Envio envio); public void editarEnvio(Envio envio); public Envio obtenerEnvio(long id); public List<Envio> listarEnvios(); public List<Envio> listarEnviosPorSocioLogistico(String cod); public List<Lote> listarLotesPendientesDeEnviar(); public List<DTVistaEnvio> ListarEnviosVista(); public boolean ExisteLote(Lote lote); public List<Envio> cantVacEnviado(long idVacunatorio, LocalDate fecha); } <file_sep>/comp-cent-ejb/src/main/java/datos/EnfermedadDato.java package datos; import java.util.ArrayList; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import entidades.Enfermedad; /** * Session Bean implementation class EnfermedadDato */ @Stateless @LocalBean public class EnfermedadDato implements EnfermedadDatoLocal { @PersistenceContext(name = "comp-centPersistenceUnit") private EntityManager em; public EnfermedadDato() { } @Override public void agregarEnfermedad(Enfermedad enfermedad) { em.persist(enfermedad); } @Override public List<Enfermedad> listarEnfermedades (){ ArrayList<Enfermedad> lista = new ArrayList<Enfermedad>(); for (Object obj : em.createQuery("Select e from Enfermedad e").getResultList()) { Enfermedad e = (Enfermedad) obj; lista.add(e); } return lista; } @Override public Enfermedad buscarEnfermedad (String nombre) { Enfermedad enfermedad =(Enfermedad) em.createQuery("Select e from Enfermedad e where e.nombre = :nombre").setParameter("nombre", nombre).getSingleResult(); return enfermedad; } @Override public Boolean existeEnfermedad(String nombre) { Boolean existe = (em.createQuery("Select e from Enfermedad e where e.nombre = :nombre").setParameter("nombre", nombre).getResultList().size() > 0); return existe; } @Override public void eliminarEnfermedad(Enfermedad enfermedad) { em.remove(enfermedad); } @Override public Enfermedad obtenerEnfermedadPorId(long id) { Enfermedad enf = em.find(Enfermedad.class, id); return enf; } @Override public void editarEnfermedad(Enfermedad enf) { em.merge(enf); } } <file_sep>/comp-cent-web/src/main/java/beans/LoteBean.java package beans; import java.io.Serializable; import java.time.LocalDate; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.view.ViewScoped; import javax.inject.Named; import org.primefaces.PrimeFaces; import datatypes.DTLote; import datatypes.DTVacuna; import negocio.LoteNegocioLocal; import negocio.VacunaNegocioLocal; @Named("loteBean") @ViewScoped public class LoteBean implements Serializable { private static final long serialVersionUID = 1L; @EJB private VacunaNegocioLocal vacunaLocal; @EJB private LoteNegocioLocal loteLocal; private DTVacuna vacuna; private List<DTLote> lotes; private DTLote lote; private List<DTVacuna> vacunas; private String nombreLote; private int cantVacunas; private String nombreVacuna; private String nombreBoton; private String estiloBoton; private Boolean editar; @PostConstruct public void init() { lotes = loteLocal.listarLotes(); vacunas = vacunaLocal.obtenerVacunas(); lote = new DTLote(); vacuna = new DTVacuna(); } public DTVacuna getVacuna() { return vacuna; } public void setVacuna(DTVacuna vacuna) { this.vacuna = vacuna; } public List<DTLote> getLotes() { return lotes; } public void setLotes(List<DTLote> lotes) { this.lotes = lotes; } public DTLote getLote() { return lote; } public void setLote(DTLote lote) { this.lote = lote; } public List<DTVacuna> getVacunas() { return vacunas; } public void setVacunas(List<DTVacuna> vacunas) { this.vacunas = vacunas; } public String getNombreLote() { return nombreLote; } public void setNombreLote(String nombreLote) { this.nombreLote = nombreLote; } public int getCantVacunas() { return cantVacunas; } public void setCantVacunas(int cantVacunas) { this.cantVacunas = cantVacunas; } public String getNombreVacuna() { return nombreVacuna; } public void setNombreVacuna(String nombreVacuna) { this.nombreVacuna = nombreVacuna; } public String getnombreBoton() { return nombreBoton; } public void setnombreBoton(String nombreBoton) { this.nombreBoton = nombreBoton; } public String getEstiloBoton() { return estiloBoton; } public void setEstiloBoton(String estiloBoton) { this.estiloBoton = estiloBoton; } public void editarLote(DTLote lote) throws Exception { this.editar = true; this.nombreBoton="Editar Lote"; this.estiloBoton="pi pi-pencil"; setLote(lote); nombreVacuna = lote.getVacuna().getNombre(); } public void eliminarLoteSeleccionado(DTLote dtLote) throws Exception { try { loteLocal.eliminarLote(dtLote); this.lotes.remove(dtLote); lote = null; FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Confirmado", "Lote eliminado Correctamente"); FacesContext.getCurrentInstance().addMessage(null, message); } catch (Exception e) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, message); } } public void buscarLote () { try { lote = loteLocal.obtenerLote(nombreLote); } catch (Exception e) { this.lote = null; } } public void agregarEditarLote () throws Exception { DTVacuna vacAux = new DTVacuna(); if (lote.getCantVacunas()<=0) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Cantidad de vacunas debe ser mayor a 0", "")); } else { for (DTVacuna vac: vacunas) { if (vac.getNombre().equals(nombreVacuna)) vacAux = vac; } lote.setVacuna(vacAux); lote.setFechaCreado(LocalDate.now()); try { if (editar) { loteLocal.editarLote(lote); this.lote = null; PrimeFaces.current().executeScript("PF('loteDialog').hide()"); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Lote editado correctamente","" )); } else { loteLocal.agregarLote(lote); lote.setId(loteLocal.obtenerLote(lote.getNombre()).getId()); lotes.add(lote); this.lote = null; PrimeFaces.current().executeScript("PF('loteDialog').hide()"); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Lote agregado correctamente","" )); } } catch (Exception e){ FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(),"" )); } } } public void reiniciarLote(){ this.lote = new DTLote(); this.nombreVacuna = null; this.nombreLote = null; this.nombreBoton="Agregar Lote"; this.estiloBoton="pi pi-check"; this.editar= false; } } <file_sep>/comp-cent-web/src/main/java/rest/VacunadorREST.java package rest; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import datatypes.DTVacunatorio; import negocio.VacunadorNegocioLocal; import negocio.VacunatorioNegocioLocal; import negocio.VacunatorioVacunadorNegocioLocal; @RequestScoped @Path("/vacunador") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class VacunadorREST { @EJB VacunadorNegocioLocal vnl; @EJB VacunatorioNegocioLocal vacnl; @EJB VacunatorioVacunadorNegocioLocal vvnl; @GET @Path("/es-vacunador/{ci}") public Response existeCiudadano(@PathParam("ci") String ci) { try { int numeroCi = Integer.parseInt(ci); return Response .status(Response.Status.OK) .entity(vnl.esVacunador(numeroCi)) .build(); } catch(NumberFormatException ex){ return Response .status(Response.Status.BAD_REQUEST) .entity("Ha ocurrido un error procesando la cedula") .build(); } } @GET @Path("/puesto-vacunador/{ciVacunador}/{codigoVacunatorio}") public Response puestoVacunador(@PathParam("ciVacunador") String ciVacunador, @PathParam("codigoVacunatorio") String codigoVacunatorio) { try { DTVacunatorio dtVacunatorio = vacnl.obtenerVacunatorioPorCodigo(codigoVacunatorio); int numeroCi = Integer.parseInt(ciVacunador); return Response .status(Response.Status.OK) .entity(vvnl.obtenerPuestoVacunador(numeroCi, dtVacunatorio)) .build(); } catch(Exception e) { return Response .status(Response.Status.INTERNAL_SERVER_ERROR) .build(); } } } <file_sep>/comp-cent-ejb/src/main/java/negocio/RegistroVacunaNegocio.java package negocio; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import datatypes.DTCertificado; import datatypes.DTRegistroVacuna; import datos.CiudadanoDatoLocal; import datatypes.DTVacuna; import datos.RegistroVacunaDatoLocal; import datos.ReservaDatoLocal; import datos.VacunaDatoLocal; import datos.VacunatorioDatoLocal; import entidades.Ciudadano; import entidades.RegistroVacuna; import entidades.Reserva; import entidades.Vacuna; import enumeradores.EstadoReserva; import enumeradores.Sexo; import entidades.Vacunatorio; /** * Session Bean implementation class RegistroVacunaNegocio */ @Stateless @LocalBean public class RegistroVacunaNegocio implements RegistroVacunaNegocioLocal { @EJB private RegistroVacunaDatoLocal registroVacunaDatoLocal; @EJB private VacunaDatoLocal vacunaDatoLocal; @EJB private VacunatorioDatoLocal vacunatorioDatoLocal; @EJB private CiudadanoDatoLocal ciudadanoDatoLocal; @EJB private ReservaDatoLocal reservaDatoLocal; /** * Default constructor. */ public RegistroVacunaNegocio() { // TODO Auto-generated constructor stub } public List<DTCertificado> obtenerCertificados(String ci){ List<RegistroVacuna> listRegVac = registroVacunaDatoLocal.obtenerRegistroPorCi(Integer.valueOf(ci)); List<DTCertificado> listCert = new ArrayList<DTCertificado>(); if (listRegVac != null) { for (RegistroVacuna regVac: listRegVac) { Vacuna vac = regVac.getVacuna(); DTCertificado dtCert = new DTCertificado(); dtCert.setFechaVacuna(regVac.getFecha().toString()); dtCert.setIdVacuna(String.valueOf(vac.getId())); dtCert.setNombreVacuna(vac.getNombre()); dtCert.setLaboratorioVacuna(vac.getLaboratorio()); dtCert.setCodigoVacuna(vac.getCodigo()); dtCert.setCantDosis(String.valueOf(vac.getDosis())); dtCert.setPeriodoInmunidad(String.valueOf(vac.getPeriodoInmune())); dtCert.setIdEnfermedad(String.valueOf(vac.getEnfermedad().getId())); dtCert.setNombreEnfermedad(vac.getEnfermedad().getNombre()); dtCert.setIdReserva(String.valueOf(regVac.getReserva().getId())); listCert.add(dtCert); } } return listCert; } public List<RegistroVacuna> listarRegistros(){ List<RegistroVacuna> registros = registroVacunaDatoLocal.obtenerRegistro(); return registros; } public void altaRegistroVacuna (List<DTRegistroVacuna> regVacunas) { for(DTRegistroVacuna regVacuna : regVacunas ) { Ciudadano usuario = ciudadanoDatoLocal.obtenerCiudadano(regVacuna.getCedula()); Vacunatorio vacunatorio = vacunatorioDatoLocal.obtenerVacunatorio(regVacuna.getIdVacunatorio()); Vacuna vacuna = vacunaDatoLocal.obtenerVacunaPorId(regVacuna.getIdVacuna()); Reserva reserva = reservaDatoLocal.obtenerReserva(regVacuna.getIdReserva()); //reserva.setDosisSuministradas(reserva.getDosisSuministradas()+1); if (reserva.getDosisSuministradas() < vacuna.getDosis()) { Reserva reservaNueva = new Reserva(); reservaNueva.setCiudadano(usuario); reservaNueva.setPlanVacunacion(reserva.getPlanVacunacion()); reservaNueva.setEstado(EstadoReserva.Pendiente); reservaNueva.setDepartamento(reserva.getDepartamento()); reservaNueva.setUbicacion(reserva.getUbicacion()); reservaNueva.setVacuna(vacuna); reservaNueva.setDosisSuministradas(reserva.getDosisSuministradas()+1); reservaDatoLocal.crearReserva(reservaNueva); } RegistroVacuna registroVac = new RegistroVacuna(vacuna, usuario,vacunatorio, reserva, LocalDate.parse(regVacuna.getFecha())); registroVacunaDatoLocal.agregarRegistroVacuna(registroVac); } } public List<Integer> obtenerCantVac(DTVacuna vacuna, int anio) { Vacuna vac = vacunaDatoLocal.obtenerVacunaPorId(vacuna.getId()); List<Integer> listaCantidadXMes = new ArrayList<Integer>(); for (int i=1; i<=12; i++){ listaCantidadXMes.add(registroVacunaDatoLocal.cantRegistroPorMes(vac, i, anio)); } ; return listaCantidadXMes; } public List<Integer> cantRegistroPorSexo(DTVacuna vacuna, int anio) { Vacuna vac = vacunaDatoLocal.obtenerVacunaPorId(vacuna.getId()); List<Integer> listaCantidadXSexo = new ArrayList<Integer>(); listaCantidadXSexo.add(registroVacunaDatoLocal.cantRegistroPorSexo(vac, Sexo.Mujer, anio)); listaCantidadXSexo.add(registroVacunaDatoLocal.cantRegistroPorSexo(vac, Sexo.Hombre, anio)); return listaCantidadXSexo; } public List<Integer> cantRegistroPorEdad(DTVacuna vacuna, int anio){ Vacuna vac = vacunaDatoLocal.obtenerVacunaPorId(vacuna.getId()); List<Integer> listaCantidadXEdad = new ArrayList<Integer>(); listaCantidadXEdad.add(registroVacunaDatoLocal.cantRegistroPorEdad(vac, 0, 11, anio)); listaCantidadXEdad.add(registroVacunaDatoLocal.cantRegistroPorEdad(vac, 12, 18, anio)); listaCantidadXEdad.add(registroVacunaDatoLocal.cantRegistroPorEdad(vac, 19, 25, anio)); listaCantidadXEdad.add(registroVacunaDatoLocal.cantRegistroPorEdad(vac, 26, 40, anio)); listaCantidadXEdad.add(registroVacunaDatoLocal.cantRegistroPorEdad(vac, 41, 60, anio)); listaCantidadXEdad.add(registroVacunaDatoLocal.cantRegistroPorEdad(vac, 61, 75, anio)); listaCantidadXEdad.add(registroVacunaDatoLocal.cantRegistroPorEdad(vac, 75, 150, anio)); return listaCantidadXEdad; } @Override public int countVacunadosHoy(long vacunaId) { int retorno = 0; List<RegistroVacuna> registros = registroVacunaDatoLocal.obtenerRegistro(); for(RegistroVacuna r: registros) { if( r.getFecha().equals(LocalDate.now()) && r.getVacuna().getId() == vacunaId ) { retorno++; } } return retorno; } @Override public int[] countVacunadosPorMes(long vacunaId, int ano){ List<RegistroVacuna> registros = registroVacunaDatoLocal.obtenerRegistro(); int[] countVacunadosPorMes = new int[12]; LocalDate fechaIni = LocalDate.of(ano, 1, 1); LocalDate fechaFin = LocalDate.of(ano, 12, 31); for(RegistroVacuna rv: registros) { if( rv.getFecha().isAfter(fechaIni) && rv.getFecha().isBefore(fechaFin) && rv.getVacuna().getId() == vacunaId ){ countVacunadosPorMes[rv.getFecha().getMonthValue() - 1] = countVacunadosPorMes[rv.getFecha().getMonthValue() - 1] + 1; } } return countVacunadosPorMes; } public int[] countVacunadosPorDepartamento(long vacunaId, int ano){ List<RegistroVacuna> registros = registroVacunaDatoLocal.obtenerRegistro(); int[] countVacunadosPorDepartamento = new int[19]; LocalDate fechaIni = LocalDate.of(ano, 1, 1); LocalDate fechaFin = LocalDate.of(ano, 12, 31); for(RegistroVacuna rv: registros) { if( rv.getFecha().isAfter(fechaIni) && rv.getFecha().isBefore(fechaFin) && rv.getVacuna().getId() == vacunaId ){ switch(rv.getReserva().getDepartamento().getDescripcion().toUpperCase()) { case "ARTIGAS": countVacunadosPorDepartamento[0] = countVacunadosPorDepartamento[0] + 1; break; case "CANELONES": countVacunadosPorDepartamento[1] = countVacunadosPorDepartamento[1] + 1; break; case "<NAME>": countVacunadosPorDepartamento[2] = countVacunadosPorDepartamento[2] + 1; break; case "COLONIA": countVacunadosPorDepartamento[3] = countVacunadosPorDepartamento[3] + 1; break; case "DURAZNO": countVacunadosPorDepartamento[4] = countVacunadosPorDepartamento[4] + 1; break; case "FLORIDA": countVacunadosPorDepartamento[5] = countVacunadosPorDepartamento[5] + 1; break; case "FLORES": countVacunadosPorDepartamento[6] = countVacunadosPorDepartamento[6] + 1; break; case "LAVALLEJA": countVacunadosPorDepartamento[7] = countVacunadosPorDepartamento[7] + 1; break; case "MALDONADO": countVacunadosPorDepartamento[8] = countVacunadosPorDepartamento[8] + 1; break; case "MONTEVIDEO": countVacunadosPorDepartamento[9] = countVacunadosPorDepartamento[9] + 1; break; case "PAYSANDÚ": countVacunadosPorDepartamento[10] = countVacunadosPorDepartamento[10] + 1; break; case "<NAME>": countVacunadosPorDepartamento[11] = countVacunadosPorDepartamento[11] + 1; break; case "ROCHA": countVacunadosPorDepartamento[12] = countVacunadosPorDepartamento[12] + 1; break; case "RIVERA": countVacunadosPorDepartamento[13] = countVacunadosPorDepartamento[13] + 1; break; case "SALTO": countVacunadosPorDepartamento[14] = countVacunadosPorDepartamento[14] + 1; break; case "<NAME>": countVacunadosPorDepartamento[15] = countVacunadosPorDepartamento[15] + 1; break; case "SORIANO": countVacunadosPorDepartamento[16] = countVacunadosPorDepartamento[16] + 1; break; case "TACUAREMBÓ": countVacunadosPorDepartamento[17] = countVacunadosPorDepartamento[17] + 1; break; case "<NAME>": countVacunadosPorDepartamento[18] = countVacunadosPorDepartamento[18] + 1; break; } } } return countVacunadosPorDepartamento; } @Override public DTCertificado obtenerCertificadoReserva(long idReserva) { RegistroVacuna registroVacuna = registroVacunaDatoLocal.obtenerCertificadoReserva(idReserva); DTCertificado retorno = new DTCertificado(); Vacuna vac = registroVacuna.getVacuna(); Ciudadano cdn = registroVacuna.getCiudadano(); retorno.setNombreCompleto( cdn.getPrimerNombre() + " " + cdn.getPrimerApellido() ); retorno.setCedula(String.valueOf(cdn.getCi())); retorno.setFechaNacimiento(cdn.getFnac().toString()); retorno.setFechaVacuna(registroVacuna.getFecha().toString()); retorno.setIdVacuna(String.valueOf(vac.getId())); retorno.setNombreVacuna(vac.getNombre()); retorno.setLaboratorioVacuna(vac.getLaboratorio()); retorno.setCodigoVacuna(vac.getCodigo()); retorno.setCantDosis(String.valueOf(vac.getDosis())); retorno.setPeriodoInmunidad(String.valueOf(vac.getPeriodoInmune())); retorno.setIdEnfermedad(String.valueOf(vac.getEnfermedad().getId())); retorno.setNombreEnfermedad(vac.getEnfermedad().getNombre()); retorno.setIdReserva(String.valueOf(registroVacuna.getReserva().getId())); return retorno; } public int cantVacHastaFecha(long vacunaId, LocalDate fecha) { return registroVacunaDatoLocal.cantVacHastaFecha(vacunaId, fecha); } } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTCiudadano.java package datatypes; import entidades.Ciudadano; public class DTCiudadano { private int ci; private String primerNombre; private String segundoNombre; private String primerApellido; private String segundoApellido; private int telefono; private String email; private String tipoCiudadano; private String fnac; public DTCiudadano() { super(); // TODO Auto-generated constructor stub } public DTCiudadano(int ci, String primerNombre, String segundoNombre, String primerApellido, String segundoApellido, int telefono, String email, String tipoCiudadano, String fnac) { super(); this.ci = ci; this.primerNombre = primerNombre; this.segundoNombre = segundoNombre; this.primerApellido = primerApellido; this.segundoApellido = segundoApellido; this.telefono = telefono; this.email = email; this.tipoCiudadano = tipoCiudadano; this.fnac = fnac; } public DTCiudadano(Ciudadano ciudadano) { super(); this.ci = ciudadano.getCi(); this.primerNombre = ciudadano.getPrimerNombre(); this.segundoNombre = ciudadano.getSegundoNombre(); this.primerApellido = ciudadano.getPrimerApellido(); this.segundoApellido = ciudadano.getSegundoApellido(); this.telefono = ciudadano.getTelefono(); this.email = ciudadano.getEmail(); this.tipoCiudadano = ciudadano.getTipoCiudadano(); this.fnac = ciudadano.getFnac().toString(); } public int getCi() { return ci; } public void setCi(int ci) { this.ci = ci; } public String getPrimerNombre() { return primerNombre; } public void setPrimerNombre(String primerNombre) { this.primerNombre = primerNombre; } public String getSegundoNombre() { return segundoNombre; } public void setSegundoNombre(String segundoNombre) { this.segundoNombre = segundoNombre; } public String getPrimerApellido() { return primerApellido; } public void setPrimerApellido(String primerApellido) { this.primerApellido = primerApellido; } public String getSegundoApellido() { return segundoApellido; } public void setSegundoApellido(String segundoApellido) { this.segundoApellido = segundoApellido; } public int getTelefono() { return telefono; } public void setTelefono(int telefono) { this.telefono = telefono; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTipoCiudadano() { return tipoCiudadano; } public void setTipoCiudadano(String tipoCiudadano) { this.tipoCiudadano = tipoCiudadano; } public String getFnac() { return fnac; } public void setFnac(String fnac) { this.fnac = fnac; } @Override public String toString() { return "DTCiudadano [ci=" + ci + ", primerNombre=" + primerNombre + ", segundoNombre=" + segundoNombre + ", primerApellido=" + primerApellido + ", segundoApellido=" + segundoApellido + ", telefono=" + telefono + ", email=" + email + "]"; } } <file_sep>/comp-cent-ejb/src/main/java/datos/PlanVacunacionDatoLocal.java package datos; import java.util.List; import javax.ejb.Local; import entidades.PlanVacunacion; @Local public interface PlanVacunacionDatoLocal { void agregarPlanVacunacion(PlanVacunacion plan); public List<PlanVacunacion> listarPlanesDeVacunacion(); public Boolean existePlanVacunacion(String nombre); public PlanVacunacion obtenerPlanVacunacion(String nombre); public PlanVacunacion obtenerPlanVacunacionPorId(long id); public void editarPlanVacunacion(PlanVacunacion plan); public void eliminarPlanVacunacion(PlanVacunacion plan); public List<PlanVacunacion> obtenerPlanesVacunacionObjetivoEdad(String poblacionObjetivo, String fnac); } <file_sep>/comp-cent-ejb/src/main/java/negocio/CiudadanoNegocioLocal.java package negocio; import javax.ejb.Local; import datatypes.DTCiudadano; @Local public interface CiudadanoNegocioLocal { public void agregarCiudadano(DTCiudadano dtCiudadano); public DTCiudadano obtenerCiudadano(int ci); public boolean existeCiudadano(int ci); } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTDepartamento.java package datatypes; public class DTDepartamento { String descripcion; public DTDepartamento() { super(); // TODO Auto-generated constructor stub } public DTDepartamento(String descripcion) { super(); this.descripcion = descripcion; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } @Override public String toString() { return descripcion; } } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTReservaVacunatorio.java package datatypes; import java.util.List; public class DTReservaVacunatorio { private int ci; private long idVacuna; private long idReserva; private String fecha; public DTReservaVacunatorio() { } public int getCi() { return ci; } public void setCi(int ci) { this.ci = ci; } public long getIdVacuna() { return idVacuna; } public void setIdVacuna(long idVacuna) { this.idVacuna = idVacuna; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public long getIdReserva() { return idReserva; } public void setIdReserva(long idReserva) { this.idReserva = idReserva; } } <file_sep>/comp-cent-ejb/src/main/java/datos/LoteDatoLocal.java package datos; import java.util.List; import javax.ejb.Local; import entidades.Lote; @Local public interface LoteDatoLocal { public void agregarLote(Lote lote); public List<Lote> listarLotes(); public Lote obtenerLote(String nombre); public Boolean existeLote(String nombre); public void eliminarLote(Lote lote); public Lote obtenerLotePorId(long id); public void editarLote(Lote lote); } <file_sep>/comp-cent-ejb/src/main/java/datos/DepartamentoDatoLocal.java package datos; import java.util.List; import javax.ejb.Local; import entidades.Departamento; import entidades.Ubicacion; @Local public interface DepartamentoDatoLocal { public List<Departamento> obtenerDepartamentos(); public List<Ubicacion> obtenerDepartamentoUbicaciones(String nombre); public Ubicacion obtenerDepartamentoUbicacion(String descDepartamento, String descUbicacion); public Departamento obtenerDepartamentoPorNombre(String nombre); } <file_sep>/comp-cent-web/src/main/java/beans/EnvioBean.java package beans; import java.io.Serializable; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.view.ViewScoped; import javax.inject.Named; import datatypes.DTEnvio; import datatypes.DTLote; import datatypes.DTSocioLogistico; import datatypes.DTVacunatorio; import datatypes.DTVistaEnvio; import datos.EnvioDatoLocal; import enumeradores.EstadoEnvio; import negocio.EnvioNegocioLocal; import negocio.LoteNegocioLocal; import negocio.SocioLogisticoNegocioLocal; import negocio.VacunatorioNegocioLocal; import negocio.VistaEnvioNegocioLocal; @Named("envioBean") @ViewScoped public class EnvioBean implements Serializable{ private static final long serialVersionUID = 1L; @EJB private VistaEnvioNegocioLocal vistaLocal; @EJB private EnvioNegocioLocal envioLocal; @EJB private EnvioDatoLocal datoEnvioLocal; @EJB private LoteNegocioLocal loteLocal; @EJB private SocioLogisticoNegocioLocal socioLocal; @EJB private VacunatorioNegocioLocal vacunatorioLocal; private List<String> estados; private String nombreVacunatorio; private String nombreSocioLogistico; private String nombreLote; private EstadoEnvio estado; private DTEnvio envio; private List<DTEnvio> envios; //private List<Envio> enviosEntidad; private List<DTVistaEnvio> listaEnvios; private DTLote lote; private List<DTLote> lotes; private DTSocioLogistico socioLogistico; private List<DTSocioLogistico> socioLogisticos; private DTVacunatorio vacunatorio; private List<DTVacunatorio> vacunatorios; //Agrego String para saber el estado del botón private String nombreBoton; private String estiloBoton; private Boolean editar; @PostConstruct public void init() { this.setListaEnvios(vistaLocal.listarEnvios()); // this.enviosEntidad = datoEnvioLocal.listarEnvios(); this.lotes = envioLocal.listarLotePendientesDeEnviar(); this.socioLogisticos = socioLocal.listarSocioLogistico(); this.vacunatorios = vacunatorioLocal.listarVacunatorio(); this.setEstados(envioLocal.listarEstado()); this.envio = new DTEnvio(); this.lote = new DTLote(); this.socioLogistico = new DTSocioLogistico(); this.vacunatorio = new DTVacunatorio(); } public static long getSerialversionuid() { return serialVersionUID; } public LoteNegocioLocal getLoteLocal() { return loteLocal; } public SocioLogisticoNegocioLocal getSocioLocal() { return socioLocal; } public VacunatorioNegocioLocal getVacunatorioLocal() { return vacunatorioLocal; } public DTLote getLote() { return lote; } public List<DTLote> getLotes() { return lotes; } public DTSocioLogistico getSocioLogistico() { return socioLogistico; } public List<DTSocioLogistico> getSocioLogisticos() { return socioLogisticos; } public DTVacunatorio getVacunatorio() { return vacunatorio; } public List<DTVacunatorio> getVacunatorios() { return vacunatorios; } public String getNombreBoton() { return nombreBoton; } public String getEstiloBoton() { return estiloBoton; } public Boolean getEditar() { return editar; } public void setLoteLocal(LoteNegocioLocal loteLocal) { this.loteLocal = loteLocal; } public void setSocioLocal(SocioLogisticoNegocioLocal socioLocal) { this.socioLocal = socioLocal; } public void setVacunatorioLocal(VacunatorioNegocioLocal vacunatorioLocal) { this.vacunatorioLocal = vacunatorioLocal; } public void setLote(DTLote lote) { this.lote = lote; } public void setLotes(List<DTLote> lotes) { this.lotes = lotes; } public void setSocioLogistico(DTSocioLogistico socioLogistico) { this.socioLogistico = socioLogistico; } public void setSocioLogisticos(List<DTSocioLogistico> socioLogisticos) { this.socioLogisticos = socioLogisticos; } public void setVacunatorio(DTVacunatorio vacunatorio) { this.vacunatorio = vacunatorio; } public void setVacunatorios(List<DTVacunatorio> vacunatorios) { this.vacunatorios = vacunatorios; } public void setNombreBoton(String nombreBoton) { this.nombreBoton = nombreBoton; } public void setEstiloBoton(String estiloBoton) { this.estiloBoton = estiloBoton; } public void setEditar(Boolean editar) { this.editar = editar; } public DTEnvio getEnvio() { return envio; } public List<DTEnvio> getEnvios() { return envios; } public void setEnvio(DTEnvio envio) { this.envio = envio; } public void setEnvios(List<DTEnvio> envios) { this.envios = envios; } public List<String> getEstados() { return estados; } public void setEstados(List<String> estados) { this.estados = estados; } public String getNombreVacunatorio() { return nombreVacunatorio; } public void setNombreVacunatorio(String nombreVacunatorio) { this.nombreVacunatorio = nombreVacunatorio; } public String getNombreSocioLogistico() { return nombreSocioLogistico; } public void setNombreSocioLogistico(String nombreSocioLogistico) { this.nombreSocioLogistico = nombreSocioLogistico; } public String getNombreLote() { return nombreLote; } public void setNombreLote(String nombreLote) { this.nombreLote = nombreLote; } public EstadoEnvio getEstado() { return estado; } public void setEstado(EstadoEnvio estado) { this.estado = estado; } public List<DTVistaEnvio> getListaEnvios() { return listaEnvios; } public void setListaEnvios(List<DTVistaEnvio> listaEnvios) { this.listaEnvios = listaEnvios; } // public List<Envio> getEnviosEntidad() { // return enviosEntidad; // } // // // // public void setEnviosEntidad(List<Envio> enviosEntidad) { // this.enviosEntidad = enviosEntidad; // } public void reiniciarEnvio(){ editar = false; this.nombreBoton = "Agregar Envio"; this.estiloBoton = "pi pi-check"; this.envio = new DTEnvio(); this.nombreLote = null; this.nombreSocioLogistico = null; this.nombreVacunatorio = null; } public void agregarEnvio() throws Exception { for (DTVacunatorio vac: vacunatorios) { if (vac.getNombre().equals(nombreVacunatorio)) { vacunatorio = vac; } } lote = loteLocal.obtenerLote(nombreLote); for (DTSocioLogistico soc: socioLogisticos) { if (soc.getNombre().equals(nombreSocioLogistico)) { socioLogistico = soc; } } try { if(editar) { //Funcion para editar el envio. }else { //Funcion para Agregar Envio envio.setEstado(estado.Pendiente); envioLocal.AgregarEnvio(envio, lote, vacunatorio, socioLogistico); this.init(); } }catch (Exception e) { // TODO: handle exception } } } <file_sep>/comp-cent-ejb/src/main/java/negocio/EnfermedadNegocio.java package negocio; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import datatypes.DTEnfermedad; import datatypes.DTVacuna; import datos.EnfermedadDatoLocal; import entidades.Enfermedad; import entidades.Vacuna; import enumeradores.PoblacionObjetivo; /** * Session Bean implementation class EnfermedadNegocio */ @Stateless @LocalBean public class EnfermedadNegocio implements EnfermedadNegocioLocal { @EJB private EnfermedadDatoLocal datoLocal; public EnfermedadNegocio() { // TODO Auto-generated constructor stub } @Override public List<DTEnfermedad> listarEnfermedades() { List<Enfermedad> enfermedades = datoLocal.listarEnfermedades(); List<DTEnfermedad> lista = new ArrayList<DTEnfermedad>(); for (Enfermedad enf:enfermedades) { DTEnfermedad enfermedad = new DTEnfermedad(enf); lista.add(enfermedad); } return lista; } @Override public void agregarEnfermedad(String nombre) throws Exception { if (datoLocal.existeEnfermedad(nombre)) throw new Exception("\nEnfermedad ya existe en el sistema"); else { LocalDate date1 = LocalDate.now(); Enfermedad enf = new Enfermedad(nombre,date1); datoLocal.agregarEnfermedad(enf); } } @Override public DTEnfermedad buscarEnfermedad(String nombre) throws Exception { if (datoLocal.existeEnfermedad(nombre)) { DTEnfermedad enfermedad = new DTEnfermedad(datoLocal.buscarEnfermedad(nombre)); return enfermedad; } else { throw new Exception("\nEnfermedad no encontrada en el sistema"); } } @Override public List<DTVacuna> listarVacunasPorEnfermedad(String nombreEnfermedad) throws Exception { if (datoLocal.existeEnfermedad(nombreEnfermedad)) { List<DTVacuna> lista = new ArrayList<DTVacuna>(); List<Vacuna> vacunas = (datoLocal.buscarEnfermedad(nombreEnfermedad)).getVacunas(); if (vacunas!= null) { for (Vacuna vac:vacunas) { DTVacuna vacuna = new DTVacuna(vac); lista.add(vacuna); } } return lista; } else throw new Exception("\nEnfermedad no encontrada en el sistema"); } @Override public List<String> listarPoblacionObjetivo () { List<String> poblacion = Stream.of(PoblacionObjetivo.values()) .map(Enum::name) .collect(Collectors.toList()); return poblacion; } @Override public void eliminarEnfermedad(String nombre) throws Exception{ Enfermedad enf = datoLocal.buscarEnfermedad(nombre); if(enf != null) { datoLocal.eliminarEnfermedad(enf); }else { throw new Exception("\nNo se encontro la Enfermedad con el id ingresado"); } } @Override public DTEnfermedad obtenerEnfermedadPorId(long id){ Enfermedad enf= datoLocal.obtenerEnfermedadPorId(id); DTEnfermedad dtEnf = new DTEnfermedad(enf); return dtEnf; } public void editarEnfermedad(DTEnfermedad dtEnf) throws Exception{ Enfermedad enf = datoLocal.obtenerEnfermedadPorId(dtEnf.getId()); if(enf != null){ enf.setNombre(dtEnf.getNombre()); datoLocal.editarEnfermedad(enf); }else{ throw new Exception("\nNo se encontro el Proveedor con el id ingresado"); } } } <file_sep>/comp-cent-ejb/src/main/java/negocio/SocioLogisticoNegocioLocal.java package negocio; import java.util.List; import javax.ejb.Local; import datatypes.DTSocioLogistico; @Local public interface SocioLogisticoNegocioLocal { public void agregarSocioLogistico(DTSocioLogistico dtSocio) throws Exception; public void editarSocioLogistico(DTSocioLogistico dtSocio) throws Exception; public void eliminarSocioLosgistico(DTSocioLogistico dtSocio) throws Exception; public Boolean existeSocioLogistico(String codigo); public DTSocioLogistico obtenerSocioLogistico(String codigo) throws Exception; public List<DTSocioLogistico> listarSocioLogistico(); } <file_sep>/comp-cent-ejb/src/main/java/negocio/DepartamentoNegocio.java package negocio; import java.util.ArrayList; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.inject.Inject; import datatypes.DTDepartamento; import datatypes.DTUbicacion; import datos.DepartamentoDatoLocal; import entidades.Departamento; import entidades.Ubicacion; /** * Session Bean implementation class DepartamentoNegocio */ @Stateless @LocalBean public class DepartamentoNegocio implements DepartamentoNegocioLocal { @Inject DepartamentoDatoLocal md; /** * Default constructor. */ public DepartamentoNegocio() { // TODO Auto-generated constructor stub } @Override public List<DTDepartamento> obtenerDepartamentos() { ArrayList<Departamento> departamentos = (ArrayList<Departamento>) md.obtenerDepartamentos(); ArrayList<DTDepartamento> dTDepartamentos = new ArrayList<DTDepartamento>(); departamentos.forEach( (d) -> { dTDepartamentos.add( new DTDepartamento(d.getDescripcion())) ; } ); return dTDepartamentos; } @Override public List<DTUbicacion> obtenerDepartamentoUbicaciones(String nombre) { List<Ubicacion> ubicaciones = md.obtenerDepartamentoUbicaciones(nombre); List<DTUbicacion> dTUbicaciones = new ArrayList<DTUbicacion>(); ubicaciones.forEach( (u) -> { dTUbicaciones.add( new DTUbicacion(u.getDescripcion(),u.getId())) ; } ); return dTUbicaciones; } @Override public DTUbicacion obtenerDepartamentoUbicacion(String descDepartamento, String descUbicacion) { Ubicacion ubicacion = md.obtenerDepartamentoUbicacion(descDepartamento, descUbicacion); if(ubicacion != null) { DTUbicacion dtUbicacion = new DTUbicacion(ubicacion); return dtUbicacion; } else { return null; } } @Override public DTDepartamento obtenerDepartamentoPorUbicacion(long idUbicacion) { ArrayList<Departamento> departamentos = (ArrayList<Departamento>) md.obtenerDepartamentos(); DTDepartamento departamento = new DTDepartamento(); for (Departamento dpto : departamentos) { for (Ubicacion ubi: dpto.getUbicaciones()) { if (ubi.getId() == idUbicacion) { departamento.setDescripcion(dpto.getDescripcion()); } } } return departamento; } } <file_sep>/comp-cent-ejb/src/main/java/entidades/Reserva.java package entidades; import java.time.LocalDate; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import datatypes.DTReserva; import enumeradores.EstadoReserva; @Entity public class Reserva { @Id @GeneratedValue private long id; private int hora; private LocalDate fecha; private int dosisSuministradas; @Enumerated(value = EnumType.STRING) private EstadoReserva estado; @ManyToOne private Ciudadano ciudadano; @ManyToOne private Vacuna vacuna; @ManyToOne private Agenda agenda; @ManyToOne private PlanVacunacion planVacunacion; @ManyToOne private Departamento departamento; @ManyToOne private Ubicacion ubicacion; public Reserva() { super(); // TODO Auto-generated constructor stub } public Reserva(DTReserva res) { super(); this.hora = res.getHora(); this.fecha = res.getFecha(); this.estado = res.getEstado(); } public Reserva(long id, int hora, LocalDate fecha, EstadoReserva estado, Ciudadano ciudadano, Agenda agenda, PlanVacunacion planVacunacion, Departamento departamento, Ubicacion ubicacion) { super(); this.id = id; this.hora = hora; this.fecha = fecha; this.estado = estado; this.ciudadano = ciudadano; this.agenda = agenda; this.planVacunacion = planVacunacion; this.departamento = departamento; this.ubicacion = ubicacion; this.dosisSuministradas = 1; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getHora() { return hora; } public void setHora(int hora) { this.hora = hora; } public LocalDate getFecha() { return fecha; } public void setFecha(LocalDate fecha) { this.fecha = fecha; } public Ciudadano getCiudadano() { return ciudadano; } public void setCiudadano(Ciudadano ciudadano) { this.ciudadano = ciudadano; } public Agenda getAgenda() { return agenda; } public void setAgenda(Agenda agenda) { this.agenda = agenda; } public PlanVacunacion getPlanVacunacion() { return planVacunacion; } public void setPlanVacunacion(PlanVacunacion planVacunacion) { this.planVacunacion = planVacunacion; } public EstadoReserva getEstado() { return estado; } public void setEstado(EstadoReserva estado) { this.estado = estado; } public Vacuna getVacuna() { return vacuna; } public void setVacuna(Vacuna vacuna) { this.vacuna = vacuna; } public Departamento getDepartamento() { return departamento; } public void setDepartamento(Departamento departamento) { this.departamento = departamento; } public Ubicacion getUbicacion() { return ubicacion; } public void setUbicacion(Ubicacion ubicacion) { this.ubicacion = ubicacion; } public int getDosisSuministradas() { return dosisSuministradas; } public void setDosisSuministradas(int dosisSuministradas) { this.dosisSuministradas = dosisSuministradas; } @Override public String toString() { return "Reserva [id=" + id + ", hora=" + hora + ", fecha=" + fecha + ", ciudadano=" + ciudadano + ", agenda=" + agenda + ", planVacunacion=" + planVacunacion + "]"; } } <file_sep>/comp-cent-web/src/main/java/rest/AgendaREST.java package rest; import java.util.ArrayList; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.naming.NamingException; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import datatypes.DTAgenda; import negocio.AgendaNegocioLocal; @RequestScoped @Path("/agendas") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class AgendaREST { @Inject private AgendaNegocioLocal an; public AgendaREST() throws NamingException { } @GET public Response getAgenda() { ArrayList<DTAgenda> dtAgenda = (ArrayList<DTAgenda>) an.listarAgenda(); if (!dtAgenda.isEmpty()) { return Response .status(Response.Status.OK) .entity(dtAgenda) .build(); } else { return Response .status(Response.Status.NOT_FOUND) .build(); } } @GET @Path("/activas") public Response agendasActivas() { ArrayList<DTAgenda> agendas = (ArrayList<DTAgenda>) an.listarAgendasActivas(); if(!agendas.isEmpty()) { return Response .status(Response.Status.OK) .entity(agendas) .build(); } else { return Response .status(Response.Status.OK) .entity("Por el momento no hay agendas activas!") .build(); } } @GET @Path("/count-activas/{id}") public Response countAgendasActivasHoy(@PathParam("id")long vacunaId) { try { return Response .status(Response.Status.OK) .entity(an.countAgendasActivasHoy(vacunaId)) .build(); } catch(Exception e){ return Response .status(Response.Status.OK) .entity("Error") .build(); } } @GET @Path("/agendas-vacunador/{ci}") public Response agendasVacunador(@PathParam("ci")int ci) { try { return Response.status(Response.Status.OK) .entity(an.agendasVacunador(ci)) .build(); } catch(Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } } <file_sep>/comp-cent-ejb/src/test/java/negocio/EnvioNegocioTest.java package negocio; import static org.junit.Assert.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.ejb.EJB; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import datatypes.DTEnvio; import datatypes.DTLote; import datatypes.DTSocioLogistico; import datatypes.DTStockVacuna; import datatypes.DTVacuna; import datatypes.DTVacunatorio; import datos.EnvioDatoLocal; import datos.LoteDatoLocal; import datos.SocioLogisticoDatoLocal; import datos.VacunatorioDatoLocal; import entidades.Enfermedad; import entidades.Envio; import entidades.Lote; import entidades.SocioLogistico; import entidades.Vacuna; import entidades.Vacunatorio; import enumeradores.EstadoEnvio; import static org.mockito.ArgumentMatchers.any; public class EnvioNegocioTest { @Mock private EnvioDatoLocal envioLocal; @Mock private LoteDatoLocal loteLocal; @Mock private VacunatorioDatoLocal vacunatorioLocal; @Mock private SocioLogisticoDatoLocal socioLocal; @Mock private EnvioNegocio envNegocio; @InjectMocks private EnvioNegocio en; private static List<Envio> envios; private static List<Lote> lotes; private static Envio envio; private static DTLote dtLote; private static DTVacunatorio dtVacunatorio; private static DTSocioLogistico dtSocio; private static DTEnvio dtEnvio; private static Lote lote; private static SocioLogistico socio; private static Vacunatorio vacunatorio; private static Vacuna vacuna; private static Enfermedad enfermedad; private static List<String> estados ; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); dtVacunatorio = new DTVacunatorio(); dtVacunatorio.setId(1); dtSocio = new DTSocioLogistico(); dtSocio.setCodigo("prueba"); dtLote = new DTLote(); dtLote.setNombre("prueba"); lote = new Lote(); lote.setFechaCreado(LocalDate.now()); envio = new Envio(); envio.setEstado(EstadoEnvio.Entransito); envio.setFechaCreacion(LocalDate.now()); envios = new ArrayList<Envio>(); lotes = new ArrayList<Lote>(); vacuna = new Vacuna(); enfermedad = new Enfermedad(); vacuna.setEnfermedad(enfermedad); lote.setVacuna(vacuna); envio.setLote(lote); envios.add(envio); lotes.add(lote); estados = Stream.of(EstadoEnvio.values()) .map(Enum::name) .collect(Collectors.toList()); } @Test public void testListarEnvios() { Mockito.when(envioLocal.listarEnvios()).thenReturn(envios); List<DTEnvio> dtEnvios= en.listarEnvios(); assertEquals(envios.size(), dtEnvios.size()); } @Test public void testListarEnviosPorSocioLogistico() { Mockito.when(envioLocal.listarEnviosPorSocioLogistico("prueba")).thenReturn(envios); List<DTEnvio> dtEnvios= en.listarEnviosPorSocioLogistico("prueba"); assertEquals(envios.size(), dtEnvios.size()); } @Test public void testCambiarEstadoEnvio() { Mockito.when(envioLocal.obtenerEnvio(any(Long.class))).thenReturn(envio); Mockito.doNothing().when(envioLocal).editarEnvio(envio); en.cambiarEstadoEnvio(EstadoEnvio.Entregado, any(Long.class)); Mockito.verify(envioLocal ,Mockito.times(1)).editarEnvio(envio); } @Test public void testAgregarEnvio() throws Exception { dtEnvio = Mockito.mock(DTEnvio.class); socio = Mockito.mock(SocioLogistico.class); vacunatorio = Mockito.mock(Vacunatorio.class); Mockito.when(loteLocal.obtenerLote("prueba")).thenReturn(lote); Mockito.when(socioLocal.obtenerSocioLogistico("prueba")).thenReturn(socio); Mockito.when(vacunatorioLocal.obtenerVacunatorio(any(Long.class))).thenReturn(vacunatorio); Mockito.doNothing().when(envioLocal).guardarEnvio(envio); en.AgregarEnvio(dtEnvio, dtLote, dtVacunatorio, dtSocio); Mockito.verify(loteLocal ,Mockito.times(1)).obtenerLote("prueba"); } @Test public void testListarEstado() { Mockito.when(en.listarEstado()).thenReturn(estados); List<String> result = en.listarEstado(); assertEquals(estados,result); } @Test public void testListarLotePendientesDeEnviar() { Mockito.when(loteLocal.listarLotes()).thenReturn(lotes); Mockito.when(envioLocal.ExisteLote(lote)).thenReturn(false); List<DTLote> dtLotes = en.listarLotePendientesDeEnviar(); assertEquals(lotes.size(),dtLotes.size()); } @Test public void testStockEnviado() { Mockito.when(envioLocal.cantVacEnviado(any(Long.class), any(LocalDate.class))).thenReturn(envios); List<DTStockVacuna> stock = en.stockEnviado(any(Integer.class), any(LocalDate.class)); assertTrue (stock!=null); } } <file_sep>/comp-cent-ejb/src/main/java/negocio/VistaEnvioNegocio.java package negocio; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import datatypes.DTVistaEnvio; import datos.EnvioDatoLocal; /** * Session Bean implementation class VistaEnvioNegocio */ @Stateless @LocalBean public class VistaEnvioNegocio implements VistaEnvioNegocioLocal { @EJB private EnvioDatoLocal envioLocal; /** * Default constructor. */ public VistaEnvioNegocio() { // TODO Auto-generated constructor stub } @Override public List<DTVistaEnvio> listarEnvios(){ List<DTVistaEnvio> envios = new ArrayList<DTVistaEnvio>(); envios = envioLocal.ListarEnviosVista(); return envios; } } <file_sep>/comp-cent-ejb/src/main/java/datos/VacunaDatoLocal.java package datos; import java.util.List; import javax.ejb.Local; import entidades.Enfermedad; import entidades.Proveedor; import entidades.Vacuna; @Local public interface VacunaDatoLocal { public void agregarVacuna(Vacuna vac); public List<Vacuna> obtenerVacunas(); Vacuna obtenerVacuna(String nombre); public Boolean existeVacuna(String nombre); void editarVacuna(Vacuna vacuna); public void eliminarVacuna(Vacuna vacuna); public Proveedor obtenerProveedorDeVacuna(String nomVac); public Enfermedad obtenerEnfermedadDeVacuna(String nomVac); public Vacuna obtenerVacunaPorId(long id); } <file_sep>/comp-cent-ejb/src/main/java/negocio/AgendaNegocio.java package negocio; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import datatypes.DTAgenda; import datatypes.DTPlanVacunacion; import datos.AgendaDatoLocal; import datos.PlanVacunacionDatoLocal; import datos.ReservaDatoLocal; import datos.VacunadorDatoLocal; import datos.VacunatorioDatoLocal; import datos.VacunatorioVacunadorDatoLocal; import entidades.Agenda; import entidades.PlanVacunacion; import entidades.Vacuna; import entidades.Vacunador; import entidades.Vacunatorio; /** * Session Bean implementation class AgendaNegocio */ @Stateless @LocalBean public class AgendaNegocio implements AgendaNegocioLocal { @EJB private AgendaDatoLocal agendaLocal; @EJB private VacunatorioDatoLocal vacunatorioLocal; @EJB private PlanVacunacionDatoLocal planLocal; @EJB private ReservaDatoLocal reservaLocal; @EJB private VacunatorioVacunadorDatoLocal vvl; @EJB private VacunadorDatoLocal vdl; /** * Default constructor. */ public AgendaNegocio() { // TODO Auto-generated constructor stub } public void agregarAgenda(DTAgenda dtAgenda) throws Exception { Agenda agenda = new Agenda(dtAgenda); Vacunatorio vacunatorio = vacunatorioLocal.obtenerVacunatorio(dtAgenda.getDtVacunatorio().getId()); agenda.setVacunatorio(vacunatorio); if (!agendaLocal.agendaSuperpuesta(agenda)) { List<DTPlanVacunacion> planes = dtAgenda.getListDtPlanVacunacion(); List<PlanVacunacion> planesAux = new ArrayList<PlanVacunacion>(); for (DTPlanVacunacion plan : planes) { PlanVacunacion planVac = planLocal.obtenerPlanVacunacion(plan.getNombre()); planesAux.add(planVac); } agenda.setPlanes(planesAux); this.agendaLocal.agregarAgenda(agenda); } else { throw new Exception("\n No se puede crear agenda, se superponen las fechas con otra agenda para ese vacunatorio"); } } public List<DTAgenda> listarAgenda(){ List <Agenda> agendas = (ArrayList<Agenda>)(this.agendaLocal.listarAgenda()); List <DTAgenda> dtAgenda = new ArrayList<DTAgenda>(); if (agendas != null) { agendas.forEach((a)->{dtAgenda.add(new DTAgenda(a));}); } return dtAgenda; } @Override /*Devuelve una lista con todas las agendas no vencidas*/ public List<DTAgenda> listarAgendasActivas(){ List <Agenda> agendas = (ArrayList<Agenda>)(this.agendaLocal.listarAgenda()); List <DTAgenda> retorno = new ArrayList<DTAgenda>(); if(!agendas.isEmpty()) { for(Agenda agenda: agendas) { if(agenda.getFin().isAfter(LocalDate.now())){ retorno.add(new DTAgenda(agenda)); } } return retorno; } else { return null; } } @Override public void editarAgenda (DTAgenda dtAgenda) throws Exception { Agenda agenda = agendaLocal.obtenerAgendaPorId(dtAgenda.getId()); Agenda ag = new Agenda(dtAgenda); if (agenda != null) { Vacunatorio vac = vacunatorioLocal.obtenerVacunatorio(dtAgenda.getDtVacunatorio().getId()); agenda.setVacunatorio(vac); ag.setVacunatorio(vac); if (!agendaLocal.agendaSuperpuesta(ag)) { agenda.setInicio(LocalDate.parse(dtAgenda.getInicio())); agenda.setFin(LocalDate.parse(dtAgenda.getFin())); agenda.setHoraInicio(dtAgenda.getHoraInicio()); agenda.setHoraFin(agenda.getHoraFin()); List<DTPlanVacunacion> dtPlan = dtAgenda.getListDtPlanVacunacion(); List<PlanVacunacion> planes = new ArrayList<PlanVacunacion>(); for (DTPlanVacunacion plan: dtPlan) { planes.add(planLocal.obtenerPlanVacunacionPorId(plan.getId())); } agenda.setPlanes(planes); agendaLocal.editarAgenda(agenda); } else { throw new Exception("\n No se puede modificar agenda, se superponen las fechas con otra agenda para ese vacunatorio"); } } else { throw new Exception("\nNo se encontro una agenda con el id ingresado"); } } @Override public void eliminarAgenda (DTAgenda dtAgenda) throws Exception { Agenda agenda = agendaLocal.obtenerAgendaPorId(dtAgenda.getId()); if (agenda != null) { if (!reservaLocal.existeReserva(agenda.getId())) { agendaLocal.eliminarAgenda(agenda); } else { throw new Exception("\nNo se puede eliminar la agenda, porque tiene reservas asociadas"); } } else { throw new Exception("\nNo se encontro un agenda con el id ingresado"); } } @Override public Agenda obtenerAgendaActiva(long idVac, LocalDate fecha) { Agenda agenda = agendaLocal.obtenerAgendaActivaVacunatorio(idVac, fecha); return agenda; } @Override public int countAgendasActivasHoy(long vacunaId) { List<Agenda> agendas = agendaLocal.listarAgenda(); int retorno = 0; LocalDate hoy = LocalDate.now(); for(Agenda a: agendas) { if( (a.getInicio().equals(hoy) || a.getInicio().isBefore(hoy)) && (a.getFin().equals(hoy) || a.getFin().isAfter(hoy)) ){ List<PlanVacunacion> planes = a.getPlanes(); for(PlanVacunacion pv: planes) { List<Vacuna> vacunas = pv.getVacunas(); for(Vacuna v: vacunas) { if(v.getId() == vacunaId) { retorno++; } } } } } return retorno; } @Override public List<DTAgenda> agendasVacunador(int ci){ List<DTAgenda> retorno = new ArrayList<DTAgenda>(); Vacunador vacunador = vdl.obteneVacunadorPorCI(ci); Vacunatorio vacunatorio = vvl.buscarVacunatorio(vacunador); List<Agenda> agendas = agendaLocal.obtenerAgendasActivasYPasadasVacunatorio(vacunatorio.getId()); for(Agenda a: agendas) { DTAgenda dtagenda = new DTAgenda(a); //dtagenda.setFechaAsignado(vvl.obtenerFechaAsignado(vacunatorio.getId(), ci).toString()); retorno.add(dtagenda); } return retorno; } } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTReservaWS.java package datatypes; public class DTReservaWS { private String ci; private String planVacunacion; private String departamento; private String ubicacion; public DTReservaWS(String ci, String planVacunacion, String departamento, String ubicacion) { super(); this.ci = ci; this.planVacunacion = planVacunacion; this.departamento = departamento; this.ubicacion = ubicacion; } public DTReservaWS() { super(); // TODO Auto-generated constructor stub } public String getCi() { return ci; } public void setCi(String ci) { this.ci = ci; } public String getPlanVacunacion() { return planVacunacion; } public void setPlanVacunacion(String planVacunacion) { this.planVacunacion = planVacunacion; } public String getDepartamento() { return departamento; } public void setDepartamento(String departamento) { this.departamento = departamento; } public String getUbicacion() { return ubicacion; } public void setUbicacion(String ubicacion) { this.ubicacion = ubicacion; } } <file_sep>/comp-cent-ejb/src/main/java/datos/EnfermedadDatoLocal.java package datos; import java.util.List; import javax.ejb.Local; import entidades.Enfermedad; @Local public interface EnfermedadDatoLocal { public List<Enfermedad> listarEnfermedades (); public void agregarEnfermedad(Enfermedad enfermedad); public Enfermedad buscarEnfermedad(String nombre); public Boolean existeEnfermedad(String nombre); public void eliminarEnfermedad(Enfermedad enfermedad); public Enfermedad obtenerEnfermedadPorId(long id); public void editarEnfermedad(Enfermedad enf); } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTTransportista.java package datatypes; public class DTTransportista { } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTCertificado.java package datatypes; public class DTCertificado { private String cedula; private String nombreCompleto; private String fechaNacimiento; private String fechaVacuna; private String idVacuna; private String nombreVacuna; private String laboratorioVacuna; private String codigoVacuna; private String cantDosis; private String periodoInmunidad; private String idEnfermedad; private String nombreEnfermedad; private String idReserva; public DTCertificado() { super(); // TODO Auto-generated constructor stub } public DTCertificado(String cedula, String nombreCompleto, String fechaNacimiento, String fechaVacuna, String idVacuna, String nombreVacuna, String laboratorioVacuna, String codigoVacuna, String cantDosis, String periodoInmunidad, String idEnfermedad, String nombreEnfermedad, String idReserva) { super(); this.cedula = cedula; this.nombreCompleto = nombreCompleto; this.fechaNacimiento = fechaNacimiento; this.fechaVacuna = fechaVacuna; this.idVacuna = idVacuna; this.nombreVacuna = nombreVacuna; this.laboratorioVacuna = laboratorioVacuna; this.codigoVacuna = codigoVacuna; this.cantDosis = cantDosis; this.periodoInmunidad = periodoInmunidad; this.idEnfermedad = idEnfermedad; this.nombreEnfermedad = nombreEnfermedad; this.idReserva = idReserva; } public String getFechaVacuna() { return fechaVacuna; } public void setFechaVacuna(String fechaVacuna) { this.fechaVacuna = fechaVacuna; } public String getIdVacuna() { return idVacuna; } public void setIdVacuna(String idVacuna) { this.idVacuna = idVacuna; } public String getNombreVacuna() { return nombreVacuna; } public void setNombreVacuna(String nombreVacuna) { this.nombreVacuna = nombreVacuna; } public String getLaboratorioVacuna() { return laboratorioVacuna; } public void setLaboratorioVacuna(String laboratorioVacuna) { this.laboratorioVacuna = laboratorioVacuna; } public String getCodigoVacuna() { return codigoVacuna; } public void setCodigoVacuna(String codigoVacuna) { this.codigoVacuna = codigoVacuna; } public String getCantDosis() { return cantDosis; } public void setCantDosis(String cantDosis) { this.cantDosis = cantDosis; } public String getPeriodoInmunidad() { return periodoInmunidad; } public void setPeriodoInmunidad(String periodoInmunidad) { this.periodoInmunidad = periodoInmunidad; } public String getIdEnfermedad() { return idEnfermedad; } public void setIdEnfermedad(String idEnfermedad) { this.idEnfermedad = idEnfermedad; } public String getNombreEnfermedad() { return nombreEnfermedad; } public void setNombreEnfermedad(String nombreEnfermedad) { this.nombreEnfermedad = nombreEnfermedad; } public String getIdReserva() { return idReserva; } public void setIdReserva(String idReserva) { this.idReserva = idReserva; } public String getCedula() { return cedula; } public void setCedula(String cedula) { this.cedula = cedula; } public String getNombreCompleto() { return nombreCompleto; } public void setNombreCompleto(String nombreCompleto) { this.nombreCompleto = nombreCompleto; } public String getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(String fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTPlanVacunacion.java package datatypes; import java.util.List; import entidades.PlanVacunacion; import enumeradores.PoblacionObjetivo; public class DTPlanVacunacion { private long id; private String nombre; private PoblacionObjetivo poblacionObjetivo; int edadMinima; int edadMaxima; private DTEnfermedad enfermedad; private List<DTVacuna> vacunas; public DTPlanVacunacion() { // TODO Auto-generated constructor stub } public DTPlanVacunacion(PlanVacunacion plan) { super(); this.id = plan.getId(); this.nombre = plan.getNombre(); this.poblacionObjetivo = plan.getPoblacionObjetivo(); this.edadMinima = plan.getEdadMinima(); this.edadMaxima = plan.getEdadMaxima(); //this.enfermedad = plan.getDTEnfermedad; // para despues //this.vacuna = plan.getDTVacuna; // para despues } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public PoblacionObjetivo getPoblacionObjetivo() { return poblacionObjetivo; } public void setPoblacionObjetivo(PoblacionObjetivo poblacionObjetivo) { this.poblacionObjetivo = poblacionObjetivo; } public int getEdadMinima() { return edadMinima; } public void setEdadMinima(int edadMinima) { this.edadMinima = edadMinima; } public int getEdadMaxima() { return edadMaxima; } public void setEdadMaxima(int edadMaxima) { this.edadMaxima = edadMaxima; } public DTEnfermedad getEnfermedad() { return enfermedad; } public void setEnfermedad(DTEnfermedad enfermedad) { this.enfermedad = enfermedad; } public List<DTVacuna> getVacunas() { return vacunas; } public void setVacunas(List<DTVacuna> vacunas) { this.vacunas = vacunas; } } <file_sep>/comp-cent-ejb/src/test/java/negocio/LoteNegocioTest.java package negocio; import static org.junit.Assert.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import datatypes.DTEnvio; import datatypes.DTLote; import datatypes.DTVacuna; import datos.LoteDatoLocal; import datos.VacunaDatoLocal; import entidades.Lote; import entidades.Vacuna; import static org.mockito.ArgumentMatchers.any; public class LoteNegocioTest { @Mock private LoteDatoLocal datoLocal; @Mock private VacunaDatoLocal vacunaDatoLocal; @InjectMocks private LoteNegocio ln; private static List<Lote> lotes; private static Lote lote; private static DTLote dtLote; private static Vacuna vacuna; private static DTVacuna dtVacuna; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); lote = new Lote(); vacuna = new Vacuna(); vacuna.setNombre("prueba"); vacuna.setId(1); lote.setVacuna(vacuna); lote.setFechaCreado(LocalDate.now()); dtVacuna = Mockito.mock(DTVacuna.class); dtLote = new DTLote(lote); dtLote.setNombre("prueba"); dtLote.setVacuna(dtVacuna); lote.setFechaCreado(LocalDate.now()); lotes = new ArrayList<Lote>(); lotes.add(lote); } @Test public void testListarLotes() { Mockito.when(datoLocal.listarLotes()).thenReturn(lotes); Mockito.when(vacunaDatoLocal.obtenerVacuna("prueba")).thenReturn(vacuna); List<DTLote> dtLotes= ln.listarLotes(); assertEquals(lotes.size(), dtLotes.size()); } @Test public void testAgregarLote() throws Exception { Mockito.when(datoLocal.existeLote(any(String.class))).thenReturn(false); Mockito.when(vacunaDatoLocal.obtenerVacuna(null)).thenReturn(vacuna); Mockito.doNothing().when(datoLocal).agregarLote(lote); ln.agregarLote(dtLote); Mockito.verify(vacunaDatoLocal ,Mockito.times(1)).obtenerVacuna(null); } @Test(expected = Exception.class) public void testAgregarLoteException() throws Exception { Mockito.when(datoLocal.existeLote("prueba")).thenReturn(true); ln.agregarLote(dtLote); } @Test public void testObtenerLote() throws Exception { Mockito.when(datoLocal.existeLote("prueba")).thenReturn(true); Mockito.when(datoLocal.obtenerLote("prueba")).thenReturn(lote); DTLote dt = ln.obtenerLote("prueba"); assertTrue(dt!=null); } @Test(expected = Exception.class) public void testObtenerLoteException() throws Exception { Mockito.when(datoLocal.existeLote("prueba")).thenReturn(false); DTLote dt = ln.obtenerLote("prueba"); } @Test public void testEditarLote() throws Exception { Mockito.when(datoLocal.obtenerLotePorId(any(Long.class))).thenReturn(lote); Mockito.when(vacunaDatoLocal.obtenerVacuna(null)).thenReturn(vacuna); Mockito.doNothing().when(datoLocal).editarLote(lote); ln.editarLote(dtLote); Mockito.verify(datoLocal ,Mockito.times(1)).editarLote(lote); } @Test(expected = Exception.class) public void testEditarLoteException() throws Exception { Mockito.when(datoLocal.obtenerLotePorId(any(Long.class))).thenReturn(null); ln.editarLote(dtLote); } @Test public void testEliminarLote() throws Exception { Mockito.when(datoLocal.obtenerLotePorId(any(Long.class))).thenReturn(lote); Mockito.doNothing().when(datoLocal).eliminarLote(lote); ln.eliminarLote(dtLote); Mockito.verify(datoLocal ,Mockito.times(1)).eliminarLote(lote); } @Test(expected = Exception.class) public void testEliminarLoteException() throws Exception { Mockito.when(datoLocal.obtenerLotePorId(any(Long.class))).thenReturn(null); ln.eliminarLote(dtLote); } } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTVacunatorioVacunador.java package datatypes; import java.time.LocalDate; import java.util.List; import datatypes.DTVacunador; import datatypes.DTVacunatorio; import entidades.VacunatorioVacunador; public class DTVacunatorioVacunador { public DTVacunatorioVacunador() { // TODO Auto-generated constructor stub } private DTVacunatorio dtVacunatorio; private List<DTVacunador> dtVacunador; public DTVacunatorioVacunador(DTVacunatorio dtVacunatorio, List<DTVacunador> dtVacunador) { super(); this.dtVacunatorio = dtVacunatorio; this.dtVacunador = dtVacunador; } public DTVacunatorioVacunador(VacunatorioVacunador vacunatorioVacunador) { this.dtVacunatorio = new DTVacunatorio(vacunatorioVacunador.getVacunatorio()); } public DTVacunatorio getDtVacunatorio() { return dtVacunatorio; } public void setDtVacunatorio(DTVacunatorio dtVacunatorio) { this.dtVacunatorio = dtVacunatorio; } public List<DTVacunador> getDtVacunador() { return dtVacunador; } public void setDtVacunador(List<DTVacunador> dtVacunador) { this.dtVacunador = dtVacunador; } } <file_sep>/comp-cent-ejb/src/main/java/datos/UsuarioDatoLocal.java package datos; import javax.ejb.Local; import entidades.Usuario; @Local public interface UsuarioDatoLocal { public Boolean existeUsuario(int ci); public Usuario obtenerUsuarioPorCI(int ci); public void eliminarUsuario(int ci); public void editarUsuario(Usuario usuario); } <file_sep>/comp-cent-ejb/src/main/java/negocio/UsuarioNegocio.java package negocio; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.xml.bind.DatatypeConverter; import datatypes.DTAdministrador; import datatypes.DTAutoridad; import datatypes.DTCiudadano; import datatypes.DTContrasenia; import datatypes.DTVacunador; import datos.AdministradorDatoLocal; import datos.AutoridadDatoLocal; import datos.CiudadanoDatoLocal; import datos.UsuarioDatoLocal; import datos.VacunadorDatoLocal; import entidades.Usuario; import entidades.Vacunador; import entidades.Ciudadano; import entidades.Administrador; import entidades.Autoridad; /** * Session Bean implementation class UsuarioNegocio */ @Stateless @LocalBean public class UsuarioNegocio implements UsuarioNegocioLocal { @EJB private AutoridadDatoLocal autoridadDato; @EJB private AdministradorDatoLocal administradorDato; @EJB private CiudadanoDatoLocal ciudadanoDato; @EJB private UsuarioDatoLocal usuarioDato; @EJB private VacunadorDatoLocal vacunadorDato; public UsuarioNegocio() { // TODO Auto-generated constructor stub } @Override public void registrarUsuario(Usuario user) throws Exception { if (!usuarioDato.existeUsuario(user.getCi())) { if((user instanceof Autoridad)){ Autoridad aut = (Autoridad)user; try { aut.setContrasenia(hashPassword(aut.getContrasenia())); autoridadDato.guardarAutoridad(aut); } catch (NoSuchAlgorithmException e2) { throw new Exception("\nOcurrio un error interno, vuelva a intentar"); } } else { Administrador admin = (Administrador)user; try { admin.setContrasenia(hashPassword(admin.getContrasenia())); administradorDato.guardarAdministrador(admin); } catch (NoSuchAlgorithmException e2) { throw new Exception("\nOcurrio un error interno, vuelva a intentar"); } } }else { throw new Exception("\nYa existe un usuario para la cedula ingresada"); } } /* AUXILIAR */ private String hashPassword(String clave) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(clave.getBytes()); byte[] digest = md.digest(); String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); return myHash; } @Override public void actualizarDatos(Usuario user) throws Exception { if (usuarioDato.existeUsuario(user.getCi())) { if((user instanceof Autoridad)){ autoridadDato.editarAutoridad((Autoridad)user); } else if ((user instanceof Administrador )) { administradorDato.editarAdministrador((Administrador)user); } else { ciudadanoDato.editarCiudadano((Ciudadano)user); } }else { throw new Exception("\nNo se encontro un usuario con la cedula ingresado"); } } @Override public List<DTCiudadano> mostrarCiudadanos(){ List<Ciudadano> ciudadanos = ciudadanoDato.obtenerCiudadanos(); List<DTCiudadano> lista = new ArrayList<DTCiudadano>(); for(Ciudadano c : ciudadanos) { DTCiudadano dtCiudadano = new DTCiudadano(c); lista.add(dtCiudadano); } return lista; } @Override public boolean autenticarUsuario (int ci, String pass) { try { if (administradorDato.obtenerAdministradorPorCI(ci) != null ) return administradorDato.obtenerAdministradorPorCI(ci).getContrasenia().equals(hashPassword(pass)); //return administradorDato.obtenerAdministradorPorCI(ci).getContrasenia().equals(pass); else if (autoridadDato.obtenerAutoridadPorCI(ci) != null) return autoridadDato.obtenerAutoridadPorCI(ci).getContrasenia().equals(hashPassword(pass)); //return autoridadDato.obtenerAutoridadPorCI(ci).getContrasenia().equals(pass); else return false; /* El usuario no existe en la base de datos */ }catch (Exception e) { System.out.println("ERROR: No se pudo obtener el hash MD5 para la password."); return false; } } @Override public List<DTAdministrador> mostrarAdministradores(){ List<Administrador> administradores = administradorDato.obtenerAdministradores(); List<DTAdministrador> lista = new ArrayList<DTAdministrador>(); for(Administrador a : administradores) { DTAdministrador dtAdministrador = new DTAdministrador(a); lista.add(dtAdministrador); } return lista; } @Override public List<DTVacunador> mostrarVacunadores() { List<Vacunador> vacunadores = vacunadorDato.obtenerVacunadores(); List<DTVacunador> lista = new ArrayList<DTVacunador>(); for(Vacunador a : vacunadores) { DTVacunador dtVacunador = new DTVacunador(a); lista.add(dtVacunador); } return lista; } @Override public DTVacunador obtenerVacunador(int cedula) throws Exception { Vacunador vac = vacunadorDato.obteneVacunadorPorCI(cedula); if (vac == null) { throw new Exception("\nNo se encontro un usuario con la cedula ingresado"); } else { DTVacunador dtVac = new DTVacunador(vac); return dtVac; } } @Override public List<DTAutoridad> mostrarAutoridades() { List<Autoridad> autoridades = autoridadDato.obtenerAutoridades(); List<DTAutoridad> lista = new ArrayList<DTAutoridad>(); for(Autoridad a : autoridades) { DTAutoridad dtAutoridad = new DTAutoridad(a); lista.add(dtAutoridad); } return lista; } @Override public DTAdministrador obtenerAdministrador(int cedula) throws Exception { Administrador admin = administradorDato.obtenerAdministradorPorCI(cedula); if (admin == null) { throw new Exception("\nNo se encontro un usuario con la cedula ingresado"); } else { DTAdministrador dtAdmin = new DTAdministrador(admin); return dtAdmin; } } @Override public DTAutoridad obtenerAutoridad(int cedula) throws Exception { Autoridad aut = autoridadDato.obtenerAutoridadPorCI(cedula); if (aut == null) { throw new Exception("\nNo se encontro un usuario con la cedula ingresado"); } else { DTAutoridad dtAut = new DTAutoridad(aut); return dtAut; } } @Override public void eliminarUsuario(int cedula) throws Exception { if (usuarioDato.existeUsuario(cedula)) { usuarioDato.eliminarUsuario(cedula); }else { throw new Exception("\nNo se encontro un usuario con la cedula ingresado"); } } @Override public void editarContraseniaUsuario (DTContrasenia editarContrasenia) throws Exception { if (usuarioDato.existeUsuario(editarContrasenia.getCi())) { Usuario user = usuarioDato.obtenerUsuarioPorCI(editarContrasenia.getCi()); try { user.setContrasenia(hashPassword(editarContrasenia.getContrasenia())); usuarioDato.editarUsuario(user); } catch (NoSuchAlgorithmException e2) { throw new Exception("\nOcurrio un error interno, vuelva a intentar"); } }else { throw new Exception("\nNo se encontro un usuario con la cedula ingresada"); } } } <file_sep>/comp-cent-ejb/src/main/java/datatypes/DTAgenda.java package datatypes; import java.util.ArrayList; import java.util.List; import entidades.Agenda; import entidades.PlanVacunacion; public class DTAgenda { private long id; //private Vacunatorio vacunatorio; //private Plan plan; private String inicio; private String fin; private int horaInicio; private int horaFin; private DTVacunatorio dtVacunatorio; private List<DTPlanVacunacion> listDtPlanVacunacion; private String fechaAsignado; public DTAgenda() { super(); } public DTVacunatorio getDtVacunatorio() { return dtVacunatorio; } public void setDtVacunatorio(DTVacunatorio dtVacunatorio) { this.dtVacunatorio = dtVacunatorio; } public List<DTPlanVacunacion> getListDtPlanVacunacion() { return listDtPlanVacunacion; } public void setListDtPlanVacunacion(List<DTPlanVacunacion> listDtPlanVacunacion) { this.listDtPlanVacunacion = listDtPlanVacunacion; } public DTAgenda(long id, String inicio, String fin, int horaInicio, int horaFin) { super(); this.id = id; this.inicio = inicio; this.fin = fin; this.horaInicio = horaInicio; this.horaFin = horaFin; } public DTAgenda(Agenda agenda) { super(); this.id = agenda.getId(); this.horaInicio = agenda.getHoraInicio(); this.horaFin = agenda.getHoraFin(); this.dtVacunatorio = new DTVacunatorio(agenda.getVacunatorio().getNombre(),agenda.getVacunatorio().getCodigo()); this.inicio = agenda.getInicio().toString(); this.fin = agenda.getFin().toString(); this.listDtPlanVacunacion = new ArrayList<DTPlanVacunacion>(); for (PlanVacunacion planes : agenda.getPlanes()) { DTPlanVacunacion plan = new DTPlanVacunacion(planes); plan.setEnfermedad(new DTEnfermedad(planes.getEnfermedad())); this.listDtPlanVacunacion.add(plan); } } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getInicio() { return inicio; } public void setInicio(String inicio) { this.inicio = inicio; } public String getFin() { return fin; } public void setFin(String fin) { this.fin = fin; } public int getHoraInicio() { return horaInicio; } public void setHoraInicio(int horaInicio) { this.horaInicio = horaInicio; } public int getHoraFin() { return horaFin; } public void setHoraFin(int horaFin) { this.horaFin = horaFin; } public String getFechaAsignado() { return fechaAsignado; } public void setFechaAsignado(String fechaAsignado) { this.fechaAsignado = fechaAsignado; } @Override public String toString() { return "DTAgenda [id=" + id + ", inicio=" + inicio + ", fin=" + fin + ", horaInicio=" + horaInicio + ", horaFin=" + horaFin + ", dtVacunatorio=" + dtVacunatorio + ", listDtPlanVacunacion=" + listDtPlanVacunacion + "]"; } } <file_sep>/comp-cent-ejb/src/main/java/datos/VacunadorDato.java package datos; import java.util.ArrayList; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import entidades.Usuario; import entidades.Vacunador; /** * Session Bean implementation class VacunadorDato */ @Stateless @LocalBean public class VacunadorDato implements VacunadorDatoLocal { @PersistenceContext(name = "comp-centPersistenceUnit") private EntityManager em; /** * Default constructor. */ public VacunadorDato() { // TODO Auto-generated constructor stub } @Override public void guardarVacunador(Vacunador vacunador) { em.persist(vacunador); } @Override public void editarVacunador(Vacunador vacunador) { em.merge(vacunador); } @Override public List<Vacunador> obtenerVacunadores() { return em.createQuery("SELECT r FROM Vacunador r", Vacunador.class).getResultList(); } @Override public Vacunador obteneVacunadorPorCI(int ci) { return em.find(Vacunador.class, ci); } @Override public List<Vacunador> obtenerVacunadoresLibres() { // TODO Auto-generated method stub List<Vacunador> vacunadores = em.createQuery("SELECT v FROM Vacunador v WHERE v.ci not in (SELECT vv.vacunador.ci FROM VacunatorioVacunador vv)", Vacunador.class).getResultList(); return vacunadores; } } <file_sep>/comp-cent-ejb/src/main/java/entidades/Proveedor.java package entidades; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import datatypes.DTProveedor; @Entity public class Proveedor { @Id @GeneratedValue private long id; private String nombre; private int telefono; @OneToMany(mappedBy="proveedor",cascade=CascadeType.ALL,orphanRemoval=true) private List<Vacuna> vacunas = new ArrayList<>(); public Proveedor() { // TODO Auto-generated constructor stub } public Proveedor(DTProveedor proveedor) { super(); this.nombre = proveedor.getNombre(); this.telefono = proveedor.getTelefono(); } public Proveedor(String nombre, int tel) { super(); this.nombre = nombre; this.telefono = tel; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getTelefono() { return telefono; } public void setTelefono(int telefono) { this.telefono = telefono; } public List<Vacuna> getVacunas() { return vacunas; } public void setVacunas(List<Vacuna> vacunas) { this.vacunas = vacunas; } /* Esto no se si está teóricamente correcto */ public void agregarVacuna(Vacuna vacuna) { vacunas.add(vacuna); vacuna.setProveedor(this); } public void eliminarVacuna(Vacuna vacuna) { vacunas.remove(vacuna); vacuna.setProveedor(null); } } <file_sep>/comp-cent-web/src/main/java/beans/LoginBean.java package beans; import java.io.IOException; import java.io.Serializable; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import entidades.Usuario; import negocio.AdministradorNegocioLocal; import negocio.AutoridadNegocioLocal; import negocio.SessionBeanLocal; @Named("loginBean") @SessionScoped public class LoginBean implements Serializable { private static final long serialVersionUID = 1L; @EJB private SessionBeanLocal sessionBeanLocal; @EJB private AdministradorNegocioLocal administradorLocal; @EJB private AutoridadNegocioLocal autoridadLocal; private int ci; public int getCi() { return ci; } public void setCi(int ci) { this.ci = ci; } private String contrasenia; private String mensaje; private String sessionToken; private String url; private Usuario currentUser; private static HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); public LoginBean() { // TODO Auto-generated constructor stub } public String getContrasenia() { return contrasenia; } public void setContrasenia(String contrasenia) { this.contrasenia = contrasenia; } public String getMensaje() { return mensaje; } public void setMensaje(String mensaje) { this.mensaje = mensaje; } public String getSessionToken() { return sessionToken; } public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String login() { // FacesContext fc = FacesContext.getCurrentInstance(); // ExternalContext ec = fc.getExternalContext(); // // // try { // ec.redirect(url); // } catch (IOException ex) { // Logger.getLogger(Navigation.class.getName()).log(Level.SEVERE, null, ex); // } // boolean res = sessionBeanLocal.iniciarSesion(ci, contrasenia); String redirect = ""; if (res) { if (administradorLocal.obtenerAdministradorPorCi(ci)!=null) { currentUser = administradorLocal.obtenerAdministradorPorCi(ci); redirect ="/administrador/home?faces-redirect=true"; }else if(autoridadLocal.obtenerAutoridadPorCi(ci)!= null) { currentUser = autoridadLocal.obtenerAutoridadPorCi(ci); redirect ="/autoridad/home?faces-redirect=true"; } // guardo el usuario logueado en sesión session.setAttribute("currentUser", currentUser); // System.out.println("usuario y contraseña Correcta"); return redirect; } else { this.mensaje = "Usuario inexistente o las credenciales son incorrectas."; System.out.println("no se pudo entrar al login"); return "login?faces-redirect=true"; } } public String logout() { currentUser = null; session.removeAttribute("currentUser"); HttpServletRequest origRequest = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); String redirectUri = "login.xhtml"; if (origRequest.getRequestURI().contains("administrador") || origRequest.getRequestURI().contains("autoridad")) redirectUri = "../"+redirectUri; try { FacesContext.getCurrentInstance().getExternalContext().redirect(redirectUri); FacesContext.getCurrentInstance().responseComplete(); return "login"; } catch (IOException e) { //e.printStackTrace(); return "login"; } } } <file_sep>/comp-cent-ejb/src/main/java/entidades/Lote.java package entidades; import java.time.LocalDate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import datatypes.DTLote; @Entity public class Lote { @Id @GeneratedValue private long id; private String nombre; private int cantVacunas; private LocalDate fechaCreado; @ManyToOne private Vacuna vacuna; public Lote() { super(); // TODO Auto-generated constructor stub } public Lote(DTLote lote) { super(); this.nombre = lote.getNombre(); this.cantVacunas = lote.getCantVacunas(); this.fechaCreado = LocalDate.parse(lote.getFechaCreado()); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public LocalDate getFechaCreado() { return fechaCreado; } public void setFechaCreado(LocalDate fechaCreado) { this.fechaCreado = fechaCreado; } public Vacuna getVacuna() { return vacuna; } public void setVacuna(Vacuna vacuna) { this.vacuna = vacuna; } public int getCantVacunas() { return cantVacunas; } public void setCantVacunas(int cantVacunas) { this.cantVacunas = cantVacunas; } } <file_sep>/comp-cent-ejb/src/main/java/entidades/Vacunador.java package entidades; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import datatypes.DTVacunador; @Entity @DiscriminatorValue("vacunador") public class Vacunador extends Usuario { public Vacunador() { super(); // TODO Auto-generated constructor stub } public Vacunador(int ci, String primerNombre, String segundoNombre, String primerApellido, String segundoApellido, int telefono, String email) { super(ci, primerNombre, segundoNombre, primerApellido, segundoApellido, telefono, email); // TODO Auto-generated constructor stub } } <file_sep>/comp-cent-ejb/src/main/java/entidades/Vacunatorio.java package entidades; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import datatypes.DTVacunatorio; @Entity public class Vacunatorio { @Id @GeneratedValue private long id; private String nombre; private int cantidadPuestos; private String codigo; private String dominio; @OneToOne(mappedBy="vacunatorio", cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.LAZY) private Ubicacion ubicacion; @OneToMany(mappedBy="vacunatorio",cascade=CascadeType.ALL,orphanRemoval=true) private List<Agenda> agendas; public Vacunatorio() { super(); // TODO Auto-generated constructor stub } public Vacunatorio(DTVacunatorio vacunatorio) { super(); this.nombre = vacunatorio.getNombre(); this.codigo = vacunatorio.getCodigo(); this.cantidadPuestos = vacunatorio.getCantidadPuestos(); this.dominio = vacunatorio.getDominio(); } public Vacunatorio(String nombre, String codigo, int cantPuestos, String dominio) { super(); this.nombre = nombre; this.codigo = codigo; this.cantidadPuestos= cantPuestos; this.dominio = dominio; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public Ubicacion getUbicacion() { return ubicacion; } public void setUbicacion(Ubicacion ubicacion) { this.ubicacion = ubicacion; } public List<Agenda> getAgendas() { return agendas; } public void setAgendas(List<Agenda> agendas) { this.agendas = agendas; } public String getDominio() { return dominio; } public void setDominio(String dominio) { this.dominio = dominio; } public int getCantidadPuestos() { return cantidadPuestos; } public void setCantidadPuestos(int cantidadPuestos) { this.cantidadPuestos = cantidadPuestos; } public void agregarUbicacion(Ubicacion ub) { ub.setVacunatorio(this); this.ubicacion = ub; } public void eliminarUbicacion() { if(ubicacion!=null) { ubicacion.setVacunatorio(null); this.ubicacion=null; } } public void agregarAgenda(Agenda agenda) { agendas.add(agenda); agenda.setVacunatorio(this); } public void eliminarAgenda(Agenda agenda) { agendas.remove(agenda); agenda.setVacunatorio(null); } } <file_sep>/comp-cent-ejb/src/main/java/datos/UbicacionDatoLocal.java package datos; import javax.ejb.Local; import entidades.Ubicacion; @Local public interface UbicacionDatoLocal { public Ubicacion obtenerUbicacionPorId(long id); public void actualizarVacunatorio(Ubicacion ubi); public Ubicacion obtenerUbicacionVacunatorio(long id); public void eliminarVacunatorio(long id); }
019f6a2d49a7bfafc72a1728a74ed009f8a212ff
[ "Java", "SQL" ]
79
Java
TaricaTarica/vacunasuy-backend
7944d658b493007444230b708fca02d532aa8dc4
0605398e4a8f7f7a2fb7551672c5c5c6f5a59765
refs/heads/master
<repo_name>thankslana/the_sixth_redrock_homework<file_sep>/接口文档.md 请求url:http://localhost:8888/ 参数:username,password username:用户名 password用户密码 请求方式:Post 注册成功返回登录界面 登陆成功自动进入成功界面,自动跳转进入小x网,手动点击进入普通页面 失败返回fail<file_sep>/src/RegisterServlet.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; public RegisterServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPut(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); int id=Integer.valueOf(request.getParameter("id")); String name=request.getParameter("name"); String password=<PASSWORD>.getParameter("password"); int role=Integer.valueOf(request.getParameter("role")); User user=new User(); user.setId(id); user.setName(name); user.setPassword(<PASSWORD>); user.setRole(role); UserDAO userDAO=new UserDAO(); userDAO.addUser(user); System.out.println("注册成功!!!"); request.getRequestDispatcher("Login.jsp").forward(request, response); } } <file_sep>/逻辑分析.md 逻辑分析 注册时用户填表单->传给服务器执行servlet逻辑,存入我的数据库->注册成功客户端跳转至登录界面,用户输入登录信息->提交给servlet逻辑,进行数据库校验->根据数据库记录响应跳转至相应的页面
1c0705ed8c1caf71544be42c6b15648245732401
[ "Markdown", "Java" ]
3
Markdown
thankslana/the_sixth_redrock_homework
261e966653699ea616de24116429080210a62efc
25a267fe43e68789ddcd97015e4af721afb2a5b6
refs/heads/master
<file_sep># Header 1 @cirosantilli <file_sep>This repo is only for testing how Github works. # markdown tests # h1 ## h2 ### h3 #### h4 ## 012 UPERCASE underline_hyphen-spaces others%%%end new line <file_sep>def f(x) return x + 1 end
0e43b8ad5043d91322c497a7b81c207244fd6dbd
[ "Markdown", "Ruby" ]
3
Markdown
cirosantilli-puppet/test
7a4b6e436a365cecd9591dbaa1934dfe2c278bf0
ecc9050baf454ef9ae09144497f74b4dd7b409d1
HEAD
<repo_name>ushis/silo<file_sep>/app/reports/application_report.rb require 'prawn' # The ApplicationReport is parent class of all reports. It intializes the # prawn document and sets the global content and style. class ApplicationReport < Prawn::Document include AbstractController::Translation attr_reader :title # Initializes the Document and sets the title. def initialize(record, user, options = {}) options[:page_size] = [595.28, 841.86] if options.delete(:layout) == :landscape options[:page_size].reverse! end super(options) @width = options[:page_size].first @height = options[:page_size].last @record = record @model = record.class @title = record.to_s head(user.full_name) h1 @title end # Builds the page head. def head(name) font 'Helvetica', size: 9 stroke_color 'd0d0d0' bounding_box [0, (y - 30)], width: (@width - 72) do text "#{name} - #{l(Time.now, format: :long)}", size: 9 stroke { line(bounds.bottom_left, bounds.bottom_right) } end gap 22 end # Adds a first level headline. def h1(content) text content, size: 20, style: :bold gap 10 end # Adds a second level headline to the report. def h2(content, is_attr = true) content = @model.human_attribute_name(content) if is_attr text content, size: 12, style: :bold gap 10 end # Adds a first level headline. def h3(content) text content, size: 10, style: :bold gap 10 end # Adds an indeted text. def p(content) indent(5) { text content } end # Moves the cursor down. def gap(len = 16) move_down len end # Sets some default table options. def table(data, options = {}) settings = { cell_style: { borders: [], padding: 5 } }.merge(options) super(data, settings) do |table| table.width = @width - 72 table.row_colors = ['f6f6f6', 'ffffff'] yield(table) if block_given? end end # Builds a info table for a record. def info_table(record = @record) model = record.class data = model.exposable_attributes(:pdf, human: true).map do |attr, method| [model.human_attribute_name(attr), record.send(method).to_s] end table data gap end # Builds a contact table. def contacts_table(record = @record) data = Contact::FIELDS.map do |field| values = record.contact.send(field) [t(field, scope: [:values, :contacts]), values.join(', ')] end table data gap end # Builds a comment. def comment h2 :comment p @record.comment.blank? ? '-' : @record.comment.to_s gap end end <file_sep>/spec/models/expert_spec.rb require 'spec_helper' describe Expert do include AttachmentSpecHelper describe :validations do it { should validate_presence_of(:name) } end describe :associations do it { should have_and_belong_to_many(:languages) } it { should have_many(:attachments).dependent(:destroy) } it { should have_many(:addresses).dependent(:destroy) } it { should have_many(:list_items).dependent(:destroy) } it { should have_many(:lists).through(:list_items) } it { should have_many(:cvs).dependent(:destroy) } it { should have_many(:project_members).dependent(:destroy) } it { should have_many(:projects).through(:project_members) } it { should have_one(:contact).dependent(:destroy) } it { should have_one(:comment).dependent(:destroy) } it { should belong_to(:user) } it { should belong_to(:country) } end describe :full_name do subject { build(:expert, prename: 'John', name: 'Doe').full_name } it 'should be a combination of prename and name' do expect(subject).to eq('<NAME>') end end describe :full_name_with_degree do subject do build(:expert, prename: 'John', name: 'Doe', degree: degree).full_name_with_degree end context 'with a degree' do let(:degree) { 'Ph.D.' } it 'should be a combination of prename, name and degree' do expect(subject).to eq('<NAME>, Ph.D.') end end context 'without a degree' do let(:degree) { nil } it 'should be the full name' do expect(subject).to eq('<NAME>') end end end describe :former_collaboration do it 'should be false by default' do expect(subject.former_collaboration).to be_false end end describe 'human_former_collaboration' do subject do build(:expert, former_collaboration: value).human_former_collaboration end context 'when it is false' do let(:value) { false } it 'should be the translated string for false' do expect(subject).to eq(I18n.t('values.boolean.false')) end end context 'when it is true' do let(:value) { true } it 'should be the translated string for true' do expect(subject).to eq(I18n.t('values.boolean.true')) end end end describe :human_birthday do subject do build(:expert, birthday: Date.new) end it 'should be the short localized date' do expect(subject.human_birthday).to eq(I18n.l(subject.birthday, format: :short)) end context 'when argument is :long' do it 'should be the long localized date' do expect(subject.human_birthday(:long)).to eq(I18n.l(subject.birthday, format: :long)) end end end describe :age do subject { build(:expert, birthday: birthday).age } context 'when birthday is nill' do let(:birthday) { nil } it 'should be nil' do expect(subject).to be_nil end end context 'when expert is 24' do let(:birthday) { 24.years.ago.utc.to_date } it 'should be 24' do expect(subject).to eq(24) end end context 'when expert is 23' do let(:birthday) { 24.years.ago + 1.day } it 'should be 23' do expect(subject).to eq(23) end end end describe :to_s do subject { build(:expert, name: name, prename: prename).to_s } let(:name) { 'Walter' } let(:prename) { 'Bill' } it 'should be a combination of last name, first name' do expect(subject).to eq('<NAME>') end context 'without a first name' do let(:prename) { nil } it 'should be the last name' do expect(subject).to eq('Walter') end end context 'without a last name' do let(:name) { nil } it 'should be the first name' do expect(subject).to eq('Bill') end end context 'without any name' do let(:name) { nil } let(:prename) { nil } it 'should be empty' do expect(subject).to be_empty end end end end <file_sep>/app/searchers/partner_searcher.rb # Searches the partners table and its associations. class PartnerSearcher < ApplicationSearcher search_helpers :company, :q protected # Searches the company attribute. def company(company) @scope.where('company LIKE ?', "%#{company}%") end # Performs a fuzzy search. def q(query) search_ids(search_fuzzy(query)) end private # Executes the fuzzy search. # # Returns an array of partner ids. def search_fuzzy(query) execute_sql(<<-SQL, q: query, like: "%#{query}%").map(&:first) ( SELECT partners.id FROM partners WHERE partners.street LIKE :like OR partners.zip LIKE :like OR partners.city LIKE :like OR partners.region LIKE :like ) UNION ( SELECT employees.partner_id FROM employees WHERE employees.prename LIKE :like OR employees.name LIKE :like ) UNION ( SELECT advisers_partners.partner_id FROM advisers_partners JOIN advisers ON advisers.id = advisers_partners.adviser_id WHERE advisers.adviser LIKE :like ) UNION ( SELECT comments.commentable_id FROM comments WHERE comments.commentable_type = 'Partner' AND MATCH (comments.comment) AGAINST (:q) ) UNION ( SELECT descriptions.describable_id FROM descriptions WHERE descriptions.describable_type = 'Partner' AND MATCH (descriptions.description) AGAINST (:q) ) SQL end end <file_sep>/app/controllers/ajax/attachments_controller.rb # The Ajax::AttachmentsController handles Attachment specific AJAX requests. class Ajax::AttachmentsController < Ajax::ApplicationController respond_to :html, only: [:new] caches_action :new # Serves an empty attachment form. def new @attachment = Attachment.new @url = { controller: '/attachments', action: :create } end end <file_sep>/app/helpers/project_helper.rb # Provides project specific helpers. module ProjectHelper # Returns a string containing links to the CV downloads. def list_infos(project, html_options = {}) project.infos.inject('') do |html, info| html << link_to(info.language, project_path(project, info.language), html_options) end.html_safe end # Returns a select tag with all available languages of the project. def project_info_selector(info, html_options = {}) html_options = html_options.merge({ 'data-selector' => project_path(info.project, ':lang') }) options = options_from_collection_for_select(info.project.infos, :language, :human_language, info.language) select_tag(:lang, options, html_options) end # Returns a select tag with project languages. def project_form_selector(info, html_options = {}) path = info.project.try(:id) ? edit_project_path(info.project, ':lang') : new_project_path(':lang') html_options = html_options.merge({'data-selector' => path}) options = options_for_select(ProjectInfo.language_values, info.language) select_tag(:lang, options, html_options) end # def project_form_action_path(project, info) if project.persisted? project_path(project, info.language) else projects_path end end end <file_sep>/public/500.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"/> <link href="/errors.css" media="all" rel="stylesheet" type="text/css" /> <title>500 | silo</title> </head> <body> <div id="error"> <div id="msg"> <div id="type"> <p> 500 </p> </div> <div id="descr"> <p> A server sided error occured. <br/> Please try again later. </p> </div> <a href="/">Want to go back to the start page?</a> </div> </div> </body> </html> <file_sep>/lib/tasks/experts.rake require 'carmen' require 'colorize' require 'psych' namespace :experts do task :import, [:input, :output] => [:environment] do |task, args| countries = nil File.open(File.expand_path('../countries.yml', __FILE__)) do |f| countries = Psych.load(f.read).fetch('countries') end countries.each { |c, code| countries[c] = Carmen::Country.coded(code) } country_from_s = lambda do |s| c = s.split('/')[0].gsub(/!|\?/, '').strip.titleize unless (co = countries[c]) || (co = Carmen::Country.named(c)) puts "Country Code for: \"#{c}\"" begin code = STDIN.gets.chomp end while ! (co = Carmen::Country.coded(code)) countries[c] = co end Country.find_by_country(co.code) end puts "Importing experts data from XML file: #{args[:input]}" File.open(args[:input]) do |f| user = User.first output = File.open(args[:output], 'w') experts = Hash.from_xml(f.read)['dataroot']['Adressen'] len, err = [experts.length, 0] experts.each_with_index do |data, i| $stdout.write("Importing: #{i}/#{len}\r") e = Expert.new e.user = user # Base data e.name = data.fetch('Name', '').strip prename = "#{data.fetch('Vorname1', '')} #{data.fetch('Vorname2', '')}" e.prename = prename.split(/\s+/).join(' ').strip if data['m'] == '1' e.gender = :male else e.gender = :female end e.birthday = data['Geburtsdatum'].try(:to_datetime) || nil e.degree = data.fetch('Titel', '').strip # Job job = data['FirmaT'].try(:strip) company = ['Firma1', 'Firma2'].collect do |f| data[f].try(:strip) || '' end.join(' ').strip if job.blank? e.job = company elsif company.blank? e.job = job else e.job = [job, company].join(' - ') end # Citizenship if (c = data['Staatsb']) e.country = country_from_s.call(c) end # Contact data e.contact.m_phones << data['Handy'] if data['Handy'] e.contact.p_phones << data['TelefonP'] if data['TelefonP'] e.contact.b_phones << data['TelefonD'] if data['TelefonD'] if (email = data['E_Mail']) unless (parts = email.strip.split(/\s+|#/)).empty? e.contact.emails << parts[0] end end # First address if ['Stra', 'Wohnort'].any? { |v| ! data[v].blank? } address = Address.new address.address = [data['Stra'], data['Wohnort']].delete_if do |f| f.blank? end.join("\n") if (c = data['Land']) address.country = country_from_s.call(c) end e.addresses << address end # Comment unless (comment = data['Bemerkung']).blank? e.comment = Comment.new(comment: comment) end # Yay! if e.save output.puts "#{data['Index']}:#{e.id}" else $stderr.puts '=> Could not save dataset.'.red err += 1 e.errors.each do |attr, msg| $stderr.puts "===> #{Expert.human_attribute_name(attr)}: #{msg}".yellow end end end output.close puts "Imported #{len - err}/#{len} experts." puts "Wrote index shifts to: #{output.path}" end end end <file_sep>/spec/lib/active_record_helpers_spec.rb require 'spec_helper' describe ActiveRecordHelpers do before(:all) do build_model :active_record_helpers_dummy do belongs_to :category has_one :author has_many :comments has_and_belongs_to_many :tags end end describe :filter_associations do subject { ActiveRecordHelpersDummy.filter_associations(fields) } context 'with a bunch of fields' do let(:fields) { [:category, :title, :body, :tags] } it 'should filter the associations' do expect(subject).to match_array([:category, :tags]) end end context 'with stringified fields' do let(:fields) { %w(author body comments tags) } it 'should filter the associations' do expect(subject).to match_array([:author, :comments, :tags]) end end end describe :association? do subject { ActiveRecordHelpersDummy.association?(value) } context 'when value is no association' do let(:value) { :title } it { should be_false } end context 'when value is a association' do let(:value) { :tags } it { should be_true } end context 'when value is a stringified association' do let(:value) { 'comments' } it { should be_true} end end describe :belongs_to? do subject { ActiveRecordHelpersDummy.belongs_to?(value) } context 'when value is no association' do let(:value) { :title } it { should be_false } end context 'when value is no belongs_to association' do let(:value) { :author } it { should be_false } end context 'when value is a belongs_to association' do let(:value) { :category } it { should be_true } end context 'when value is a stringified belongs_to association' do let(:value) { 'category' } it { should be_true } end end describe :has_one? do subject { ActiveRecordHelpersDummy.has_one?(value) } context 'when value is no association' do let(:value) { :title } it { should be_false } end context 'when value is no has_one association' do let(:value) { :category } it { should be_false } end context 'when value is a has_one association' do let(:value) { :author } it { should be_true } end context 'when value is a stringified has_one association' do let(:value) { 'author' } it { should be_true } end end describe :has_many? do subject { ActiveRecordHelpersDummy.has_many?(value) } context 'when value is no association' do let(:value) { :title } it { should be_false } end context 'when value is no has_many association' do let(:value) { :tags } it { should be_false } end context 'when value is a has_many association' do let(:value) { :comments } it { should be_true } end context 'when value is a stringified has_many association' do let(:value) { 'comments' } it { should be_true } end end describe :has_and_belongs_to_many? do subject { ActiveRecordHelpersDummy.has_and_belongs_to_many?(value) } context 'when value is no association' do let(:value) { :title } it { should be_false } end context 'when value is no has_and_belongs_to_many association' do let(:value) { :comments } it { should be_false } end context 'when value is a has_and_belongs_to_many association' do let(:value) { :tags } it { should be_true } end context 'when value is a stringified has_and_belongs_to_many association' do let(:value) { 'tags' } it { should be_true } end end end <file_sep>/app/controllers/ajax/areas_controller.rb # The Ajax::AreasController is like the Ajax::LanguagesController for # areas/countries. class Ajax::AreasController < Ajax::ApplicationController caches_action :index # Serves a multi select box for countries grouped by areas. def index @areas = Area.with_ordered_countries respond_with(@areas) end end <file_sep>/spec/factories/project_info.rb require 'securerandom' FactoryGirl.define do factory :project_info do sequence(:title) { |_| SecureRandom.hex(16) } sequence(:language) { |_| ProjectInfo.languages.sample } trait :with_project do association :project, factory: :project end end end <file_sep>/app/models/country.rb # The Country model provides the ability to associate arbitrary models with # one or more countries. # # Database scheme: # # - *id* integer # - *area_id* integer # - *country* string class Country < ActiveRecord::Base attr_accessible :country, :area validates :country, presence: true, uniqueness: true has_many :addresses has_many :experts has_many :partners belongs_to :area # Polymorphic method to find a country. # # Country.find_country("GB") # #=> #<Country id: 77, country: "GB", area: "E2"> # # Returns nil, when no country is found. def self.find_country(country) country.is_a?(self) ? country : find_countries(country).first end # Finds countries by id or country code. # # Returns a ActiveRecord::Relation. def self.find_countries(query) where('countries.id IN (:q) OR countries.country IN (:q)', q: query) end # Returns the localized country name. def human I18n.t(country, scope: :countries) end alias :to_s :human end <file_sep>/app/sweepers/employee_sweeper.rb # Observes the Employee model for changes and expires the caches. class EmployeeSweeper < ActionController::Caching::Sweeper observe Employee # Expires the cache for the updated employee. def after_update(employee) expire_cache_for(employee) end # Expires the cache for destroyed employee. def after_destroy(employee) expire_cache_for(employee) end private # Expires the cache for the specified employee. def expire_cache_for(employee) key = "/ajax/partners/#{employee.partner.try(:id)}/employees/#{employee.id}/edit" I18n.available_locales.each do |locale| expire_fragment("#{locale}#{key}") end end end <file_sep>/spec/models/contact_spec.rb require 'spec_helper' describe Contact do describe :associations do it { should belong_to(:contactable) } end describe :callbacks do it 'should initialize contacts with an empty hash' do expect(subject.contacts).to eq({}) end it 'should remove blank elements before saving' do subject.emails.concat(['', ' ', '<EMAIL>', nil]) subject.save expect(subject.emails).to eq(['<EMAIL>']) end end describe :FIELDS do it 'should be an array of fields' do fields = ['emails', 'p_phones', 'b_phones', 'm_phones', 'skypes', 'websites', 'fax'] expect(Contact::FIELDS.to_a).to match_array(fields) end it 'should define a method for each field' do Contact::FIELDS.each do |field| expect(subject).to respond_to(field) expect(subject.send(field)).to be_a(Array) end end end describe :add do context 'when everything is fine' do it 'should be the array of values' do expect(subject.emails).to be_empty expect(subject.add(:emails, '<EMAIL>')).to match_array(['<EMAIL>']) expect(subject.add(:emails, '<EMAIL>')).to match_array(['<EMAIL>', '<EMAIL>']) end it 'should add the value to the contacts' do expect(subject.emails).to be_empty subject.add(:emails, '<EMAIL>') subject.add(:emails, '<EMAIL>') expect(subject.emails).to match_array(['<EMAIL>', '<EMAIL>']) end end context 'when contact already in the field' do# before(:each) { subject.emails << '<EMAIL>' } it 'should be false' do expect(subject.add(:emails, '<EMAIL>')).to be_false end it 'should not add the value to the contacts' do subject.add(:emails, '<EMAIL>') expect(subject.emails).to match_array(['<EMAIL>']) end end context 'when the value is blank' do it 'should be false' do expect(subject.add(:emails, ' ')).to be_false end it 'should not add the value to the contacts' do subject.add(:emails, ' ') expect(subject.emails).to be_empty end end context 'when the field is invalid' do it 'should be false' do expect(subject.add(:invalid, '<EMAIL>')).to be_false end end end describe :add! do context 'when everything is fine' do it 'should be true' do expect(subject.add!(:emails, '<EMAIL>')).to be_true end it 'should be saved' do expect(subject).to be_new_record subject.add!(:emails, '<EMAIL>') expect(subject).to be_persisted end end context 'when something is wrong' do it 'should be false' do expect(subject.add!(:emails, ' ')).to be_false end it 'should not be saved' do expect(subject).to be_new_record subject.add!(:invalid, '<EMAIL>') expect(subject).to be_new_record end end end describe :remove do context 'when everything is fine' do it 'should be the removed value' do subject.emails << '<EMAIL>' expect(subject.remove(:emails, '<EMAIL>')).to eq('<EMAIL>') end it 'should remove the value from the contacts' do subject.emails << '<EMAIL>' subject.remove(:emails, '<EMAIL>') expect(subject.emails).to be_empty end end context 'when the contact is missing' do it 'should be nil' do expect(subject.remove(:emails, '<EMAIL>')).to be_nil end end context 'when fiels is invalid' do it 'should be false' do expect(subject.remove(:invalid, '<EMAIL>')).to be_false end end end describe :remove! do context 'when everything is fine' do it 'should be true' do subject.emails << '<EMAIL>' expect(subject.remove!(:emails, '<EMAIL>')).to be_true end it 'should save the record' do expect(subject).to be_new_record subject.emails << '<EMAIL>' subject.remove!(:emails, '<EMAIL>') expect(subject).to be_persisted end end end describe :empty? do it 'should be true if there are no contacts' do expect(subject).to be_empty end it 'should be false if there is at least one contact' do contact = build(:contact_with_contacts) expect(contact).to_not be_empty end end end <file_sep>/app/controllers/ajax/addresses_controller.rb # The Ajax::AddressesController handles Address specific AJAX requests. class Ajax::AddressesController < Ajax::ApplicationController respond_to :html, only: [:new] caches_action :new # Serves an empty address form. def new @address = Address.new @url = { controller: '/addresses', action: :create } end end <file_sep>/spec/models/attachment_spec.rb require 'spec_helper' describe Attachment do include AttachmentSpecHelper describe :validations do [:filename, :original_filename].each do |attr| it { should validate_presence_of(attr) } end it { should validate_uniqueness_of(:filename) } end describe :associations do it { should belong_to(:attachable) } end describe :after_destroy do subject { Attachment.create!(file: fixture_file_upload('kittens.jpg')) } it 'should unlink the file' do expect(subject.absolute_path).to be_file expect { subject.destroy }.to change { count_files(Attachment::STORE) }.by(-1) expect(subject.absolute_path).to_not be_exist end end describe :DIRNAME do subject { Attachment::DIRNAME } it 'should be the dirname for the attachment store defined in the config' do expect(subject).to eq(@store.basename.to_s) end end describe :STORE do subject { Attachment::STORE } it 'should be the absolute path to the attachment store' do expect(subject).to eq(@store) end end describe :file= do context 'when valid file input' do let(:file) { fixture_file_upload('kittens.jpg') } it 'should store the file' do expect { subject.file = file }.to change { count_files(Attachment::STORE) }.by(1) expect(FileUtils.identical?(fixture_file_path('kittens.jpg'), subject.absolute_path)).to be_true end it 'should be valid' do subject.file = file expect(subject).to be_valid end it 'should detect the file extension' do subject.file = file expect(subject.ext).to eq('.jpg') end end context 'when invalid input file' do let(:file) { 'kittens.jpg' } it 'should raise a TypeError' do expect { subject.file = file }.to raise_error(TypeError) end end end describe :set_title do subject { build(:attachment, title: title, original_filename: 'xyz.pdf') } context 'when title is present' do let(:title) { 'something' } it 'should stay the same' do expect { subject.set_title }.to_not change { subject.title } end end context 'when title is blank' do let(:title) { nil } it 'should assign the original filename without extension' do subject.set_title expect(subject.title).to eq('xyz') end end end describe :ext do subject { build(:attachment, original_filename: original_filename).ext } context 'when original_filename has an extension' do let(:original_filename) { 'xyz.pdf' } it 'should be the extension of the original filename' do expect(subject).to eq('.pdf') end end context 'when original filename has no extension' do let(:original_filename) { 'some_file' } it 'should be blank' do expect(subject).to be_blank end end end describe :public_filename do subject { build(:attachment, params).public_filename } context 'when title has no extension' do let(:params) { { title: 'Sweet Document', original_filename: '123.pdf' } } it 'should be a safe combination of title and extension' do expect(subject).to eq('sweet-document.pdf') end end context 'when title has a file extension' do let(:params) { { title: 'index.html', original_filename: '123.html' } } it 'should remove the titles extension before making it safe' do expect(subject).to eq('index.html') end end end describe :absolute_path do subject { build(:attachment, filename: 'xyz.doc').absolute_path } it 'should be the absolute path to the stored file' do expect(subject).to eq(@store.join('xyz.doc')) end end end <file_sep>/app/controllers/login_controller.rb # The LoginController provides basic login/logout actions. class LoginController < ApplicationController layout 'login' skip_before_filter :authenticate, only: [:welcome, :login] skip_before_filter :authorize, only: [:welcome, :login, :logout] before_filter :forward, except: [:logout] # Forwards the user to the root url, if he/she is already logged in. def forward redirect_to root_url if current_user end # Serves a simple login form def welcome @title = t('labels.generic.welcome') end # Checks the users credentials and loggs he/she in, if they are correct. def login @title = t('labels.generic.welcome') @username = params[:username] user = User.find_by_username(@username) unless user.try(:authenticate, params[:password]) flash.now[:alert] = t('messages.user.errors.credentials') render :welcome and return end unless user.refresh_login_hash! flash.now[:alert] = t('messages.generics.errors.error') render :welcome and return end session[:login_hash] = user.login_hash redirect_to root_url end # Loggs out the user and renders the login form. def logout @title = t('labels.generic.welcome') @username = current_user.username session[:login_hash] = nil render :welcome end end <file_sep>/lib/acts_as_tag/acts_as_tag.rb module ActsAsTag module ActsAsTag extend ActiveSupport::Concern # Defines the magic methods ClassMethods#acts_as_tag # # See ActsAsTag for more info. module ClassMethods # Makes a model acting as a tag. def acts_as_tag(attribute_name) class_attribute :tag_attribute self.tag_attribute = attribute_name attr_accessible(attribute_name) default_scope(order(attribute_name)) validates(attribute_name, presence: true, uniqueness: true) extend ClassMethodsOnActivation include InstanceMethodsOnActivation end end # Mixes class methods into the model. module ClassMethodsOnActivation # Labels the model as a tag. def acts_as_tag? true end # Extracts tags from a string. # # Returns a collection of tag like objects. def from_s(s, delimiter = ',') tags = s.split(delimiter).inject({}) do |hsh, tag| tag.strip! hsh[tag.downcase] ||= tag unless tag.empty? hsh end tags.empty? ? [] : multi_find_or_initialize(tags.values) end # Finds or initialized multiple tags by tag attribute. # # Returns a collection of old and fresh tag like objects. def multi_find_or_initialize(tags) old_tags = where("LOWER(#{tag_attribute}) IN (?)", tags.map(&:downcase)) old_tags.each do |old_tag| tags.delete_if { |tag| tag.casecmp(old_tag.to_s) == 0 } end old_tags + tags.map { |tag| new(tag_attribute => tag) } end end # Mixes instance methods into the model. module InstanceMethodsOnActivation # Returns the tag attribute. def to_s send(tag_attribute).to_s end end end end ActiveRecord::Base.send :include, ActsAsTag::ActsAsTag <file_sep>/lib/exposable_attributes.rb # The ExposableAttributes module mixes the exposable_attributes method # into ActiveRecord. # # With exposable attributes it is possible to define read access for specific # profiles, such as PDF or CSV. # # They are defined with ExposableAttributes::ClassMethods#attr_exposable... # # class Post < ActiveRecord::Base # attr_exposable :title, :body, :published, as: :csv # # def human_published # I18n.translate published?.to_s, scope: [:values, :boolean] # end # end # # ...and can be retrieved with # ExposableAttributes::ClassMethods#exposable_attributes. # # The method handles some filter options. # # Post.exposable_attribtues(:csv) # #=> ["title", "body", "published"] # # Post.exposable_attributes(:csv, only: [:title, :user_id]) # #=> ["title"] # # Post.exposable_attributes(:csv, exclude: :body) # #=> ["title", "published"] # # Post.exposable_attributes(:csv, human: true, exclude: [:body]) # #=> [["title", "title"], ["published", "human_published"]] # # This is useful to filter attribute names from untrusted sources. # # attributes = Post.exposable_attributes(:csv, only: params[:attributes]) # # CSV::generate do |csv| # csv << attributes # # category.posts.each do |post| # csv << post.values_at(attributes) # end # end # # It falls back to the *:default* profile, when no profile is specified. module ExposableAttributes extend ActiveSupport::Concern included do class_attribute :_exposable_attributes end # Defines the exposable_attributes method. module ClassMethods # Defines exposable attributes. See the ExposableAttributes module for # more info. def attr_exposable(*attrs) options = attrs.extract_options! self._exposable_attributes = exposable_attributes_config Array.wrap(options.fetch(:as, :default)).each do |role| self._exposable_attributes[role] += attrs.map(&:to_s) end self._exposable_attributes end # Retrieves exposable attributes for a specified profile. See the # ExposableAttributes module for more info. def exposable_attributes(role = :default, options = {}) attributes = self._exposable_attributes[role] if (only = options[:only]) attributes &= Array.wrap(only).map(&:to_s) elsif (except = options[:except]) attributes -= Array.wrap(except).map(&:to_s) end unless options[:human] return attributes.to_a end attributes.map do |attr| [attr, method_defined?("human_#{attr}") ? "human_#{attr}" : attr] end end private # Helper to init the models exposable attributes hash. def exposable_attributes_config self._exposable_attributes ||= Hash.new { |hsh, key| hsh[key] = Set.new } end end end ActiveRecord::Base.send :include, ExposableAttributes <file_sep>/lib/acts_as_tag.rb # Tha ActsAsTag module defines methods making arbitrary models acting as # tags or taggable, using the tag like models as associations. # # To make a model acting as a tag, you can do something like: # # class KeyWord < ActiveRecord::Base # acts_as_tag :word # :word is a database column. # end # # Every tag like model has a from_s method, extracting tags from a string. The # default seperator is a comma, but can be overriden by a second argument. # # KeyWord.from_s('Programming, Ruby, CoffeeScript') # #=> [ # # #<KeyWord id: 12, word: 'Programming'>, # # #<KeyWord id: 44, word: 'Ruby'>, # # #<KeyWord id: nil, word: 'CoffeeScript'> # # ] # # Another method that is available for tag like models is to_s, returning the # specified attribute: # # KeyWord.find(44).to_s #=> 'Ruby' # # To determine if a model acts as a tag, use: # # KeyWord.acts_as_tag? #=> true # # This is pretty nice. To make it awesome, use a second model and define it as # taggable: # # class Article < ActiveRecord::Base # is_taggable_with :key_words # end # # Now it is possible to use it like this: # # article = Article.last # # article.key_words = 'Ruby, CSS , JavaScript' # #=> [ # # #<KeyWord id: 44, word: 'Ruby'>, # # #<KeyWord id: 89, word: 'CSS'>, # # #<KeyWord id: 90, word: 'JavaScript'> # # ] # # article.key_words.join(', ') # #=> 'Ruby, CSS, JavaScript' # # ==== SECURITY NOTE: # # Every association used with is_taggable_with is white listed for # mass assignment using attr_accessible. This is very useful, if # you want to do something like this: # # Article.new(title: 'Hello World', key_words: 'Ruby, CSS, SQL') # # But can be a problem in some cases. module ActsAsTag end require 'acts_as_tag/not_a_tag' require 'acts_as_tag/acts_as_tag' require 'acts_as_tag/is_taggable_with' <file_sep>/spec/factories/description.rb FactoryGirl.define do factory :description do description 'Some random description.' end end <file_sep>/app/models/project_member.rb # Joins experts with projects. # # Database schema: # # - *id:* integer # - *expert_id:* integer # - *project_id:* integer # - *role:* string # # The fields *expert_id*, *project_id* and *role* are required. class ProjectMember < ActiveRecord::Base attr_accessible :expert_id, :role belongs_to :expert belongs_to :project, inverse_of: :members validates :role, presence: true validates :expert_id, uniqueness: {scope: :project_id} # def self.ordered includes(:expert).order(Expert::DEFAULT_ORDER) end # Returns the experts name. def name expert.try(:to_s) end # Returns the experts name and role. def to_s "#{name} (#{role})" end end <file_sep>/app/models/address.rb # The Address model provides the ability to store addresses and connect # the to other models through the polymorphic association _addressable_. # # Database scheme: # # - *id* integer # - *addressable_id* integer # - *addressable_type* string # - *country_id* integer # - *address* text class Address < ActiveRecord::Base attr_accessible :address, :country validates :address, presence: true belongs_to :addressable, polymorphic: true belongs_to :country default_scope includes(:country) # Sets the country from an id. def country=(country) super(Country.find_country(country)) end end <file_sep>/app/controllers/lists_controller.rb # The ListsController provides the actions to handle some list specific # requests. See Ajax::LitsController to find more. class ListsController < ApplicationController before_filter :check_password, only: :destroy before_filter :find_list, only: [:update, :concat, :copy, :destroy] skip_before_filter :authorize cache_sweeper :list_sweeper, only: :update # Serves all lists. def index @lists = current_user.accessible_lists.search(params).page(params[:page]) @title = t('labels.list.all') end # Creates a new list and sets the users current list. def create list = current_user.lists.build(params[:list]) list.current_users << current_user if list.save flash[:notice] = t('messages.list.success.create', title: list.title) redirect_to list_experts_url(list) else flash[:alert] = t('messages.list.errors.create') redirect_to lists_url end end # Updates a list. def update if @list.update_attributes(params[:list]) flash[:notice] = t('messages.list.success.save') else flash[:alert] = t('messages.list.errors.save') end redirect_to list_experts_url(@list) end # Concats a list with another. def concat other = current_user.accessible_lists.find(params[:other]) @list.concat(other) flash[:notice] = t('messages.list.success.concat', title: other.title) redirect_to list_experts_url(@list) end # Copies a list. def copy copy = @list.copy(params[:list]) copy.user = current_user copy.private = true if copy.save flash[:notice] = t('messages.list.success.copy', title: @list.title) redirect_to list_experts_url(copy) else flash[:alert] = t('messages.list.errors.copy') redirect_to list_experts_url(@list) end end # Destroys a list. def destroy if @list.destroy flash[:notice] = t('messages.list.success.delete', title: @list.title) redirect_to lists_url else flash[:alert] = t('messages.list.errors.delete') redirect_to list_experts_url(@list) end end private # Finds the list. def find_list @list = current_user.accessible_lists.find(params[:id]) end # Sets a flash and redirects the user. def not_found flash[:alert] = t('messages.list.errors.find') redirect_to(@list ? list_experts_url(@list) : lists_url) end end <file_sep>/spec/factories/attachment.rb FactoryGirl.define do factory :attachment do title 'Some Random File' filename 'some-random-file.pdf' after(:build) { |attachment| attachment.attachable = build(:expert) } end end <file_sep>/spec/models/list_spec.rb require 'spec_helper' describe List do describe :validations do it { should validate_presence_of(:title) } describe 'public lists cant be set to private' do subject { create(:list, private: privacy) } context 'when list is private and updated to be public' do let(:privacy) { true } before { subject.private = false } it 'should be valid' do expect(subject).to be_valid end end context 'when list is public and updated to be private' do let(:privacy) { false } before { subject.private = true } it 'should not be valid' do expect(subject).to_not be_valid expect(subject.errors[:private]).to_not be_empty end end end end describe :associations do it { should have_many(:list_items).dependent(:destroy) } it { should have_many(:current_users) } it { should have_many(:experts).through(:list_items) } it { should have_many(:partners).through(:list_items) } it { should have_one(:comment).dependent(:destroy) } it { should belong_to(:user) } end describe :accessible_for do before do create(:list, private: true) create(:list, private: false) create(:list, private: true, user: user) end let(:user) { create(:user) } subject { List.accessible_for(user) } it { should have(2).items } it 'should have lists which are accesible by the user' do expect(subject).to be_all { |list| list.accessible_for?(user) } end end describe :accessible_for? do subject { list.accessible_for?(user) } let(:user) { build(:user) } context 'when list is private and user is not the owner' do let(:list) { build(:list, private: true) } it { should be_false } end context 'when list is public' do let(:list) { build(:list, private: false) } it { should be_true } end context 'when user is the owner' do let(:list) { build(:list, private: true, user: user) } it { should be_true } end end describe :add do context 'when item type is invalid' do subject { build(:list) } it 'should raise an ArgumentError' do expect { subject.add(:invalid, [1, 2]) }.to raise_error(ArgumentError) end end context 'when valid arguments' do subject { create(:list) } let(:experts) { (1..4).map { |_| create(:expert) } } it 'should a add the items' do expect { subject.add(:experts, experts) }.to change { subject.list_items.map(&:item) }.from([]).to(experts) end context 'when adding not existing items' do let(:experts) { [0, create(:expert), 1, -12] } it 'should ignore them' do expect { subject.add(:experts, experts) }.to change { subject.list_items.map(&:item) }.from([]).to([experts[1]]) end end end end describe :remove do context 'when item type is invalid' do subject { build(:list) } it 'should raise an ArgumentError' do expect { subject.remove(:invalid, [1, 2]) }.to raise_error(ArgumentError) end end context 'when valid arguments' do subject { create(:list) } let(:partners) { (1..4).map { |_| create(:partner) } } before { subject.add(:partners, partners) } it 'remove the items' do expect { subject.remove(:partners, partners[0..1]) }.to change { subject.list_items(true).map(&:item) }.from(partners).to(partners[2..3]) end context 'when removing none existing items' do it 'should ignore them' do expect { subject.remove(:partners, [1, -12, 0, partners.last]) }.to change { subject.list_items(true).map(&:item) }.from(partners).to(partners[0..-2]) end end end end describe :copy do subject { create(:list_with_items) } it 'should be be the same as the original' do expect(subject.copy).to_not eq(subject) end it 'should not change the original list' do expect { subject.copy }.to_not change { subject.changed? } end it 'should be a new record' do expect(subject.copy).to be_new_record end it 'should have excat same number of items as the original list' do expect(subject.copy.list_items.length).to eq(subject.list_items.count) end it 'should have fresh copies of the list items' do expect(subject.copy.list_items).to be_all(&:new_record?) end it 'should have list items with copied notes' do expect(subject.copy.list_items).to be_all { |item| item.note.present? } end context 'with params' do let(:title) { 'Yet Another List Title' } it 'should merge the params' do expect(subject.copy(title: title).title).to eq(title) end end context 'with evil params' do it 'should raise an error' do expect { subject.copy(user_id: 12) }.to raise_error end end end describe :concat do subject { create(:list_with_3_items) } before do @other = create(:list_with_items) end it 'should not change to other list' do expect { subject.concat(@other) }.to_not change { @other.changed? } end it 'should not change the list items of the other list' do expect { subject.concat(@other) }.to_not change { @other.list_items.any?(&:changed?) } end it 'should include the items of the other list' do expect { subject.concat(@other) }.to change { subject.list_items.length }.from(3).to(3 + @other.list_items.count) end it 'should have fresh items' do expect { subject.concat(@other) }.to_not change { subject.list_items(true) & @other.list_items } end end describe :public? do context 'when list is private' do subject { build(:list, private: true) } it 'should be false' do expect(subject.public?).to be_false end end context 'when list is public' do subject { build(:list, private: false) } it 'should be true' do expect(subject.public?).to be_true end end end describe :to_s do subject { build(:list, title: 'Example List') } it 'should be the title' do expect(subject.to_s).to eq('Example List') end end end <file_sep>/spec/searchers/list_searcher_spec.rb require 'spec_helper' describe ListSearcher do subject { List.search(conditions).all } before(:all) do @private_jane = create(:list, title: '<NAME>') @private_adam = create(:list, title: '<NAME>') @public_peter = create(:list, title: '<NAME>', private: false) end after(:all) do [@private_adam, @private_jane, @public_peter].each do |list| list.user.destroy list.destroy end end describe :search do context 'when searching for private lists' do let(:conditions) { { private: true } } it 'should be private lists only' do expect(subject).to match_array([@private_adam, @private_jane]) end end context 'when searching for public lists' do ['0', 0, false].each do |value| let(:conditions) { { private: value } } it 'should be public lists only' do expect(subject).to eq([@public_peter]) end end end context 'when searching for title' do let(:conditions) { { title: 'ane' } } it 'should be lists found by partial match' do expect(subject).to eq([@private_jane]) end end context 'when excluding lists' do let(:conditions) { { exclude: [@private_jane, @public_peter] } } it 'should be an without the excluded lists' do expect(subject).to match_array([@private_adam]) end end context 'when searching for title "a" and excluding adam' do let(:conditions) { { title: 'a', exclude: @private_adam } } it 'should be jane only' do expect(subject).to eq([@private_jane]) end end context 'when search for private lists with title "doe"' do let(:conditions) { { title: 'doe', private: true } } it 'should be jane only' do expect(subject).to eq([@private_jane]) end end context 'when searching for public lists and title "ad"' do let(:conditions) { { title: 'ad', private: false } } it 'should be empty' do expect(subject).to be_empty end end context 'when searching a scoped model' do subject { List.limit(1).search(private: true).all } it 'should resect the scope' do expect(subject).to have(1).item expect(subject.first.private?).to be_true end end end end <file_sep>/app/helpers/list_item_helper.rb module ListItemHelper # Renders a print list dialog for a given item type. It yields the print # options in a nested array. Use it this way: # # <%= print_list_dialog_for(:experts, @list_id) do |options| %> # <% options.each do |name, attr, human| %> # <label> # <%= check_box_tag(name, attr, true) %> <%= human %> # </label> # <% end %> # <% end %> # # Raises an ArgumentError for invalid item types. def print_list_dialog_for(item_type, list_id) klass = ListItem.class_for_item_type(item_type) url = url_for({ controller: '/list_items', action: item_type, list_id: list_id, format: :pdf }) form_tag(url, method: :get) do yield(options_for_print_list_dialog(klass)) end end private # Returns a nested array of options used by the print dialog # in the list view. def options_for_print_list_dialog(klass) klass.exposable_attributes(:pdf).map do |attr| ['attributes[]', attr, klass.human_attribute_name(attr)] end << [:note, :note, ListItem.human_attribute_name(:note)] end end <file_sep>/lib/discrete_values.rb # Mixes support for discrete values into ActiveRecord. # # To define discrete values for an attribute you can write: # # class User < ActiveRecord::Base # discrete_values :locale, [:en, :de, :fr], default: :de # end # # This defines some possible values for the locale attribute. It also adds # validation, a before_save callback to set the default value (when specified) # and additional methods: # # # All values in a select box friendly format. # User.locale_values # #=> [['English', 'en'], ['German', 'de'], ['French', 'fr']] # # # I18n # user.locale #=> 'de' # user.human_locale #=> 'German' # # === Options # # - *:default* Sets the default value before save, when it is nil. # - *:validate* Set to false to disable validation. # - *:allow_blank* Passed to the validation. # - *:allow_nil* Passed to the validation. # - *:i18n_scope* Use a custom i18n scope. # # === I18n # # The default search paths are: # # - activerecord.discrete.{model}.{attribute}.{value} # - activerecord.discrete.values.{attribute}.{value} # # Example of a working en.yml: # # --- # en: # activerecord: # discrete: # values: # size: # s: 'Small' # m: 'Medium' # l: 'Large' # user: # locale: # en: 'English' # de: 'German' # fr: 'French' # # These paths can be overriden with the *:i18n_scope* option. module DiscreteValues extend ActiveSupport::Concern # Defines ClassMethods#discrete_values module ClassMethods # Defines discrete values for an attribute. # # See the DiscreteValues module for more info. def discrete_values(attribute_name, values, options = {}) extend ClassMethodsOnActivation include InstanceMethodsOnActivation unless respond_to?(:_discrete_values) class_attribute(:_discrete_values) self._discrete_values = {} end _discrete_values[attribute_name] = { values: values.map { |v| convert_discrete_value(v) }, default: convert_discrete_value(options[:default]), i18n_scope: options[:i18n_scope] } define_singleton_method("#{attribute_name}_values") do discrete_values_for(attribute_name) end define_method(attribute_name) do read_discrete_value_attribute(attribute_name) end define_method("#{attribute_name}=") do |value| write_discrete_value_attribute(attribute_name, value) end define_method("set_default_#{attribute_name}") do set_default_discrete_value_for(attribute_name) end define_method("human_#{attribute_name}") do human_discrete_value(attribute_name) end if options.key?(:default) before_save("set_default_#{attribute_name}") end if options.fetch(:validate, true) validation_options = options.slice(:allow_nil, :allow_blank) validation_options[:inclusion] = _discrete_values[attribute_name][:values] validates(attribute_name, validation_options) end end end # Mixes class methods into the model. module ClassMethodsOnActivation # Converts the value. def convert_discrete_value(value) value.is_a?(Symbol) ? value.to_s : value end # Returns all possible values for an attribute in a select box friendly # format. def discrete_values_for(attribute_name) _discrete_values[attribute_name][:values].map do |value| [human_discrete_value(attribute_name, value), value] end end # Returns value in a human readable format. def human_discrete_value(attribute_name, value) return nil if value.nil? scope = _discrete_values[attribute_name][:i18n_scope] keys = [] keys << :"#{scope}.#{value}" if scope keys << :"#{i18n_scope}.discrete.#{model_name.i18n_key}.#{attribute_name}.#{value}" keys << :"#{i18n_scope}.discrete.values.#{attribute_name}.#{value}" I18n.t(keys.shift, default: keys) end end # Mixes instance methods into the model. module InstanceMethodsOnActivation # Sets the default value if it is empty. def set_default_discrete_value_for(attribute_name) if read_attribute(attribute_name).nil? write_attribute(attribute_name, _discrete_values[attribute_name][:default]) end end # Returns the value or the default if its empty. def read_discrete_value_attribute(attribute_name) read_attribute(attribute_name) || _discrete_values[attribute_name][:default] end # Converts and assigns the value. def write_discrete_value_attribute(attribute_name, value) write_attribute(attribute_name, self.class.convert_discrete_value(value)) end # Returns the value of the attribute in a human readable format. def human_discrete_value(attribute_name) self.class.human_discrete_value(attribute_name, read_discrete_value_attribute(attribute_name)) end end end ActiveRecord::Base.send :include, DiscreteValues <file_sep>/spec/models/project_info_spec.rb require 'spec_helper' describe ProjectInfo do describe :validations do it { should ensure_inclusion_of(:language).in_array(%w(de en es fr)) } it { should validate_presence_of(:title) } describe :language_cannot_be_changed do subject { create(:project_info, :with_project, language: :en) } context 'when the language has not changed' do before { subject.language = 'en' } it 'should be valid' do expect(subject).to be_valid end end context 'when the language has changed' do before { subject.language = 'de' } it 'should not be valid' do expect(subject).to_not be_valid expect(subject.errors[:language]).to_not be_empty end end end end describe :associations do it { should have_one(:description).dependent(:destroy) } it { should have_one(:service_details).dependent(:destroy) } it { should belong_to(:project) } end describe :after_save do subject { create(:project_info, :with_project) } it 'should send :update_title to the project' do expect(subject.project).to receive(:update_title) subject.save end end end <file_sep>/app/controllers/ajax/cvs_controller.rb # The Ajax::CvsController handles Cv specific AJAX requests. class Ajax::CvsController < Ajax::ApplicationController respond_to :html, only: [:new] caches_action :new # Serves an empty cvs form. def new @cv = Cv.new @url = { controller: '/cvs', action: :create } end end <file_sep>/lib/acts_as_tag/not_a_tag.rb module ActsAsTag # Should be raised when a model does not act as a tag. class NotATag < StandardError # Initializes the exception. Takes the name of the model. def initialize(name) super("#{name} does not act as tag.") end end end <file_sep>/app/helpers/user_helper.rb # Provides user specific helpers. module UserHelper # Returns a string, containing all the users privileges in _spans_. # The CSS _checked_ class is applied, if the user has access to the # corresponding section. # # list_privileges(user, 'checked') # #=> '<span>experts</span><span class="checked">partners</span>' def list_privileges(user, klass) if user.admin? return content_tag(:span, class: klass) do Privilege.human_attribute_name(:admin) end end Privilege::SECTIONS.inject('') do |html, section| html << content_tag(:span, class: user.access?(section) ? klass : nil) do Privilege.human_attribute_name(section) end end.html_safe end # Returns the user's fullname and its username in brackets. def full_user_link(user) link_to edit_user_path(user) do html = content_tag :strong, "#{user.prename} #{user.name}" html << " (#{user.username})" end end end <file_sep>/db/migrate/003_add_cv.rb class AddCv < ActiveRecord::Migration def up create_table :cvs do |t| t.integer :expert_id, null: false t.integer :language_id, null: false t.text :cv, null: true end add_index :cvs, :expert_id add_index :cvs, :language_id execute('ALTER TABLE cvs ENGINE = MyISAM') execute('CREATE FULLTEXT INDEX fulltext_cv ON cvs (cv)') create_table :attachments do |t| t.references :attachable, polymorphic: true t.string :filename, null: false t.string :title, null: false t.timestamp :created_at end add_index :attachments, [:attachable_id, :attachable_type] add_index :attachments, :filename, unique: true end def down drop_table :cvs drop_table :attachments end end <file_sep>/app/controllers/list_items_controller.rb # Handles list item related requests. class ListItemsController < ApplicationController before_filter :find_list skip_before_filter :authorize # Destroys a list item. # # DELETE /lists/:list_id/list_items/:id def destroy item = @list.list_items.find(params[:id]) if item.destroy flash[:alert] = t('messages.list_item.success.delete', name: item.name) else flash[:notice] = t('messages.list_item.errors.delete') end redirect_to :back end # Serves a csv with the lists partners including their employees. # # GET /lists/:list_id/employees def employees title = "#{@list.title}-employees" partners = @list.partners respond_to do |format| format.csv { send_csv partners.as_csv(include: :employees), title } format.xlsx { send_xlsx partners.as_xlsx(include: :employees), title } end end # Defines the actions needed to show the list items. # # GET /lists/:list_id/experts # GET /lists/:list_id/partners # GET /lists/:list_id/projects ListItem::TYPES.each_key do |item_type| define_method(item_type) { index(item_type) } end private # Serves the lists items in various formats. def index(item_type) @title = @list.title respond_to do |format| format.html { html_index(item_type) } format.pdf { pdf_index(item_type) } format.csv { csv_index(item_type) } format.xlsx { xlsx_index(item_type) } end end # Serves the lists items as html. def html_index(item_type) @item_type = item_type @items = @list.list_items.by_type(item_type, order: true).includes(:item) body_class << (body_class.delete(item_type) + '-list') render :index end # Serves the lists items as pdf. def pdf_index(item_type) send_report ListReport.new(@list, item_type, current_user, params) end # Serves the lists items as csv. def csv_index(item_type) send_csv @list.send(item_type).as_csv, "#{@title} #{item_type}" end # Serves the lists items as xlsx. def xlsx_index(item_type) send_xlsx @list.send(item_type).as_xlsx, "#{@title} #{item_type}" end # Finds the list. def find_list @list = current_user.accessible_lists.find(params[:list_id]) rescue ActiveRecord::RecordNotFound flash[:alert] = t('messages.list.errors.find') redirect_to lists_url end # Sets a flash and redirects to the list. def not_found flash[:alert] = t('messages.list_item.errors.find') redirect_to list_experts_url(params[:list_id]) end end <file_sep>/app/models/list_item.rb # The ListItem model provides the ability to connect arbitrary models with # the List model and add some notes to them. # # Database schema: # # - *id:* integer # - *list_id:* integer # - *item_id:* integer # - *item_type:* string # - *note:* string # - *created_at:* datetime # - *updated_at:* datetime # # There is a unique index over list_id, item_id and item_type. class ListItem < ActiveRecord::Base attr_accessible :note belongs_to :list belongs_to :item, polymorphic: true # Hash containing possible item types. TYPES = { experts: Expert, partners: Partner, projects: Project } # Setup a belongs to association for each item type. TYPES.each_value do |klass| belongs_to klass.to_s.downcase.to_sym, foreign_key: :item_id, foreign_type: klass end # Returns the model class for an item type. # # ListItem.class_for_item_type(:experts) # #=> Expert(id: integer, ...) # # Raises ArgumentError for invalid item types. def self.class_for_item_type(item_type) TYPES.fetch(item_type) rescue KeyError raise ArgumentError, "Invalid item type: #{item_type}" end # Adds a proper condition to the scope, to filter list items with a the # specified item type. Set the order option, to get the list items ordered # by their actual items default value. # # List.list_items.by_type(:experts, order: true) # #=> [ # # #<ListItem id: 35, item_id: 13, item_type: "Expert">, # # #<ListItem id: 14, item_id: 37, item_type: "Expert"> # # ] # # Raises ArgumentError for invalid item types. def self.by_type(item_type, options = {}) klass = class_for_item_type(item_type) scope = joins(klass.to_s.downcase.to_sym).where(item_type: klass) options[:order] ? scope.order(klass::DEFAULT_ORDER) : scope end # Returns a collection of fresh ListItem objects, generated from an item # type and a set of ids. # # ListItem.collection(:experts, [1, 2, 3]) # #=> [ # # #<ListItem id: nil, item_id: 1, item_type: "Expert">, # # #<ListItem id: nil, item_id: 2, item_type: "Expert">, # # #<ListItem id: nil, item_id: 3, item_type: "Expert"> # # ] # # Raises ArgumentError for invalid item types. def self.collection(item_type, item_ids) class_for_item_type(item_type).where(id: item_ids).map do |item| new.tap { |list_item| list_item.item = item } end end # Returns a copy of the list item after merging the optional attributes. def copy(attributes = {}) dup.tap { |copy| copy.attributes = attributes } end # Returns the name of the list item. def name item.to_s end alias :to_s :name # Adds the name to the JSON representation of the list item. def as_json(options = {}) super(options.merge(methods: [:name])) end end <file_sep>/app/controllers/experts_controller.rb # The ExpertsController provides basic CRUD actions for the experts data. class ExpertsController < ApplicationController before_filter :check_password, only: [:destroy] before_filter :find_expert, only: [:show, :documents, :edit, :update, :destroy] skip_before_filter :authorize, only: [:index, :show, :documents] # Serves a paginated table of all experts. # # GET /experts def index _params = params.merge(arrayified_params(:country, :languages)) @experts = Expert.with_meta.search(_params).page(params[:page]) @title = t('labels.expert.all') end # Serves the experts details page. # # GET /experts/:id def show @title = @expert.full_name_with_degree respond_to do |format| format.html format.pdf { send_report ExpertReport.new(@expert, current_user) } end end # Serves the experts documents page. # # GET /experts/:id/documents def documents @title = @expert.full_name_with_degree end # Servers a blank experts form # # GET /experts/new def new @expert = Expert.new render_form(:new) end # Creates a new expert and redirects to the experts details page on success. # # POST /experts def create @expert = current_user.experts.build(params[:expert]) if @expert.save flash[:notice] = t('messages.expert.success.create', name: @expert.name) redirect_to expert_url(@expert) else flash.now[:alert] = t('messages.expert.errors.create') render_form(:new) end end # Serves an edit form, populated with the experts data. # # GET /experts/:id/edit def edit render_form(:edit) end # Updates an expert and redirects to the experts details page on success. # # PUT /experts/:id def update @expert.user = current_user if @expert.update_attributes(params[:expert]) flash[:notice] = t('messages.expert.success.save') redirect_to expert_url(@expert) else flash.now[:alert] = t('messages.expert.errors.save') render_form(:edit) end end # Deletes the expert and redirects to the experts index page. # # DELETE /experts/:id def destroy if @expert.destroy flash[:notice] = t('messages.expert.success.delete', name: @expert.name) redirect_to experts_url else flash[:alert] = t('messages.expert.errors.delete') redirect_to expert_url(@expert) end end private # Checks if the user has access to the experts section. def authorize super(:experts, experts_url) end # Finds the expert. def find_expert @expert = Expert.find(params[:id]) end # Renders the experts form def render_form(action) body_class << action @title = t("labels.expert.#{action}") render :form end # Sets a not found flash and redirects to the experts index page. def not_found flash[:alert] = t('messages.expert.errors.find') redirect_to experts_url end end <file_sep>/spec/factories/business.rb require 'securerandom' FactoryGirl.define do factory :business do sequence(:business) { |_| SecureRandom.hex(32) } end end <file_sep>/app/helpers/form_helper.rb # Defines our custom form builder and some form specific helpers. module FormHelper # Renders a multi select text field. def multi_select_field_tag(name, value, selected = nil, options = {}) options = { 'data-multi-select' => name.to_s.pluralize, 'data-selected' => selected, }.merge(options) text_field_tag name, value, options end # Returns a contact field select box with localized options. def contact_field_select_tag(name, options = {}) select_tag(name, options_for_select(contact_field_list, options.delete(:value)), options) end private # Returns a select box friendly list of all contact fields def contact_field_list @contact_field_list ||= Contact::FIELDS.map do |f| [I18n.t(f.singularize, scope: [:values, :contacts]), f] end end public # Silos custom FormBuilder defines several helpers such as # FormBuilder#country_select and FormBuilder#language_select. class FormBuilder < ActionView::Helpers::FormBuilder require_dependency 'area' require_dependency 'country' require_dependency 'language' # Returns a grouped collection select box containing all countries grouped # by area and ordered by their localized names. def country_select(method, options = {}, html_options = {}) grouped_collection_select(method, all_areas, :countries, :human, :id, :human, options, html_options) end # Returns a collection select box containing all languages. def language_select(method, options = {}, html_options = {}) collection_select(method, all_languages, :id, :human, options, html_options) end # Renders an autocomplete text field. def autocomplete_field(method, options = {}) options = { 'data-complete' => method, 'data-attribute' => method.to_s.singularize, value: @object.send(method).join(', ') }.merge(options) text_field(method, options) end # Renders a multi select text field. def multi_select_field(method, options = {}) options = { 'data-multi-select' => method.to_s.pluralize, 'data-selected' => @object.send(method).map(&:id).join(' '), value: @object.send(method).join(', '), }.merge(options) text_field(method, options) end # Returns fields for privileges. Its a bunch of check boxes and labels. def privilege_fields(method, disabled = false) fields_for(method, include_id: ! disabled) do |fields| html = fields.check_box(:admin, disabled: disabled, class: :admin) html << fields.label(:admin, class: :admin) Privilege::SECTIONS.reverse_each do |section| html << fields.check_box(section, disabled: disabled) html << fields.label(section) end html end end private # Returns all areas with their ordered countries. def all_areas @all_areas ||= Rails.cache.fetch("#{I18n.locale}/all_areas") do Area.with_ordered_countries end end # Returns all languages ordered by priority. def all_languages @all_languages ||= Rails.cache.fetch("#{I18n.locale}/all_languages") do Language.priority_ordered end end end end <file_sep>/db/migrate/002_add_experts.rb class AddExperts < ActiveRecord::Migration def up create_table :experts do |t| t.integer :user_id, null: false t.integer :country_id, null: true t.string :name, null: false t.string :prename, null: false t.string :gender, null: false t.date :birthday, null: true t.string :degree, null: true t.boolean :former_collaboration, null: false, default: false t.string :fee, null: true t.string :job, null: true t.timestamps end add_index :experts, :user_id add_index :experts, :country_id add_index :experts, :name add_index :experts, :prename create_table :areas do |t| t.string :area, null: false end add_index :areas, :area, unique: true create_table :countries do |t| t.integer :area_id, null: false t.string :country, null: false end add_index :countries, :area_id add_index :countries, :country, unique: true create_table :contacts do |t| t.references :contactable, polymorphic: true t.text :contacts, null: false end add_index :contacts, [:contactable_id, :contactable_type] create_table :addresses do |t| t.references :addressable, polymorphic: true t.integer :country_id, null: true t.text :address, null: false end add_index :addresses, [:addressable_id, :addressable_type] end def down drop_table :experts drop_table :areas drop_table :countries drop_table :contacts drop_table :addresses end end <file_sep>/spec/factories/country.rb FactoryGirl.define do factory :country do sequence(:country) { |n| I18n.t(:countries).keys[n] } association :area, factory: :area end end <file_sep>/app/models/comment.rb # The Comment model provides the ability to add comments to another model, # just by doing something like: # # class Article < ActiveRecord::Base # has_many :comments, as: commentable # end # # Or for has_one associations: # # class Product < ActiveRecord::Base # is_commentable_with :comment, as: :commentable # end # # The comment is saved in the _comment_ attribute. # # Database scheme: # # - *id* integer # - *commentable_id* integer # - *commentable_type* string # - *comment* text # - *created_at* datetime # - *updated_at* datetime # # See the ActsAsComment module for more info. class Comment < ActiveRecord::Base acts_as_comment :comment, for: :commentable, polymorphic: true end <file_sep>/app/controllers/project_members_controller.rb # class ProjectMembersController < ApplicationController before_filter :find_project, only: [:index, :create, :update, :destroy] before_filter :find_member, only: [:update, :destroy] skip_before_filter :authorize, only: [:index] # GET /projects/:project_id/members def index @info = @project.info @title = @info.title end # POST /projects/:project_id/members def create member = @project.members.build(params[:project_member]) if member.save flash[:notice] = t('messages.project_member.success.create', name: member.name) else flash[:alert] = t('messages.project_member.errors.create') end redirect_to project_members_path(@project) end # DELETE /projects/:project_id/members/:id def destroy if @member.destroy flash[:notice] = t('messages.project_member.success.delete', name: @member.name) else flash[:alert] = t('messages.project_member.errors.delete') end redirect_to project_members_path(@project) end private # Checks the users authorization. def authorize super(:projects, projects_url) end # Finds the project. def find_project @project = Project.find(params[:project_id]) rescue ActiveRecord::RecordNotFound flash[:alert] = t('messages.project.errors.find') redirect_to projects_url end # Finds the member. def find_member @member = @project.members.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:alert] = t('messages.project_member.errors.find') redirect_to project_members_url(@project) end end <file_sep>/app/controllers/addresses_controller.rb # The AddressesController is the parent controller of all controllers in the # Addresses module. It provides generic methods to manipulate the polymorphic # Address model. class AddressesController < ApplicationController before_filter :find_parent, only: [:create, :destroy] polymorphic_parent :experts # Adds a new address to a model and redirects the user to a url. It is # expected that the _params_ hash contains another info hash accessible # through the _:address_ key. # # POST /parents/:parent_id/addresses def create if (@parent.addresses << Address.new(params[:address])) flash[:notice] = t('messages.address.success.save') else flash[:alert] = t('messages.address.errors.save') end redirect_to :back end # Destroys an Address. # # DELETE /parents/:parent_id/addresses/:id def destroy if @parent.addresses.find(params[:id]).destroy flash[:notice] = t('messages.address.success.delete') else flash[:alert] = t('messages.address.errors.delete') end redirect_to :back end private # Checks the users permissions sends a redirect if necessary. def authorize super(parent[:controller], :back) end # Sets a proper error message and redirects back. def not_found flash[:alert] = t('messages.address.errors.find') redirect_to :back end end <file_sep>/app/controllers/users_controller.rb # The UsersController provides CRUD actions for the users data. # # It is accessible as admin only. class UsersController < ApplicationController before_filter :check_password, only: [:destroy] before_filter :find_user, only: [:destroy, :edit, :update] before_filter :block_current_user, only: [:destroy] # Serves a list of all users. # # GET /users def index @users = User.includes(:privilege).order('name, prename') @title = t('labels.user.all') end # Serves a blank user form. # # GET /users/new def new @user = User.new render_form(:new) end # Creates a new user and redirects to the new users edit page. # # POST /users def create @user = User.new(params[:user], as: :admin) if @user.save flash[:notice] = t('messages.user.success.create', name: @user.username) redirect_to users_url else flash.now[:alert] = t('messages.user.errors.create') render_form(:new) end end # Serves an edit form, populated with the users data. # # GET /users/:id/edit def edit render_form(:edit) end # Updates the users data and serves the edit form. # # PUT /users/:id def update context = current_user?(@user) ? :current_admin : :admin if @user.update_attributes(params[:user], as: context) I18n.locale = @user.locale if current_user?(@user) flash[:notice] = t('messages.user.success.save') redirect_to users_url else flash.now[:alert] = t('messages.user.errors.save') render_form(:edit) end end # Destroys a user and redirects to the users index page. # # DELETE /users/:id def destroy if @user.destroy flash[:notice] = t('messages.user.success.delete', name: @user.username) else flash[:alert] = t('messages.user.errors.delete') end redirect_to users_url end private # Finds the user def find_user @user = User.find(params[:id]) end # Redirects if @user == current_user. def block_current_user unauthorized(users_url) if current_user?(@user) end # Renders the users form. def render_form(action) body_class << action @title = t("labels.user.#{action}") render :form end # Sets a "user not found" alert and redirects to the users index page. def not_found flash[:alert] = t('messages.user.errors.find') redirect_to users_url end end <file_sep>/spec/models/cv_spec.rb require 'spec_helper' describe Cv do include AttachmentSpecHelper describe :validations do it { should validate_presence_of(:cv) } end describe :associations do it { should have_one(:attachment).dependent(:destroy) } it { should belong_to(:language) } it { should belong_to(:expert) } end describe :file= do context 'when argument is a valid file' do let(:file) { fixture_file_upload('lorem-ipsum.txt') } it 'should store the file' do expect { subject.file = file }.to change { count_files(Attachment::STORE) }.by(1) expect(subject.absolute_path).to be_file end it 'should load the files content into the cv attribute' do expect(subject.cv).to be_nil subject.file = file file.rewind expect(subject.cv.strip).to eq(file.read.strip) end end ['acme.pdf', 'acme.doc'].each do |filename| context "when file is #{filename}" do let(:file) { fixture_file_upload(filename) } it 'should work too' do expect(subject.cv).to be_nil subject.file = file expect(subject.cv.strip).to eq('ACME Inc. - We do it right.') end end end ['empty', 'kittens.jpg'].each do |filename| context "when file is #{filename}" do let(:file) { fixture_file_upload(filename) } it 'should have a blank cv attribute' do expect(subject.cv).to be_nil subject.file = file expect(subject.cv).to be_blank end end end context 'when argument is not a file' do let(:file) { 'kittens.jpg' } it 'should raise a TypeError' do expect { subject.file = file }.to raise_error(TypeError) end end end describe :delegations do subject { create(:cv, file: fixture_file_upload('acme.pdf')) } [:created_at, :absolute_path, :ext].each do |method| it "should delegate :#{method} to the attachment" do expect(subject.send(method)).to eq(subject.attachment.send(method)) end end end describe :public_filename do subject do expert = build(:expert, prename: 'John', name: 'Doe') language = build(:language, language: :de) attachment = build(:attachment, original_filename: 'example.pdf') build(:cv, expert: expert, language: language, attachment: attachment).public_filename end it 'should be combination of "cv", experts full_name, language and ext' do expect(subject).to eq('cv-john-doe-de.pdf') end end end <file_sep>/lib/tasks/cvs.rake require 'pathname' require 'colorize' namespace :cvs do task :import, [:cvdir, :refs, :shifts] => [:environment] do |task, args| cvs = Dir[File.join(args[:cvdir], '*')] trash = Pathname.new(File.join('/tmp', 'silo-cvs')) len = cvs.size refs, old_refs = [{}, {}] langs = { 'd' => :de, 'f' => :fr, 's' => :es, 'p' => :pt } puts "Loading references: #{args[:refs]}" File.open(args[:refs]) do |f| f.each do |line| index, filename = line.chomp.split(':') old_refs[filename] = index end end puts "Loding shifts: #{args[:shifts]}" File.open(args[:shifts]) do |f| f.each do |line| index, id = line.chomp.split(':') old_refs.each do |filename, i| refs[filename] = id if index == i end end end trash.rmtree if trash.exist? trash.mkpath cvs.each_with_index do |cv, i| base = File.basename(cv) puts "[#{i + 1}/#{len}] Processing: #{base}".blue if (id = refs[base]).nil? || ! (e = Expert.find_by_id(id)) puts "=> Expert not found for: #{base}".red FileUtils.cp(cv, trash.join(base)) next end lang = :en if (a = /_([a-z])(?:\.|_)/.match(base)) lang = langs[a[1]] || :en end f = File.open(cv) if e.cvs.build(file: f, language: lang).save_or_destroy f.close next end puts "=> Could not load cv: #{base}".red puts "=> Storing as attachment".yellow f.rewind if e.attachments.build(file: f).save_or_destroy f.close next end puts "=> Could not store attachment: #{base}".red FileUtils.cp(cv, trash.join(base)) end end end <file_sep>/lib/acts_as_comment.rb # The ActsAsComment module defines methods making arbitrary models acting as a # comment or being commentable, using comment like models. # # To make a model acting as a comment, do something like: # # class Comment < ActiveRecord::Base # acts_as_comment :comment, for: :commentable, polymorphic: true # end # # To determine if a model acts as a comment, use the class method # acts_as_comment?. # # Comment.acts_as_comment? #=> true # # With the :for option is it possible to initialize a belongs_to # relationship to another model: # # class Text < ActiveRecord::Base # acts_as_comment :text, for: :book # end # # The above has the same effect as: # # class Text < ActiveRecord::Base # acts_as_comment :text # belongs_to :book # end # # Every comment like model has the method to_s, returning the comment. # # Comment.new(comment: 'Hello World').to_s #=> 'Hello World' # # Another remarkable behavior is, that the commentable attribute is # initialized with an empty string, when empty. # # Comment.new.comment #=> '' # # This is not very fancy. To make it useful, take a second model and define it # as commentable. # # class Product < ActiveRecord::Base # is_commentable_with :comment, as: :commentable # end # # Now the comment behaves like an attribute of the product model: # # product.comment = 'Hello World' # product.comment #=> #<Comment id: 12, comment: 'Hello World'> # product.comment.to_s #=> 'Hello World' # # ==== SECURITY NOTE: # # Every association used with is_commentable_with is white listed for # mass assignment using attr_accessible. This is nice, if you want to do # things like: # # Product.new(name: 'Keyboard', comment: 'The keys are very loud.') # # But can be a problem in some situations. module ActsAsComment end require 'acts_as_comment/not_a_comment' require 'acts_as_comment/acts_as_comment' require 'acts_as_comment/is_commentable_with' <file_sep>/app/models/user.rb require 'digest/sha1' require 'securerandom' # The User model provides access to the users data and several methods for # manipulation. # # Database scheme: # # - *id* integer # - *current_list_id* integer # - *username* string # - *email* string # - *password_digest* string # - *login_hash* string # - *name* string # - *prename* string # - *locale* string # - *created_at* datetime # # It uses _bcrypt-ruby_ for password encryption. It provides the two properties # _password_ and _password_confirmation_. They are used the following way: # # user.password = <PASSWORD>] # user.password_confirmation = <PASSWORD>] # user.save # # If the two passwords are not equal, the _save_ call will fail. class User < ActiveRecord::Base attr_accessor :password_old attr_accessible :email, :password, :password_confirmation, :password_old, :name, :prename, :locale attr_accessible :username, :email, :password, :password_confirmation, :name, :prename, :locale, as: :current_admin attr_accessible :username, :email, :password, :password_confirmation, :name, :prename, :locale, :privilege_attributes, as: :admin has_secure_password discrete_values :locale, I18n.available_locales, default: I18n.default_locale, i18n_scope: :languages validates :password, presence: true, on: :create validates :username, presence: true, uniqueness: true, format: /\A[a-z0-9]+\z/ validates :email, presence: true, uniqueness: true validates :login_hash, allow_nil: true, uniqueness: true validates :name, presence: true validates :prename, presence: true validates_with OldPasswordValidator, if: :check_old_password_before_save? has_many :experts has_many :partners has_many :lists has_many :projects has_one :privilege, autosave: true, dependent: :destroy belongs_to :current_list, class_name: :List delegate :access?, :admin?, to: :privilege accepts_nested_attributes_for :privilege # Auto initializes the users privileges on access. def privilege super || self.privilege = Privilege.new end # Check the old password before saving the record. def check_old_password_before_save @check_old_password_before_save = true end # Ist it necessary to check the old password before saving thwe record? def check_old_password_before_save? !! @check_old_password_before_save end # Sets a fresh login hash and returns it. def refresh_login_hash self.login_hash = unique_hash end # Sets a fresh login hash and saves it in the database. # # if user.refresh_login_hash! # session[:login_hash] = user.login_hash # end # # Returns true on success, else false. def refresh_login_hash! refresh_login_hash save end # Returns a ActiveRecord::Relation with lists accessible for the user. def accessible_lists List.accessible_for(self) end # Returns a string containing prename and name of the user. # # user.full_name # #=> "<NAME>" def full_name "#{prename} #{name}" end alias :to_s :full_name # Sets the fields for the JSON representation of the user. def as_json(options = {}) super(options.merge(only: [:id, :name, :prename])) end private # Returns a unique hash. def unique_hash Digest::SHA1.hexdigest(SecureRandom::uuid) end end <file_sep>/db/migrate/011_rename_references.rb class RenameReferences < ActiveRecord::Migration def up rename_column :privileges, :references, :projects end def down rename_column :privileges, :projects, :references end end <file_sep>/spec/lib/exposable_attributes_spec.rb require 'spec_helper' describe ExposableAttributes do class Dummy < ActiveRecord::Base; end class DummyWithExposableAttributes < Dummy attr_exposable :name, :first_name, :gender, :email, as: :pdf end class DummyWithHumanMethods < DummyWithExposableAttributes def human_gender; end end describe :exposable_attributes do context 'with exposable attributes' do subject { DummyWithExposableAttributes.exposable_attributes(*params) } context 'without options' do let(:params) { [:pdf] } it 'should be an array including all exposable attributes' do expect(subject).to eq(['name', 'first_name', 'gender', 'email']) end end context 'with the :only option' do let(:params) { [:pdf, { only: [:name, :first_name] }] } it 'should be an array including only name and first_name' do expect(subject).to eq(['name', 'first_name']) end end context 'with the :except option' do let(:params) { [:pdf, { except: [:name, :email] }] } it 'should be an array including attributes except name and email' do expect(subject).to eq(['first_name', 'gender']) end end end context 'with human_* methods' do subject { DummyWithHumanMethods.exposable_attributes(*params) } context 'with the :human option' do let(:params) { [:pdf, { human: true, only: [:gender, :email] }] } it 'should be an array of attributes with their human methods' do expect(subject).to eq([['gender', 'human_gender'], ['email', 'email']]) end end context 'without the human option' do let(:params) { [:pdf, { only: [:gender, :email] }] } it 'should be an array of attributes without their human methods' do expect(subject).to eq(['gender', 'email']) end end end end end <file_sep>/db/structure.sql CREATE TABLE `addresses` ( `id` int(11) NOT NULL AUTO_INCREMENT, `addressable_id` int(11) DEFAULT NULL, `addressable_type` varchar(255) DEFAULT NULL, `country_id` int(11) DEFAULT NULL, `address` text NOT NULL, PRIMARY KEY (`id`), KEY `index_addresses_on_addressable_id_and_addressable_type` (`addressable_id`,`addressable_type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `advisers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `adviser` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_advisers_on_adviser` (`adviser`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `advisers_partners` ( `adviser_id` int(11) NOT NULL, `partner_id` int(11) NOT NULL, UNIQUE KEY `index_advisers_partners_on_adviser_id_and_partner_id` (`adviser_id`,`partner_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `areas` ( `id` int(11) NOT NULL AUTO_INCREMENT, `area` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_areas_on_area` (`area`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `attachments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `attachable_id` int(11) DEFAULT NULL, `attachable_type` varchar(255) DEFAULT NULL, `filename` varchar(255) NOT NULL, `title` varchar(255) NOT NULL, `created_at` datetime DEFAULT NULL, `original_filename` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_attachments_on_filename` (`filename`), KEY `index_attachments_on_attachable_id_and_attachable_type` (`attachable_id`,`attachable_type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `businesses` ( `id` int(11) NOT NULL AUTO_INCREMENT, `business` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_businesses_on_business` (`business`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `businesses_partners` ( `business_id` int(11) NOT NULL, `partner_id` int(11) NOT NULL, UNIQUE KEY `index_businesses_partners_on_business_id_and_partner_id` (`business_id`,`partner_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `commentable_id` int(11) DEFAULT NULL, `commentable_type` varchar(255) DEFAULT NULL, `comment` text NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), KEY `index_comments_on_commentable_id_and_commentable_type` (`commentable_id`,`commentable_type`), FULLTEXT KEY `fulltext_comment` (`comment`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE `contacts` ( `id` int(11) NOT NULL AUTO_INCREMENT, `contactable_id` int(11) DEFAULT NULL, `contactable_type` varchar(255) DEFAULT NULL, `contacts` text NOT NULL, PRIMARY KEY (`id`), KEY `index_contacts_on_contactable_id_and_contactable_type` (`contactable_id`,`contactable_type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `countries` ( `id` int(11) NOT NULL AUTO_INCREMENT, `area_id` int(11) NOT NULL, `country` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_countries_on_country` (`country`), KEY `index_countries_on_area_id` (`area_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `cvs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `expert_id` int(11) NOT NULL, `language_id` int(11) NOT NULL, `cv` text, PRIMARY KEY (`id`), KEY `index_cvs_on_expert_id` (`expert_id`), KEY `index_cvs_on_language_id` (`language_id`), FULLTEXT KEY `fulltext_cv` (`cv`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE `descriptions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `describable_id` int(11) DEFAULT NULL, `description` text NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `describable_type` varchar(255) NOT NULL DEFAULT 'Partner', PRIMARY KEY (`id`), KEY `index_descriptions_on_describable_id_and_describable_type` (`describable_id`,`describable_type`), FULLTEXT KEY `fulltext_description` (`description`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE `employees` ( `id` int(11) NOT NULL AUTO_INCREMENT, `partner_id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `prename` varchar(255) DEFAULT NULL, `gender` varchar(255) DEFAULT NULL, `title` varchar(255) DEFAULT NULL, `job` varchar(255) DEFAULT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), KEY `index_employees_on_partner_id` (`partner_id`), KEY `index_employees_on_name` (`name`), KEY `index_employees_on_prename` (`prename`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `experts` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `country_id` int(11) DEFAULT NULL, `name` varchar(255) NOT NULL, `prename` varchar(255) NOT NULL, `gender` varchar(255) NOT NULL, `birthday` date DEFAULT NULL, `degree` varchar(255) DEFAULT NULL, `former_collaboration` tinyint(1) NOT NULL DEFAULT '0', `fee` varchar(255) DEFAULT NULL, `job` varchar(255) DEFAULT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), KEY `index_experts_on_user_id` (`user_id`), KEY `index_experts_on_country_id` (`country_id`), KEY `index_experts_on_name` (`name`), KEY `index_experts_on_prename` (`prename`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `experts_languages` ( `expert_id` int(11) NOT NULL, `language_id` int(11) NOT NULL, KEY `index_experts_languages_on_expert_id_and_language_id` (`expert_id`,`language_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `languages` ( `id` int(11) NOT NULL AUTO_INCREMENT, `language` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_languages_on_language` (`language`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `list_items` ( `id` int(11) NOT NULL AUTO_INCREMENT, `list_id` int(11) NOT NULL, `item_id` int(11) NOT NULL, `item_type` varchar(255) NOT NULL, `note` varchar(255) DEFAULT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_list_items_on_list_id_and_item_id_and_item_type` (`list_id`,`item_id`,`item_type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `lists` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `title` varchar(255) NOT NULL, `private` tinyint(1) NOT NULL DEFAULT '1', `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), KEY `index_lists_on_user_id` (`user_id`), KEY `index_lists_on_title` (`title`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `partners` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `country_id` int(11) DEFAULT NULL, `company` varchar(255) NOT NULL, `street` varchar(255) DEFAULT NULL, `city` varchar(255) DEFAULT NULL, `zip` varchar(255) DEFAULT NULL, `region` varchar(255) DEFAULT NULL, `website` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `phone` varchar(255) DEFAULT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `fax` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), KEY `index_partners_on_company` (`company`), KEY `index_partners_on_user_id` (`user_id`), KEY `index_partners_on_country_id` (`country_id`), KEY `index_partners_on_street` (`street`), KEY `index_partners_on_city` (`city`), KEY `index_partners_on_zip` (`zip`), KEY `index_partners_on_region` (`region`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `partners_projects` ( `partner_id` int(11) NOT NULL, `project_id` int(11) NOT NULL, UNIQUE KEY `index_partners_projects_on_partner_id_and_project_id` (`partner_id`,`project_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `privileges` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `admin` tinyint(1) NOT NULL DEFAULT '0', `experts` tinyint(1) NOT NULL DEFAULT '0', `partners` tinyint(1) NOT NULL DEFAULT '0', `projects` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `index_privileges_on_user_id` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `project_infos` ( `id` int(11) NOT NULL AUTO_INCREMENT, `project_id` int(11) NOT NULL, `language` varchar(255) NOT NULL, `title` varchar(255) NOT NULL, `region` varchar(255) DEFAULT NULL, `client` varchar(255) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, `funders` varchar(255) DEFAULT NULL, `staff` varchar(255) DEFAULT NULL, `staff_months` varchar(255) DEFAULT NULL, `focus` text, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_project_infos_on_project_id_and_language` (`project_id`,`language`), KEY `index_project_infos_on_title` (`title`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `project_members` ( `id` int(11) NOT NULL AUTO_INCREMENT, `expert_id` int(11) NOT NULL, `project_id` int(11) NOT NULL, `role` varchar(255) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_project_members_on_expert_id_and_project_id` (`expert_id`,`project_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `projects` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `country_id` int(11) DEFAULT NULL, `title` varchar(255) DEFAULT NULL, `status` varchar(255) NOT NULL, `carried_proportion` int(11) NOT NULL DEFAULT '0', `start` date DEFAULT NULL, `end` date DEFAULT NULL, `order_value_us` int(11) DEFAULT NULL, `order_value_eur` int(11) DEFAULT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), KEY `index_projects_on_country_id` (`country_id`), KEY `index_projects_on_status` (`status`), KEY `index_projects_on_start` (`start`), KEY `index_projects_on_end` (`end`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `schema_migrations` ( `version` varchar(255) NOT NULL, UNIQUE KEY `unique_schema_migrations` (`version`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password_digest` varchar(255) NOT NULL, `login_hash` varchar(255) DEFAULT NULL, `name` varchar(255) NOT NULL, `prename` varchar(255) NOT NULL, `locale` varchar(255) NOT NULL DEFAULT 'en', `created_at` datetime NOT NULL, `current_list_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_users_on_username` (`username`), KEY `index_users_on_email` (`email`), KEY `index_users_on_login_hash` (`login_hash`), KEY `index_users_on_current_list_id` (`current_list_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO schema_migrations (version) VALUES ('1'); INSERT INTO schema_migrations (version) VALUES ('10'); INSERT INTO schema_migrations (version) VALUES ('11'); INSERT INTO schema_migrations (version) VALUES ('12'); INSERT INTO schema_migrations (version) VALUES ('13'); INSERT INTO schema_migrations (version) VALUES ('2'); INSERT INTO schema_migrations (version) VALUES ('3'); INSERT INTO schema_migrations (version) VALUES ('4'); INSERT INTO schema_migrations (version) VALUES ('5'); INSERT INTO schema_migrations (version) VALUES ('6'); INSERT INTO schema_migrations (version) VALUES ('7'); INSERT INTO schema_migrations (version) VALUES ('8'); INSERT INTO schema_migrations (version) VALUES ('9');<file_sep>/spec/factories/list.rb FactoryGirl.define do factory :list do title 'My List' private true association :user, factory: :user trait :public do private false end end factory :list_with_items, parent: :list do after(:build) do |list| 4.times { list.list_items << build(:list_item, list: list) } end end factory :list_with_3_items, parent: :list do after(:build) do |list| 3.times { list.list_items << build(:list_item, list: list) } end end end <file_sep>/app/searchers/expert_searcher.rb # Searches the experts table and associations. class ExpertSearcher < ApplicationSearcher search_helpers :name, :q, :languages protected # Searches name and prename. def name(name) @scope.where('name LIKE :n OR prename LIKE :n', n: "%#{name}%") end # Searches the fulltext associations. def q(query) search_ids(execute_sql(<<-SQL, q: query).map(&:first)) ( SELECT comments.commentable_id AS expert_id FROM comments WHERE comments.commentable_type = 'Expert' AND MATCH (comments.comment) AGAINST (:q IN BOOLEAN MODE) ) UNION ( SELECT cvs.expert_id FROM cvs WHERE MATCH (cvs.cv) AGAINST (:q IN BOOLEAN MODE) ) SQL end # Search languages conjunct. def languages(value) search_ids(search_join_table_conjunct( @klass.reflect_on_association(:languages), value)) end end <file_sep>/lib/active_record_helpers.rb # Mixes missing methods into active record. module ActiveRecordHelpers extend ActiveSupport::Concern # Additional class methods. module ClassMethods # Filters associations from an array of attributes/association names. # # class Article < ActiveRecord::Base # belongs_to :category # has_and_belongs_to_many :tags # end # # Article.filter_associations([:title, :body, :tags, :category]) # #=> [:tags, :category] # # Returns an array of association names. def filter_associations(names) names.map(&:to_sym) & reflect_on_all_associations.map(&:name) end # Checks if the model has a association. # # Article.association?(:tags) #=> true # # Returns true if the passed value is an association name, else false. def association?(name) ! reflect_on_association(name.to_sym).nil? end # Checks if the model has a belongs_to association. # # Article.belongs_to?(:category) #=> true # # Returns true if the model has a belongs_to association of the specified # name, else false. def belongs_to?(name) association_of_macro?(name, :belongs_to) end # Checks if the model has a has_one association. # # Article.has_one?(:category) #=> false # # Returns true if the model has a has_one association of the specified # name, else false. def has_one?(name) association_of_macro?(name, :has_one) end # Checks if the model has a has_many association. # # Article.has_many?(:tags) #=> false # # Returns true if the model has a has_many association of the specified # name else false. def has_many?(name) association_of_macro?(name, :has_many) end # Checks if the model has a has_and_belongs_to_many association. # # Article.has_and_belongs_to_many?(:tags) #=> true # # Returns true if the model has a has_and_belongs_to_many association of # the specified name else false. def has_and_belongs_to_many?(name) association_of_macro?(name, :has_and_belongs_to_many) end private # Checks if the model has a association of specific macro. # # Article.association_of_macro?(:category, :belongs_to) #=> true # # Returns true if the model has a association of the specified name and # macro else false. def association_of_macro?(name, macro) reflect_on_association(name.to_sym).try(:macro) == macro end end end ActiveRecord::Base.send :include, ActiveRecordHelpers <file_sep>/app/validators/old_password_validator.rb # Checks the users old password if it has changed. class OldPasswordValidator < ActiveModel::Validator # Performs the validation. def validate(record) if record.password_digest_changed? && BCrypt::Password.new(record.password_digest_was) != record.password_old record.errors.add(:password_old, I18n.t('messages.user.errors.password')) end end end <file_sep>/app/searchers/application_searcher.rb require 'set' # Base class of all searchers. # # class ArticleSearcher < ApplicationSearcher # search_helpers :title # # def title(value) # @scope.where('title LIKE ?', "%#{value}%") # end # end # # class Article < ActiveRecord::Base # has_and_belongs_to_many :tags # # def self.search(params) # ArticleSearcher.new(params.slice(:title, :tags)).search(scoped) # end # # def self.published # where(published: true) # end # end # # class ArticleController < ApplicationController # def index # @articles = Article.published.search(params).page(params[:page]) # end # end # # The vanilla ApplicationSearcher can search the associated tables by # default. Simply specify the the association name as key and an array of # ids as value. Additional search methods must be implemented in the # subclasses. class ApplicationSearcher class_attribute :_search_helpers # Inits the searcher. Takes a hash of conditions. def initialize(conditions) @conditions = normalize_conditions(conditions) end # Performs the search. # # Returns a ActiveRecord::Relation. def search(scope) @scope = scope @klass = scope.klass @conditions.each { |method, value| @scope = search_for(method, value) } @scope rescue ActiveRecord::RecordNotFound @klass.where('1 < 0') end private # Registers and returns a set of search helpers. def self.search_helpers(*methods) self._search_helpers ||= Set.new self._search_helpers += methods end # Returns the set of registered search helpers. def search_helpers self.class.search_helpers end # Returns an array of tuples from a hash. # # normalize_conditions("method" => "value", foo: 0, bar: ' ') # #=> [[:method, "value"], [:foo, 0]] # # Blanks are removed and method names symbolized. def normalize_conditions(conditions) conditions.map do |k, v| [k.to_sym, v] if v.present? || v.is_a?(FalseClass) end.compact end # Triggers the search method and passes the query. # # Returns ActiveRecord::Relation. def search_for(attr, value) if search_helpers.include?(attr) send(attr, value) else search_association(attr, value) end end # Searches an association and returns a ActiveRecord::Relation # # Raises ArgumentError for invalid association names. def search_association(name, value) if (reflection = @klass.reflect_on_association(name)) send(reflection.macro, reflection, value) else raise ArgumentError, "#@model has no association called #{name}" end end # Adds a id search condition to the relation. def search_ids(ids) if ids.empty? raise ActiveRecord::RecordNotFound, "Couldn't find any records." else @scope.where(@klass.primary_key => ids) end end # Executes some sql and returns the selected rows. def execute_sql(*args) @klass.connection.select_rows(@klass.send(:sanitize_sql, args)) end # Searches a has_one association. def has_many(reflection, ids) @scope.joins(reflection.name).where(reflection.table_name => { reflection.association_primary_key => ids }) end alias :belongs_to :has_many alias :has_one :has_many # Searches a has_and_belongs_to_many association. def has_and_belongs_to_many(reflection, ids) search_ids(search_join_table(reflection, ids)) end # Searches a join table and returns an array of ids. def search_join_table(reflection, ids) execute_sql(<<-SQL, ids: ids).map(&:first) SELECT join_table.#{reflection.foreign_key} FROM #{reflection.options[:join_table]} AS join_table WHERE join_table.#{reflection.association_foreign_key} IN (:ids) GROUP BY join_table.#{reflection.foreign_key} SQL end # Searches a join table conjunct and returns an array of ids. def search_join_table_conjunct(reflection, ids) execute_sql(<<-SQL, ids: ids, num: ids.length).map(&:first) SELECT join_table.#{reflection.foreign_key}, COUNT(*) AS num FROM #{reflection.options[:join_table]} AS join_table WHERE join_table.#{reflection.association_foreign_key} IN (:ids) GROUP BY join_table.#{reflection.foreign_key} HAVING num >= :num SQL end end <file_sep>/spec/factories/partner.rb FactoryGirl.define do factory :partner do company 'ACME Inc.' association :user, factory: :user end end <file_sep>/lib/tasks/db.rake namespace :db do task clean: :environment do Rails.application.eager_load! destroy_orphaned_tags end # Destroys all orphaned tags and sweeps the related caches. def destroy_orphaned_tags sweeper = TagSweeper.send(:new) sweeper.send(:controller=, ActionController::Base.new) klasses = ActiveRecord::Base.descendants.select do |klass| klass.respond_to?(:acts_as_tag?) && klass.acts_as_tag? end klasses.each do |klass| relation = klass klass.reflect_on_all_associations(:has_and_belongs_to_many).each do |ref| relation = relation.where <<-SQL #{klass.table_name}.id NOT IN ( SELECT DISTINCT join_table.#{ref.foreign_key} FROM #{ref.options[:join_table]} join_table ) SQL end ActiveRecord::Base.connection.transaction do relation.each do |record| puts "Destroy #{klass.name}: #{record.to_s}" if record.destroy sweeper.expire_caches_for(record) end end end end end end <file_sep>/app/models/business.rb # The Business model provides the possibility to add several industry sectors # to the partner companies. It is like tagging the partners. See the ActsAsTag # module for further description. # # Database schema: # # - *id:* integer # - *business:* string # # The business attribute is unique. class Business < ActiveRecord::Base acts_as_tag :business has_and_belongs_to_many :partners, uniq: true end <file_sep>/lib/tasks/partners.rake # encoding: UTF-8 require 'carmen' require 'colorize' require 'psych' require 'csv' namespace :partners do task :import, [:input] => [:environment] do |task, args| countries = nil File.open(File.expand_path('../countries.yml', __FILE__)) do |f| countries = Psych.load(f.read).fetch('countries') end countries.each { |c, code| countries[c] = Carmen::Country.coded(code) } country_from_s = lambda do |s| c = s.split('/')[0].gsub(/!|\?/, '').strip.titleize unless (co = countries[c]) || (co = Carmen::Country.named(c)) puts "Country Code for: \"#{c}\"" begin code = STDIN.gets.chomp end while ! (co = Carmen::Country.coded(code)) countries[c] = co end Country.find_by_country(co.code) end i = 0 user = User.first puts "Importing partners data from CSV file: #{args[:input]}" CSV.foreach(args[:input], col_sep: ';', headers: true) do |row| next if row.empty? data = row.to_hash $stdout.write "Importing: #{i += 1}\r" p = Partner.new p.user = user { company: 'Firma', zip: 'PLZ', street: 'Straße', city: 'Ort', phone: 'TelefonD', fax: 'Fax', email: 'EmailD', website: 'Homepage' }.each { |attr, key| p[attr] = data[key].try(:strip) } p.country = country_from_s.call(data['Land']) unless data['Land'].blank? p.comment.comment = data['Bemerkungen'].strip unless data['Bemerkungen'].blank? p.businesses = data['Kategorie'] if data['Kategorie'].present? unless (advisers = data['Ansprechpartner']).blank? evil = ['dr.', 'd.k.', 'dk', 'bs', 'dr', 'f', 'd', 'm'] p.advisers = advisers.underscore.split(/[,_\s\/\+]+/).reject do |adviser| evil.include?(adviser) end.map(&:capitalize).join(',') end unless (name = data['Name']).blank? p.employees << Employee.new.tap do |emp| { name: 'Name', prename: 'Vorname', job: 'Tätigkeit', title: 'Titel' }.each { |attr, key| emp[attr] = data[key].try(:strip) } emp.gender = (data['Anrede2'] =~ /Frau/) ? :female : :male { p_phones: 'TelefonP', b_phones: 'TelefonD2', m_phones: 'Handy', emails: 'EmailP' }.each do |attr, key| emp.contact.send(attr) << data[key] unless data[key].blank? end end end unless p.save $stderr.puts '=> Could not save dataset'.red p.errors.each do |attr, msg| $stderr.puts "===> #{Partner.human_attribute_name(attr)}: #{msg}".yellow end end end end end <file_sep>/spec/factories/user.rb FactoryGirl.define do factory :user do sequence(:username) { |n| "user#{n}" } sequence(:email) { |n| "<EMAIL>" } password 'doe' prename 'john' name 'doe' end factory :user_with_login_hash, parent: :user do after(:build) { |user| user.refresh_login_hash } end end <file_sep>/app/controllers/ajax/project_partners_controller.rb # class Ajax::ProjectPartnersController < Ajax::ApplicationController before_filter :find_project, only: [:index, :search] before_filter :find_potential_partners, only: [:index, :search] respond_to :html, only: [:index, :search] # GET /ajax/projects/:project_id/partners def index # implicit render(:index) end # GET /ajax/projects/:project_id/partners/search def search # implicit render(:search) end private def find_project @project = Project.find(params[:project_id]) end def find_potential_partners @partners = @project.potential_partners.search(params).limit(10) end end <file_sep>/app/models/contact.rb require 'set' # The Contact model provides an interface to store and retrieve contact # data. It uses the polymorphic association _contactable_ and stores the # data serialized as JSON. # # Every field described in the FIELDS list is accessible through # a method with the same name and returns a list. # # Example: # # class User < ActiveRecord::Base # has_one :contact, as: contactable, autosave: true # end # # user = User.find(1) # user.contact.emails # #=> ['<EMAIL>'] # user.contact.emails << '<EMAIL>' # #=> ['<EMAIL>', '<EMAIL>'] # user.save # # Database scheme: # # - *id* integer # - *contactable_id* integer # - *contactable_type* string # - *contact* text class Contact < ActiveRecord::Base serialize :contacts, JSON before_save :remove_blanks belongs_to :contactable, polymorphic: true after_initialize :init_contacts # List of contact fields. See model description above for more info. FIELDS = %w(emails p_phones b_phones m_phones fax skypes websites).to_set # Defines an access method for each field in the FIELDS array. FIELDS.each do |method| define_method(method) { self.contacts[method] ||= [] } end # Adds a contact to a field. Checks for valid fields, values and duplicates. # # contact.add(:emails, '<EMAIL>') # #=> ['<EMAIL>', '<EMAIL>'] # # Returns the field or false on error. def add(field, value) field, value = normalize_input(field, value) if value.present? && FIELDS.include?(field) && ! send(field).include?(value) send(field) << value else false end end # Does the same as Contact#add, but saves the record. # # Returns true on success, else false. def add!(field, value) add(field, value) && save end # Removes a contact from a field. Checks the validity of field. # # contact.remove(:emails, '<EMAIL>') # #=> '<EMAIL>' # # Returns the removed contact, or something falsy on error. def remove(field, value) field, value = normalize_input(field, value) FIELDS.include?(field) && send(field).delete(value) end # Does the same as Contact#remove, but saves the record. # # Returns true on success, else false. def remove!(field, value) remove(field, value) && save end # Returns true, if all contact fields are empty, else false. def empty? FIELDS.all? { |f| send(f).empty? } end private # Initializes the contacts hash. def init_contacts self.contacts ||= {} end # Removes all blank values from the contact hash. def remove_blanks FIELDS.each { |f| send(f).delete_if(&:blank?) } end # Normalizes untrusted input values. def normalize_input(field, value) [ field.to_s.downcase.strip, value.to_s.strip ] end end <file_sep>/app/models/employee.rb # The Employee model provides the possibility to add contact persons to a # partner company. # # Database schema: # # - *id:* integer # - *partner_id:* integer # - *name:* string # - *prename:* string # - *title:* string # - *gender:* string # - *job:* string # - *created_at:* datetime # - *updated_at:* datetime # # Every employee has one Contact. class Employee < ActiveRecord::Base attr_accessible :title, :name, :prename, :gender, :job attr_exposable :title, :name, :prename, :gender, :job, as: :csv attr_exposable :title, :name, :prename, :gender, :job, as: :pdf discrete_values :gender, [:male, :female], allow_nil: true validates :name, presence: true has_one :contact, autosave: true, dependent: :destroy, as: :contactable belongs_to :partner # Returns the employees Contact and initializes one if necessary. def contact super || self.contact = Contact.new end # Returns a string containing first name and last name. def full_name "#{prename} #{name}" end # Returns a string containing first name, last name and title. Returns # Employee#full_name() if the title attribute is blank. def full_name_with_title title.blank? ? full_name : "#{title} #{full_name}" end end <file_sep>/spec/lib/discrete_values_spec.rb require 'spec_helper' describe DiscreteValues do before(:all) do build_model :discrete_values_dummy do string :gender string :locale string :color string :size attr_accessible :gender, :locale, :color, :size discrete_values :gender, [:female, :male] discrete_values :locale, [:en, :de, :fr, :cs], default: :en, i18n_scope: :languages discrete_values :color, [:blue, :red], allow_blank: true discrete_values :size, [:s, :m, :l], validate: false end end describe :validations do subject { DiscreteValuesDummy.new } it { should ensure_inclusion_of(:gender).matches?(%w(female male)) } it { should ensure_inclusion_of(:locale).matches?(%w(en de fr cs)) } it { should ensure_inclusion_of(:color).matches?(%w(blue red)) } it { should_not ensure_inclusion_of(:size).matches?(%w(s m l)) } end describe :before_save do context 'with the default option' do subject { DiscreteValuesDummy.create(params) } context 'and an empty value' do let(:params) { { gender: :female } } it 'should be the default value' do expect(subject.locale).to eq('en') end end context 'and a valid value' do let(:params) { { gender: :female, locale: :cs } } it 'should be the assigned value' do expect(subject.locale).to eq('cs') end end end end describe :convert_discrete_value do subject { DiscreteValuesDummy.convert_discrete_value(value) } context 'when argument is a sympol' do let(:value) { :hello } it 'should be a string' do expect(subject).to eq('hello') end end [[1, 2, 3], { name: 'Peter' }, true, 12, 'example'].each do |value| context "when argument is #{value.inspect}" do let(:value) { value } it "should be #{value.inspect}" do expect(subject).to eq(value) end end end end describe :discrete_values_for do subject { DiscreteValuesDummy.locale_values } it 'should be a select box friendly list of all values' do expect(subject).to match_array([['English', 'en'], ['German', 'de'], ['French', 'fr'], ['Czech', 'cs']]) end end describe :set_default_discrete_value_for do subject { DiscreteValuesDummy.new(params) } before(:each) { subject.set_default_locale } context 'when value is empty' do let(:params) { {} } it 'should set the default value' do expect(subject.locale).to eq('en') end end context 'when value is set' do let(:params) { { locale: :example } } it 'should be the assigned value' do expect(subject.locale).to eq('example') end end end describe :read_discrete_value_attribute do subject { DiscreteValuesDummy.new(params) } context 'with a value' do let(:params) { { locale: :xx } } it 'should be the value as string' do expect(subject.locale).to eq('xx') end end context 'with an empty attribute' do let(:params) { {} } context 'and no default' do it 'should be nil' do expect(subject.gender).to be_nil end end context 'and a default' do it 'should be the default' do expect(subject.locale).to eq('en') end end end end describe :write_discrete_value_attribute do subject { DiscreteValuesDummy.new(params) } context 'when a symbol is assigned' do let(:params) { { locale: :de } } it 'should be a string' do expect(subject.read_attribute(:locale)).to eq('de') end end [[1, 2, 3], { num: 12 }, 1, true, 'string'].each do |value| context "when #{value.inspect} is assigned" do let(:params) { { gender: value } } it "should be #{value.inspect}" do expect(subject.gender).to eq(value) end end end end describe :human_discrete_value do subject { DiscreteValuesDummy.new(params) } context 'when value is nil' do let(:params) { {} } it 'should be nil' do expect(subject.human_gender).to be_nil end end context 'with custom i18n scope' do let(:params) { { locale: :de } } it 'should use the scope' do expect(subject.human_locale).to eq('German') end end context 'without custom i18n scope' do let(:params) { { gender: :female } } it 'should search the default scopes' do expect(subject.human_gender).to eq('Female') end end end end <file_sep>/app/helpers/application_helper.rb require 'bluecloth' require 'silo_page_links' # Contains several generic helper methods. module ApplicationHelper ActionView::Base.default_form_builder = FormHelper::FormBuilder # Returns all flash messages in separate div boxes. # # flash_all # #=> '<div class="flash alert">Something happend!</div>' def flash_all flash.inject('') do |html, item| html << content_tag(:div, item[1], class: "flash #{item[0].to_s}") end.html_safe end # Renders markdown formatted text. def markdown(txt = nil, &block) txt = capture(&block).strip_heredoc if block_given? content_tag :div, class: 'markdown' do BlueCloth.new(txt, auto_links: true, escape_html: true).to_html.html_safe end end # Returns an empty <div> with a proper icon-* class. # # icon(:lock) #=> '<div class="icon-lock"></div>' def icon(icon_name) content_tag :div, nil, class: "icon-#{icon_name}" end # Creates a delete button for a record. def delete_button_for(record, options = {}) options = { url: record, method: :delete, password: true, class: 'icon-trash', confirm: t(:"messages.#{record.class.name.underscore.downcase}.confirm.delete") }.merge(options) options['data-password'] = options.delete(:password) link_to(t('actions.delete'), options.delete(:url), options) end # Creates an editable button for a records attribute. def editable_button_for(record, method, options = {}) klass = record.class options = { url: [:ajax, record], 'data-editable' => method, 'data-prefix' => klass.name.underscore, 'data-name' => klass.human_attribute_name(method), 'data-editable-type' => klass.columns_hash[method.to_s].type, class: 'editable' }.merge(options) link_to(record.send(method) || '', options.delete(:url), options) end # Checks if the current user has access to the section and adds a # 'disabled' class to the link if not. # # resctricted_link_to 'secure stuff', url, :experts # #=> '<a href="#" class="disabled">secure stuff</a>' def restricted_link_to(txt, path, section, opt = {}) unless current_user.access?(section) opt[:class] = opt[:class].to_s << ' disabled' end link_to(txt, path, opt) end # Returns a pagination list. # # paginate(@experts) # #=> '<ul><li><span>1</span></li><li><a>2</a></li></ul>' def paginate(collection) if collection && collection.respond_to?(:total_pages) will_paginate collection, outer_window: 0, inner_window: 2, renderer: SiloPageLinks::Renderer end end end <file_sep>/app/controllers/projects_controller.rb # class ProjectsController < ApplicationController before_filter :check_password, only: [:destroy] before_filter :find_project, only: [:show, :documents, :edit, :update, :destroy] skip_before_filter :authorize, only: [:index, :show] # def authorize super(:projects, projects_url) end # GET /projects(/page/:page) def index @title = t('labels.project.all') @projects = Project.includes(:infos).search(params).page(params[:page]) end # GET /projects/:id(/:lang) def show if params.key?(:lang) @info = @project.info_by_language!(params[:lang]) else @info = @project.info end @title = @info.title end # GET /projects/:id/documents def documents @info = @project.info @title = @info.try(:title) end # GET /projects/new def new @project = Project.new @info = ProjectInfo.new render_form(:new) end # POST /projects def create @project = current_user.projects.build(params[:project]) @info = @project.infos.build(params[:project_info]) if @info.save flash[:notice] = t('messages.project.success.create', title: @info.title) redirect_to project_url(@project, @info.language) else flash.now[:alert] = t('messages.project.errors.create') render_form(:new) end end # GET /projects/:id/edit/:lang def edit @info = @project.info_by_language(params[:lang]) render_form(:edit) end # PUT /projects/:id/:lang def update @info = @project.info_by_language(params[:lang]) @info.project.attributes = params[:project] @info.project.user = current_user if @info.update_attributes(params[:project_info]) flash[:notice] = t('messages.project.success.save') redirect_to project_url(@project, @info.language) else flash.now[:alert] = t('messages.project.erros.save') render_form(:edit) end end # DELETE /projects/:id def destroy if @project.destroy flash[:notice] = t('messages.project.success.delete', title: @project.title) redirect_to projects_url else flash[:alert] = t('messages.project.errors.delete') redirect_to project_url(@project) end end private # Finds the project. def find_project @project = Project.find(params[:id]) end # Renders the projects form. def render_form(action) body_class << action @title = t("labels.project.#{action}") render :form end # Sets an error message and redirects the user. def not_found flash[:alert] = t('messages.project.errors.find') redirect_to projects_url end end <file_sep>/app/controllers/ajax/list_items_controller.rb # Handles list item related ajax requests. class Ajax::ListItemsController < Ajax::ApplicationController before_filter :find_list, except: [:print] skip_before_filter :authorize, only: [:update] respond_to :json, only: [:update] # Updates the list item. # # PUT /lists/:list_id/list_items/:id def update item = @list.list_items.find(params[:id]) if item.update_attributes(params[:list_item]) render json: item else error(t('messages.list_item.errors.update')) end end # Defines needed actions the print/add/remove list items. # # GET /ajax/lists/:list_id/{item_type}/print # POST /ajax/lists/:list_id/{item_type} # DELETE /ajax/lists/:list_id/{item_type} ListItem::TYPES.each_key do |item_type| [:print, :create, :destroy].each do |action| define_method("#{action}_#{item_type}") { send(action, item_type) } end end private # Serves a print dialog. def print(item_type) @item_type = item_type render :print end # Creates list items. def create(item_type) @list.add(item_type, arrayified_param(:ids)) render json: @list end # Destroys list items. def destroy(item_type) @list.remove(item_type, arrayified_param(:ids)) render json: @list end # Finds the list. def find_list if params[:list_id] == 'current' @list = current_list! else @list = current_user.accessible_lists.find(params[:list_id]) end end # Sets a proper not found error message. def not_found super(t('messages.list_item.errors.find')) end end <file_sep>/app/controllers/ajax/help_controller.rb # The HelpController serves help views. It is intended that they were loaded # via AJAX, so they were not rendered within a layout. # # To add a new help section create the view # _app/views/ajax/help/my_section.html.erb_. You can vistit it at # _/ajax/help/my_section_. class Ajax::HelpController < Ajax::ApplicationController caches_action :show # Serves a help section. def show render params[:id] rescue ActionView::MissingTemplate raise ActionController::RoutingError, 'Help not found.' end end <file_sep>/spec/models/user_spec.rb require 'spec_helper' describe User do describe :validations do before(:all) { @u = create(:user_with_login_hash) } after(:all) { @u.destroy } %w(password username name prename email).each do |attr| it { should validate_presence_of(attr) } end %w(username email login_hash).each do |attr| it { should validate_uniqueness_of(attr) } end ['Uppercase', 'white space', 'strange_*#'].each do |value| it { should_not allow_value(value).for(:username) } end it { should allow_value('lowercase1and1numbers304').for(:username) } end describe :associations do it { should have_many(:experts) } it { should have_many(:partners) } it { should have_many(:lists) } it { should have_one(:privilege).dependent(:destroy) } it { should belong_to(:current_list).class_name(:List) } end describe :delegations do subject { build(:user) } { access?: [:experts], admin?: [] }.each do |m, args| it "should delegate :#{m} to privilege" do expect(subject.send(m, *args)).to eq(subject.privilege.send(m, *args)) end end end describe :check_old_password_before_save do before { subject.check_old_password_before_save } it 'should set the check_old_password_before_save flag to true' do expect(subject.check_old_password_before_save?).to be_true end end describe :check_old_password_validation do subject { create(:user, password: '<PASSWORD>') } before do subject.check_old_password_before_save subject.password = '<PASSWORD>' end context 'when password changed without old password' do it 'should not be valid' do expect(subject).to_not be_valid expect(subject.errors[:password_old]).to_not be_empty end end context 'when password changed and old password is correct' do before { subject.password_old = '<PASSWORD>' } it 'should be valid' do expect(subject).to be_valid end end end describe :refresh_login_hash do subject { build(:user_with_login_hash) } it 'should be a 160 bit hexdigest' do expect(subject.refresh_login_hash).to match(%r{\A[a-f0-9]{40}\z}) end it 'should change the login hash' do expect { subject.refresh_login_hash }.to change { subject.login_hash } end it 'should be the same as the assigned login_hash' do expect(subject.refresh_login_hash).to eq(subject.login_hash) end end describe :refresh_login_hash! do subject { build(:user_with_login_hash) } it 'should be true' do expect(subject.refresh_login_hash!).to be_true end it 'should save the record' do expect { subject.refresh_login_hash! }.to change { subject.persisted? }.from(false).to(true) end it 'should change the login_hash' do expect { subject.refresh_login_hash! }.to change { subject.login_hash } end end describe :full_name do subject { build(:user, prename: 'John', name: 'Doe').full_name } it 'should be a combination of name and prename' do expect(subject).to eq('<NAME>') end end describe :to_s do subject { build(:user) } it 'should be the users full_name' do expect(subject.to_s).to eq(subject.full_name) end end end <file_sep>/db/migrate/008_add_lists.rb class AddLists < ActiveRecord::Migration def up create_table :lists do |t| t.integer :user_id, null: false t.string :title, null: false t.boolean :private, null: false, default: true t.timestamps end add_index :lists, :user_id add_index :lists, :title create_table :list_items do |t| t.integer :list_id, null: false t.integer :item_id, null: false t.string :item_type, null: false t.string :note, null: true t.timestamps end add_index :list_items, [:list_id, :item_id, :item_type], unique: true add_column :users, :current_list_id, :integer, null: true add_index :users, :current_list_id end def down remove_column :users, :current_list_id drop_table :list_items drop_table :lists end end <file_sep>/app/controllers/ajax/project_members_controller.rb class Ajax::ProjectMembersController < Ajax::ApplicationController before_filter :authorize, only: [:update] before_filter :find_project, only: [:index, :search, :new, :update] before_filter :find_member, only: [:update] before_filter :find_potential_expert, only: [:new] before_filter :find_potential_experts, only: [:index, :search] respond_to :html, only: [:index, :search] respond_to :json, only: [:update] # GET /ajax/projects/:project_id/project_members def index # implicit render(:index) end # GET /ajax/projects/:project_id/project_members/search def search # implicit render(:search) end # GET /ajax/projects/:project_id/project_members/new/:expert_id def new @member = @expert.project_members.build @url = { controller: '/project_members', action: :create } render(:form) end # PUT /ajax/projects/:project_id/project_members/:id def update if @member.update_attributes(params[:project_member]) render json: @member else error(t('messages.project_member.errors.save')) end end private # Checks the users authorization. def authorize super(:projects) end # Finds the project. def find_project @project = Project.find(params[:project_id]) end # Finds the member. def find_member @member = @project.members.find(params[:id]) end # Finds the potential expert def find_potential_expert @expert = @project.potential_experts.find(params[:expert_id]) end # Finds potential experts. def find_potential_experts @experts = @project.potential_experts.search(params).limit(10) end end <file_sep>/lib/acts_as_comment/not_a_comment.rb module ActsAsComment # Should be raised when a model does not act as a comment. class NotAComment < StandardError # Initializes the exception. Takes the model name as argument. def initialize(name) super("#{name} does not act as comment.") end end end <file_sep>/db/migrate/005_add_languages.rb class AddLanguages < ActiveRecord::Migration def up create_table :languages do |t| t.string :language, null: false end add_index :languages, :language, unique: true create_table :langs do |t| t.integer :language_id, null: false t.references :langable, polymorphic: true end add_index :langs, :language_id add_index :langs, [:langable_id, :langable_type] end def down drop_table :languages drop_table :langs end end <file_sep>/app/controllers/cvs_controller.rb # The CvsController provides actions to upload/download and destroy Cvs. class CvsController < ApplicationController before_filter :find_expert, only: [:create] skip_before_filter :authorize, only: [:show] # Sends the stored Cv document. # # GET /experts/:expert_id/cvs/:id def show cv = Cv.find(params[:id]) send_file cv.absolute_path.to_s, filename: cv.public_filename end # Creates a new Cv by storing an uploaded file and loading its content # into the database. # # POST /experts/:expert_id/cvs def create if @expert.cvs.build(params[:cv]).save_or_destroy flash[:notice] = t('messages.cv.success.store') else flash[:alert] = t('messages.cv.errors.store') end redirect_to documents_expert_url(@expert) end # Destroys a Cv. # # DELETE /experts/:expert_id/cvs/:id def destroy if Cv.find(params[:id]).destroy flash[:notice] = t('messages.cv.success.delete') else flash[:alert] = t('messages.cv.errors.delete') end redirect_to documents_expert_url(id: params[:expert_id]) end private # Checks, if the user has access to the experts section. def authorize super(:experts, expert_url(params[:expert_id])) end # Finds the expert def find_expert @expert = Expert.find(params[:expert_id]) rescue ActiveRecord::RecordNotFound flash[:alert] = t('messages.expert.errors.find') redirect_to experts_url end # Sets an alert flash and redirect to the experts detail page. def not_found flash[:alert] = t('messages.cv.errors.find') redirect_to documents_expert_url(params[:expert_id]) end # Sets a proper redirect url. def file_not_found super(documents_expert_path(params[:expert_id])) end end <file_sep>/spec/factories/contact.rb require 'securerandom' FactoryGirl.define do factory :contact do contacts 'emails' => ['<EMAIL>'] end factory :contact_with_contacts, parent: :contact do after(:build) do |contact| Contact::FIELDS.each do |field| 3.times { contact.send(field) << SecureRandom.hex(32) } end end end end <file_sep>/spec/lib/as_csv_spec.rb require 'spec_helper' describe AsCsv do before(:all) do build_model :keyboard do string :vendor integer :price boolean :nice has_many :keys, autosave: true, dependent: :destroy attr_accessible :vendor, :price, :nice attr_exposable :vendor, :price, :nice, as: :csv end build_model :key do string :code integer :keyboard_id belongs_to :keyboard attr_accessible :code attr_exposable :code, as: :csv end (1..2).each do |i| kb = Keyboard.create!(vendor: "ACME-#{i}", price: i - 2) %w(x y z).each { |code| kb.keys.create!(code: code) } end Keyboard.create! Keyboard.create!(vendor: "ACME-3", price: 10, nice: true) end after(:all) { Keyboard.destroy_all } describe :as_csv do subject { Keyboard.as_csv(params) } context 'without options' do let(:params) { {} } it 'should include all exposable attributes' do expect(subject).to eq(<<-CSV.strip_heredoc) vendor,price,nice ACME-1,-1,"" ACME-2,0,"" "","","" ACME-3,10,true CSV end context 'scoped' do subject { Keyboard.limit(2).as_csv } it 'should respect the scope' do expect(subject).to eq(<<-CSV.strip_heredoc) vendor,price,nice ACME-1,-1,"" ACME-2,0,"" CSV end end end context 'with options' do let(:params) { { only: :price } } it 'should respect them' do expect(subject).to eq(<<-CSV.strip_heredoc) price -1 0 "" 10 CSV end end context 'with the include option' do let(:params) { { include: :keys } } it 'should join the association' do expect(subject).to eq(<<-CSV.strip_heredoc) vendor,price,nice,code ACME-1,-1,"",x ACME-1,-1,"",y ACME-1,-1,"",z ACME-2,0,"",x ACME-2,0,"",y ACME-2,0,"",z "","","", ACME-3,10,true, CSV end end end end <file_sep>/spec/models/project_spec.rb require 'spec_helper' describe Project do describe :validations do it { should ensure_inclusion_of(:carried_proportion).in_range(0..100) } it { should ensure_inclusion_of(:status).in_array( [:forecast, :interested, :offer, :execution, :stopped, :complete]) } describe :start_must_be_earlier_than_end do subject { build(:project, start: startDate, end: endDate) } context 'when start is earlier than end' do let(:startDate) { Date.new(1980, 3, 3) } let(:endDate) { Date.new(2000, 2, 1) } it 'should be valid' do expect(subject).to be_valid end end context 'when start is nil' do let(:startDate) { nil } let(:endDate) { Date.new(2000, 2, 1) } it 'should be valid' do expect(subject).to be_valid end end context 'when end is nil' do let(:startDate) { Date.new(1980, 3, 3) } let(:endDate) { nil } it 'should be valid' do expect(subject).to be_valid end end context 'when start is later than end' do let(:startDate) { Date.new(2000, 2, 1) } let(:endDate) { Date.new(1980, 3, 3) } it 'should not be valid' do expect(subject).to_not be_valid expect(subject.errors[:start]).to_not be_empty expect(subject.errors[:end]).to_not be_empty end end end end describe :associations do it { should have_and_belong_to_many(:partners) } it { should have_many(:infos).dependent(:destroy) } it { should have_many(:members).dependent(:destroy) } it { should have_many(:attachments).dependent(:destroy) } it { should have_many(:list_items).dependent(:destroy) } it { should have_many(:lists).through(:list_items) } it { should belong_to(:user) } it { should belong_to(:country) } end describe :first_period_year do subject { Project.first_period_year } it 'should be 1970' do expect(subject).to eq(1970) end end describe :last_period_year do subject { Project.last_period_year } it 'should be 50 years after today' do expect(subject).to eq(Time.now.year + 50) end end describe :max_period do subject { Project.max_period } it 'should be range from the first possible year to the last' do expect(subject).to eq(Project.first_period_year..Project.last_period_year) end end describe :human_start do subject { build(:project, start: date).human_start(:short) } context 'when the start date is nil' do let(:date) { nil } it 'should be nil' do expect(subject).to be_nil end end context 'when the start date is a valid date' do let(:date) { Date.new(2001, 1, 13) } it 'should be the human readable start date' do expect(subject).to eq('January 13, 2001') end end end describe :human_end do subject { build(:project, end: date).human_end(:short) } context 'when the start date is nil' do let(:date) { nil } it 'should be nil' do expect(subject).to be_nil end end context 'when the start date is a valid date' do let(:date) { Date.new(2001, 1, 13) } it 'should be the human readable end date' do expect(subject).to eq('January 13, 2001') end end end describe :info? do context 'without any infos' do subject { create(:project) } it 'should be false' do expect(subject.info?).to be_false end end context 'with infos' do subject { create(:project, :with_infos) } it 'should be true' do expect(subject.info?).to be_true end end end describe :info do subject { create(:project, :with_infos) } it 'should be the first info' do expect(subject.info).to eq(subject.infos.first) end end describe :info_by_language do context 'without the specified info' do subject { create(:project) } it 'should not be persisted' do expect(subject.info_by_language(:de)).to_not be_persisted end it 'have the specified language' do expect(subject.info_by_language(:de).language).to eq('de') end it 'should be associated with the project' do expect(subject.info_by_language(:de).project).to eq(subject) end end context 'with the specified info' do subject { create(:project, :with_infos) } it 'should be the correct info' do expect(subject.info_by_language(:en)).to eq(subject.infos.find_by_language(:en)) end end end describe :info_by_language! do context 'without the specified info' do subject { create(:project) } it 'should throw an exception' do expect { subject.info_by_language!(:es) }.to raise_error(ActiveRecord::RecordNotFound) end end context 'with the specified info' do subject { create(:project, :with_infos) } it 'should be the correct info' do expect(subject.info_by_language!(:fr)).to eq(subject.infos.find_by_language(:fr)) end end end describe :potential_experts do before(:all) { @members = (1..3).map { create(:project_member) } } after(:all) { [Expert, Project, User].each { |m| m.destroy_all } } subject { create(:project, members: members).potential_experts } context 'when the project has no members' do let(:members) { [] } it 'should be a collection of all members' do expect(subject).to match_array(@members.map(&:expert)) end end context 'when the project has all members' do let(:members) { @members } it 'should find nothing' do expect(subject).to eq([]) end end context 'when project has one member' do let(:members) { [@members[0]] } it 'should find the other partners' do expect(subject).to match_array(@members[1..2].map(&:expert)) end end end describe :potential_partners do before(:all) { @partners = (1..3).map { create(:partner) } } after(:all) { [Partner, User].each { |m| m.destroy_all } } subject { create(:project, partners: partners).potential_partners } context 'when the project has no partners' do let(:partners) { [] } it 'should be a collection of all partners' do expect(subject).to match_array(@partners) end end context 'when the project has all partners' do let(:partners) { @partners } it 'should find nothing' do expect(subject).to eq([]) end end context 'when project has one partner' do let(:partners) { [@partners[0]] } it 'should find the other partners' do expect(subject).to match_array(@partners[1..2]) end end end describe :add_partner do subject { create(:project, :with_partners) } context 'when adding a new partner' do it 'should be the new collection of partners' do expect(subject.add_partner(build(:partner))).to match_array(subject.partners) end end context 'when adding an already added partner' do it 'should be false' do expect(subject.add_partner(subject.partners.first)).to be_false end end end describe :update_title do subject { create(:project, :with_infos) } before { subject.update_attribute(:title, 'Something') } it 'should be true' do expect(subject.update_title).to be_true end it 'should change the title from "Something" to the title of the first info' do expect { subject.update_title }.to change { subject.title }.from('Something').to(subject.info.title) end end describe :to_s do subject { create(:project, title: 'Something').to_s } it 'should be title' do expect(subject).to eq('Something') end end end <file_sep>/spec/models/project_member_spec.rb require 'spec_helper' describe ProjectMember do describe :validations do it { should validate_presence_of(:role) } end describe :associations do it { should belong_to(:expert) } it { should belong_to(:project) } end describe :db_indexes do it { should have_db_index([:expert_id, :project_id]).unique(true) } end describe :name do subject { create(:project_member) } it 'should be the name of the expert' do expect(subject.name).to eq(subject.expert.to_s) end end describe :to_s do subject { create(:project_member) } it 'should the combination of role and name' do expect(subject.to_s).to eq("#{subject.name} (#{subject.role})") end end end <file_sep>/spec/searchers/project_searcher_spec.rb require 'spec_helper' describe ProjectSearcher do before(:all) do @europe = build(:project, start: Date.new(1980), end: Date.new(2009), status: :forecast) @europe.partners << build(:partner, company: 'ACME') @europe.partners << build(:partner, company: 'Linux Foundation') @europe.infos << build(:project_info, language: :en, title: 'Europe', funders: 'World Bank', description: 'Crazy Project', service_details: 'Consulting and Management') @europe.infos << build(:project_info, language: :de, title: 'Europa', funders: 'Weltbank', description: 'Verrücktes Projekt', service_details: 'Beratung und Management') @europe.save @america = build(:project, start: Date.new(1950), end: Date.new(1956), status: :complete) @america.partners << build(:partner, company: 'Linux Foundation') @america.infos << build(:project_info, language: :en, title: 'America', funders: 'EDF', description: 'Holy crap', service_details: 'Consulting') @america.infos << build(:project_info, language: :de, title: 'Amerika', funders: 'EDF', description: 'Heilige Scheiße', service_details: 'Beratung') @america.infos << build(:project_info, language: :fr, title: 'Amérique', funders: 'EDF', description: 'sainte merde', service_details: 'Conseils') @america.save end after(:all) do [Partner, Project, ProjectInfo, User].each { |m| m.destroy_all } end subject { Project.search(conditions).all } describe :search do context 'when searching for partial title' do let(:conditions) { { title: 'urop' } } it 'should find the project with the right title' do expect(subject).to eq([@europe]) end end context 'when searching for status' do let(:conditions) { { status: :complete } } it 'should find the project with the correct status' do expect(subject).to eq([@america]) end end context 'when searching for start' do let(:conditions) { { start: '1924' } } it 'should find the projects with a start date later than the given year' do expect(subject).to eq([@america, @europe]) end end context 'when searching for end' do let(:conditions) { { end: '1999' } } it 'should find the projects with a end date earlier than the given year' do expect(subject).to eq([@america]) end end context 'when searching full text' do let(:conditions) { { q: 'Management' } } it 'should find the corerect projects' do expect(subject).to eq([@europe]) end end context 'when searching full text for funders' do let(:conditions) { { q: 'welt' } } it 'should find the project with the correct funders' do expect(subject).to eq([@europe]) end end context 'when searching full text in partners table' do let(:conditions) { { q: 'linux' } } it 'should find the corerect projects' do expect(subject).to eq([@america, @europe]) end end context 'when searching full text, start and end' do let(:conditions) { { q: 'Conseils Management', start: 1940, end: 2000 } } it 'should find the corerect projects' do expect(subject).to eq([@america]) end end context 'when searching full text and status' do let(:conditions) { { q: 'Management', status: :complete } } it 'should find the corerect projects' do expect(subject).to eq([]) end end end end <file_sep>/config/initializers/logging.rb # Disable colorized logging. ActiveRecord::LogSubscriber.colorize_logging = false <file_sep>/spec/factories/privilege.rb FactoryGirl.define do factory :privilege do admin false experts false partners false projects false association :user, factory: :user end end <file_sep>/spec/models/list_item_spec.rb require 'spec_helper' describe ListItem do describe :associations do it { should belong_to(:list) } it { should belong_to(:item) } end describe :TYPES do subject { ListItem::TYPES } it 'should be a hash containing item types' do expect(subject).to eq({ experts: Expert, partners: Partner, projects: Project }) end end describe :class_for_item_type do context 'invalid item type' do it 'should raise an ArgumentError' do expect { ListItem.class_for_item_type(:invalid) }.to raise_error(ArgumentError) end end context 'valid item type' do subject { ListItem.class_for_item_type(:experts) } it 'should be the model class' do expect(subject).to eq(Expert) end end end describe :by_type do context 'with invalid item type' do it 'should raise an ArgumentError' do expect { ListItem.by_type(:invalid) }.to raise_error(ArgumentError) end end context 'with valid item type' do before do 3.times { create(:list_item, item: build(:expert)) } 3.times { create(:list_item, item: build(:partner)) } end subject { ListItem.by_type(:experts) } it 'should have all experts' do expect(subject).to have(3).items end it 'should be a collection of list items of the specified type' do expect(subject).to be_all { |item| item.item_type == 'Expert' } end end context 'with the order option' do before do 3.times { create(:list_item, item: build(:expert)) } end subject { ListItem.by_type(:experts, order: true) } it 'should include the ordered items' do expect(subject.map(&:item)).to eq(Expert.order(Expert::DEFAULT_ORDER)) end end end describe :collection do context 'invalid item type' do it 'should raise an ArgumentError' do expect { ListItem.collection(:invalid, [1, 2, 3]) }.to raise_error(ArgumentError) end end context 'not exsiting ids' do subject { ListItem.collection(:experts, [2, 3, 4]) } it 'should be an empty' do expect(subject).to be_empty end end context 'when everything is fine' do before do 3.times { create(:partner) } @experts = (1..3).map { |_| create(:expert) } end subject { ListItem.collection(:experts, @experts.map(&:id)) } it 'should be not be empty' do expect(subject).to_not be_empty end it 'should be a collection of list items' do expect(subject).to be_all { |item| item.is_a?(ListItem) } end it 'should be a collection of new records' do expect(subject).to be_all { |item| item.new_record? } end it 'should contain all created items' do expect(subject.map(&:item)).to match_array(@experts) end end end describe :copy do before { @item = create(:list_item) } subject { @item.copy } it 'should be a new record' do expect(subject).to be_new_record end it 'should have the same note as the original' do expect(subject.note).to eq(@item.note) end context 'with params' do subject { @item.copy(note: 'Some other note.') } it 'should merge the params' do expect(subject.note).to eq('Some other note.') end end context 'with evil params' do it 'should raise an error' do expect { @item.copy(item_id: 12) }.to raise_error end end end describe :name do subject { build(:list_item) } it 'should be string representation of the actual item' do expect(subject.name).to eq(subject.item.to_s) end end describe :to_s do subject { build(:list_item) } it 'should be the list items name' do expect(subject.to_s).to eq(subject.name) end end end <file_sep>/app/reports/expert_report.rb # The ExpertsReport provides report rendering of the reports for an Expert. class ExpertReport < ApplicationReport # Builds the report. def initialize(expert, user) super(expert, user) info_table languages contacts addresses comment end private # Builds the languages section. def languages h2 :languages p (langs = @record.languages).empty? ? '-' : langs.map(&:to_s).join(', ') gap end # Builds the contacts def contacts h2 :contacts contacts_table end # Builds the addresses table. def addresses h2 :addresses @record.addresses.empty? ? p('-') : addresses_table gap end # Renders the addresses table def addresses_table data = [] @record.addresses.each_slice(4) do |slice| data << slice.map do |address| "#{address.address}\n\n#{address.country.try(:to_s)}" end end table data do |table| table.row_colors = ['ffffff'] table.columns(0..3).width = table.width / data.first.length table.cells.padding_bottom = 30 end end end <file_sep>/spec/controllers/users_controller_spec.rb require 'spec_helper' describe UsersController do include AccessSpecHelper before(:all) { grant_access(:admin) } after(:all) { revoke_access(:admin) } before(:each) { login } describe :index do before(:each) { get :index } it 'should assign @users' do expect(assigns(:users)).to_not be_empty expect(assigns(:users)).to be_all { |u| u.is_a?(User) } end end describe :new do before(:each) { get :new } it 'should assign @user' do expect(assigns(:user)).to be_a(User) expect(assigns(:user)).to be_new_record end it 'should render :form' do expect(response).to render_template(:form) end end describe :create do before(:each) { post :create, user: params } context 'when valid params' do let(:params) do { username: 'jd', name: 'Doe', prename: 'John', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } end it 'should create a new user' do expect(assigns(:user)).to be_a(User) expect(assigns(:user)).to be_persisted expect(assigns(:user).username).to eq('jd') end it 'should redirect to :index' do expect(response).to redirect_to(users_url) end end context 'when invalid params' do let(:params) { { prename: 'Mr.', name: 'Invalid' } } it 'should not save the user' do expect(assigns(:user)).to be_new_record end it 'should render :form' do expect(response).to render_template(:form) end end end describe :edit do before(:each) { get :edit, id: @user } it 'should assign @user' do expect(assigns(:user)).to eq(@user) end it 'should render :form' do expect(response).to render_template(:form) end end describe :update do before(:all) { @u = create(:user) } after(:all) { @u.destroy } before(:each) do put :update, id: id, user: params end let(:id) { @u } context 'when params invalid' do let(:params) { { username: '' } } it 'should not save the record' do expect(assigns(:user)).to be_changed expect(assigns(:user)).to_not be_valid end it 'should render :form' do expect(response).to render_template(:form) end end context 'when params valid' do let(:params) { { username: 'username123' } } it 'should save the record' do expect(assigns(:user)).to_not be_changed expect(@u.reload.username).to eq('username123') end it 'should redirect to users_url' do expect(response).to redirect_to(users_url) end end end describe :destroy do before(:each) { @u = create(:user) } context 'when action is not confirmed with password' do before(:each) { delete :destroy, id: @u } it 'should not delete the user' do expect(User.exists?(@u)).to be_true end it 'should redirect' do expect(response).to be_redirect end end context 'when user is current_user' do before(:each) do delete :destroy, id: @user, password: @credentials[:password] end it 'should not delete the user' do expect(User.exists?(@user)).to be_true end it 'should redirect to users_url' do expect(response).to redirect_to(users_url) end end context 'when everything is fine' do before(:each) do delete :destroy, id: @u, password: @credentials[:password] end it 'should delete the user' do expect(User.exists?(@u)).to be_false end it 'should redirect to users_url' do expect(response).to redirect_to(users_url) end end end end <file_sep>/lib/silo_page_links.rb require 'will_paginate/view_helpers/action_view' # Provides a custom LinkRenderer used with WillPaginate. module SiloPageLinks # The applications custom LinkRenderer used with WillPaginate. # # will_paginate collection, renderer: SiloPageLinks::Renderer class Renderer < WillPaginate::ActionView::LinkRenderer include ActionView::Context include ActionView::Helpers # Returns the page links HTML. def to_html content_tag :ul, class: 'pagination' do pagination.collect do |page| if page.is_a? Fixnum page_number(page) else send(page) end end.join('').html_safe end end # Returns the link for a single page number. def page_number(nr) content_tag :li do nr == current_page ? content_tag(:span, nr) : link_to(nr, url(nr)) end end # Returns the link to the previous page. def previous_page if current_page > 1 content_tag :li, class: 'back' do link_to '', url(current_page - 1) end end end # Returns the link to the next page. def next_page if current_page < total_pages content_tag :li, class: 'next' do link_to '', url(current_page + 1) end end end # Returns the gap. # # gap # #=> '<li><span class="gap">...</span></li>' def gap content_tag :li, content_tag(:span, '...', class: 'gap') end end end <file_sep>/spec/support/attachment_spec_helper.rb module AttachmentSpecHelper def self.included(base) base.before(:all) do @store = Rails.root.join(Rails.application.config.attachment_store) FileUtils.remove_entry_secure(@store) if @store.directory? end base.after(:all) do FileUtils.remove_entry_secure(@store) if @store.directory? end end def count_files(store) store.directory? ? store.children(false).length : 0 end def fixture_file_path(filename) ::Rails.root.join('spec', 'fixtures', 'files', filename) end def fixture_file_upload(filename, type = nil) ::ActionDispatch::Http::UploadedFile.new({ tempfile: open(fixture_file_path(filename)), filename: filename, type: type }) end end <file_sep>/spec/models/area_spec.rb require 'spec_helper' describe Area do context 'validations' do it 'must have an area' do a = Area.new a.should_not be_valid a.errors[:area].should_not be_empty end it 'must have a unique area' do create(:area, area: :EU) a = build(:area, area: :EU) a.should_not be_valid a.errors[:area].should_not be_empty end end context 'associations' do it { should have_many(:countries) } end describe 'with_ordered_countries' do it 'should be a collection of areas with ordered countries' do af = create(:area, area: :AF) # Africa eu = create(:area, area: :EU) # Europe gb = create(:country, country: :GB, area: eu) # United Kingdom de = create(:country, country: :DE, area: eu) # Germany cz = create(:country, country: :CZ, area: eu) # Czech Republic bj = create(:country, country: :BJ, area: af) # Benin ao = create(:country, country: :AO, area: af) # Angola Area.all.should =~ [af, eu] Country.all.should =~ [de, gb, cz, bj, ao] areas = Area.with_ordered_countries areas.should == [af, eu] areas[0].countries.should == [ao, bj] areas[1].countries.should == [cz, de, gb] end end describe 'human' do it 'should be the localized area name' do a = build(:area, area: :AF) a.human.should == I18n.t('areas.AF') end end describe 'to_s' do it 'should be the human area name' do a = build(:area) a.to_s.should == a.human end end end <file_sep>/app/models/cv.rb require 'yomu' # The Cv model provides the ability to add cvs to the Expert model. The # uploaded Cv is stored on the file system and its content is loaded into # the database (using the yomu gem) to allow fast fulltext search. # # Database scheme: # # - *id* intger # - *expert_id* integer # - *language_id* integer # - *cv* text class Cv < ActiveRecord::Base attr_accessible :file, :language validates :cv, presence: true validates :language_id, presence: true has_one :attachment, autosave: true, dependent: :destroy, as: :attachable belongs_to :expert belongs_to :language delegate :absolute_path, :created_at, :ext, to: :attachment, allow_nil: true default_scope includes(:language) # Saves the record or destroys it on failure. # # It triggers all after_destroy callbacks, e.g. Attachment#unlink(). def save_or_destroy success = save destroy unless success success end # Stores the file and loads its content into the cv attribute. def file=(file) build_attachment(file: file) load_document end # Assignes a language. def language=(language) super(Language.find_language(language)) end # Returns the public filename of the cv document. # # cv.public_filname # #=> 'cv-arthur-hoffmann-en.doc' def public_filename "cv #{expert.full_name} #{language.language}".parameterize + ext.to_s end private # Loads the documents text and stores it in the cv attribute. # # cv.load_document # #=> 'Hello Silo,\n\nHow are you today?' # # cv.cv # #=> 'Hello Silo,\n\nHow are you today?' # # Returns the documents text. def load_document self.cv = Yomu.new(absolute_path).text rescue self.cv = nil end end <file_sep>/app/models/adviser.rb # The Adviser model provides the possibility to add internal advisers to the # partner companies. It is like tagging the partners. See the ActsAsTag # module for further description. # # Database schema: # # - *id:* integer # - *adviser:* string # # The adviser attribute is unique. class Adviser < ActiveRecord::Base acts_as_tag :adviser has_and_belongs_to_many :partners, uniq: true end <file_sep>/app/controllers/ajax/application_controller.rb # The Ajax::ApplicationController is the base of all controllers in the Ajax # namespace. It provides special error handling and some tools to ensure a # nice ajaxified day. class Ajax::ApplicationController < ApplicationController before_filter :check_xhr skip_before_filter :authorize layout false respond_to :html, :json private # Renders an error message and sets the 401 status. def unauthorized error(t('messages.generics.errors.access'), 401) end # Renders an error message and sets the 404 status. def not_found(message = t('messages.generics.errors.find')) error(message, 404) end # Renders an error message and sets the 401, if the user is not logged in. def authenticate unauthorized unless current_user end # Renders an error message and sets the 401, if the user is not authorized. def authenticate(section = nil) unless (section ? current_user.access?(section) : current_user.admin?) unauthorized end end # Redirects the user the root url, if this is no ajax request. def check_xhr redirect_to(root_url) unless request.xhr? || Rails.env.development? end # Renders an error message and sets the response status code. def error(message, status = 422) render text: message, status: status end end <file_sep>/app/helpers/list_helper.rb # Defines several list related helpers. module ListHelper # Renders a link to the current list. def link_to_current_list if current_list link_to current_list.try(:title), list_experts_path(list_id: current_list) else link_to nil, lists_path end end # Renders a "print this list" button. def print_list_button_for(list, item_type) options = { url: send("print_ajax_list_#{item_type}_path", list), class: 'icon-print hidden-form' } link_to(t('actions.print'), options.delete(:url), options) end # Renders a "Remove item from this list" link. def remove_from_list_button_for(list, list_item, options = {}) options = { method: :delete, class: 'icon-removefromlist' }.merge(options) link_to(t('actions.remove'), [list, list_item], options) end # Renders a "share this list" button. def share_list_button_for(list) options = { method: :put, data: { '[list][private]' => 0 }, class: 'icon-globe' } options[:class] << ' disabled' unless list.private? link_to(t('actions.share'), list_path(list, options.delete(:data)), options) end # Creates an "open this list" link. def open_list_button_for(list) options = { remote: true, method: :put, 'data-id' => list.id, 'data-type' => :json, class: 'icon-folder-open open-list' } link_to(t('actions.open'), open_ajax_list_path(list), options) end # Creates a "import this list into that list" button. def import_list_button_for(list, other) options = { method: :put, 'data-other' => other.id, class: 'icon-addtolist' } link_to(t('actions.import'), concat_list_path(list), options) end # Returns the lilstable url for the specified item type. def listable_url(item_type) send(:"ajax_list_#{item_type}_path", list_id: :current) end # Renders a listable button for a single record or a collection of records. # # listable_button_for(expert) # #=> '<a href="/ajax/lists/current/experts" data-ids="432" ...></a>' # # listable_button_for(partners) # #=> '<a href="/ajax/lists/current/partners" data-ids="12 54 7" ...></a>' # # If a block is given, it is captured and used as the buttons content. def listable_button_for(record_or_collection, &block) collection = Array.wrap(record_or_collection) return nil if collection.empty? options = { remote: true, 'data-type' => :json, 'data-ids' => collection.map(&:id).join(' '), 'data-item-type' => ListItem::TYPES.key(collection.first.class), class: 'listable' } options['data-params'] = "ids=#{options['data-ids']}" url = listable_url(options['data-item-type']) if block_given? link_to(url, options, &block) else link_to(content_tag(:div, nil, class: 'marker'), url, options) end end end <file_sep>/app/models/list.rb # The List model provides the ability to group other models in lists. # # Database schema: # # - *id:* integer # - *user_id* integer # - *title* string # - *private* boolean # - *created_at* datetime # - *updated_at* datetime # # A title must be present. class List < ActiveRecord::Base attr_accessible :title, :private self.per_page = 50 is_commentable_with :comment, autosave: true, dependent: :destroy, as: :commentable validates :title, presence: true validate :public_list_can_not_be_set_to_private, on: :update has_many :list_items, autosave: true, dependent: :destroy has_many :current_users, class_name: :User, foreign_key: :current_list_id # Set up a has_many association for each item type. ListItem::TYPES.each do |type, klass| has_many type, through: :list_items, source: :item, source_type: klass end belongs_to :user default_scope order('lists.private DESC, lists.title ASC') # Selects lists, that are accessible for a user, which means that they # are associated with the user or that they are not private. # # current_user.id #=> 2 # # List.accessible_for(current_user) # #=> [ # # #<List id: 21, user_id: 2, private: true>, # # #<List id: 33, user_id: 2, private: false>, # # #<List id: 11, user_id: 7, private: false> # # ] # # Returns a ActiveRecord::Relation. def self.accessible_for(user) where('lists.user_id = ? OR lists.private = 0', user) end # Searches for lists. Taks a hash of conditions: # # - *:title* A (partial) title. # - *:private* Wether the list should be private or not. # - *:exclude* A list or a collection of lists to exclude. # # Returns a ActiveRecord::Relation. def self.search(params) ListSearcher.new(params.slice(:title, :private, :exclude)).search(scoped) end # Validates the value of private. It is not allowed to set public lists # private. Use List#copy instead. def public_list_can_not_be_set_to_private if private? && ! private_was errors.add(:private, I18n.t('messages.list.errors.public_to_private')) end end # Checks if a list is accessible for a user. Returns true if the user # has access to the list else false. def accessible_for?(user) public? || user_id == user.try(:id) end # Returns a copy of the list with all its list items. def copy(attributes = {}) dup.tap do |copy| copy.attributes = attributes copy.list_items = list_items.map(&:copy) end end # Adds one or more items to the list. # # list.add(:experts, 12) # #=> [#<ListItem id: 44, item_id: 12, item_type: 'Expert'>] # # list.add(:experts, [13, 44]) # #=> [ # # #<ListItem id: 15, item_id: 12, item_type: 'Expert'>, # # #<ListItem id: 16, item_id: 44, item_type: 'Expert'>, # # ] # # list.experts # #=> [#<Expert id: 12>, #<Expert id: 13>, #<Expert id: 44>] # # Returns a collection of the added items. def add(item_type, item_ids) add_collection(ListItem.collection(item_type, item_ids)) end # Removes one or more items from the list. # # list.partners # #=> [#<Partner id: 42>, #<Partner id: 11>, #<Partner id: 43>] # # list.remove(:partners, 42) # #=> [#<ListItem id: 9, item_id: 42, item_type: 'Partner'>] # # list.remove(:partners, [11, 43]) # #=> [ # # #<ListItem id: 91, item_id: 11, item_type: 'Partner'>, # # #<ListItem id: 17, item_id: 43, item_type: 'Partner'> # # ] # # list.partners # #=> [] # # Returns a collection of the removed items. def remove(item_type, item_ids) connection.transaction do ListItem.where(list_id: id, item_id: item_ids).by_type(item_type).destroy_all end end # Concatenates the list with another. # # list.experts # #=> [#<Expert id: 12>] # # another_list.experts # #=> [#<Expert id: 44>, #<Expert id: 23>] # # list.concat(another_list) # #=> #<List id: 12> # # list.experts # #=> [#<Expert id: 12>, #<Expert id: 44>, #<Expert id: 23>] # # Returns the list. def concat(other) add_collection(other.list_items.map { |item| item.copy(note: nil) }) self end # Adds the list items to the JSON reprensentation. def as_json(options = {}) super(options.merge(include: ListItem::TYPES.keys)) end # Returns true if the list is public, else false. def public? ! private? end # Returns the title def to_s title.to_s end private # Adds a collection of potetial list items to the list. # # list.add_collection(list.experts, Expert.where(id: [12, 13, 44]) # #=> [#<Expert id: 12>, #<Expert id: 13>, #<Expert id: 44>] # # Returns the collection. def add_collection(collection) connection.transaction do collection.each do |list_item| begin list_items << list_item rescue ActiveRecord::RecordNotUnique next end end end end end <file_sep>/config/initializers/modules.rb # Load custom modules. require 'as_csv' require 'acts_as_tag' require 'acts_as_comment' require 'active_record_helpers' require 'body_class' require 'discrete_values' require 'exposable_attributes' require 'human_attribute_names' require 'polymorphic_parent' <file_sep>/app/controllers/application_controller.rb # The ApplicationController handles authentication and provides generic # methods, used by several other controllers. All controllers extend the # ApplicationController. class ApplicationController < ActionController::Base rescue_from ActiveRecord::RecordNotFound, with: :not_found rescue_from ActionController::MissingFile, with: :file_not_found rescue_from ActionController::RedirectBackError, with: :go_home protect_from_forgery before_filter :authenticate before_filter :authorize before_filter :set_locale helper_method :current_list helper_method :current_user helper_method :current_user? # Appends a proper cache_path to all ActiveSupport::Concern.caches_action # calls. def self.caches_action(*actions) super *actions, cache_path: lambda { |_| action_cache_path } end private # Sets an error message and redirects the the root url. def unauthorized(url = root_url) flash[:alert] = t('messages.generics.errors.access') redirect_to url end # Sets a not found alert and redirects to the root url. def not_found flash[:alert] = t('messages.generics.errors.find') redirect_to root_url end # Sets a file not found alert and redirects to the root url. def file_not_found(url = root_url) flash[:alert] = t('messages.generics.errors.file_not_found') redirect_to url end # Redirects the user to the root url. def go_home redirect_to root_url end # Checks the users password and redirects her back, if it fails. It is # itended to be used as confirmation tool: # # "Are your sure? Please confirm with your password." # # Use it as a before filter. def check_password unless current_user.authenticate(params[:password]) flash[:alert] = t('messages.user.errors.password') redirect_to :back end end # Sets the users preferred locale. def set_locale I18n.locale = current_user.try(:locale) || locale_from_header end # Authorizes the user (or not) to complete a request. If the the user has # not the corresponding permissions, a flash message is set and the user # is redirected. def authorize(section = nil, url = root_url) unless (section ? current_user.access?(section) : current_user.admin?) unauthorized(url) end end # Redirects the user to the login, unless he/she is already logged in. def authenticate redirect_to login_url unless current_user end # Returns cache a path for a actions view, dependent on current controller, # action and locale. def action_cache_path I18n.locale.to_s << request.path end # Sends a report to the browser. def send_report(report) send_data report.render, filename: "report-#{report.title.parameterize}.pdf", type: 'application/pdf', disposition: 'inline' end # Returns a hash of arrayified params. # # params[:some_ids] #=> '123 423 65 34' # arrayified_params(:some_ids) #=> {some_ids: [123, 423, 65, 34]} # # This is useful in combination with params.merge to arrayify special keys. def arrayified_params(*keys) keys.inject({}) do |hsh, key| hsh[key] = arrayified_param(key) hsh end end # Returns an arrayified parameter. # # params[:some_ids] #=> '23 34 546' # arrayified_param(:some_ids) #=> [23, 34, 546] # # Returns an Array in any case. def arrayified_param(key) case (value = params[key]) when Array then value when Hash then value.values else value.to_s.split end end # Returns the body class. # # See the BodyClass module for more info. def body_class @body_class ||= super.tap { |b| b << :admin if current_user.try(:admin?) } end # Returns the current list of the current user. def current_list current_user.try(:current_list) end # Returns the current list, but raises ActiveRecord::RecordNotfound, # when current_list is nil. def current_list! current_list || raise(ActiveRecord::RecordNotFound, 'Couldn\'t find current list.') end # Returns the current user, if he/she is logged in. def current_user if session[:login_hash] @current_user ||= User.find_by_login_hash(session[:login_hash]) end end # Checks if a user is the current user. Returns true if the user is the # current user, else false. def current_user?(user) user == current_user end # Extracts the preferred locale from the ACCEPT-LANGUAGE header. def locale_from_header request.env['HTTP_ACCEPT_LANGUAGE'].to_s.scan(/^[a-z]{2}/).first end end <file_sep>/spec/models/language_spec.rb require 'spec_helper' describe Language do describe :validations do it 'must have a language' do expect(subject).to_not be_valid expect(subject.errors[:language]).to_not be_empty end it 'must have a unique language' do create(:language, language: 'de') subject.language = :de expect(subject).to_not be_valid expect(subject.errors).to_not be_nil end end describe :associations do it { should have_and_belong_to_many(:experts) } it { should have_many(:cvs) } end describe :PRIORITIES do it 'should be a set of symbols' do expect(Language::PRIORITIES).to eq(%w(de en fr es).to_set) end end describe :find_language do before(:all) do @de = create(:language, language: :de) @en = create(:language, language: :en) end after(:all) do @de.destroy @en.destroy end context 'when the language exists' do it 'should be found by symbol' do lang = Language.find_language(:de) expect(lang).to eq(@de) end it 'should be found by string' do lang = Language.find_language('de') expect(lang).to eq(@de) end it 'should be found by language' do lang = Language.find_language(@en) expect(lang).to eq(@en) end it 'should be found by id' do lang = Language.find_language(@de.id) expect(lang).to eq(@de) end it 'should be found by stringified id' do lang = Language.find_language(@en.id.to_s) expect(lang).to eq(@en) end end context 'when the language does not exist' do it 'should be nil' do lang = Language.find_language('fr') expect(lang).to be_nil end end end describe :find_language! do before(:all) do @de = create(:language, language: :de) end after(:all) do @de.destroy end context 'when the language exists' do it 'should be the language' do lang = Language.find_language!(:de) expect(lang).to eq(@de) end end context 'when the language does not exist' do it 'should raise ActiveRecord::RecordNotFound' do expect { Language.find_language!(:en) }.to raise_error(ActiveRecord::RecordNotFound) end end end describe :find_languages do before(:all) do @de = create(:language, language: :de) @en = create(:language, language: :en) @hi = create(:language, language: :hi) @fr = create(:language, language: :fr) end after(:all) do [@de, @en, @hi, @fr].each { |l| l.destroy } end context 'when searched by a mixed array' do it 'should find the languages' do languages = Language.find_languages(['de', @en.id, @hi]) expect(languages).to match_array([@de, @en, @hi]) end end context 'when searched by string' do it 'should find the languages in the string' do languages = Language.find_languages('en hi cz') expect(languages).to match_array([@en, @hi]) end end end describe :prioritized do before(:all) do @langs = (Language::PRIORITIES + %w('hi it').to_set).map do |l| create(:language, language: l) end end after(:all) do @langs.each { |l| l.destroy } end subject { Language.prioritized.pluck(:language) } it 'should find all prioritized languages' do expect(subject).to match_array(Language::PRIORITIES.to_a) end end describe 'ordered' do before(:all) do @hi = create(:language, language: :hi) # Hindi @en = create(:language, language: :en) # English @de = create(:language, language: :de) # German @fr = create(:language, language: :fr) # French end after(:all) do [@hi, @en, @de, @fr].each { |l| l.destroy } end it 'should be a collection ordered by human name' do expect(Language.all).to match_array([@hi, @en, @de, @fr]) expect(Language.ordered).to eq([@en, @fr, @de, @hi]) end end describe 'priority_ordered' do before(:all) do @hi = create(:language, language: :hi) # Hindi @en = create(:language, language: :en) # English (prioritized) @de = create(:language, language: :de) # German (prioritized) @cs = create(:language, language: :cs) # Czech end after(:all) do [@hi, @en, @de, @cs].each { |l| l.destroy } end it 'should be a collection ordered by human name and priority' do expect(Language.all).to match_array([@hi, @en, @de, @cs]) expect(Language.priority_ordered).to eq([@en, @de, @cs, @hi]) end end describe 'prioritzed?' do it 'should be true for prioritized languages' do build(:language, language: :en).prioritized?.should be_true build(:language, language: :de).prioritized?.should be_true end it 'should be false for unprioritized languages' do build(:language, language: :hi).prioritized?.should be_false build(:language, language: :cs).prioritized?.should be_false end end describe 'human' do it 'should be the localized language name' do l = build(:language, language: :en) l.human.should == I18n.t('languages.en') end end describe 'to_s' do it 'should be the human name' do l = build(:language) l.to_s.should == l.human end end end <file_sep>/spec/controllers/employees_controller_spec.rb require 'spec_helper' describe EmployeesController do include AccessSpecHelper before(:all) { @partner = create(:partner) } after(:all) do @partner.user.destroy @partner.destroy end before(:each) { login } describe :index do before { get :index, partner_id: @partner } it 'should assign @partner' do expect(assigns(:partner)).to eq(@partner) end end describe :create do before(:all) { grant_access(:partners) } after(:all) { revoke_access(:partners) } def send_request post :create, partner_id: @partner, employee: params end context 'when invalid data' do let(:params) { {} } it 'should not save the record' do expect { send_request }.to_not change { Employee.count } end end context 'when valid data' do let(:params) { { name: 'Doe', prename: 'John' } } it 'should save the record' do expect { send_request }.to change { Employee.count }.by(1) end it 'should attach the employee to the partner' do expect { send_request }.to change { @partner.employees(true).count }.by(1) end end end describe :update do before(:all) do grant_access(:partners) @employee = create(:employee, partner: @partner) end after(:all) do revoke_access(:partners) @employee.destroy end before { put :update, partner_id: @partner, id: @employee, employee: params } subject { @employee.reload } context 'when invalid data' do let(:params) { { name: '', prename: 'griffin' } } it 'should not save the record' do expect(subject.name).to_not be_blank end end context 'when data is valid' do let(:params) { { prename: 'peter', name: 'griffin' } } it 'should save the record' do expect(subject.prename).to eq('peter') expect(subject.name).to eq('griffin') end end end describe :destroy do before(:all) do grant_access(:partners) @employee = create(:employee, partner: @partner) end after(:all) do revoke_access(:partners) @employee.destroy end before { delete :destroy, partner_id: @partner, id: @employee } subject { @employee } it 'should destroy the record' do expect { subject.reload }.to raise_error(ActiveRecord::RecordNotFound) end end end <file_sep>/spec/controllers/profile_controller_spec.rb require 'spec_helper' describe ProfileController do include AccessSpecHelper before(:each) { login } describe :edit do before(:each) { get :edit } context 'when normal user' do it 'should assign @user with the current user' do expect(assigns(:user)).to eq(@user) end end context 'when admin' do before(:all) { grant_access(:admin) } after(:all) { revoke_access(:admin) } it 'should redirect to edit' do expect(response).to redirect_to(edit_user_url(@user)) end end end describe :update do before(:each) { put :update, user: params } let(:params) { {} } it 'should render :edit' do expect(response).to render_template(:edit) end it 'should assign the current user' do expect(assigns(:user)).to eq(@user) end context 'when everything is fine' do let(:params) { { name: 'Something valid' } } it 'should update the current user' do expect(@user.reload.name).to eq('Something valid') end end context 'when updating the password' do context 'and providing a wrong old password' do let(:params) { { password: '<PASSWORD>', password_old: '<PASSWORD>' } } it 'should not update the user' do expect(assigns(:user)).to be_changed expect(@user.reload.authenticate(@credentials[:password])).to eq(@user) end end context 'and providing correct old password' do let(:params) { { password: '<PASSWORD>', password_old: @credentials[:password] } } it 'should update the users password' do expect(assigns(:user)).to_not be_changed expect(@user.reload.authenticate('new password')).to eq(@user) end end end end end <file_sep>/spec/factories/cv.rb require 'securerandom' FactoryGirl.define do factory :cv do cv SecureRandom.hex(32) association :language, factory: :language association :expert, factory: :expert end end <file_sep>/db/migrate/012_add_projects.rb class AddProjects < ActiveRecord::Migration def up create_table :projects do |t| t.integer :user_id, null: false t.integer :country_id, null: true t.string :title, null: true t.string :status, null: false t.integer :carried_proportion, null: false, default: 0 t.date :start, null: true t.date :end, null: true t.integer :order_value_us, null: true t.integer :order_value_eur, null: true t.timestamps end [:country_id, :status, :start, :end].each do |col| add_index :projects, col end create_table :project_infos do |t| t.integer :project_id, null: false t.string :language, null: false t.string :title, null: false t.string :region, null: true t.string :client, null: true t.string :address, null: true t.string :funders, null: true t.string :staff, null: true t.string :staff_months, null: true t.text :focus, null: true t.timestamps end add_index :project_infos, :title add_index :project_infos, [:project_id, :language], unique: true create_table :project_members do |t| t.integer :expert_id, null: false t.integer :project_id, null: false t.string :role, null: false t.timestamps end add_index :project_members, [:expert_id, :project_id], unique: true create_table :partners_projects, id: false do |t| t.integer :partner_id, null: false t.integer :project_id, null: false end add_index :partners_projects, [:partner_id, :project_id], unique: true end def down drop_table :partners_projects drop_table :project_members drop_table :project_infos drop_table :projects end end <file_sep>/spec/factories/list_item.rb require 'securerandom' FactoryGirl.define do factory :list_item do sequence(:note) { |_| SecureRandom.hex(32) } association :list, factory: :list after(:build) do |list_item| list_item.item ||= build((rand(2) == 1) ? :expert : :partner) end end end <file_sep>/app/controllers/partners_controller.rb # Handles all partner related requests. class PartnersController < ApplicationController before_filter :check_password, only: [:destroy] before_filter :find_partner, only: [:show, :documents, :edit, :update, :destroy] skip_before_filter :authorize, only: [:index, :show, :documents] cache_sweeper :tag_sweeper, only: [:create, :update] # Searches for partners. # # GET /partners def index _params = params.merge(arrayified_params(:businesses, :country)) @partners = Partner.with_meta.search(_params).page(params[:page]) @title = t('labels.partner.all') end # Serves the partners details page. # # GET /partners/:id def show @title = @partner.company respond_to do |format| format.html format.pdf { send_report PartnerReport.new(@partner, current_user) } end end # Serves the experts documents page. # # GET /partners/:id/documents def documents @title = @partner.company end # Serves an empty partner form. # # GET /partners/new def new @partner = Partner.new render_form(:new) end # Creates a new partner. # # POST /partners def create @partner = current_user.partners.build(params[:partner]) if @partner.save flash[:notice] = t('messages.partner.success.create', name: @partner.company) redirect_to partner_url(@partner) else flash.now[:alert] = t('messages.partner.errors.create') render_form(:new) end end # Serves an edit form. # # GET /partners/:id/edit def edit render_form(:edit) end # Updates the partner. # # PUT /partners/:id def update @partner.user = current_user if @partner.update_attributes(params[:partner]) flash[:notice] = t('messages.partner.success.save') redirect_to partner_url(@partner) else flash.now[:alert] = t('messages.partner.errors.save') render_form(:edit) end end # Deletes the partner. # # DELETE /partners/:id def destroy if @partner.destroy flash[:notice] = t('messages.partner.success.delete', name: @partner.company) redirect_to partners_url else flash[:alert] = t('messages.partner.errors.delete') redirect_to partner_url(@partner) end end private # Checks the users permissions. def authorize super(:partners, partners_url) end # Finds the partner. def find_partner @partner = Partner.find(params[:id]) end # Renders the partners form. def render_form(action) body_class << action @title = t("labels.partner.#{action}") render :form end # Sets an error message and redirects the user. def not_found flash[:alert] = t('messages.partner.errors.find') redirect_to partners_url end end <file_sep>/app/controllers/profile_controller.rb # Provides actions to show/update the users profiles. class ProfileController < ApplicationController before_filter { body_class << :users } skip_before_filter :authorize # Serves the users profile. Admins are redirected to their edit page. # # GET /profile def edit if current_user.admin? redirect_to edit_user_url(current_user) else @user = current_user @title = t('labels.user.profile') end end # Updates a users profile. If a user wants to change his(her password, the # old password is required. # # PUT /profile def update @user = current_user @user.check_old_password_before_save if @user.update_attributes(params[:user]) I18n.locale = @user.locale flash.now[:notice] = t('messages.generics.success.save') else flash.now[:alert] = t('messages.generics.errors.save') end @title = t('labels.user.profile') body_class << :edit render :edit end end <file_sep>/app/sweepers/tag_sweeper.rb # Observes tag like models and expires the caches. class TagSweeper < ActionController::Caching::Sweeper observe Business, Adviser # Expires all tag related caches. def expire_caches_for(record) key = "/ajax/tags/#{record.class.name.downcase.pluralize}" I18n.available_locales.each do |locale| expire_fragment("#{locale}#{key}") expire_fragment("#{locale}#{key}.json") end end alias after_create expire_caches_for alias after_update expire_caches_for alias after_destroy expire_caches_for end <file_sep>/lib/acts_as_comment/is_commentable_with.rb module ActsAsComment module IsCommentableWith extend ActiveSupport::Concern # Defines ClassMethods#is_commentable_with # # See ActsAsComment for more info. module ClassMethods # Makes model commentable with one or more comment models. def is_commentable_with(assoc, options = {}) attr_accessible(assoc) klass = has_one(assoc, options).klass unless klass.respond_to?(:acts_as_comment?) && klass.acts_as_comment? raise NotAComment, klass.name end define_method(assoc) do |reload = false| super(reload) || association(assoc).writer(klass.new) end define_method("#{assoc}=") do |value| if value.is_a?(klass) super(value) else send(assoc).write_comment_attribute(value) end end end end end end ActiveRecord::Base.send :include, ActsAsComment::IsCommentableWith <file_sep>/app/reports/partner_report.rb # The PartnerReport provides report rendering of the reports for a Partner. class PartnerReport < ApplicationReport # Builds the report. def initialize(partner, user) super(partner, user) info_table comment employees end private # Lists the employees. def employees h2 :employees @record.employees.empty? ? p('-') : employee_tables end # Renders the employee tables. def employee_tables @record.employees.each do |employee| h3 employee.full_name info_table(employee) contacts_table(employee) end end end <file_sep>/spec/factories/project_member.rb require 'securerandom' FactoryGirl.define do factory :project_member do sequence(:role) { |_| SecureRandom.hex(16) } association :expert, factory: :expert association :project, factory: :project end end <file_sep>/spec/searchers/partner_searcher_spec.rb require 'spec_helper' describe PartnerSearcher do before(:all) do @businesses = %w(Tech Finance Pharma).each_with_object({}) do |val, hsh| hsh[val.downcase.to_sym] = create(:business, business: val) end @acme = build(:partner, company: 'ACME Inc.') @acme.businesses = @businesses.values_at(:tech, :finance) @acme.save @silo = build(:partner, company: 'Silo Inc.') @silo.businesses = @businesses.values_at(:tech, :pharma) @silo.save end after(:all) do [Business, Partner, User].each { |m| m.destroy_all } end subject { Partner.search(conditions).all } describe :search do context 'when searching for company' do let(:conditions) { { company: 'CME' } } it 'should find partners with partial company names' do expect(subject).to match_array([@acme]) end end context 'when searching for businesses' do context 'when searching for tech' do let(:conditions) { { businesses: @businesses.values_at(:tech) } } it 'should be silo and acme' do expect(subject).to match_array([@acme, @silo]) end end context 'when searching for finance' do let(:conditions) { { businesses: @businesses.values_at(:finance) } } it 'should be acme' do expect(subject).to match_array([@acme]) end end context 'when searching for finance and pharma' do let(:conditions) do { businesses: @businesses.values_at(:finance, :pharma) } end it 'should be acme and silo' do expect(subject).to match_array([@acme, @silo]) end end context 'when searching for finance, tech and something strange' do let(:conditions) do { businesses: @businesses.values_at(:finance, :tech, :strange) } end it 'should be acme and silo' do expect(subject).to match_array([@acme, @silo]) end end end end end <file_sep>/spec/lib/acts_as_comment_spec.rb require 'spec_helper' describe ActsAsComment do before(:all) do build_model :dummy_comment do integer :commentable_id string :commentable_type text :comment acts_as_comment :comment, for: :commentable, polymorphic: true end build_model :dummy_description do integer :dummy_id text :description acts_as_comment :description, for: :dummy end build_model :dummy_text do text :text acts_as_comment :text end build_model :dummy do string :name is_commentable_with :comment, class_name: :DummyComment, autosave: true, dependent: :destroy, as: :commentable end end describe :acts_as_comment do describe :associations do context 'when no association is specified' do it 'should not exist' do expect(DummyText.reflect_on_all_associations).to be_empty end end context 'when association is specified' do it 'should be present' do expect(DummyDescription.new).to belong_to(:dummy) end context 'and options are given' do it 'should be present' do reflection = DummyComment.reflect_on_association(:commentable) expect(reflection.options[:polymorphic]).to be_true end end end end describe :acts_as_comment? do context 'when model acts as comment' do it 'should be true' do expect(DummyComment.acts_as_comment?).to be_true end end context 'when model does not act as coment' do it 'should not be defined' do expect(Dummy).to_not respond_to(:acts_as_comment?) end end end describe :write_comment_attribute do it 'should assign the stringified value' do comment = DummyComment.new comment.write_comment_attribute(12) expect(comment.comment).to eq('12') end end describe :after_initialize do context 'when comment is blank' do it 'should initialize comment with an empty string' do expect(DummyComment.new.comment).to eq('') end end context 'when comment is not blank' do before(:all) { @comment = DummyComment.create(comment: 'Hello') } after(:all) { @comment.destroy } it 'should not override the comment' do expect(@comment.reload.comment).to eq('Hello') end end end describe :to_s do it 'should be the comment attribute as string' do c = DummyComment.new expect(c.to_s).to eq('') c.comment = 'Example' expect(c.to_s).to eq('Example') c.comment = 12 expect(c.to_s).to eq('12') end end end describe :is_commentable_with do context 'when associated model is invalid' do class InvalidDummy < ActiveRecord::Base; end context 'when it does not exist' do it 'should raise NameError' do expect { InvalidDummy.is_commentable_with :invalid }.to raise_error(NameError) end end context 'when it is not commentable' do it 'should raise a NotAComment error' do expect { InvalidDummy.is_commentable_with :dummy }.to raise_error(ActsAsComment::NotAComment) end end end context 'when associated model is valid' do it 'should define a has_one association' do expect(Dummy.new).to have_one(:comment).dependent(:destroy) end end describe :comment_reader do context 'when new record' do it 'should be a new comment' do comment = Dummy.new.comment expect(comment).to be_a(DummyComment) expect(comment).to be_new_record end end context 'when persisted record' do before(:all) do @comment = DummyComment.new @dummy = Dummy.create(comment: @comment) end after(:all) { @dummy.destroy } it 'should be the comment' do expect(@dummy.reload.comment(true)).to eq(@comment) end end end describe :comment_writer do before(:each) do @dummy = Dummy.new @comment = DummyComment.new end context 'when comment is a Comment' do it 'should assign the comment' do @dummy.comment = @comment expect(@dummy.comment).to eq(@comment) end end context 'when comment is not a Comment' do it 'should assign the stringified value to the comment' do @dummy.comment = 'Example' expect(@dummy.comment).to be_a(DummyComment) expect(@dummy.comment.to_s).to eq('Example') end end end end end <file_sep>/spec/factories/expert.rb require 'securerandom' FactoryGirl.define do factory :expert do sequence(:name) { |_| SecureRandom.hex(32) } sequence(:prename) { |_| SecureRandom.hex(32) } gender :male association :user, factory: :user trait :female do prename 'Jane' gender :female end end end <file_sep>/app/models/description.rb # The Description model provides the ability to equip the Partner model # with searchable description. # # Database scheme: # # - *id:* integer # - *partner_id:* integer # - *description:* text # - *created_at:* datetime # - *updated_at:* datetime # # There is a MySQL fulltext index on the description column. # # See ActsAsComment for more info. class Description < ActiveRecord::Base acts_as_comment :description, for: :describable, polymorphic: true end <file_sep>/db/seeds.rb # Add the initial user [['ushi', 'kalcher'], ['hendrik', 'froemmel']].each do |prename, name| user = User.new(name: name.capitalize, prename: prename.capitalize) user.username = prename user.password = <PASSWORD> user.email = <EMAIL>" user.privilege.admin = true user.save! end # Add all available languages I18n.t(:languages).each do |k, _| Language.create!(language: k) end # Continents => Countries map areas = { # Africa Area.new(area: :AF) => [ :DZ, :AO, :BW, :BI, :CM, :CV, :CF, :TD, :KM, :YT, :CG, :CD, :BJ, :GQ, :ET, :ER, :DJ, :GA, :GM, :GH, :GN, :CI, :KE, :LS, :LR, :LY, :MG, :MW, :ML, :MR, :MU, :MA, :MZ, :NA, :NE, :NG, :GW, :RE, :RW, :SH, :ST, :SN, :SC, :SL, :SO, :ZA, :ZW, :SS, :EH, :SD, :SZ, :TG, :TN, :UG, :EG, :TZ, :BF, :ZM ], # America Area.new(area: :AM) => [ :AG, :BS, :BB, :BM, :BZ, :VG, :CA, :KY, :CR, :CU, :DM, :DO, :SV, :GL, :GD, :GP, :GT, :HT, :HN, :JM, :MQ, :MX, :MS, :AN, :CW, :AW, :SX, :BQ, :NI, :UM, :PA, :PR, :BL, :KN, :AI, :LC, :MF, :PM, :VC, :TT, :TC, :US, :VI, :AR, :BO, :BR, :CL, :CO, :EC, :FK, :GF, :GY, :PY, :PE, :SR, :UY, :VE ], # Antarktika Area.new(area: :AN) => [:AQ, :BV, :GS, :TF, :HM], # Asia Area.new(area: :AS) => [ :AF, :AZ, :BH, :BD, :AM, :BT, :IO, :BN, :MM, :KH, :LK, :CN, :TW, :CX, :CC, :GE, :PS, :HK, :IN, :ID, :IR, :IQ, :IL, :JP, :KZ, :JO, :KP, :KR, :KW, :KG, :LA, :LB, :MO, :MY, :MV, :MN, :OM, :NP, :PK, :PH, :TL, :QA, :RU, :SA, :SG, :VN, :SY, :TJ, :TH, :AE, :TR, :TM, :UZ, :YE, :XE, :XD, :XS ], # European Union Area.new(area: :E2) => [ :AT, :BE, :BG, :CY, :CZ, :DK, :EE, :FI, :FR, :DE, :GR, :HU, :IE, :IT, :LV, :LT, :LU, :MT, :NL, :PL, :PT, :RO, :SK, :SI, :ES, :SE, :GB ], # Europe Area.new(area: :EU) => [ :AL, :AD, :AZ, :AM, :BA, :BY, :HR, :FO, :AX, :GE, :GI, :VA, :IS, :KZ, :LI, :MC, :MD, :ME, :NO, :RU, :SM, :RS, :SJ, :CH, :TR, :UA, :MK, :GG, :JE, :IM ], # Oceania Area.new(area: :OC) => [ :AS, :AU, :SB, :CK, :FJ, :PF, :KI, :GU, :NR, :NC, :VU, :NZ, :NU, :NF, :MP, :UM, :FM, :MH, :PW, :PG, :PN, :TK, :TO, :TV, :WF, :WS, :XX ] } # Add all countries I18n.t(:countries).each do |k, _| Country.create!(country: k, area: areas.find { |_, v| v.include? k }.first) end <file_sep>/spec/models/comment_spec.rb require 'spec_helper' describe Comment do it 'should acts as comment' do expect(Comment.acts_as_comment?).to be_true end describe :associations do it { should belong_to(:commentable) } end end <file_sep>/db/migrate/013_polymorphic_descriptions.rb class PolymorphicDescriptions < ActiveRecord::Migration def up remove_index :descriptions, :partner_id add_column :descriptions, :describable_type, :string, null: false, default: 'Partner' rename_column :descriptions, :partner_id, :describable_id add_index :descriptions, [:describable_id, :describable_type] end def down remove_index :descriptions, column: [:describable_id, :describable_type] rename_column :descriptions, :describable_id, :partner_id remove_column :descriptions, :describable_type add_index :descriptions, :partner_id end end <file_sep>/app/searchers/list_searcher.rb # Searches the lists table. class ListSearcher < ApplicationSearcher search_helpers :title, :private, :exclude protected # Searches the title. def title(title) @scope.where('lists.title LIKE ?', "%#{title}%") end # Searches the private/public lists. def private(value) @scope.where(private: value) end # Excludes lists by id. def exclude(ids) @scope.where('lists.id NOT IN (?)', ids) end end <file_sep>/app/models/privilege.rb # The Privilege model is used to hold User permissions. # # Database Scheme: # # - *user_id* integer # - *amdin* boolean # - *experts* boolean # - *partners* boolean # - *projects* boolean # # This is not very fancy. class Privilege < ActiveRecord::Base belongs_to :user attr_accessible :admin, :experts, :partners, :projects, as: :admin # A list of all sections. SECTIONS = [:experts, :partners, :projects] # Checks for access privileges for a specified section. # # if privilege.access?(:experts) # write_some_experts_data(data) # end # # Returns true if access is granted, else false. def access?(section) admin? || (respond_to?(section) && send(section)) end # Checks permissions to write some employees data. Employee is a subresource # of Partner, so the user needs the permissions to write partners data. def employees partners? end end <file_sep>/app/models/area.rb # The Area model provides access to the areas data. It is used to group the # countries from the Country model. # # Database scheme: # # - *id* integer # - *area* string class Area < ActiveRecord::Base attr_accessible :area validates :area, presence: true, uniqueness: true has_many :countries default_scope order(:area).includes(:countries) # Returns all areas and their countries, ordered by their localized name. def self.with_ordered_countries all.each do |area| area.countries.sort! { |x, y| x.human <=> y.human } end end # Returns the localized name of the area. def human I18n.t(area, scope: :areas) end alias :to_s :human end <file_sep>/app/controllers/contacts_controller.rb # The ContactsController provides all actions needed to add/remove contacts # to/from a associated model. class ContactsController < ApplicationController before_filter :find_parent, only: [:create, :destroy] polymorphic_parent :experts, :employees # Adds a contact to a model, that has a _has_one_ association to the Contact # model. It uses the _params_ hash to determine the contact field and the # contact value. # # It is expected that the params hash includes both fields # # params[:contact][:field] # Fieldname, such as :emails or :phones # params[:contact][:contact] # Value, such as '<EMAIL>' # # The user is redirected to the parents show page. # # POST /parents/:parent_id/contacts def create field, contact = params[:contact].try(:values_at, :field, :contact) if @parent.contact.add!(field, contact) flash[:notice] = t('messages.contact.success.save') else flash[:alert] = t('messages.contact.errors.save') end redirect_to :back end # Removes a contact from a field. It behaves like # ContactsController#add_to(), but vice versa. # # DELETE /parents/:parent_id/contacts/:id def destroy field, contact = params.values_at(:field, :contact) if @parent.contact.remove!(field, contact) flash[:notice] = t('messages.contact.success.delete') else flash[:alert] = t('messages.contact.errors.delete') end redirect_to(:back) end private # Checks the users privileges. def authorize super(parent[:controller], :back) end end <file_sep>/app/searchers/project_searcher.rb # Searches the projects table and its associations. class ProjectSearcher < ApplicationSearcher search_helpers :title, :status, :start, :end, :q protected # Searches the title attribute. def title(q) @scope.includes(:infos).where('project_infos.title LIKE ?', "%#{q}%") end # Searches the status attribute. def status(q) @scope.where(status: q) end # Searches the start attribute. def start(q) @scope.where('projects.start > ?', Date.new(q.to_i)) end # Searches the end attribute. def end(q) @scope.where('projects.end < ?', Date.new(q.to_i)) end # Performs a fuzzy search. def q(q) search_ids(search_fuzzy(q)) end private # Executes the fuzzy search. # # Returns an array of partner ids. def search_fuzzy(query) execute_sql(<<-SQL, q: query, like: "%#{query}%").map(&:first) ( SELECT project_infos.project_id FROM project_infos WHERE project_infos.funders LIKE :like ) UNION ( SELECT partners_projects.project_id FROM partners_projects JOIN partners ON partners.id = partners_projects.partner_id WHERE partners.company LIKE :like ) UNION ( SELECT project_infos.project_id FROM project_infos JOIN comments ON comments.commentable_id = project_infos.id AND comments.commentable_type = 'ProjectInfo' JOIN descriptions ON descriptions.describable_id = project_infos.id AND descriptions.describable_type = 'ProjectInfo' WHERE MATCH (comments.comment) AGAINST (:q) OR MATCH (descriptions.description) AGAINST (:q) ) SQL end end <file_sep>/db/migrate/006_remove_langs.rb class RemoveLangs < ActiveRecord::Migration def up create_table :experts_languages, id: false do |t| t.integer :expert_id, null: false t.integer :language_id, null: false end add_index :experts_languages, [:expert_id, :language_id], unqiue: true execute <<-SQL INSERT INTO experts_languages (expert_id, language_id) SELECT langs.langable_id, langs.language_id FROM langs SQL drop_table :langs end def down create_table :langs do |t| t.integer :language_id, null: false t.references :langable, polymorphic: true end add_index :langs, :language_id add_index :langs, [:langable_id, :langable_type] execute <<-SQL INSERT INTO langs (langable_id, language_id) SELECT experts_languages.expert_id, experts_languages.language_id FROM experts_languages SQL execute 'UPDATE langs SET langable_type = \'Expert\'' drop_table :experts_languages end end <file_sep>/spec/factories/area.rb FactoryGirl.define do factory :area do sequence(:area) { |n| I18n.t(:areas).keys[n] } end end <file_sep>/spec/support/access_spec_helper.rb module AccessSpecHelper def self.included(base) base.before(:all) do @credentials = { username: 'john', password: '<PASSWORD>' } @user = create(:user_with_login_hash, @credentials) end base.after(:all) do @user.destroy end end def login session[:login_hash] = @user.login_hash end def logout session[:login_hash] = nil end def set_access(section, value) @user.privilege[section] = value @user.privilege.save end def grant_access(section) set_access(section, true) end def revoke_access(section) set_access(section, false) end end <file_sep>/spec/models/employee_spec.rb require 'spec_helper' describe Employee do context 'validations' do it 'must have a name' do e = Employee.new e.should_not be_valid e.errors[:name].should_not be_empty end end context 'associations' do it { should have_one(:contact).dependent(:destroy) } it { should belong_to(:partner) } end describe 'full_name' do it 'should be a combination of prename and name' do e = build(:employee, prename: 'John', name: 'Doe') e.full_name.should == '<NAME>' end end describe 'full_name_with_title' do it 'should be full_name, if title is blank' do e = build(:employee, prename: 'John', name: 'Doe', title: '') e.full_name_with_title.should == e.full_name end it 'should be a combination of title, prename and name' do e = build(:employee, title: 'King', prename: 'John', name: 'Doe') e.full_name_with_title.should == 'King <NAME>' end end end <file_sep>/spec/controllers/login_controller_spec.rb require 'spec_helper' describe LoginController do include AccessSpecHelper before(:each) { @user.reload } describe 'GET welcome' do context 'for logged in users' do before(:each) { get :welcome } it 'should have a 200 status code' do expect(response.code).to eq('200') end it 'should set a title' do expect(assigns(:title)).to_not be_blank end end context 'for already logged in users' do before(:each) do login get :welcome end it 'should redirect to root' do expect(response).to redirect_to(:root) end end end describe 'POST login' do context 'for not logged in users' do context 'and invalid credentials' do before(:each) do post :login, username: @user.username, password: '<PASSWORD>' end it 'should render welcome' do expect(response).to render_template(:welcome) end it 'should set a alert flash' do expect(flash.now[:alert]).to_not be_blank end end context 'and valid credentials' do before(:each) do @login_hash = @user.login_hash post :login, @credentials end it 'should set a new login hash' do @user.reload expect(@user.login_hash).to_not eq(@login_hash) expect(session[:login_hash]).to eq(@user.login_hash) end it 'should redirect to root' do expect(response).to redirect_to(:root) end end end context 'for logged in users' do before(:each) do login post :login end it 'should redirect to root' do expect(response).to redirect_to(:root) end end end describe 'DELETE logout' do context 'for not logged in users' do before(:each) { delete :logout } it 'should redirect to welcome' do expect(response).to redirect_to(controller: :login, action: :welcome) end end context 'for logged in users' do before(:each) do login delete :logout end it 'should unset the login_hash' do expect(session[:login_hash]).to be_nil end it 'should render welcome' do expect(response).to render_template(:welcome) end it 'should set the title' do expect(assigns(:title)).to_not be_blank end end end end <file_sep>/Gemfile source 'https://rubygems.org' # Rails & mysql gem 'rails', '3.2.14' gem 'mysql2' # Assets group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' gem 'jquery-rails', '~> 2.2.1' gem 'jquery-ui-rails', '~> 4.0.1' gem 'uglifier', '>= 1.0.3' gem 'therubyracer', platforms: :ruby end # Development group :test, :development do gem 'rspec-rails', '~> 2.0' gem 'shoulda-matchers', '~> 1.5.1' gem 'factory_girl_rails', '~> 4.2.0' gem 'acts_as_fu' , '~> 0.0.8' gem 'carmen-rails', '~> 1.0.0.beta2' gem 'colorize' end # Documentation group :doc do gem 'sdoc', '~> 0.3.19' end # Password encryption gem 'bcrypt-ruby', '~> 3.0.0' # Pagination gem 'will_paginate', '~> 3.0' # Pump plain text out of everything (needs a JRE!) gem 'yomu', '~> 0.1.1' # PDF gem 'prawn', '~> 0.12.0' # Markdown gem 'bluecloth', '~> 2.2.0' # Excel export gem 'axlsx', '~> 1.3.5' # To use debugger # gem 'debugger' <file_sep>/app/controllers/ajax/helpers_controller.rb # The HelperController serves helper views. Such as generic confirm dialogs. class Ajax::HelpersController < Ajax::ApplicationController caches_action :show # Serves a helper. def show render params[:id] rescue ActionView::MissingTemplate raise ActionController::RoutingError, 'Helper not found.' end end <file_sep>/spec/factories/employee.rb FactoryGirl.define do factory :employee do prename 'Jane' name 'Doe' title 'Queen' gender :female trait :male do prename 'John' title 'King' gender :male end end end <file_sep>/app/sweepers/list_sweeper.rb # Observes the List model for changes and expires the caches. class ListSweeper < ActionController::Caching::Sweeper observe List # Expires the cache for the updated list. def after_update(list) expire_cache_for(list) end # Expires the cache for destroyed list. def after_destroy(list) expire_cache_for(list) end private # Expires the cache for the specified list. def expire_cache_for(list) key = "/ajax/lists/#{list.id}" I18n.available_locales.each do |locale| expire_fragment("#{locale}#{key}/edit") expire_fragment("#{locale}#{key}/copy") end end end <file_sep>/lib/acts_as_comment/acts_as_comment.rb module ActsAsComment module ActsAsComment extend ActiveSupport::Concern # Defines ClassMethods#acts_as_comment. # # See ActsAsComment for more info. module ClassMethods # Makes a model acting as a comment. def acts_as_comment(attribute_name, options = {}) class_attribute :comment_attribute self.comment_attribute = attribute_name attr_accessible(attribute_name) after_initialize do read_attribute(attribute_name) || write_attribute(attribute_name, '') end if options.key?(:for) belongs_to(options.delete(:for), options) end extend ClassMethodsOnActivation include InstanceMethodsOnActivation end end # Mixes class methods into the comment model. module ClassMethodsOnActivation # Labels the model as a comment. def acts_as_comment? true end end # Mixes instance methods into the model. module InstanceMethodsOnActivation # Writes the comment attribute. def write_comment_attribute(value) write_attribute(comment_attribute, value.to_s) end # Returns the comment attribute. def to_s send(comment_attribute).to_s end end end end ActiveRecord::Base.send :include, ActsAsComment::ActsAsComment <file_sep>/lib/as_csv.rb require 'csv' require 'axlsx' # Generates a CSV from a ActiveRecord::Relation. It uses # ExposableAttributes::ClassMethods#exposable_attributes to choose the # attributes to be exported. # # class Article < ActiveRecord::Base # attr_exposable :title, :sub_title, as: :csv # end # # To generate some CSV simply write something like this. # # Article.limit(2).as_csv # # # title,sub_title # # Hello World,My First Article # # Some Title,Just An Experiment # # Exporting associated records should be no problem too. Checkout the # following setup. # # class Article < ActiveRecord::Base # attr_exposable :title, :sub_title, as: :csv # # belongs_to :author # has_and_belongs_to_many :tags # end # # class Tag < ActiveRecord::Base # attr_exposable :tag, as: :csv # # has_and_belongs_to_many :articles # end # # class Author < ActiveRecord::Base # attr_accessible :name, :email # # has_many :articles # end # # With the :include option it is possible to include associated records # into the export. For single record associations (:belongs_to, :has_one) # the data is simply appended to the rows. # # Article.limit(2).as_csv(include: :author) # # # title,sub_title,name,email # # Hello World,My First Article,<NAME>,<EMAIL> # # Some Title,Just An Experiment,<NAME>,<EMAIL> # # For multiple record associtations (:has_many, :has_and_belongs_to_many) # every associated record leads to a new row. # # Article.limit(2).as_csv(include: :tags) # # # title,sub_title,tag # # Hello World,My First Article,hello # # Hello World,My First Article,world # # Hello World,My First Article,funny # # Some Title,Just An Experiment, # # It is also possible to specify multiple includes. # # Article.limit(2).as_csv(include: [:tags, :author]) # # # title,sub_title,tag,name,email # # Hello World,My First Article,hello,<NAME>,<EMAIL> # # Hello World,My First Article,world,<NAME>,<EMAIL> # # Hello World,My First Article,funny,<NAME>,<EMAIL> # # Some Title,Just An Experiment,,<NAME>,<EMAIL> # # To use it in your Controller you can write something like this. # # def index # @articles = Article.limit(10) # # respond_to do |format| # format.html # format.csv { send_data @articles.as_csv(include: :author) } # end # end # # AsCSV::ActiveRecord::ClassMethods#as_csv returns a string or raises a # SecurityError if one of the models has no exposable attributes. See # ExposableAttributes::ClassMethods#exposable_attributes for more info. module AsCsv # Generates the CSV from a ::ActiveRecord::Relation. class Generator # Inits a new Generator. Recognizes the options :only, :except, :inlcude. # # AsCsv::Generator.new(User.limit(2), only: :username, include: :posts) # # See ExposableAttributes for info about the options. def initialize(scope, options = {}) @scope, @includes, @attributes = scope, {}, [] includes(*options[:include]) attributes(*scope.exposable_attributes(:csv, options.slice(:only, :except))) end # Adds associations to the CSV. # # generator.includes :comments, :tags # # Invalid associations were ignored. def includes(*associations) associations.each do |association| if (reflection = @scope.reflect_on_association(association)) @includes[association] = reflection.klass.exposable_attributes(:csv) @scope = @scope.includes(association) end end end # Adds attributes to the CSV. # # generator = AsCsv::Generator.new(User, only: :username) # # generator.attributes :email, :created_at # #=> [:username, :email, :created_at] # # Returns an Array of all included attribtues. def attributes(*attributes) @attributes.concat(attributes) @scope = @scope.includes(@scope.filter_associations(attributes)) end private # Returns the Csv headers. def headers @attributes + @includes.values.flatten end # This method builds the rows for a single record. # # You should override this, if you are not happy with the default behavior. def rows_for(record, &block) [row_for(record)].product(*associated_rows_for(record), &block) end # Builds the associated rows for a record. # # Returns a 3 level deep nested Array. def associated_rows_for(record) @includes.map do |method, attributes| associated_rows(Array.wrap(record.send(method)), attributes) end end # Builds the rows for the records of a single association. # # Returns a 2 level deep nested Array. def associated_rows(records, attributes) if records.empty? [Array.new(attributes.length)] else records.map { |record| row_for(record, attributes) } end end # Builds the row for a single record. # # Returns an Array. def row_for(record, attributes = @attributes) attributes.map { |attr| record.send(attr).to_s } end end # Generates CSV. class CsvGenerator < Generator # Generates the CSV. Takes a hash of CSV specific options. # # See the CSV module for more info. def generate(options = {}) CSV::generate(options) do |csv| csv << headers @scope.each do |record| rows_for(record) { |row| csv << row.flatten } end end end end # Generates the XLSX. Takes a hash of XLSX specific options. class XlsxGenerator < Generator # Generates the XLSX def generate(options = {}) pkg = Axlsx::Package.new pkg.workbook.add_worksheet(name: options.fetch(:name, 'Sheet')) do |sheet| sheet.add_row(headers) @scope.each do |record| rows_for(record) { |row| sheet.add_row(row.flatten) } end end pkg.to_stream.string end end # Mixin for ::ActiveRecord. See AsCsv for more info. module ActiveRecord extend ActiveSupport::Concern # Implements ClassMethods#as_csv. See AsCsv for more info. module ClassMethods # Generates a CSV from a ::ActiveRecord::Relation. # # See AsCsv for more info. def as_csv(options = {}, csv_options = {}) CsvGenerator.new(scoped, options).generate(csv_options) end # Generates a XLSX from a ::ActiveRecord::Relation. def as_xlsx(options = {}, xlsx_options = {}) XlsxGenerator.new(scoped, options).generate(xlsx_options) end end end # Mixin for ::ActionController. module ActionController extend ActiveSupport::Concern def send_csv(data, title) send_data data, filename: "#{title.parameterize}.csv", type: :csv end def send_xlsx(data, title) send_data data, filename: "#{title.parameterize}.xlsx", type: :xlsx end end end ActiveRecord::Base.send :include, AsCsv::ActiveRecord ActionController::Base.send :include, AsCsv::ActionController <file_sep>/spec/factories/comment.rb FactoryGirl.define do factory :comment do comment 'Some random comment.' end end <file_sep>/app/models/attachment.rb require 'pathname' require 'securerandom' # The Attachment model provides the ability to store uploaded files on # the file system. It can be connected to any arbitrary model through the # polymorphic _attachable_ association. # # Database scheme: # # - *id:* integer # - *attachable_id:* integer # - *attachable_type:* string # - *filename:* string # - *original_filename:* string # - *title:* string # - *created_at:* datetime # - *updated_at:* datetime # # The attributes *filename* and *original_filename* must be present. The # *title* attribute is populated before save, if it is blank. class Attachment < ActiveRecord::Base attr_accessible :title, :file before_save :set_title after_destroy :unlink validates :filename, presence: true, uniqueness: true validates :original_filename, presence: true validates_with FileExistsValidator belongs_to :attachable, polymorphic: true # Directory name of the attachment store. DIRNAME = Rails.application.config.attachment_store # Absolute path to the attachment store. STORE = Rails.root.join(DIRNAME) # Saves the record or destroys it on failure. # # It triggers all after_destroy callbacks, e.g. Attachment#unlink(). def save_or_destroy success = save destroy unless success success end # Sets the title from the original filename if it is blank. def set_title self.title = File.basename(original_filename.to_s, ext) if title.blank? end # Stores the file. def file=(file) store(file) rescue IOError, SystemCallError unlink end # Returns the file extension of the stored file. def ext File.extname(original_filename.to_s).downcase end # Returns a nice filename generated from the title. def public_filename File.basename(title, ext).parameterize + ext end # Returns the absolute path to the stored file. def absolute_path STORE.join(filename.to_s) end private # Stores the attachment on the filesystem, sets filename # and original_filename. # # attachment.store(upload) # # attachment.filename # #=> 'e4b969da-10df-4374-afd7-648b15b09903.doc' # # attachment.original_filename # #=> 'my-cv.doc' # # Raises IOError and SystemCallError on failure. def store(file) case file when ActionDispatch::Http::UploadedFile self.original_filename = file.original_filename when File self.original_filename = File.basename(file.path) else raise TypeError, 'Argument must be a File or a UploadedFile.' end empty_file(ext) do |f| self.filename = File.basename(f.path) IO.copy_stream(file, f) end end # Opens a file with unique filename in _wb_ mode. # # cv.empty_file('.doc') # #=> <File:/path/to/store/e4b969da-10df-4374-afd7-648b15b09903.doc> # # Raises IOError and SystemCallError on failure. def empty_file(suffix = nil, &block) date = Date.today.to_formatted_s(:db) begin path = STORE.join("#{date}-#{SecureRandom.uuid}#{suffix}") end while path.exist? STORE.mkpath unless STORE.exist? path.open('wb', &block) end # Removes the attachment from the file system. # # Returns true on success, else false. def unlink !! absolute_path.delete rescue false end end <file_sep>/app/controllers/project_partners_controller.rb # class ProjectPartnersController < ApplicationController before_filter :find_project, only: [:index, :create, :destroy] before_filter :find_partner, only: [:create, :destroy] skip_before_filter :authorize, only: [:index] # GET /projects/:project_id/partners def index @title = @project.info.try(:title) end # POST /projects/:project_id/partners def create if @project.add_partner(@partner) flash[:notice] = t('messages.project.success.add_partner', name: @partner.to_s) else flash[:alert] = t('messages.project.errors.add_partner') end redirect_to project_partners_url(@project) end # DELETE /projects/:project_id/partners/:id def destroy if @project.partners.destroy(@partner) flash[:notice] = t('messages.project.success.remove_partner', name: @partner.to_s) else flash[:alert] = t('messages.project.errors.remove_partner') end redirect_to project_partners_url(@project) end private # Checks the users privileges. def authorize super(:projects, projects_url) end # Finds the project. def find_project @project = Project.find(params[:project_id]) rescue ActiveRecord::RecordNotFound flash[:alert] = t('messages.project.errors.find') redirect_to projects_url end # Finds the partner. def find_partner @partner = Partner.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:alert] = t('messages.partner.errors.find') redirect_to project_partners_url(@project) end end <file_sep>/app/models/expert.rb # The Expert model provides access to the experts data and several methods # for manipulation. # # Database scheme: # # - *id:* integer # - *user_id:* integer # - *country_id:* integer # - *name:* string # - *prename:* string # - *gender:* string # - *birthday:* date # - *degree:* string # - *former_collaboration:* boolean # - *fee:* string # - *job:* string # - *created_at:* datetime # - *updated_at:* datetime class Expert < ActiveRecord::Base attr_accessible :name, :prename, :degree, :gender, :birthday, :fee, :job, :former_collaboration, :country_id, :languages attr_exposable :name, :prename, :degree, :gender, :birthday, :fee, :job, :former_collaboration, :country, as: :csv attr_exposable :name, :prename, :degree, :gender, :age, :fee, :job, :former_collaboration, :country, as: :pdf self.per_page = 50 DEFAULT_ORDER = 'experts.name, experts.prename' discrete_values :gender, [:male, :female] is_commentable_with :comment, autosave: true, dependent: :destroy, as: :commentable validates :name, presence: true has_and_belongs_to_many :languages, uniq: true has_many :attachments, autosave: true, dependent: :destroy, as: :attachable has_many :addresses, autosave: true, dependent: :destroy, as: :addressable has_many :list_items, autosave: true, dependent: :destroy, as: :item has_many :lists, through: :list_items has_many :project_members, autosave: true, dependent: :destroy has_many :projects, through: :project_members has_many :cvs, autosave: true, dependent: :destroy, select: [:id, :expert_id, :language_id], order: :language_id has_one :contact, autosave: true, dependent: :destroy, as: :contactable belongs_to :user, select: [:id, :name, :prename] belongs_to :country scope :with_meta, includes(:country, :attachments, :cvs) # Searches for experts. Takes a hash with condtions: # # - *:name* a (partial) name used to search _name_ and _prename_ # - *:country* one or more country ids # - *:languages* an array of language ids # - *:q* arbitrary string used for a fulltext search # # The results are ordered by name and prename. def self.search(params) ExpertSearcher.new( params.slice(:name, :country, :languages, :q) ).search(scoped).ordered end # Returns a collection of ordered experts. def self.ordered order(DEFAULT_ORDER) end # Initializes the contact on access, if not already initalized. def contact super || self.contact = Contact.new end # Sets the experts country. def country=(country) super(Country.find_country(country)) end # Sets the experts languages. # # See Language.find_languages for more info. def languages=(ids) super(Language.find_languages(ids)) end # Returns a string containing name and prename. def full_name "#{prename} #{name}" end # Returns a string containing degree, prename and name. # # expert.full_name_with_degree # #=> "<NAME>, Ph.D." # # If degree is blank, Expert#full_name is returned. def full_name_with_degree degree.blank? ? full_name : "#{full_name}, #{degree}" end # Returns the localized former collaboration value. def human_former_collaboration I18n.t(former_collaboration.to_s, scope: [:values, :boolean]) end # Returns the localized date of birth. # # expert.human_birthday # #=> "12. September 2012" # # Returns nil, if birthday is nil. def human_birthday(format = :short) I18n.l(birthday, format: format) if birthday end # Returns the experts age in years. # # expert.age #=> 43 # # Returns nil if the birthday is unknown. def age return nil unless birthday now = Time.now.utc.to_date age = now.year - birthday.year (now.month < birthday.month || (now.month == birthday.month && now.day < birthday.day)) ? age - 1 : age end # Returns a combination of name and prename. def to_s [name, prename].reject(&:blank?).join(', ') end end <file_sep>/app/helpers/expert_helper.rb # Provides expert specific helpers. module ExpertHelper # Returns a string containing links to the CV downloads. # # list_cvs(expert) # #=> '<a href="">en</a><a href="">de</a>' def list_cvs(expert, html_options = {}) expert.cvs.inject('') do |html, cv| html << link_to(cv.language.language, [expert, cv], html_options) end.html_safe end end <file_sep>/spec/factories/project.rb require 'securerandom' FactoryGirl.define do factory :project do sequence(:title) { |_| SecureRandom.hex(16) } sequence(:carried_proportion) { |_| rand(100) } sequence(:status) { |_| Project.status_values.map(&:last).sample } association :user, factory: :user trait :with_infos do after(:build) do |project| ProjectInfo.language_values.map(&:last).each do |lang| project.infos << build(:project_info, language: lang) end end end trait :with_partners do after(:build) do |project| 3.times { project.partners << create(:partner) } end end end end <file_sep>/Rakefile #!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) Silo::Application.load_tasks # We want a custom documentation. RDoc::Task.new(:doc) do |rdoc| rdoc.rdoc_dir = 'doc/app' rdoc.options << '-f' << 'sdoc' rdoc.options << '-t' << 'Silo Documentation' rdoc.options << '-e' << 'UTF-8' rdoc.options << '-g' rdoc.options << '-m' << 'README' rdoc.options << '-a' rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('app/**/*.rb') rdoc.rdoc_files.include('lib/**/*.rb') rdoc.rdoc_files.exclude('lib/tasks/*') end <file_sep>/lib/tasks/attachments.rake namespace :attachments do task check: :environment do db = Attachment.pluck(:filename) fs = Attachment::STORE.children(false).collect { |p| p.to_s } diff = [db - fs, fs - db] if diff.all? { |d| d.size == 0 } puts "Found #{db.size} files and no errors." next end puts 'Files in database, but not on filesystem' puts '========================================' puts diff[0] puts '========================================' puts "#{diff[0].size}/#{db.size}\n\n" puts 'Files on filesystem, but not in database' puts '========================================' puts diff[1] puts '========================================' puts "#{diff[1].size}/#{fs.size}" end end <file_sep>/lib/acts_as_tag/is_taggable_with.rb module ActsAsTag module IsTaggableWith extend ActiveSupport::Concern # Defines ClassMethods#is_taggable_with # # See ActsAsTag for more info. module ClassMethods # Makes a model taggable with one or more tag models. def is_taggable_with(assoc, options = {}) options[:uniq] = options.fetch(:uniq, true) attr_accessible(assoc) klass = has_and_belongs_to_many(assoc, options).klass unless klass.respond_to?(:acts_as_tag?) && klass.acts_as_tag? raise NotATag, klass.name end define_method("#{assoc}=") do |tags| super(tags.is_a?(String) ? klass.from_s(tags) : tags) end define_method("human_#{assoc}") do send(assoc).map(&:to_s).join(', ') end end end end end ActiveRecord::Base.send :include, ActsAsTag::IsTaggableWith <file_sep>/app/controllers/ajax/contacts_controller.rb # The Ajax::ContactsController handles Contact specific AJAX requests. class Ajax::ContactsController < Ajax::ApplicationController respond_to :html, only: [:new] caches_action :new # Serves an empty contacts form. def new @url = { controller: '/contacts', action: :create } end end <file_sep>/app/controllers/employees_controller.rb # Handles Employee specific requests. class EmployeesController < ApplicationController before_filter :find_partner, only: [:index, :create, :update, :destroy] before_filter :find_employee, only: [:update, :destroy] skip_before_filter :authorize, only: [:index] cache_sweeper :employee_sweeper, only: [:update, :destroy] # Serves a list of the partners employees. # # GET /partners/:partner_id/employees def index @title = t('labels.employee.all') body_class.delete('index') end # Adds an employee to the partner. # # POST /partners/:partner_id/employees def create employee = @partner.employees.build(params[:employee]) if employee.save flash[:notice] = t('messages.employee.success.create', name: employee.name) else flash[:alert] = t('messages.employee.errors.create') end redirect_to partner_employees_url(@partner) end # Updates the employees attributes. # # PUT /partners/:partner_id/employees/:id def update if @employee.update_attributes(params[:employee]) flash[:notice] = t('messages.employee.success.save') else flash[:alert] = t('messages.employee.errors.save') end redirect_to partner_employees_url(@partner) end # Deletes the employee. # # DELETE /partners/:partner_id/employees/:id def destroy if @employee.destroy flash[:notice] = t('messages.employee.success.delete', name: @employee.name) else flash[:alert] = t('messages.employee.errors.delete') end redirect_to partner_employees_url(@partner) end private # Checks the users permissions. def authorize super(:partners, partners_url) end # Finds the employees partner. def find_partner @partner = Partner.find(params[:partner_id]) rescue ActiveRecord::RecordNotFound flash[:alert] = t('messages.partner.errors.find') redirect_to partners_url end # Finds the employee. def find_employee @employee = @partner.employees.find(params[:id]) end # Sets an error message and redirects the user to the partners employees page. def not_found flash[:alert] = t('messages.employee.errors.find') redirect_to partner_employees_url(params[:partner_id]) end end <file_sep>/app/controllers/attachments_controller.rb # The AttachmentsController provides the ability to serve, create and destroy # all attachments. class AttachmentsController < ApplicationController before_filter :find_parent, only: [:create, :destroy] skip_before_filter :authorize, only: [:show] polymorphic_parent :experts, :partners, :projects # Sends the stored file to the user. # # GET /parents/:parent_id/attachments/:id def show a = Attachment.find(params[:id]) send_file a.absolute_path, filename: a.public_filename end # Stores a new attachment and associates it with a parent model. # # POST /parents/:parent_id/attachments def create if @parent.attachments.build(params[:attachment]).save_or_destroy flash[:notice] = t('messages.attachment.success.store') else flash[:alert] = t('messages.attachment.errors.store') end redirect_to :back end # Destroys an attachment and redirects to the document page of the parent. # # DELETE /parents/:parent_id/attachments/:id def destroy if @parent.attachments.find(params[:id]).destroy flash[:notice] = t('messages.attachment.success.delete') else flash[:alert] = t('messages.attachment.errors.delete') end redirect_to :back end private # Checks if the user is authorized and redirects if not. def authorize super(parent[:controller], :back) end # Sets an error message an redirects back. def file_not_found super(:back) end # Sets an error message and redirects back. def not_found flash[:alert] = t('messages.attachment.errors.find') redirect_to :back end end <file_sep>/spec/lib/acts_as_tag_spec.rb require 'spec_helper' describe ActsAsTag do before(:all) do build_model :category do string :name acts_as_tag :name end build_model :item do string :name attr_accessible :name is_taggable_with :categories end build_model :categories_items do integer :item_id integer :category_id end end describe :acts_as_tag? do context 'model not acting as tag' do it 'should not be available' do expect(Item).to_not respond_to(:acts_as_tag?) end end context 'model acting as tag' do it 'should be true' do expect(Category.acts_as_tag?).to be_true end end end describe :from_s do context 'with a clean database' do it 'should be a collection of fresh records' do categories = Category.from_s('JavaScript, CSS, Ruby') expect(categories).to have(3).items expect(categories).to be_all(&:new_record?) expect(categories).to be_all { |c| c.is_a?(Category) } end it 'should be without duplicates and blanks' do categories = Category.from_s('JavaScript, CSS , CsS, CSS ,css,, ,') expect(categories.map(&:name)).to match_array(['JavaScript', 'CSS']) end end context 'with some records in the database' do before(:all) do ['JavaScript', 'CSS', 'Ruby'].each do |category| Category.create!(name: category) end end after(:all) do Category.destroy_all end it 'should find existing records' do categories = Category.from_s('JavaScript, css , rUBY ') expect(categories).to_not be_any(&:new_record?) end it 'should find existing and build new ones' do categories = Category.from_s('javascript ,Perl') expect(categories).to be_any(&:new_record?) expect(categories).to_not be_all(&:new_record?) expect(categories.map(&:name)).to match_array(['JavaScript', 'Perl']) end end end describe :to_s do it 'should be the name' do s = Category.new(name: 'Python').to_s expect(s).to eq('Python') end end describe :is_taggable_with do subject { Item } context 'when association name is valid' do it 'should set up a has_and_belongs_to_many association' do expect(subject.new).to have_and_belong_to_many(:categories) end end context 'when associated model does not exist' do it 'should raise a NameError' do expect { subject.is_taggable_with(:invalid) }.to raise_error(NameError) end end context 'when associated model does not acts as tag' do class NoTag < ActiveRecord::Base; end it 'should raise a NotATag error' do expect { subject.is_taggable_with(:no_tags) }.to raise_error(ActsAsTag::NotATag) end end end describe :tags= do it 'should set the tags from a string' do item = Item.new(name: 'Example') item.categories = 'JavaScript, CSS, Ruby' expect(item.categories).to have(3).items expect(item.categories).to be_all { |c| c.is_a?(Category) } end it 'should be available for mass assignment' do item = Item.new(name: 'something', categories: 'Java, CSS, Perl, Ruby') expect(item.categories).to have(4).items end end end <file_sep>/spec/searchers/expert_searcher_spec.rb require 'spec_helper' describe ExpertSearcher do before(:all) do @area = create(:area, area: :EU) @countries = [:DE, :US, :GB].inject({}) do |hsh, c| hsh[c] = create(:country, country: c, area: @area) hsh end @languages = [:de, :en, :fr, :hi].inject({}) do |hsh, l| hsh[l] = create(:language, language: l) hsh end @de_peter = build(:expert, prename: 'Peter', name: 'Griffin') @de_peter.country = @countries[:DE] @de_peter.languages = @languages.values_at(:de, :en, :fr) @de_peter.comment = build(:comment, comment: 'What a nice person.') @de_peter.save create(:cv, cv: 'I have a beautiful life.', expert: @de_peter, language: @languages[:de]) @de_jane = build(:expert, prename: 'Jane', name: 'Doe') @de_jane.country = @countries[:DE] @de_jane.languages = @languages.values_at(:fr, :hi) @de_jane.comment = build(:comment, comment: 'She is really smart.') @de_jane.save create(:cv, cv: 'I was born in the middle of the world.', expert: @de_jane, language: @languages[:en]) @us_adam = create(:expert, prename: 'Adam', name: 'Pane') @us_adam.country = @countries[:US] @us_adam.languages = @languages.values_at(:en) @us_adam.comment = build(:comment, comment: 'He is a super smart guy.') @us_adam.save create(:cv, cv: 'I have some beautiful hair.', expert: @us_adam, language: @languages[:en]) end after(:all) do [Area, Country, Language, Expert, User].each { |m| m.destroy_all } end subject { Expert.search(conditions).all } describe :search do context 'when searching for name' do let(:conditions) { { name: 'ane' } } it 'should find experts with partial match in name or prename' do expect(subject).to match_array([@de_jane, @us_adam]) end end context 'when searching for q' do let(:conditions) { { q: '+beautiful -hair' } } it 'should find experts with fulltext matches' do expect(subject).to eq([@de_peter]) end end context 'when searching for languages' do let(:conditions) { { languages: @languages.values_at(:en, :fr) } } it 'should find experts having all those languages' do expect(subject).to eq([@de_peter]) end end context 'when searching for country' do let(:conditions) { { country: @countries.values_at(:DE, :GB) } } it 'should find experts living in one of those countries' do expect(subject).to match_array([@de_peter, @de_jane]) end end context 'when searching for country "US" and q "smart"' do let(:conditions) { { country: @countries.values_at(:US), q: 'smart' } } it 'should find @us_adam only' do expect(subject).to eq([@us_adam]) end end context 'when searching for languages ["fr", "hi", "en"]' do let(:conditions) { { languages: @languages.values_at(:fr, :hi, :en) } } it 'should be empty' do expect(subject).to be_empty end end context 'when searching for country "DE", languages ["en"] and q "super"' do let(:conditions) do { country: @countries[:DE], languages: @languages.values_at(:en), q: 'super' } end it 'should find nothing' do expect(subject).to be_empty end end context 'when searching a scoped model' do subject { Expert.limit(1).search(country: @countries[:DE]).all } it 'should respect the scope' do expect(subject).to have(1).item expect(subject.first.country).to eq(@countries[:DE]) end end end end <file_sep>/spec/lib/body_class_spec.rb require 'spec_helper' describe BodyClass::BodyClass do it 'should be a subclass of Set' do expect(BodyClass::BodyClass.superclass).to eq(Set) end subject { BodyClass::BodyClass.new(enum) } describe 'indifferent access' do let(:enum) { [:class1, 'class2'] } it 'should treat symbols and string the same' do expect(subject).to include(:class1, 'class1', :class2, 'class2') end end describe :delete do let(:enum) { [:class1, :class2] } context 'when it does not include the value' do it 'should be nil' do expect(subject.delete(:class3)).to be_nil end end context 'when it does include the value' do [:class1, 'class1'].each do |val| context "and value is a #{val.class}" do it 'should be the value as a string' do expect(subject.delete(val)).to eq('class1') end end end end end describe :to_s do let(:enum) { %w(class1 class2 class3) } it 'should be a string of all values joined by a space' do expect(subject.to_s).to eq('class1 class2 class3') end end end <file_sep>/spec/models/partner_spec.rb require 'spec_helper' describe Partner do context 'validations' do it 'must have a company' do p = Partner.new p.should_not be_valid p.errors[:company].should_not be_empty end end context 'associations' do it { should have_and_belong_to_many(:advisers) } it { should have_and_belong_to_many(:businesses) } it { should have_and_belong_to_many(:projects) } it { should have_many(:employees).dependent(:destroy) } it { should have_many(:attachments).dependent(:destroy) } it { should have_many(:list_items).dependent(:destroy) } it { should have_many(:lists).through(:list_items) } it { should have_one(:description).dependent(:destroy) } it { should have_one(:comment).dependent(:destroy) } it { should belong_to(:user) } it { should belong_to(:country) } end describe 'to_s' do it 'should be company' do p = build(:partner) p.to_s.should == p.company.to_s end end end <file_sep>/db/migrate/010_add_original_filename.rb class AddOriginalFilename < ActiveRecord::Migration def up add_column :attachments, :original_filename, :string Attachment.all.each do |a| a.title = File.basename(a.title, File.extname(a.filename)) a.original_filename = a.filename a.save!(validate: false) end end def down remove_column :attachments, :original_filename end end <file_sep>/spec/models/description_spec.rb require 'spec_helper' describe Description do it 'should act as comment' do expect(Description.acts_as_comment?).to be_true end describe :associations do it { should belong_to(:describable) } end end <file_sep>/spec/models/privilege_spec.rb require 'spec_helper' describe Privilege do describe :associations do it { should belong_to(:user) } end describe :SECTIONS do it 'should be an array of sections' do expect(Privilege::SECTIONS).to match_array([:partners, :experts, :projects]) end end describe :access? do context 'by default' do it 'should always be false' do Privilege::SECTIONS.each do |section| expect(subject.access?(section)).to be_false end end end context 'as admin' do subject { build(:privilege, admin: true) } it 'should always be true' do Privilege::SECTIONS.each do |section| expect(subject.access?(section)).to be_true end end end Privilege::SECTIONS.each do |section| context "when #{section} is accessible" do subject { build(:privilege, section => true) } it "should be true for #{section} else false" do Privilege::SECTIONS.each do |_section| expect(subject.access?(_section)).to eq(_section == section) end end end end end describe :employees do context 'by default' do it 'should be false' do expect(subject.employees).to be_false end end context 'when partners section is accessible' do subject { build(:privilege, partners: true) } it 'should be true' do expect(subject.employees).to be_true end end end end <file_sep>/app/controllers/ajax/tags_controller.rb # The Ajax::TagsController provides helpers to access existing tag like models. # They should be used to help the user by filling out forms with widgets such # as autocompletion or multiselect boxes. class Ajax::TagsController < Ajax::ApplicationController before_filter :find_model caches_action :show # Serves tags in a multiselect box or as JSON. # # GET /ajax/tags/model_name def show @tags = @model.all @title = t(:"labels.#{@model.name.downcase}.index") respond_with(@tags) end private # Finds the model. def find_model begin @model = params[:id].to_s.classify.constantize rescue NameError not_found and return end unless @model.respond_to?(:acts_as_tag?) && @model.acts_as_tag? not_found end end # Sends a 404 with a proper error message. def not_found super('Tags not found.') end end <file_sep>/app/validators/file_exists_validator.rb # Validates the existence of a file. class FileExistsValidator < ActiveModel::Validator # Expects +record.absolute_path+ to return a Pathname object. def validate(record) unless record.absolute_path.file? record.errors.add(:filename, I18n.t('messages.generics.errors.file_not_found')) end end end <file_sep>/spec/models/country_spec.rb require 'spec_helper' describe Country do before(:all) do @eu = create(:area, area: :EU) @de = create(:country, country: :DE, area: @eu) @en = create(:country, country: :EN, area: @eu) @cz = create(:country, country: :CZ, area: @eu) @pt = create(:country, country: :PT, area: @eu) end after(:all) do [@eu, @de, @en, @cz, @pt].each { |c| c.destroy } end context 'validations' do it 'must have a country' do c = Country.new c.should_not be_valid c.errors[:country].should_not be_empty end it 'must have a unique country' do c = build(:country, country: :DE) c.should_not be_valid c.errors[:country].should_not be_empty end end context 'associations' do it { should have_many(:addresses) } it { should have_many(:experts) } it { should have_many(:partners) } it { should belong_to(:area) } end describe 'find_country' do it 'should be nil for unknown countries' do Country.find_country('XY').should be_nil end it 'should be the same country' do Country.find_country(@de).should == @de end it 'should be the country with the same id' do Country.find_country(@en.id).should == @en Country.find_country(@en.id.to_s).should == @en end it 'should be the country with the same country code' do Country.find_country(:CZ).should == @cz Country.find_country('CZ').should == @cz end end describe :find_countries do context 'when searched by a mixed array' do it 'should find the specified countries' do countries = Country.find_countries([@de, @en.id, 'CZ']) expect(countries).to match_array([@de, @en, @cz]) end end end describe :human do it 'should be the localized country name' do c = build(:country, country: :DE) c.human.should == I18n.t('countries.DE') end end describe :to_s do it 'should be the human country name' do c = build(:country) c.to_s.should == c.human end end end <file_sep>/app/models/partner.rb # The Partner model provides the ability to manage partner companies. # # Database schema: # # - *id:* integer # - *user_id:* integer # - *country_id:* integer # - *company:* string # - *street:* string # - *city:* string # - *zip:* string # - *region:* string # - *website:* string # - *email:* string # - *phone:* string # - *fax:* string # - *created_at:* datetime # - *updated_at:* datetime # # The company attribute is required. class Partner < ActiveRecord::Base attr_accessible :company, :street, :city, :zip, :region, :country_id, :website, :email, :phone, :fax attr_exposable :company, :street, :zip, :city, :region, :country, :website, :email, :phone, :fax, as: :csv attr_exposable :company, :businesses, :street, :zip, :city, :region, :country, :website, :email, :phone, :fax, as: :pdf self.per_page = 50 DEFAULT_ORDER = 'partners.company' is_taggable_with :advisers is_taggable_with :businesses is_commentable_with :comment, autosave: true, dependent: :destroy, as: :commentable is_commentable_with :description, autosave: true, dependent: :destroy, as: :describable validates :company, presence: true has_and_belongs_to_many :projects, uniq: true has_many :employees, autosave: true, dependent: :destroy has_many :attachments, autosave: true, dependent: :destroy, as: :attachable has_many :list_items, autosave: true, dependent: :destroy, as: :item has_many :lists, through: :list_items belongs_to :user belongs_to :country scope :with_meta, includes(:country, :attachments) # Searches for partners. Takes a hash of conditions. # # - *:company* a (partial) company name # - *:country* one or more country ids # - *:advisers* an array of adviser ids # - *:businesses* an array of business ids # - *:q* a string used for fulltext search # # The results are ordered by company. def self.search(params) PartnerSearcher.new( params.slice(:company, :country, :advisers, :businesses, :q) ).search(scoped).ordered end # def self.ordered order(DEFAULT_ORDER) end # Returns the company name. def to_s company end end <file_sep>/app/reports/list_report.rb # The ListReport renders a list in PDF. class ListReport < ApplicationReport # Builds a list report. def initialize(list, item_type, user, options = {}) super(list, user, layout: :landscape) @item_type = item_type @options = options text list.comment.to_s gap items end private # Adds the list items. def items klass = ListItem.class_for_item_type(@item_type) cols = klass.exposable_attributes(:pdf, only: @options[:attributes], human: true) incl = klass.filter_associations(cols.map(&:first)) items = @record.list_items.includes(item: incl).by_type(@item_type, order: true) h2 @item_type if cols.empty? || items.empty? p '-' else items_table(items, cols, klass) end end # Renders the items table. def items_table(list_items, cols, klass) note = !! @options[:note] head = cols.map { |attr, _| klass.human_attribute_name(attr) } head << ListItem.human_attribute_name(:note) if note data = [head] data += list_items.map do |list_item| row = cols.map { |_, method| list_item.item.send(method).to_s } row << list_item.note if note row end table data end end <file_sep>/spec/factories/language.rb FactoryGirl.define do factory :language do sequence(:language) { |n| I18n.t(:languages).keys[n] } end end <file_sep>/app/controllers/ajax/employees_controller.rb # Handles Employee specific AJAX requests. class Ajax::EmployeesController < Ajax::ApplicationController respond_to :html, only: [:new, :edit] caches_action :new, :edit # Serves an empty employee form. # # GET /ajax/partners/:partner_id/employees/new def new @employee = Employee.new @url = { controller: '/employees', action: :create } render :form end # Serves an employee form. # # GET /ajax/partners/:partner_id/employees/:id/edit def edit @employee = Employee.find(params[:id]) @url = { controller: '/employees', action: :update } render :form end private # Sets a proper "Not Found" message. def not_found super(t('messages.employee.errors.find')) end end <file_sep>/config/routes.rb Silo::Application.routes.draw do root to: 'experts#index' # Login get 'login' => 'login#welcome' post 'login' => 'login#login' delete 'login' => 'login#logout' # Profile get 'profile' => 'profile#edit' put 'profile' => 'profile#update' # Users resources :users, except: [:show] # Experts get 'experts(/page/:page)' => 'experts#index', as: :experts resources :experts, except: [:index] do resources :cvs, only: [:show, :create, :destroy] resources :attachments, only: [:show, :create, :destroy] resources :contacts, only: [:create, :destroy] resources :addresses, only: [:create, :destroy] get :documents, on: :member end # Partners get 'partners(/page/:page)' => 'partners#index', as: :partners resources :partners, except: [:index] do resources :attachments, only: [:show, :create, :destroy] resources :employees, only: [:index, :create, :update, :destroy] get :documents, on: :member end resources :employees, only: [] do resources :contacts, only: [:create, :destroy] end # Projects get 'projects(/page/:page)' => 'projects#index', as: :projects resources :projects, only: [:new, :create] do resources :attachments, only: [:show, :create, :destroy] resources :project_members, only: [:index, :create, :destroy], as: :members resources :partners, only: [:index, :create, :destroy], controller: :project_partners get :documents, on: :member end get 'projects/:id/edit/:lang' => 'projects#edit', as: :edit_project get 'projects/:id(/:lang)' => 'projects#show', as: :project put 'projects/:id/:lang' => 'projects#update' delete 'projects/:id' => 'projects#destroy', as: :destroy_project # Lists get 'lists(/page/:page)' => 'lists#index', as: :lists resources :lists, only: [:create, :update, :destroy] do resources :list_items, only: [:destroy] put :copy, on: :member put :concat, on: :member [:experts, :partners, :projects, :employees].each do |item_type| resources item_type, only: [], controller: :list_items do get :index, action: item_type, on: :collection end end end # Ajax namespace :ajax do resources :help, only: :show resources :helpers, only: :show resources :tags, only: :show resources :experts, only: [] do resources :addresses, only: :new resources :contacts, only: :new resources :attachments, only: :new resources :cvs, only: :new end resources :partners, only: [] do resources :attachments, only: :new resources :employees, only: [:new, :edit] end resources :employees, only: [] do resources :contacts, only: :new end resources :projects, only: [] do resources :attachments, only: :new resources :project_members, only: [:index, :update], as: :members do collection do get 'new/:expert_id' => 'project_members#new', as: :new get :search end end resources :partners, only: [:index], controller: :project_partners do get :search, on: :collection end end [:areas, :languages].each do |controller| resources controller, only: :index end resources :lists, except: [:create, :update, :destroy] do resources :list_items, only: [:update] member do put :open get :copy get :import end [:experts, :partners, :projects].each do |resource| resources resource, only: [], controller: :list_items do collection do get :print, action: "print_#{resource}" post :create, action: "create_#{resource}" delete :destroy, action: "destroy_#{resource}" end end end end end end <file_sep>/db/migrate/007_add_partners.rb class AddPartners < ActiveRecord::Migration def up create_table :businesses do |t| t.string :business, null: false end add_index :businesses, :business, unique: true create_table :advisers do |t| t.string :adviser, null: false end add_index :advisers, :adviser, unique: true create_table :partners do |t| t.integer :user_id, null: false t.integer :country_id, null: true t.string :company, null: false t.string :street, null: true t.string :city, null: true t.string :zip, null: true t.string :region, null: true t.string :website, null: true t.string :email, null: true t.string :phone, null: true t.timestamps end [:company, :user_id, :country_id, :street, :city, :zip, :region].each do |col| add_index :partners, col end create_table :businesses_partners, id: false do |t| t.integer :business_id, null: false t.integer :partner_id, null: false end add_index :businesses_partners, [:business_id, :partner_id], unique: true create_table :advisers_partners, id: false do |t| t.integer :adviser_id, null: false t.integer :partner_id, null: false end add_index :advisers_partners, [:adviser_id, :partner_id], unique: true create_table :descriptions do |t| t.integer :partner_id, null: false t.text :description, null: false t.timestamps end add_index :descriptions, :partner_id execute('ALTER TABLE descriptions ENGINE = MyISAM') execute('CREATE FULLTEXT INDEX fulltext_description ON descriptions (description)') create_table :employees do |t| t.integer :partner_id, null: false t.string :name, null: false t.string :prename, null: true t.string :gender, null: true t.string :title, null: true t.string :job, null: true t.timestamps end add_index :employees, :partner_id add_index :employees, :name add_index :employees, :prename end def down drop_table :employees drop_table :descriptions drop_table :advisers_partners drop_table :businesses_partners drop_table :partners drop_table :advisers drop_table :businesses end end <file_sep>/db/migrate/009_add_fax_to_partners.rb class AddFaxToPartners < ActiveRecord::Migration def up add_column :partners, :fax, :string, null: true end def down remove_column :partners, :fax end end <file_sep>/spec/lib/human_attribute_names_spec.rb require 'spec_helper' describe HumanAttributeNames do before(:all) do I18n.locale = :en end describe 'human_attribute_names' do it 'should be a sentence of localized attribute names' do sentence = Expert.human_attribute_names(:prename, :name, :degree) expect(sentence).to eq('First Name, Name and Degree') end end end <file_sep>/app/models/language.rb require 'set' # The Language model provides access to a bunge of language codes. # # Database scheme: # # - *id* integer # - *language* string # # The Language#human method provides access to localized language names. class Language < ActiveRecord::Base attr_accessible :language validates :language, presence: true, uniqueness: true has_and_belongs_to_many :experts, uniq: true has_many :cvs has_many :project_infos # A set of prioritized language codes. PRIORITIES = %w(de en es fr).to_set # Polymorphic language finder. Can handle Language, Fixnum, Symbol and # String arguments. Raises an ArgumentError in case of invalid input. # # Language.find_language(1) # #=> #<Language id: 1, language: "af"> # # Language.find_language(:en) # #=> #<Language id: 12, language: "en"> # # Language.find_language("de") # #=> #<Language id: 10, language: "de"> # # Language.find_language("43") # #=> #<Language id: 43, language: "mt"> # # Returns nil, if no language could be found. def self.find_language(language) language.is_a?(self) ? language : find_languages(language).first end # Does the same as Language.find_language, but raises # ActiveRecord::RecordNotFound when no language could be found. def self.find_language!(language) if (result = find_language(language)) result else raise ActiveRecord::RecordNotFound, "Couldn't find Language #{language}" end end # Finds languages by id or language code. Strings are splitted to find # multiple languages. # # Language.find_languages([10, '12']).all # #=> [#<Language id: 2, language: 'de'>, #<Language id: 4, language: 'en'>] # # Language.find_languages('de en').all # #=> [#<Language id: 2, language: 'de'>, #<Language id: 4, language: 'en'>] # # Returns a ActiveRecord::Relation. def self.find_languages(query) query = query.split if query.is_a?(String) where('languages.id IN (:q) OR languages.language IN (:q)', q: query) end # Returns all prioritized languages. # # Language.prioritized # #=> [ # #<Language id: 81, language: "de">, # #<Language id: 83, language: "en">, # #<Language id: 84, language: "es">, # #<Language id: 90, language: "fr"> # ] # # The results are in no special order. def self.prioritized where('languages.language IN (:q)', q: PRIORITIES) end # Returns a collection of all languages ordered by localized name. def self.ordered all.sort { |x, y| x.human <=> y.human } end # Returns a collection of all languages ordered by priority and localized # language name. def self.priority_ordered all.sort do |x, y| if x.prioritized? == y.prioritized? x.human <=> y.human else x.prioritized? ? -1 : 1 end end end # Returns true if the language has priority, else false. The PRIORITIES # constant is used to determine the value. def prioritized? @prioritized ||= PRIORITIES.include?(language.to_s) end # Returns the localized language. # # cv.language.human # #=> 'English' def human I18n.t(language, scope: :languages) end alias :to_s :human end <file_sep>/spec/models/adviser_spec.rb require 'spec_helper' describe Adviser do it 'should act as a tag' do Adviser.acts_as_tag?.should be_true end context 'associations' do it { should have_and_belong_to_many(:partners) } end end <file_sep>/app/models/project.rb # Handles project related data. # # Database schema: # # - *id:* integer # - *user_id:* integer # - *country_id:* integer # - *status:* string # - *carried_proportion:* integer # - *start* date # - *end* date # - *order_value_us:* integer # - *order_value_eur:* integer # - *created_at:* datetime # - *updated_at:* datetime # # The columns *user_id* and *status* are required. class Project < ActiveRecord::Base attr_accessible :country_id, :status, :carried_proportion, :start, :end, :order_value_us, :order_value_eur discrete_values :status, [:forecast, :interested, :offer, :execution, :stopped, :complete] validates :carried_proportion, inclusion: 0..100 validate :start_must_be_earlier_than_end DEFAULT_ORDER = 'projects.title' has_and_belongs_to_many :partners, uniq: true has_many :infos, autosave: true, dependent: :destroy, class_name: :ProjectInfo, inverse_of: :project has_many :members, autosave: true, dependent: :destroy, class_name: :ProjectMember, inverse_of: :project has_many :attachments, autosave: true, dependent: :destroy, as: :attachable has_many :list_items, autosave: true, dependent: :destroy, as: :item has_many :lists, through: :list_items belongs_to :user, select: [:id, :name, :prename] belongs_to :country # Searches for projects. Takes a hash of conditions. # # - *:title* a (partial) title # - *:status* a projects status # - *:start* year before the projects start # - *:end* year after the projects end # - *:q* string used for fulltext search # # The results are ordered by title. def self.search(params) ProjectSearcher.new( params.slice(:title, :status, :start, :end, :q) ).search(scoped).ordered end # Orders the projects by title. def self.ordered order(DEFAULT_ORDER) end # Returns the first year of the max possible period. def self.first_period_year 1970 end # Returns the last year of the max possible period. def self.last_period_year Time.now.year + 50 end # Returns the max possible period. def self.max_period first_period_year..last_period_year end # Returns a human readable start date. def human_start(format) I18n.l(start, format: format) if start end # Returns a human readable end date. def human_end(format) I18n.l(self.end, format: format) if self.end end # Returns true if the project has some infos, else false def info? ! infos.empty? end # Returns the first info. def info infos.first end # Returns an info by given language. Allocates a fresh ProjectInfo, if it # doesn't exist. def info_by_language(lang) infos.find_by_language(lang) || ProjectInfo.new.tap do |info| info.project = self info.language = lang end end # Returns an info by given language. Raises ActiveRecord::RecordNotFound, if # it doesn't esxist. def info_by_language!(lang) infos.find_by_language!(lang) end # Returns a collection of potential experts. def potential_experts ids = members.pluck(:expert_id) ids.empty? ? Expert.scoped : Expert.where('id NOT IN (?)', ids) end # Returns a collection of potential partners. def potential_partners ids = partners.pluck(:id) ids.empty? ? Partner.scoped : Partner.where('id NOT IN (?)', ids) end # Adds a partners to the project. def add_partner(partner) partners << partner rescue ActiveRecord::RecordNotUnique false end # Updates the title. def update_title update_attribute(:title, info.try(:title)) end # Returns the first info as a string. def to_s title.to_s end private def start_must_be_earlier_than_end if ! self.start.nil? && ! self.end.nil? && self.start > self.end errors.add(:start, I18n.t('messages.errors.project.start_later_than_end')) errors.add(:end, I18n.t('messages.errors.project.start_later_than_end')) end end end <file_sep>/app/helpers/contact_helper.rb # Contains contact specific helper methods. module ContactHelper # Returns the contact value. If field is :emails or :websites, the value # is wrapped with <a> tag. def contact_value(val, field, html_options = {}) return nil if val.blank? case field when :emails mail_to val when :websites link_to val, (URI.parse(val).scheme.blank? ? "http://#{val}" : val) else val end rescue val end # Returns a "delete contact" link. # # delete_contact_button(expert, :emails, '<EMAIL>') # # The parent argument must be a parent model of the contact. def delete_contact_button(parent, field, contact, options = {}) options = { url: [parent, parent.contact], 'data-field' => field, 'data-contact' => contact }.merge(options) delete_button_for(parent.contact, options) end end <file_sep>/lib/body_class.rb require 'set' # The BodyClass module defines the BodyClass class and a helper method to # work with body classes. The idea is to write something like this in the # controller. # # class PostsController < ApplicationController # def show # @post = Post.find(params[:id]) # body_class << @post.type # end # end # # And this in the layout template. # # <body class="<%= body_class %>"> # # The BodyClass behaves like a Set with indifferent access, which means that # that Symbols are internally converted into Strings. # # body_class = BodyClass::BodyClass.new(:example) # #=> #<BodyClass::BodyClass {'example'}> # # body_class.include?(:example) #=> true # body_class.include?('example') #=> true # # There are two more differences to a normal Set. # # - BodyClass::BodyClass#delete() returns the deleted value or nil. # - BodyClass::BodyClass#to_s returns all values joined by a space. # # Some examples. # # body_class = BodyClass::BodyClass.new([:example, :admin]) # # body_class.to_s #=> 'example admin' # body_class.delete(:example) #=> 'example' # body_class.delete(:x) #=> nil # # Much fun! module BodyClass # Handles the body class. See the ::BodyClass module for more info. class BodyClass < Set # Initializes the body class. def initialize(enum = nil, &block) @hash ||= HashWithIndifferentAccess.new super(enum, &block) end # Deletes a value from the body class. # # Returns the value as a string or nil if it is not present. def delete(value) @hash.delete(value) && @hash.send(:convert_key, value) end # Returns all body class values as a string joined by a space. def to_s to_a.join(' ') end end # Defines some helper methods. module ActionController extend ActiveSupport::Concern included { helper_method(:body_class) } # Returns the body class. def body_class @body_class ||= begin values = params.values_at(:controller, :action) BodyClass.new(values.map { |v| v.to_s.dasherize }) end end end end ActionController::Base.send :include, BodyClass::ActionController <file_sep>/lib/human_attribute_names.rb # Mixes the method HumanAttributeNames#human_attribute_names # into ActiveRecord. module HumanAttributeNames extend ActiveSupport::Concern # Defines the the modules class methods. module ClassMethods # Returns a string containing comma separated localized attribute names. # # User.human_attribute_names(:name, :firstname, :degree) # #=> "Name, Vorname und Abschluss" def human_attribute_names(*attributes) attributes.collect do |attr| human_attribute_name(attr) end.to_sentence end end end ActiveRecord::Base.send :include, HumanAttributeNames <file_sep>/app/controllers/ajax/languages_controller.rb # The Ajax::LanguagesController provides several actions to retrieve # language views via Ajax. class Ajax::LanguagesController < Ajax::ApplicationController caches_action :index # Serves a multi select box. def index @languages = Language.priority_ordered respond_with(@languages) end end <file_sep>/db/migrate/001_init_silo.rb class InitSilo < ActiveRecord::Migration def up create_table :users do |t| t.string :username, null: false t.string :email, null: false t.string :password_digest, null: false t.string :login_hash, null: true t.string :name, null: false t.string :prename, null: false t.string :locale, null: false, default: 'en' t.timestamp :created_at, null: false end add_index :users, :username, unique: true add_index :users, :email, unique: true add_index :users, :login_hash, unique: true create_table :privileges do |t| t.integer :user_id, null: false t.boolean :admin, null: false, default: false t.boolean :experts, null: false, default: false t.boolean :partners, null: false, default: false t.boolean :references, null: false, default: false end add_index :privileges, :user_id end def down drop_table :users drop_table :privileges end end <file_sep>/app/models/project_info.rb # Manages language dependent data for projects. # # Database schema: # # - *id:* integer # - *project_id:* integer # - *language:* string # - *title:* string # - *region:* string # - *client:* string # - *address:* string # - *funders:* string # - *staff:* string # - *staff_months:* string # - *focus:* text # - *created_at:* datetime # - *updated_at:* datetime # # The fields *project_id*, *language* and *title* are required. class ProjectInfo < ActiveRecord::Base attr_accessible :title, :language, :region, :client, :address, :funders, :staff, :staff_months, :focus discrete_values :language, %w(de en es fr), i18n_scope: :languages validates :title, presence: true validate :language_cannot_be_changed is_commentable_with :description, autosave: true, dependent: :destroy, as: :describable is_commentable_with :service_details, autosave: true, dependent: :destroy, as: :commentable, class_name: :Comment belongs_to :project, autosave: true, inverse_of: :infos after_save :update_project default_scope order(:language) self.per_page = 50 # Returns a list of all possible languages. def self.languages language_values.map(&:last) end # Returns the title. def to_s title.to_s end private # Update the projects title after save. def update_project project.update_title end # Checks that the language hasn't been changed. def language_cannot_be_changed if ! language_was.nil? && language_changed? errors.add(:language, I18n.t('messages.project_info.errors.language_changed')) end end end <file_sep>/app/controllers/ajax/lists_controller.rb # The Ajax::ListsController handles all list specific ajax requests. class Ajax::ListsController < Ajax::ApplicationController before_filter :find_list, only: [:show, :import, :edit, :copy, :open] respond_to :html, only: [:index, :new, :edit, :copy] respond_to :json, except: [:index, :new, :edit, :copy] caches_action :new, :edit, :copy, :print # Serves a list of all lists. # # GET /ajax/lists def index @lists = current_user.accessible_lists.search(params) @title = t('labels.list.open') respond_with(@list) end # Shows a list. # # GET /ajax/lists/:id def show respond_with(@list) end # Serves a list of lists for import purposes. # # GET /ajax/lists/import def import @lists = current_user.accessible_lists.search(params.merge(exclude: @list)) @title = t('labels.list.import') render :index end # Serves an empty list form. # # GET /ajax/lists/new def new @list = List.new @url = lists_path render :form end # Serves a form to edit a list. # # GET /ajax/lists/:id/edit def edit @url = list_path(@list) render :form end # Serves a form to copy a list. # # GET /ajax/lists/:id/copy def copy @url = copy_list_path(@list) render :form end # Opens a list. # # PUT /ajax/lists/:id/open def open current_user.current_list = @list if current_user.save render json: current_list else error(t('messages.list.errors.open')) end end private # Finds the list. def find_list if params[:id] == 'current' @list = current_list! else @list = current_user.accessible_lists.find(params[:id]) end end # Sets a proper error message. def not_found super(t('messages.list.errors.find')) end end
4dc3dc414c929fbcdf0a110433dadcf0d812ded9
[ "SQL", "Ruby", "HTML" ]
170
Ruby
ushis/silo
700fa2e1b8bef16f924fb0663d0ca0e55a37142c
6d2c8b351ee76892468e172e854b3ab6df1036ac
refs/heads/master
<repo_name>vitorarins/RevenueCrawler<file_sep>/README.md RevenueCrawler ============== A web-crawler for getting revenue data of companies from a specific website.<file_sep>/pars.py #!/usr/bin/python #coding: utf-8 from bs4 import BeautifulSoup def check_doctype(html): """This function will check which document type we are dealing with, whether is the type showing all the revenue information or the one with only a few financial info.""" soup = BeautifulSoup(html) second_div = soup.find(id="ctl00_cphPopUp_cmbGrupo_cmbGrupo_c2") if not second_div: # if it has no info at all return '' if second_div.string.strip().encode('utf-8') == 'DFs Individuais': # if it is the one with all info return 'df' for i in xrange(3,6): # This will also check for the one with all info, iterating through some items in the droplist div = soup.find(id="ctl00_cphPopUp_cmbGrupo_cmbGrupo_c"+str(i)) if div and div.string.strip().encode('utf-8') == 'DFs Individuais': return 'df' return 'info' # if none of the above, it's the one with little information def get_ativo_table(data,html): """This function will get all the data from a page that has all revenue information. Right now the format on which the data consists, is as follows: the key will be the concatenation of 'Descrição' and the year. An the value will consist on the cell that corresponds to that key on the table Ex.: 'ativo2011' : 4687123.0 """ soup = BeautifulSoup(html) header = soup.tr.extract() header_tds = header.findAll('td') dates = [] for i in xrange(2,len(header_tds)): date_tag = header_tds[i].contents[-1] date_string = date_tag.string.encode('utf-8')[-6:-2] # if it is the 'Demonstração de Resultado' page, the year starts at -6 pos. dates.append(date_string) ativo = soup.tr.extract() ativo_tds = ativo.findAll('td')[2:] for i in xrange(len(dates)): number = ativo_tds[i].string.strip().encode('utf-8') if number: number = number.replace('.','') number = number.replace(',','.') data['ativo'+dates[i]] = float(number) # Here we add the value to its according position at the dictionaire else: data['ativo'+dates[i]] = 0.0 return data,dates def get_fieldname(desc): """ Just a small function to translate the Description to a field in the table. This is used on the page that has a summary of all the financial information.""" fields = [('<NAME>','pat_liquido'), \ ('Ativo Total','ativo'), \ ('Rec. Liq./Rec. Intermed. Fin./Prem. Seg. Ganhos','receita'), \ ('Resultado Bruto','resultado_bruto'), \ ('Resultado Líquido','resultado_liq'), \ ('Número de Ações, Ex-Tesouraria','qtd_acoes'), \ ('Valor Patrimonial de Ação (Reais Unidade)','vlr_acoes'), \ ('Resultado Líquido por Ação','result_liq_acoes')] for e in fields: if desc == e[0]: return e[1] return 'none' def get_info_table(data,html): """This function will get the data that does not have all the information, but it has a little revenue info. Right now the format on which the data is as follows, the key will be 'Informação Financeira'(description) concatenated with the year. And the value will be consistent with the cell in that table key. Ex.: '<NAME>010': -5210229.0 """ soup = BeautifulSoup(html) header = soup.tr.extract() ths = header.findAll('th') dates = [ths[i].span.string[-4:] for i in range(1,len(ths)) if ths[i].span.string] # Get the years to concatenate later for tr in soup.findAll('tr'): # For each row in the table, it will get the description desc = tr.td.extract().string.strip().encode('utf-8') field = get_fieldname(desc) cols = tr.findAll('td') for i in xrange(len(cols)): # Then for each cell, it will get the value number = cols[i].string.strip().encode('utf-8') if field == 'none': continue if number: number = number.replace('.','') number = number.replace(',','.') data[field+dates[i]] = float(number) # The key with description concatenated with year else: # if it doesn't find any value data[field+dates[i]] = 0 return data def get_general_data(data,html): soup = BeautifulSoup(html) data['cnpj'] = soup.find(id='ctl00_cphPopUp_txtCnpj').string.strip().encode('utf-8') data['nome'] = soup.find(id='ctl00_cphPopUp_txtNomeEmpresarial').string.strip().encode('utf-8') nome_ant = soup.find(id='ctl00_cphPopUp_txtNomeEmpresarialAnterior').string data['nome_ant'] = nome_ant.strip().encode('utf-8') if nome_ant else '' pagina = soup.find(id='ctl00_cphPopUp_txtPaginaEmissorRedeMundialComputadores').string data['pagina'] = pagina.strip().encode('utf-8') if pagina else '' return data def get_address_data(data,html): soup = BeautifulSoup(html) if soup.find(id='ctl00_cphPopUp_txtLogradouroSede') != None: fonte = 'Sede' else: fonte = 'Correspondencia' logradouro = soup.find(id='ctl00_cphPopUp_txtLogradouro'+fonte).string complemento = soup.find(id='ctl00_cphPopUp_txtComplemento'+fonte).string bairro = soup.find(id='ctl00_cphPopUp_txtBairro'+fonte).string endereco = logradouro.strip().encode('utf-8')+' ' if logradouro else '' endereco += complemento.strip().encode('utf-8')+' ' if complemento else '' endereco += bairro.strip().encode('utf-8') if bairro else '' data['endereco'] = endereco.replace(',','') cep = soup.find(id='ctl00_cphPopUp_txtCep'+fonte).string data['cep'] = cep.strip().encode('utf-8') if cep else '' uf = soup.find(id='ctl00_cphPopUp_txtUf'+fonte).string data['uf'] = uf.strip().encode('utf-8') if uf else '' municipio = soup.find(id='ctl00_cphPopUp_txtMunicipio'+fonte).string data['municipio'] = municipio.strip().encode('utf-8') if municipio else '' ddd_tel = soup.find(id='ctl00_cphPopUp_txtDTel'+fonte).string tel = '('+ddd_tel.strip().encode('utf-8')+')' if ddd_tel else '' telefone = soup.find(id='ctl00_cphPopUp_txtTel'+fonte).string tel += telefone.strip().encode('utf-8') if telefone else '' data['telefone'] = tel ddd_fax = soup.find(id='ctl00_cphPopUp_txtDFax'+fonte).string tel_fax = '('+ddd_fax.strip().encode('utf-8')+')' if ddd_fax else '' fax = soup.find(id='ctl00_cphPopUp_txtFax'+fonte).string tel_fax += fax.strip().encode('utf-8') if fax else '' data['fax'] = tel_fax email = soup.find(id='ctl00_cphPopUp_txtEmail'+fonte).string data['email'] = email.strip().encode('utf-8') if email else '' return data def get_receita_table(data,html,dates,result=0): soup = BeautifulSoup(html) header = soup.tr.extract() desc = 'resultado_liq' if result else 'receita' receita = soup.tr.extract() receita_tds = receita.findAll('td')[2:] for i in xrange(len(dates)): number = receita_tds[i].string.strip().encode('utf-8') if number: number = number.replace('.','') number = number.replace(',','.') data[desc+dates[i]] = float(number) else: data[desc+dates[i]] = 0.0 return data def get_patrimonio_table(data,html,dates): soup = BeautifulSoup(html) dates.reverse() how_many = len(dates) rows = soup.findAll('tr')[-how_many:] for i in xrange(len(rows)): number = rows[i].findAll('td')[-1] if number: number_str = number.string.strip().encode('utf-8') if number_str: number_str = number_str.replace('.','') number_str = number_str.replace(',','.') data['pat_liquido'+dates[i]] = float(number_str) else: data['pat_liquido'+dates[i]] = 0.0 return data <file_sep>/crawler_cvm.py #!/usr/bin/python #coding: utf-8 ## This program consists in a Crawler to get revenue information ## import mechanize import cookielib import csv import pars from bs4 import BeautifulSoup # Browser br = mechanize.Browser() # CookieJar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handle_referer(True) br.set_handle_redirect(False) br.set_handle_robots(False) # Want debugging messages? br.set_debug_http(True) br.set_debug_redirects(True) br.set_debug_responses(True) # User Agent br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] # Proxy br.set_proxies({"http":"172.16.58.3:53066"}) Reviewed-by: Vitor <<EMAIL>> # This url will be used just to validate the session and check for the doc type validation_url = "" # With this url it gets all the general information such like address, name, etc. dados_gerais_url = "" endereco_url = "" # If the document is the one showing little revenue information, this will be the # url to use info_finance_url = "" # If the document has all the information, this will be the url to use dfs_url = "" # The first is used to show the 'Balanço Patrimonial Ativo' page # the other to show the 'Demonstração de Resultado' page df_ativo, df_receita, df_result, df_patrimonio = 2, 4, 5, 8 # The headers for the csv files with the final data fieldnames = ['cnpj','nome','nome_ant','pagina', \ 'endereco','cep','uf','municipio','telefone','fax','email', \ 'pat_liquido2012','pat_liquido2011','pat_liquido2010', \ 'pat_liquido2009','pat_liquido2008','pat_liquido2007', \ 'ativo2012','ativo2011','ativo2010','ativo2009','ativo2008', \ 'ativo2007','receita2012','receita2011','receita2010', \ 'receita2009','receita2008','receita2007', \ 'resultado_bruto2012','resultado_bruto2011', \ 'resultado_bruto2010','resultado_bruto2009', \ 'resultado_bruto2008','resultado_bruto2007', \ 'resultado_liq2012','resultado_liq2011','resultado_liq2010',\ 'resultado_liq2009','resultado_liq2008','resultado_liq2007', \ 'qtd_acoes2012','qtd_acoes2011','qtd_acoes2010','qtd_acoes2009',\ 'qtd_acoes2008','qtd_acoes2007','vlr_acoes2012','vlr_acoes2011',\ 'vlr_acoes2010','vlr_acoes2009','vlr_acoes2008','vlr_acoes2007',\ 'result_liq_acoes2012','result_liq_acoes2011', \ 'result_liq_acoes2010','result_liq_acoes2009', \ 'result_liq_acoes2008','result_liq_acoes2007'] dados_csv_filename = "/home/vitor/Documents/Projetos/Crawler/CVM/dados2.csv" with open(dados_csv_filename,'wb') as csvfile: writer = csv.DictWriter(csvfile,fieldnames,extrasaction='ignore') writer.writeheader() for seq_documento in xrange(1,20000): try: br.open(validation_url+str(seq_documento)) assert br.viewing_html() tipo_doc_tg = pars.check_doctype(br.response().read()) unit_data = {} br.open(dados_gerais_url+str(seq_documento)) assert br.viewing_html() unit_data = pars.get_general_data(unit_data,br.response().read()) br.open(endereco_url+str(seq_documento)) assert br.viewing_html() unit_data = pars.get_address_data(unit_data,br.response().read()) if tipo_doc_tg == 'df': br.open(dfs_url+str(df_ativo)+"&NumeroSequencialDocumento="+str(seq_documento)) assert br.viewing_html() unit_data,dates = pars.get_ativo_table(unit_data,br.response().read()) br.open(dfs_url+str(df_receita)+"&NumeroSequencialDocumento="+str(seq_documento)) assert br.viewing_html() unit_data = pars.get_receita_table(unit_data,br.response().read(),dates) br.open(dfs_url+str(df_result)+"&NumeroSequencialDocumento="+str(seq_documento)) assert br.viewing_html() unit_data = pars.get_receita_table(unit_data,br.response().read(),dates,df_result) br.open(dfs_url+str(df_patrimonio)+"&NumeroSequencialDocumento="+str(seq_documento)) assert br.viewing_html() unit_data = pars.get_patrimonio_table(unit_data,br.response().read(),dates) print 'Got: '+str(seq_documento) elif tipo_doc_tg == 'info': br.open(info_finance_url+str(seq_documento)) assert br.viewing_html() unit_data = pars.get_info_table(unit_data,br.response().read()) print 'Got: '+str(seq_documento) else: print "Got: "+str(seq_documento)+" Gen. data!" writer.writerow(unit_data) except mechanize.HTTPError as s: print "error: "+str(seq_documento)+' Not Found! 302Error!' continue
ac5ac934fab95727030d0f74f593246dc7bcecc3
[ "Markdown", "Python" ]
3
Markdown
vitorarins/RevenueCrawler
969cb56b5d695d508276d0159a5a8f02cdb01016
6774401260c8162a6787a7e8a37b2e9bfedcf8c0
refs/heads/main
<repo_name>rdjennings/StockChart<file_sep>/server/index.js const express = require('express'); const app = express(); const yf = require('yahoo-finance'); const port = 3010; const cors = require('cors'); const fs = require('fs'); const path = require('path'); app.use(cors()); let symbols = []; let jsonPath = path.join(__dirname, '..', 'server', 'data', 'symbols.txt'); fs.readFile(jsonPath, 'utf8', (err, data) => { let words = data.split('\n'); symbols = words.filter(word => word.length > 0 ); }) app.get('/', (req, res) => { const modules = [ 'price', 'summaryDetail', 'defaultKeyStatistics', // 'recommendationTrend' ] let response = {}; try { yf.quote({ symbols, modules }, {timeout: 9000}, (err, quote) => { if (err !== null) { console.error({err}) response = {}; } else if (quote === null || quote === undefined) { console.log('no quote data'); response = {}; } else { const keys = Object.keys(quote); response = keys.map(key => { if (key && quote[key]) { const q = quote[key]; // console.log(q) // q.recommendationTrend.trend.forEach(item => console.log(item)) return {[key]: { price: q.price.regularMarketPrice, bid: q.summaryDetail.bid, bidSize: q.summaryDetail.bidSize, ask: q.summaryDetail.ask, askSize: q.summaryDetail.askSize, prevClose: q.summaryDetail.previousClose, volume: q.summaryDetail.volume, averageVolume: q.summaryDetail.averageVolume, exchangeDataDelayedBy: q.price.exchangeDataDelayedBy, shortName: q.price.shortName, exchangeName: q.price.exchangeName, change: q.price.regularMarketChange, symbol: q.price.symbol, bookValue: q.defaultKeyStatistics.bookValue, open: q.summaryDetail.open, regularMarketChangePercent: q.price.regularMarketChangePercent, beta: q.summaryDetail.beta, SMA50: q.summaryDetail.fiftyDayAverage, SMA200: q.summaryDetail.twoHundredDayAverage }} } return {}; }) } res.send(response) }) } catch (error) { console.error('YF error', {error}); res.send({}); } }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
d9bbf8ada5d12072fce81e2a1bc3d990c45fb123
[ "JavaScript" ]
1
JavaScript
rdjennings/StockChart
6e08476ba511136072254894aa5fd9e2438c0923
d410bebb12179a649622e7561e2be55aeebf8139
refs/heads/master
<repo_name>battyone/pious-squid<file_sep>/src/test/propagator-test.ts import * as assert from "assert"; import { DataHandler } from "../data/data-handler"; import { EpochUTC, J2000, KeplerPropagator, RungeKutta4Propagator, Vector3D } from "../index"; import { InterpolatorPropagator } from "../propagators/interpolator-propagator"; DataHandler.setFinalsData([ "181220 58472.00 I 0.111682 0.000013 0.267043 0.000011 I-0.0268992 0.0000042 0.8116 0.0029 I -107.187 1.028 -6.992 0.043", "181221 58473.00 I 0.109899 0.000013 0.266778 0.000012 I-0.0276299 0.0000041 0.6550 0.0031 I -107.216 1.028 -6.947 0.043", "181222 58474.00 I 0.107885 0.000012 0.266558 0.000012 I-0.0282132 0.0000046 0.5105 0.0030 I -107.320 1.028 -7.168 0.043" ]); const state = new J2000( EpochUTC.fromDateString("2018-12-21T00:00:00.000Z"), new Vector3D(-1117.913276, 73.093299, -7000.018272), new Vector3D(3.531365461, 6.583914964, -0.495649656) ); const epoch = EpochUTC.fromDateString("2018-12-22T00:00:00.000Z"); const rk4Prop = new RungeKutta4Propagator(state); const kepProp = new KeplerPropagator(state.toClassicalElements()); describe("KeplerPropagator", () => { describe("two-body", () => { rk4Prop.reset(); rk4Prop.setStepSize(10); rk4Prop.forceModel.clearModel(); rk4Prop.forceModel.setEarthGravity(0, 0); kepProp.reset(); const rk4Result = rk4Prop.propagate(epoch).position; const kepResult = kepProp.propagate(epoch).position; it("should be within 1m of numerical two-body after 24 hours", () => { assert(kepResult.distance(rk4Result) < 0.001); }); }); }); describe("RungeKutta4Propagator", () => { describe("high-accuracy", () => { rk4Prop.reset(); rk4Prop.setStepSize(10); rk4Prop.forceModel.clearModel(); rk4Prop.forceModel.setEarthGravity(50, 50); rk4Prop.forceModel.setThirdBody(true, true); const actual = rk4Prop.propagate(epoch).position; const expected = new Vector3D(-212.125533, -2464.351601, 6625.907454); it("should be within 25m of real-world ephemeris after 24 hours", () => { assert(expected.distance(actual) < 0.025); }); }); }); describe("InterpolatorPropagator", () => { describe("interpolate", () => { const rk4Prop = new RungeKutta4Propagator(state); rk4Prop.setStepSize(5); rk4Prop.forceModel.setEarthGravity(50, 50); rk4Prop.forceModel.setThirdBody(true, true); const cacheDense = rk4Prop.step(state.epoch, 60, 86400 / 60); rk4Prop.reset(); const cacheSparse = rk4Prop.step(state.epoch, 900, 86400 / 900); const interpolator = new InterpolatorPropagator(cacheSparse); interpolator.forceModel.setEarthGravity(2, 0); let maxError = 0; for (let cState of cacheDense) { const iState = interpolator.propagate(cState.epoch); const dist = cState.position.distance(iState.position); maxError = Math.max(maxError, dist); } it("should have a maximum error of 30m", () => { assert(maxError < 0.03); }); }); }); <file_sep>/src/propagators/runge-kutta-4-propagator.ts import { J2000 } from "../coordinates/j2000"; import { ForceModel } from "../forces/force-model"; import { copySign } from "../math/operations"; import { Vector6D } from "../math/vector-6d"; import { EpochUTC } from "../time/epoch-utc"; import { IPropagator } from "./propagator-interface"; /** 4th order Runge-Kutta numerical integrator for satellite propagation. */ export class RungeKutta4Propagator implements IPropagator { /** force model */ public readonly forceModel: ForceModel; /** initial state */ private initState: J2000; /** cached state */ private cacheState: J2000; /** step size (seconds) */ private stepSize: number; /** * Create a new RungeKutta4 propagator object. * * @param state J2000 state vector */ constructor(state: J2000) { this.initState = state; this.cacheState = this.initState; this.stepSize = 15; this.forceModel = new ForceModel(); this.forceModel.setEarthGravity(0, 0); } /** Fetch last propagated satellite state. */ get state() { return this.cacheState; } /** * Set the integration step size. * * Smaller is slower, but more accurate. * * @param seconds step size (seconds) */ public setStepSize(seconds: number) { this.stepSize = Math.abs(seconds); } /** * Set the propagator initial state. * * @param state J2000 state */ public setInitState(state: J2000) { this.initState = state; this.reset(); } /** Reset cached state to the initialized state. */ public reset() { this.cacheState = this.initState; } /** * Calculate partial derivatives for integrations. * * @param j2kState J2000 state vector * @param hArg step size argument * @param kArg derivative argument */ private kFn(j2kState: J2000, hArg: number, kArg: Vector6D) { const epoch = j2kState.epoch.roll(hArg); const posvel = j2kState.position.join(j2kState.velocity); const [position, velocity] = posvel.add(kArg).split(); const sample = new J2000(epoch, position, velocity); return this.forceModel.derivative(sample); } /** * Calculate a future state by integrating velocity and acceleration. * * @param j2kState J2000 state vector * @param step step size (seconds) */ private integrate(j2kState: J2000, step: number) { const k1 = this.kFn(j2kState, 0, Vector6D.origin()).scale(step); const k2 = this.kFn(j2kState, step / 2, k1.scale(1 / 2)).scale(step); const k3 = this.kFn(j2kState, step / 2, k2.scale(1 / 2)).scale(step); const k4 = this.kFn(j2kState, step, k3).scale(step); const v1 = k1; const v2 = v1.add(k2.scale(2)); const v3 = v2.add(k3.scale(2)); const v4 = v3.add(k4); const tNext = j2kState.epoch.roll(step); const posvel = j2kState.position.join(j2kState.velocity); const [position, velocity] = posvel.add(v4.scale(1 / 6)).split(); return new J2000(tNext, position, velocity); } /** * Integrate cached state to a new epoch. * * @param newEpoch propagation epoch */ public propagate(newEpoch: EpochUTC) { while (!this.cacheState.epoch.equals(newEpoch)) { const delta = newEpoch.difference(this.cacheState.epoch); const mag = Math.min(this.stepSize, Math.abs(delta)); const step = copySign(mag, delta); this.cacheState = this.integrate(this.cacheState, step); } return this.cacheState; } /** * Propagate state by some number of seconds, repeatedly, starting at a * specified epoch. * * @param epoch UTC epoch * @param interval seconds between output states * @param count number of steps to take */ public step(epoch: EpochUTC, interval: number, count: number): J2000[] { const output: J2000[] = [this.propagate(epoch)]; let tempEpoch = epoch; for (let i = 0; i < count; i++) { tempEpoch = tempEpoch.roll(interval); output.push(this.propagate(tempEpoch)); } return output; } } <file_sep>/src/math/random-gaussian.ts import { TWO_PI } from "./constants"; import { Vector3D } from "./vector-3d"; /** * Class for generating random Gaussian numbers. * * Uses the Box-Mueller Transform for generating gaussian numbers from uniformly * distributed numbers. */ export class RandomGaussian { /** mean value */ private mu: number; /** standard deviation */ private sigma: number; /** gaussian storage 0 */ private z0: number; /** gaussian storage 1 */ private z1: number; /** uniform storage 1 */ private u1: number; /** uniform storage 2 */ private u2: number; /** should generate new values if true */ private generate: boolean; /** * Create a RandomGaussian object. * * @param mu mean value * @param sigma standard deviation */ constructor(mu: number, sigma: number) { this.mu = mu; this.sigma = sigma; this.z0 = 0; this.z1 = 0; this.u1 = 0; this.u2 = 0; this.generate = true; } /** Return the next random Gaussian number. */ public next() { if (!this.generate) { return this.z1 * this.sigma + this.mu; } do { this.u1 = Math.random(); this.u2 = Math.random(); } while (this.u1 <= Number.MIN_VALUE); const prefix = Math.sqrt(-2.0 * Math.log(this.u1)); this.z0 = prefix * Math.cos(TWO_PI * this.u2); this.z1 = prefix * Math.sin(TWO_PI * this.u2); return this.z0 * this.sigma + this.mu; } /** Return the next random Gaussian Vector3D object. */ public nextVector3D() { return new Vector3D(this.next(), this.next(), this.next()); } } <file_sep>/src/time/abstract-epoch.ts /** Base class for representing epochs. */ export abstract class AbstractEpoch { /** Seconds since 1 January 1970, 00:00 UTC. */ public readonly unix: number; /** * Create a new Epoch object. * * @param millis milliseconds since 1 January 1970, 00:00 UTC */ constructor(millis: number) { this.unix = millis / 1000; } /** * Calculate the difference between this and another epoch, in seconds. * * @param epoch comparison epoch */ public difference(epoch: AbstractEpoch) { return this.unix - epoch.unix; } /** * Return true if this and another epoch are equal. * * @param epoch comparison epoch */ public equals(epoch: AbstractEpoch) { return this.unix == epoch.unix; } /** Convert this to a JavaScript Date object. */ public toDate() { return new Date(this.unix * 1000); } /** String representation of this object. */ public toString() { return this.toDate().toISOString(); } /** Convert this to a Julian Date. */ public toJulianDate() { return this.unix / 86400 + 2440587.5; } /** Convert this to Julian Centuries. */ public toJulianCenturies() { return (this.toJulianDate() - 2451545) / 36525; } } <file_sep>/src/time/epoch-utc.ts import { DataHandler } from "../data/data-handler"; import { DEG2RAD, TWO_PI } from "../math/constants"; import { evalPoly } from "../math/operations"; import { AbstractEpoch } from "./abstract-epoch"; import { EpochTAI, EpochTDB, EpochTT, EpochUT1 } from "./time-scales"; /** Class representing a UTC astrodynamic epoch. */ export class EpochUTC extends AbstractEpoch { /** * Create a new Epoch object. * * @param millis milliseconds since 1 January 1970, 00:00 UTC */ constructor(millis: number) { super(millis); } /** * Create a new EpochUTC object from a valid JavaScript Date string. * * @param dateStr */ public static fromDateString(dateStr: string) { return new EpochUTC(new Date(dateStr).getTime()); } /** Return a new Epoch object, containing current time. */ public static now(): EpochUTC { return new EpochUTC(new Date().getTime()); } /** * Return a new Epoch, incremented by some desired number of seconds. * * @param seconds seconds to increment (can be negative) */ public roll(seconds: number): EpochUTC { return new EpochUTC((this.unix + seconds) * 1000); } /** Convert to UNSO Modified Julian Date. */ public toMjd() { return this.toJulianDate() - 2400000.5; } /** Convert to GSFC Modified Julian Date. */ public toMjdGsfc() { return this.toJulianDate() - 2400000.5 - 29999.5; } /** Convert to a UT1 Epoch. */ public toUT1() { const { dut1 } = DataHandler.getFinalsData(this.toMjd()); return new EpochUT1((this.unix + dut1) * 1000); } /** Convert to an International Atomic Time (TAI) Epoch. */ public toTAI() { const ls = DataHandler.leapSecondsOffset(this.toJulianDate()); return new EpochTAI((this.unix + ls) * 1000); } /** Convert to a Terrestrial Time (TT) Epoch. */ public toTT() { return new EpochTT((this.toTAI().unix + 32.184) * 1000); } /** Convert to a Barycentric Dynamical Time (TDB) Epoch. */ public toTDB() { const tt = this.toTT(); const tTT = tt.toJulianCenturies(); const mEarth = (357.5277233 + 35999.05034 * tTT) * DEG2RAD; const seconds = 0.001658 * Math.sin(mEarth) + 0.00001385 * Math.sin(2 * mEarth); return new EpochTDB((tt.unix + seconds) * 1000); } /** * Calculate the Greenwich Mean Sideral Time (GMST) angle for this epoch, * in radians. */ public gmstAngle() { const t = this.toUT1().toJulianCenturies(); const seconds = evalPoly(t, [ 67310.54841, 876600.0 * 3600.0 + 8640184.812866, 0.093104, 6.2e-6 ]); return ((seconds % 86400) / 86400) * TWO_PI; } } <file_sep>/src/coordinates/j2000.ts import { EarthBody } from "../bodies/earth-body"; import { DataHandler } from "../data/data-handler"; import { TWO_PI } from "../math/constants"; import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; import { ClassicalElements } from "./classical-elements"; import { IStateVector } from "./coordinate-interface"; import { ITRF } from "./itrf"; import { RIC } from "./ric"; import { TEME } from "./teme"; /** Class representing J2000 (J2K) inertial coordinates. */ export class J2000 implements IStateVector { /** Satellite state epoch. */ public readonly epoch: EpochUTC; /** Position vector, in kilometers. */ public readonly position: Vector3D; /** Velocity vector, in kilometers per second. */ public readonly velocity: Vector3D; /** * Create a new J2000 object. * * @param epoch UTC epoch * @param position J2000 position, in kilometers * @param velocity J2000 velocity, in kilometers per second */ constructor(epoch: EpochUTC, position: Vector3D, velocity?: Vector3D) { this.epoch = epoch; this.position = position; this.velocity = velocity || Vector3D.origin(); } /** Return a string representation of this object. */ public toString(): string { const { epoch, position, velocity } = this; const output = [ "[J2000]", ` Epoch: ${epoch.toString()}`, ` Position: ${position.toString()} km`, ` Velocity: ${velocity.toString()} km/s` ]; return output.join("\n"); } /** Calculate this orbit's mechanical energy, in km^2/s^2 */ private mechanicalEnergy() { const r = this.position.magnitude(); const v = this.velocity.magnitude(); return (v * v) / 2.0 - EarthBody.MU / r; } /** Convert to Classical Orbit Elements. */ public toClassicalElements(): ClassicalElements { const { epoch, position: pos, velocity: vel } = this; var mu = EarthBody.MU; var energy = this.mechanicalEnergy(); var a = -(mu / (2 * energy)); var eVecA = pos.scale(Math.pow(vel.magnitude(), 2) - mu / pos.magnitude()); var eVecB = vel.scale(pos.dot(vel)); var eVec = eVecA.add(eVecB.negate()).scale(1.0 / mu); var e = eVec.magnitude(); var h = pos.cross(vel); var i = Math.acos(h.z / h.magnitude()); var n = new Vector3D(0, 0, 1).cross(h); var o = Math.acos(n.x / n.magnitude()); if (n.y < 0) { o = TWO_PI - o; } var w = Math.acos(n.dot(eVec) / (n.magnitude() * eVec.magnitude())); if (eVec.z < 0) { w = TWO_PI - w; } var v = Math.acos(eVec.dot(pos) / (eVec.magnitude() * pos.magnitude())); if (pos.dot(vel) < 0) { v = TWO_PI - v; } return new ClassicalElements(epoch, a, e, i, o, w, v); } /** Convert this to a ITRF state vector object. */ public toITRF() { const { epoch, position, velocity } = this; const prec = EarthBody.precession(epoch); const rMOD = position .rot3(-prec[0]) .rot2(prec[1]) .rot3(-prec[2]); const vMOD = velocity .rot3(-prec[0]) .rot2(prec[1]) .rot3(-prec[2]); const [dPsi, dEps, mEps] = EarthBody.nutation(epoch); const epsilon = mEps + dEps; const rTOD = rMOD .rot1(mEps) .rot3(-dPsi) .rot1(-epsilon); const vTOD = vMOD .rot1(mEps) .rot3(-dPsi) .rot1(-epsilon); const ast = epoch.gmstAngle() + dPsi * Math.cos(epsilon); const rPEF = rTOD.rot3(ast); const vPEF = vTOD.rot3(ast).add( EarthBody.getRotation(this.epoch) .negate() .cross(rPEF) ); const { pmX, pmY } = DataHandler.getFinalsData(epoch.toMjd()); const rITRF = rPEF.rot1(-pmY).rot2(-pmX); const vITRF = vPEF.rot1(-pmY).rot2(-pmX); return new ITRF(epoch, rITRF, vITRF); } /** Convert this to a TEME state vector object. */ public toTEME() { const { epoch, position, velocity } = this; const [zeta, theta, zed] = EarthBody.precession(epoch); const rMOD = position .rot3(-zeta) .rot2(theta) .rot3(-zed); const vMOD = velocity .rot3(-zeta) .rot2(theta) .rot3(-zed); const [dPsi, dEps, mEps] = EarthBody.nutation(epoch); const epsilon = mEps + dEps; const rTEME = rMOD .rot1(mEps) .rot3(-dPsi) .rot1(-epsilon) .rot3(dPsi * Math.cos(epsilon)); const vTEME = vMOD .rot1(mEps) .rot3(-dPsi) .rot1(-epsilon) .rot3(dPsi * Math.cos(epsilon)); return new TEME(this.epoch, rTEME, vTEME); } /** * Convert this to a RIC relative motion object. * * @param reference target state for reference frame */ public toRIC(reference: J2000) { return RIC.fromJ2kState(this, reference); } /** * Apply an instantaneous delta-V to this state. * * Returns a new state object. * * @param radial radial delta-V (km/s) * @param intrack intrack delta-V (km/s) * @param crosstrack crosstrack delta-V (km/s) */ public maneuver(radial: number, intrack: number, crosstrack: number) { const ric = this.toRIC(this); return ric.addVelocity(radial, intrack, crosstrack).toJ2000(); } } <file_sep>/src/forces/solar-radiation-pressure.ts import { SunBody } from "../bodies/sun-body"; import { J2000 } from "../coordinates/j2000"; import { AccelerationForce, AccelerationMap } from "../forces/forces-interface"; /** Model of solar radiation pressure, for use in a ForceModel object. */ export class SolarRadiationPressure implements AccelerationForce { /** spacecraft mass, in kilograms */ private mass: number; /** spacecraft area, in square meters */ private area: number; /** reflectivity coefficient (unitless) */ private reflectCoeff: number; /** * Create a new solar radiation pressure AccelerationForce object. * * @param mass spacecraft mass, in kilograms * @param area spacecraft area, in square meters * @param reflectCoeff reflectivity coefficient (unitless) */ constructor(mass: number, area: number, reflectCoeff: number) { this.mass = mass; this.area = area; this.reflectCoeff = reflectCoeff; } /** * Calculate acceleration due to solar radiation pressure. * * @param j2kState J2000 state vector */ private radiationPressure(j2kState: J2000) { const { mass, area, reflectCoeff } = this; const rSun = SunBody.position(j2kState.epoch); const r = rSun.changeOrigin(j2kState.position); const pFac = -(SunBody.SOLAR_PRESSURE * reflectCoeff * area) / mass; return r.normalized().scale(pFac / 1000); } /** * Update the acceleration map argument with a calculated * "solar_radiation_pressure" value, for the provided state vector. * * @param j2kState J2000 state vector * @param accMap acceleration map (km/s^2) */ public acceleration(j2kState: J2000, accMap: AccelerationMap) { accMap["solar_radiation_pressure"] = this.radiationPressure(j2kState); } } <file_sep>/src/math/vector-6d.ts import { Vector3D } from "./vector-3d"; /** Class representing a vector of length 6. */ export class Vector6D { /** Vector a-axis component. */ public readonly a: number; /** Vector b-axis component. */ public readonly b: number; /** Vector c-axis component. */ public readonly c: number; /** Vector x-axis component. */ public readonly x: number; /** Vector y-axis component. */ public readonly y: number; /** Vector z-axis component. */ public readonly z: number; /** * Create a new Vector6D object. * * @param a a-axis component * @param b b-axis component * @param c c-axis component * @param x x-axis component * @param y y-axis component * @param z z-axis component */ constructor( a: number, b: number, c: number, x: number, y: number, z: number ) { this.a = a; this.b = b; this.c = c; this.x = x; this.y = y; this.z = z; } /** * Create a new Vector6D object, containing zero for each state element. */ public static origin(): Vector6D { return new Vector6D(0, 0, 0, 0, 0, 0); } /** * Perform element-wise addition of this and another Vector. * * Returns a new Vector object containing the sum. * * @param v the other vector */ public add(v: Vector6D): Vector6D { const { a, b, c, x, y, z } = this; return new Vector6D(a + v.a, b + v.b, c + v.c, x + v.x, y + v.y, z + v.z); } /** * Linearly scale the elements of this. * * Returns a new Vector object containing the scaled state. * * @param n scalar value */ public scale(n: number): Vector6D { const { a, b, c, x, y, z } = this; return new Vector6D(a * n, b * n, c * n, x * n, y * n, z * n); } /** Split this into two Vector3D objects. */ public split(): [Vector3D, Vector3D] { const { a, b, c, x, y, z } = this; return [new Vector3D(a, b, c), new Vector3D(x, y, z)]; } } <file_sep>/src/forces/forces-interface.ts import { J2000 } from "../coordinates/j2000"; import { Vector3D } from "../math/vector-3d"; /** Store acceration name and vector. */ export type AccelerationMap = { [name: string]: Vector3D; }; export interface AccelerationForce { /** Update acceleration map with a named vector for this object. */ acceleration: (j2kState: J2000, accMap: AccelerationMap) => void; } <file_sep>/src/coordinates/itrf.ts import { EarthBody } from "../bodies/earth-body"; import { DataHandler } from "../data/data-handler"; import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; import { IStateVector } from "./coordinate-interface"; import { Geodetic } from "./geodetic"; import { J2000 } from "./j2000"; import { LookAngle } from "./look-angle"; /** Class representing ITRF Earth-Fixed coordinates. */ export class ITRF implements IStateVector { /** Satellite state epoch. */ public readonly epoch: EpochUTC; /** Position vector, in kilometers. */ public readonly position: Vector3D; /** Velocity vector, in kilometers per second. */ public readonly velocity: Vector3D; /** * Create a new ITRF object. * * @param epoch UTC epoch * @param position ITRF position, in kilometers * @param velocity ITRF velocity, in kilometers per second */ constructor(epoch: EpochUTC, position: Vector3D, velocity?: Vector3D) { this.epoch = epoch; this.position = position; this.velocity = velocity || Vector3D.origin(); } /** Return a string representation of this object. */ public toString(): string { const { epoch, position, velocity } = this; const output = [ "[ITRF]", ` Epoch: ${epoch.toString()}`, ` Position: ${position.toString()} km`, ` Velocity: ${velocity.toString()} km/s` ]; return output.join("\n"); } /** Convert this to a J2000 state vector object. */ public toJ2000() { const { epoch, position, velocity } = this; const finals = DataHandler.getFinalsData(epoch.toMjd()); const pmX = finals.pmX; const pmY = finals.pmY; const rPEF = position.rot2(pmX).rot1(pmY); const vPEF = velocity.rot2(pmX).rot1(pmY); const [dPsi, dEps, mEps] = EarthBody.nutation(epoch); const epsilon = mEps + dEps; const ast = epoch.gmstAngle() + dPsi * Math.cos(epsilon); const rTOD = rPEF.rot3(-ast); const vTOD = vPEF .add(EarthBody.getRotation(this.epoch).cross(rPEF)) .rot3(-ast); const rMOD = rTOD .rot1(epsilon) .rot3(dPsi) .rot1(-mEps); const vMOD = vTOD .rot1(epsilon) .rot3(dPsi) .rot1(-mEps); const [zeta, theta, zed] = EarthBody.precession(epoch); const rJ2000 = rMOD .rot3(zed) .rot2(-theta) .rot3(zeta); const vJ2000 = vMOD .rot3(zed) .rot2(-theta) .rot3(zeta); return new J2000(epoch, rJ2000, vJ2000); } /** Convert to a Geodetic coordinate object. */ public toGeodetic() { const { position: { x, y, z } } = this; var sma = EarthBody.RADIUS_EQUATOR; var esq = EarthBody.ECCENTRICITY_SQUARED; var lon = Math.atan2(y, x); var r = Math.sqrt(x * x + y * y); var phi = Math.atan(z / r); var lat = phi; var c = 0.0; for (var i = 0; i < 6; i++) { var slat = Math.sin(lat); c = 1 / Math.sqrt(1 - esq * slat * slat); lat = Math.atan((z + sma * c * esq * Math.sin(lat)) / r); } var alt = r / Math.cos(lat) - sma * c; return new Geodetic(lat, lon, alt); } /** * Calculate the look angle between an observer and this. * * @param observer geodetic coordinates */ public toLookAngle(observer: Geodetic) { const { latitude, longitude } = observer; const { sin, cos } = Math; const { x: oX, y: oY, z: oZ } = observer.toITRF(this.epoch).position; const { x: tX, y: tY, z: tZ } = this.position; const [rX, rY, rZ] = [tX - oX, tY - oY, tZ - oZ]; const s = sin(latitude) * cos(longitude) * rX + sin(latitude) * sin(longitude) * rY - cos(latitude) * rZ; const e = -sin(longitude) * rX + cos(longitude) * rY; const z = cos(latitude) * cos(longitude) * rX + cos(latitude) * sin(longitude) * rY + sin(latitude) * rZ; const range = Math.sqrt(s * s + e * e + z * z); const elevation = Math.asin(z / range); const azimuth = Math.atan2(-e, s) + Math.PI; return new LookAngle(azimuth, elevation, range); } } <file_sep>/src/bodies/moon-body.ts import { EarthBody } from "../bodies/earth-body"; import { DEG2RAD } from "../math/constants"; import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; export class MoonBody { /** Moon gravitational parameter, in km^3/s^2. */ public static readonly MU = 4902.801; /** * Calculate the J2000 position of the Moon, in kilometers, at a given epoch. * * @param epoch satellite state epoch */ public static position(epoch: EpochUTC) { const jc = epoch.toUT1().toJulianCenturies(); const dtr = DEG2RAD; const lamEcl = 218.32 + 481267.883 * jc + 6.29 * Math.sin((134.9 + 477198.85 * jc) * dtr) - 1.27 * Math.sin((259.2 - 413335.38 * jc) * dtr) + 0.66 * Math.sin((235.7 + 890534.23 * jc) * dtr) + 0.21 * Math.sin((269.9 + 954397.7 * jc) * dtr) - 0.19 * Math.sin((357.5 + 35999.05 * jc) * dtr) - 0.11 * Math.sin((186.6 + 966404.05 * jc) * dtr); const phiEcl = 5.13 * Math.sin((93.3 + 483202.03 * jc) * dtr) + 0.28 * Math.sin((228.2 + 960400.87 * jc) * dtr) - 0.28 * Math.sin((318.3 + 6003.18 * jc) * dtr) - 0.17 * Math.sin((217.6 - 407332.2 * jc) * dtr); const pllx = 0.9508 + 0.0518 * Math.cos((134.9 + 477198.85 * jc) * dtr) + 0.0095 * Math.cos((259.2 - 413335.38 * jc) * dtr) + 0.0078 * Math.cos((235.7 + 890534.23 * jc) * dtr) + 0.0028 * Math.cos((269.9 + 954397.7 * jc) * dtr); const obq = 23.439291 - 0.0130042 * jc; const rMag = 1.0 / Math.sin(pllx * dtr); const rI = rMag * (Math.cos(phiEcl * dtr) * Math.cos(lamEcl * dtr)); const rJ = rMag * (Math.cos(obq * dtr) * Math.cos(phiEcl * dtr) * Math.sin(lamEcl * dtr) - Math.sin(obq * dtr) * Math.sin(phiEcl * dtr)); const rK = rMag * (Math.sin(obq * dtr) * Math.cos(phiEcl * dtr) * Math.sin(lamEcl * dtr) + Math.cos(obq * dtr) * Math.sin(phiEcl * dtr)); return new Vector3D(rI, rJ, rK).scale(EarthBody.RADIUS_EQUATOR); } } <file_sep>/src/propagators/propagator-interface.ts import { J2000 } from "../coordinates/j2000"; import { EpochUTC } from "../time/epoch-utc"; /** Common interface for propagator objects. */ export interface IPropagator { /** Cache for last computed statellite state. */ state: J2000; /** Propagate state to a new epoch. */ propagate(epoch: EpochUTC): J2000; /** Propagate state by some number of seconds, repeatedly. */ step(epoch: EpochUTC, interval: number, count: number): J2000[]; /** Restore initial propagator state. */ reset(): void; } <file_sep>/src/forces/force-model.ts import { J2000 } from "../coordinates/j2000"; import { Vector3D } from "../math/vector-3d"; import { Vector6D } from "../math/vector-6d"; import { AtmosphericDrag } from "./atmospheric-drag"; import { EarthGravity } from "./earth-gravity"; import { AccelerationMap } from "./forces-interface"; import { SolarRadiationPressure } from "./solar-radiation-pressure"; import { ThirdBody } from "./third-body"; /** Object for efficiently managing acceleration forces on a spacecraft. */ export class ForceModel { /** Earth gravity model, if applicable */ private earthGravity: EarthGravity | null; /** third-body model, if applicable */ private thirdBody: ThirdBody | null; /** atmospheric drag model, if applicable */ private atmosphericDrag: AtmosphericDrag | null; /** solar radiation pressure model, if applicable */ private solarRadiationPressure: SolarRadiationPressure | null; /** Create a new ForceModel object. */ constructor() { this.earthGravity = null; this.thirdBody = null; this.atmosphericDrag = null; this.solarRadiationPressure = null; } /** Clear all current AccelerationForce models for this object. */ public clearModel() { this.earthGravity = null; this.thirdBody = null; this.atmosphericDrag = null; this.solarRadiationPressure = null; } /** * Create and add a new EarthGravity force to this object. * * @param degree geopotential degree (max=70) * @param order geopotential order (max=70) */ public setEarthGravity(degree: number, order: number) { this.earthGravity = new EarthGravity(degree, order); } /** * Create and add a new ThirdBody force to this object. * * @param moon moon gravity, if true * @param sun sun gravity, if true */ public setThirdBody(moon: boolean, sun: boolean) { this.thirdBody = new ThirdBody(moon, sun); } /** * Create and add a new AtmosphericDrag force to this object. * * @param mass spacecraft mass, in kilograms * @param area spacecraft area, in square meters * @param dragCoeff drag coefficient (default=2.2) */ public setAtmosphericDrag(mass: number, area: number, dragCoeff = 2.2) { this.atmosphericDrag = new AtmosphericDrag(mass, area, dragCoeff); } /** * Create and add a new SolarRadiationPressure force to this object. * * @param mass spacecraft mass, in kilograms * @param area spacecraft area, in square meters * @param reflectCoeff reflectivity coefficient (default=1.2) */ public setSolarRadiationPressure( mass: number, area: number, reflectCoeff = 1.2 ) { this.solarRadiationPressure = new SolarRadiationPressure( mass, area, reflectCoeff ); } /** * Create an acceleration map argument with calculated values for each * acceleration source, for the provided state vector. * * @param j2kState J2000 state vector */ public accelerations(j2kState: J2000) { const accMap: AccelerationMap = {}; if (this.earthGravity !== null) { this.earthGravity.acceleration(j2kState, accMap); } if (this.thirdBody !== null) { this.thirdBody.acceleration(j2kState, accMap); } if (this.atmosphericDrag !== null) { this.atmosphericDrag.acceleration(j2kState, accMap); } if (this.solarRadiationPressure !== null) { this.solarRadiationPressure.acceleration(j2kState, accMap); } return accMap; } /** * Calculate and return the 6-dimensional derivative (velocity, acceleration) * for the provided state vector. * * @param j2kState J2000 state vector */ public derivative(j2kState: J2000) { const accMap = this.accelerations(j2kState); let accel = Vector3D.origin(); for (let k in accMap) { accel = accel.add(accMap[k]); } const { x: vx, y: vy, z: vz } = j2kState.velocity; const { x: ax, y: ay, z: az } = accel; return new Vector6D(vx, vy, vz, ax, ay, az); } } <file_sep>/src/data/data-handler.ts import { EarthBody } from "../bodies/earth-body"; import { ASEC2RAD } from "../math/constants"; import { Vector3D } from "../math/vector-3d"; import { EGM_96_DENORMALIZED } from "./values/egm96"; import { EXPONENTIAL_ATMOSPHERE } from "./values/exponential-atmosphere"; import { clearFinals, FINALS, sortFinals, zeroFinal } from "./values/finals"; import { LEAP_SECONDS } from "./values/leap-seconds"; export class DataHandler { /** * Fetch the number of leap seconds used in offset. * * @param jd julian date */ public static leapSecondsOffset(jd: number) { if (jd > LEAP_SECONDS[LEAP_SECONDS.length - 1][0]) { return LEAP_SECONDS[LEAP_SECONDS.length - 1][1]; } if (jd < LEAP_SECONDS[0][0]) { return 0; } for (let i = 0; i < LEAP_SECONDS.length - 2; i++) { if (LEAP_SECONDS[i][0] <= jd && jd < LEAP_SECONDS[i + 1][0]) { return LEAP_SECONDS[i][1]; } } return 0; } /** * Add a new entry to the leap seconds table. * * @param jd julian date * @param offset leap seconds offset, in seconds */ public static addLeapSecond(jd: number, offset: number) { LEAP_SECONDS.push([jd, offset]); } /** * Get finals data for a given MJD. * * @param mjd USNO modified julian date */ public static getFinalsData(mjd: number) { const fmjd = Math.floor(mjd); if ( FINALS.length === 0 || fmjd < FINALS[0].mjd || fmjd > FINALS[FINALS.length - 1].mjd ) { return zeroFinal(); } let low = 0; let high = FINALS.length - 1; while (low <= high) { const mid = Math.floor((high + low) / 2); const midVal = FINALS[mid].mjd; if (fmjd < midVal) { high = mid - 1; } else if (fmjd > midVal) { low = mid + 1; } else { return FINALS[mid]; } } return zeroFinal(); } /** * Cache IERS finals.all data. * * @param lines list of finals.all lines */ public static setFinalsData(lines: string[]) { clearFinals(); for (let line of lines) { const tLine = line.trimRight(); if (tLine.length <= 68) { continue; } const mjd = Math.floor(parseFloat(line.substring(7, 15))); const pmX = parseFloat(line.substring(18, 27)) * ASEC2RAD; const pmY = parseFloat(line.substring(37, 46)) * ASEC2RAD; const dut1 = parseFloat(line.substring(58, 68)); let lod = 0; let dPsi = 0; let dEps = 0; if (tLine.length >= 86) { lod = parseFloat(line.substring(79, 86)) * 1e-3; } if (tLine.length >= 125) { dPsi = parseFloat(line.substring(97, 106)) * ASEC2RAD; dEps = parseFloat(line.substring(116, 125)) * ASEC2RAD; } FINALS.push({ mjd: mjd, pmX: pmX, pmY: pmY, dut1: dut1, lod: lod, dPsi: dPsi, dEps: dEps }); } sortFinals(); } /** * Calculate the density of the Earth's atmosphere, in kg/m^3, for a given * position using the exponential atmospheric density model. * * @param position satellite position 3-vector, in kilometers */ public static getExpAtmosphericDensity(position: Vector3D): number { const rDist = position.magnitude() - EarthBody.RADIUS_EQUATOR; const expAtm = EXPONENTIAL_ATMOSPHERE; const maxVal = expAtm.length - 1; let fields = [0.0, 0.0, 0.0]; if (rDist <= expAtm[0][0]) { fields = expAtm[0]; } else if (rDist >= expAtm[maxVal][0]) { fields = expAtm[maxVal]; } else { for (let i = 0; i < maxVal; i++) { if (expAtm[i][0] <= rDist && rDist < expAtm[i + 1][0]) { fields = expAtm[i]; } } } const base = fields[0]; const density = fields[1]; const height = fields[2]; return density * Math.exp(-(rDist - base) / height); } /** Calculate appropritate 1D index for 2D coefficient lookup. */ private static egm96Index(l: number, m: number) { return ((l - 2) * (l + 2) + l) / 2 - 1 + m; } /** * Lookup denormalized EGM96 coefficients. * * @param l first P index * @param m second P index */ public static getEgm96Coeffs(l: number, m: number) { return EGM_96_DENORMALIZED[DataHandler.egm96Index(l, m)]; } } <file_sep>/src/coordinates/geodetic.ts import { EarthBody } from "../bodies/earth-body"; import { RAD2DEG } from "../math/constants"; import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; import { ITRF } from "./itrf"; /** Class representing Geodetic (LLA) coordinates. */ export class Geodetic { /** Geodetic latitude, in radians. */ public readonly latitude: number; /** Geodetic longitude, in radians. */ public readonly longitude: number; /** Geodetic altitude, in kilometers. */ public readonly altitude: number; /** * Create a new Geodetic object. * * @param latitude geodetic latitude, in radians * @param longitude geodetic longitude, in radians * @param altitude geodetic altitude, in kilometers */ constructor(latitude: number, longitude: number, altitude: number) { this.latitude = latitude; this.longitude = longitude; this.altitude = altitude; } /** Return a string representation of the object. */ public toString(): string { const { latitude, longitude, altitude } = this; const output = [ "[Geodetic]", ` Latitude: ${(latitude * RAD2DEG).toFixed(3)}\u00b0`, ` Longitude: ${(longitude * RAD2DEG).toFixed(3)}\u00b0`, ` Altitude: ${altitude.toFixed(3)} km` ]; return output.join("\n"); } /** * Convert this to an ITRF coordinate object. * * @param epoch UTC epoch */ public toITRF(epoch: EpochUTC) { const { latitude, longitude, altitude } = this; const sLat = Math.sin(latitude); const cLat = Math.cos(latitude); const nVal = EarthBody.RADIUS_EQUATOR / Math.sqrt(1 - EarthBody.ECCENTRICITY_SQUARED * sLat * sLat); const rx = (nVal + altitude) * cLat * Math.cos(longitude); const ry = (nVal + altitude) * cLat * Math.sin(longitude); const rz = (nVal * (1 - EarthBody.ECCENTRICITY_SQUARED) + altitude) * sLat; return new ITRF(epoch, new Vector3D(rx, ry, rz)); } } <file_sep>/src/math/operations.ts import { TWO_PI } from "./constants"; /** * Calculate the factorial of a number. * * Throws an error if argument is not a positive integer. * * @param n a positive integer */ export function factorial(n: number): number { n = Math.abs(n); let output = 1; for (let i = 0; i < n; i++) { output *= i + 1; } return output; } /** * Evaluate a polynomial given a variable and its coefficients. Exponents are * implied to start at zero. * * @param x variable * @param coeffs coefficients, from lowest to highest */ export function evalPoly(x: number, coeffs: number[]): number { let output = 0; for (let n = 0; n < coeffs.length; n++) { output += coeffs[n] * x ** n; } return output; } /** * Return the sign of the number, 1 if positive, -1 if negative, 0 if zero. * * @param n a number */ export function sign(n: number): number { if (n < 0) { return -1; } if (n > 0) { return 1; } return 0; } /** * Return the angle (original or inverse) that exists in the half plane of the * match argument. * * @param angle angle to (possibly) adjust * @param match reference angle */ export function matchHalfPlane(angle: number, match: number): number { const [a1, a2] = [angle, TWO_PI - angle]; const d1 = Math.atan2(Math.sin(a1 - match), Math.cos(a1 - match)); const d2 = Math.atan2(Math.sin(a2 - match), Math.cos(a2 - match)); return Math.abs(d1) < Math.abs(d2) ? a1 : a2; } /** * Linearly interpolate between two known points. * * @param x value to interpolate * @param x0 start x-value * @param y0 start y-value * @param x1 end x-value * @param y1 end y-value */ export function linearInterpolate( x: number, x0: number, y0: number, x1: number, y1: number ): number { return (y0 * (x1 - x) + y1 * (x - x0)) / (x1 - x0); } /** * Copy the sign of one number, to the magnitude of another. * * @param magnitude * @param sign */ export function copySign(magnitude: number, sign: number) { const m = Math.abs(magnitude); const s = sign >= 0 ? 1 : -1; return s * m; } /** * Calculate the mean of the input array. * * @param values an array of numbers */ export function mean(values: number[]) { const n = values.length; let sum = 0; for (let i = 0; i < n; i++) { sum += values[i]; } return sum / n; } /** * Calculate the standard deviation of the input array. * * @param values an array of numbers */ export function standardDeviation(values: number[]) { const mu = mean(values); const n = values.length; let sum = 0; for (let i = 0; i < n; i++) { const sub = values[i] - mu; sum += sub * sub; } return Math.sqrt((1 / n) * sum); } <file_sep>/src/propagators/interpolator-propagator.ts import { J2000 } from "../coordinates/j2000"; import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; import { IPropagator } from "./propagator-interface"; import { RungeKutta4Propagator } from "./runge-kutta-4-propagator"; /** Interpolator for cached satellite ephemeris. */ export class InterpolatorPropagator implements IPropagator { /** Internal propagator object. */ private readonly propagator: RungeKutta4Propagator; /** Cache of J2000 states. */ private readonly initStates: J2000[]; /** * Create a new Interpolator Propagator object. * * @param states list of J2000 state vectors */ constructor(states: J2000[]) { this.initStates = states; this.sortStates(); this.propagator = new RungeKutta4Propagator(this.initStates[0]); this.setStepSize(60); } /** Chronologically sort cached states. */ private sortStates() { this.initStates.sort((a, b) => a.epoch.unix - b.epoch.unix); } /** * Set propagator step size. * * @param seconds step size, in seconds */ public setStepSize(seconds: number) { this.propagator.setStepSize(seconds); } /** Fetch last propagated satellite state. */ get state() { return this.propagator.state; } /** Reset cached state to the initialized state. */ public reset() { this.propagator.setInitState(this.initStates[0]); } /** Propagator force model object. */ get forceModel() { return this.propagator.forceModel; } /** * Return the cached state closest to the proved epoch. * * @param epoch UTC epoch */ private getNearest(epoch: EpochUTC) { if (this.initStates.length === 0) { return new J2000(epoch, Vector3D.origin(), Vector3D.origin()); } const unix = epoch.unix; if (unix < this.initStates[0].epoch.unix) { return this.initStates[0]; } if (unix > this.initStates[this.initStates.length - 1].epoch.unix) { return this.initStates[this.initStates.length - 1]; } let low = 0; let high = this.initStates.length - 1; while (low <= high) { const mid = Math.floor((high + low) / 2); const midVal = this.initStates[mid].epoch.unix; if (unix < midVal) { high = mid - 1; } else if (unix > midVal) { low = mid + 1; } else { return this.initStates[mid]; } } const lowDiff = this.initStates[low].epoch.unix - unix; const highDiff = unix - this.initStates[high].epoch.unix; return lowDiff < highDiff ? this.initStates[low] : this.initStates[high]; } /** * Interpolate cached states to a new epoch. * * @param newEpoch propagation epoch */ public propagate(newEpoch: EpochUTC) { this.propagator.setInitState(this.getNearest(newEpoch)); this.propagator.propagate(newEpoch); return this.state; } /** * Interpolate state by some number of seconds, repeatedly, starting at a * specified epoch. * * @param epoch UTC epoch * @param interval seconds between output states * @param count number of steps to take */ public step(epoch: EpochUTC, interval: number, count: number) { const output: J2000[] = [this.propagate(epoch)]; let tempEpoch = epoch; for (let i = 0; i < count; i++) { tempEpoch = tempEpoch.roll(interval); output.push(this.propagate(tempEpoch)); } return output; } } <file_sep>/src/forces/third-body.ts import { MoonBody } from "../bodies/moon-body"; import { SunBody } from "../bodies/sun-body"; import { J2000 } from "../coordinates/j2000"; import { AccelerationForce, AccelerationMap } from "./forces-interface"; /** Model of third-body gravity, for use in a ForceModel object. */ export class ThirdBody implements AccelerationForce { /** model Moon gravity, if true */ private moonGravityFlag: boolean; /** model Sun gravity, if true */ private sunGravityFlag: boolean; /** * Create a new ThirdBody object. * * @param moonGravityFlag model Moon gravity, if true * @param sunGravityFlag model Sun gravity, if true */ constructor(moonGravityFlag: boolean, sunGravityFlag: boolean) { this.moonGravityFlag = moonGravityFlag; this.sunGravityFlag = sunGravityFlag; } /** * Calculate acceleration due to the Moon's gravity. * * @param j2kState J2000 state vector */ private moonGravity(j2kState: J2000) { const rMoon = MoonBody.position(j2kState.epoch); const aNum = rMoon.changeOrigin(j2kState.position); const aDen = Math.pow(aNum.magnitude(), 3); const bNum = rMoon; const bDen = Math.pow(rMoon.magnitude(), 3); const grav = aNum.scale(1.0 / aDen).add(bNum.scale(-1.0 / bDen)); return grav.scale(MoonBody.MU); } /** * Calculate acceleration due to the Sun's gravity. * * @param j2kState J2000 state vector */ private sunGravity(j2kState: J2000) { const rSun = SunBody.position(j2kState.epoch); const aNum = rSun.changeOrigin(j2kState.position); const aDen = Math.pow(aNum.magnitude(), 3); const bNum = rSun; const bDen = Math.pow(rSun.magnitude(), 3); const grav = aNum.scale(1.0 / aDen).add(bNum.scale(-1.0 / bDen)); return grav.scale(SunBody.MU); } /** * Update the acceleration map argument with calculated "moon_gravity" and * "sun_gravity" values, for the provided state vector. * * @param j2kState J2000 state vector * @param accMap acceleration map (km/s^2) */ public acceleration(j2kState: J2000, accMap: AccelerationMap) { if (this.moonGravityFlag) { accMap["moon_gravity"] = this.moonGravity(j2kState); } if (this.sunGravityFlag) { accMap["sun_gravity"] = this.sunGravity(j2kState); } } } <file_sep>/src/coordinates/look-angle.ts import { RAD2DEG } from "../math/constants"; /** Class representing look angles. */ export class LookAngle { /** Azimuth angle, in radians. */ public readonly azimuth: number; /** Elevation angle, in radians. */ public readonly elevation: number; /** Slant range, in kilometers. */ public readonly range: number; /** * Create a new LookAngle object. * * @param azimuth azimuth angle, in radians * @param elevation elevation angle, in radians * @param range slant range, in kilometers */ constructor(azimuth: number, elevation: number, range: number) { this.azimuth = azimuth; this.elevation = elevation; this.range = range; } /** Return a string representation of the object. */ public toString(): string { const { azimuth, elevation, range } = this; const output = [ "[Look-Angle]", ` Azimuth: ${(azimuth * RAD2DEG).toFixed(3)}\u00b0`, ` Elevation: ${(elevation * RAD2DEG).toFixed(3)}\u00b0`, ` Range: ${range.toFixed(3)} km` ]; return output.join("\n"); } } <file_sep>/src/math/spherical-harmonics.ts /** Class for handling spherical harmonics operations. */ export class SphericalHarmonics { /** dimension */ private d: number; /** associated legendre polynomial table */ private P: number[]; /** * Create a new SphericalHarmonics object. * * @param dimension degree */ constructor(dimension: number) { this.d = dimension; this.P = []; } private index(l: number, m: number) { return (l * l + l) / 2 + m; } /** * Fetch the associated legendre polynomial from the provided index. * * @param l l-index * @param m m-index */ public getP(l: number, m: number) { if (m > l) { return 0; } return this.P[this.index(l, m)] || 0; } /** Reset the polynomial table to zeroes. */ private clearTable() { this.P = []; for (let i = 0; i <= this.index(this.d, this.d); i++) { this.P.push(0); } } /** * Build a cache of associated Legendre polynomials. * * @param phi geocentric latitude */ public buildCache(phi: number) { this.clearTable(); const { d, P } = this; const sPhi = Math.sin(phi); const cPhi = Math.cos(phi); P[this.index(0, 0)] = 1; P[this.index(1, 0)] = sPhi; P[this.index(1, 1)] = cPhi; for (let l = 2; l <= d; l++) { for (let m = 0; m <= l; m++) { if (l >= 2 && m == 0) { P[this.index(l, 0)] = ((2 * l - 1) * sPhi * this.getP(l - 1, 0) - (l - 1) * this.getP(l - 2, 0)) / l; } else if (m != 0 && m < l) { P[this.index(l, m)] = this.getP(l - 2, m) + (2 * l - 1) * cPhi * this.getP(l - 1, m - 1); } else if (l == m && l != 0) { P[this.index(l, l)] = (2 * l - 1) * cPhi * this.getP(l - 1, l - 1); } } } } } <file_sep>/src/time/time-scales.ts import { AbstractEpoch } from "./abstract-epoch"; /** UT1 Epoch */ export class EpochUT1 extends AbstractEpoch { constructor(millis: number) { super(millis); } } /** International Atomic Time (TAI) Epoch */ export class EpochTAI extends AbstractEpoch { constructor(millis: number) { super(millis); } } /** Terrestrial Time (TT) Epoch */ export class EpochTT extends AbstractEpoch { constructor(millis: number) { super(millis); } } /** Barycentric Dynamical Time (TDB) Epoch */ export class EpochTDB extends AbstractEpoch { constructor(millis: number) { super(millis); } } <file_sep>/src/forces/atmospheric-drag.ts import { EarthBody } from "../bodies/earth-body"; import { J2000 } from "../coordinates/j2000"; import { DataHandler } from "../data/data-handler"; import { AccelerationForce, AccelerationMap } from "./forces-interface"; /** Model of atmospheric drag, for use in a ForceModel object. */ export class AtmosphericDrag implements AccelerationForce { /** spacecraft mass, in kilograms */ private mass: number; /** spacecraft area, in square meters */ private area: number; /** drag coefficient (unitless) */ private dragCoeff: number; /** * Create a new atmospheric drag AccelerationForce object. * * @param mass spacecraft mass, in kilograms * @param area spacecraft area, in square meters * @param dragCoeff drag coefficient (unitless) */ constructor(mass: number, area: number, dragCoeff: number) { this.mass = mass; this.area = area; this.dragCoeff = dragCoeff; } /** * Calculate acceleration due to atmospheric drag, using the Exponential * Atmospheric Density model. * * @param j2kState J2000 state vector */ public expAtmosphereDrag(j2kState: J2000) { const { position, velocity } = j2kState; const { mass, area, dragCoeff } = this; var density = DataHandler.getExpAtmosphericDensity(position); var vRel = velocity .add( EarthBody.getRotation(j2kState.epoch) .negate() .cross(position) ) .scale(1000); var fScale = -0.5 * density * ((dragCoeff * area) / mass) * Math.pow(vRel.magnitude(), 2); return vRel.normalized().scale(fScale / 1000); } /** * Update the acceleration map argument with a calculated "atmospheric_drag" * value, for the provided state vector. * * @param j2kState J2000 state vector * @param accMap acceleration map (km/s^2) */ public acceleration(j2kState: J2000, accMap: AccelerationMap) { accMap["atmospheric_drag"] = this.expAtmosphereDrag(j2kState); } } <file_sep>/src/test/coordinates-test.ts import * as assert from "assert"; import { TEME } from "../coordinates/teme"; import { DataHandler } from "../data/data-handler"; import { EpochUTC, ITRF, J2000, Vector3D } from "../index"; DataHandler.setFinalsData([ " 4 4 5 53100.00 I -0.141198 0.000079 0.331215 0.000051 I-0.4384012 0.0000027 1.5611 0.0020 I -52.007 .409 -4.039 .198 -0.141110 0.330940 -0.4383520 -52.100 -4.100", " 4 4 6 53101.00 I -0.140722 0.000071 0.333536 0.000057 I-0.4399498 0.0000028 1.5244 0.0019 I -52.215 .380 -3.846 .166 -0.140720 0.333270 -0.4399620 -52.500 -4.000", " 4 4 7 53102.00 I -0.140160 0.000067 0.336396 0.000060 I-0.4414071 0.0000026 1.3591 0.0024 I -52.703 .380 -3.878 .166 -0.140070 0.336140 -0.4414210 -52.700 -4.100" ]); const j2kState = new J2000( EpochUTC.fromDateString("2004-04-06T07:51:28.386Z"), new Vector3D(5102.5096, 6123.01152, 6378.1363), new Vector3D(-4.7432196, 0.7905366, 5.53375619) ); const itrfState = new ITRF( EpochUTC.fromDateString("2004-04-06T07:51:28.386Z"), new Vector3D(-1033.479383, 7901.2952758, 6380.3565953), new Vector3D(-3.22563652, -2.87245145, 5.531924446) ); const temeState = new TEME( EpochUTC.fromDateString("2017-04-28T12:45:00.000Z"), new Vector3D(12850.591182156, -40265.812871482, -282.022494587), new Vector3D(5.860360679, 1.871425143, -0.077719199) ); describe("J2000", () => { const testState = j2kState.toITRF(); it("should convert to ITRF within 0.6m", () => { const rDist = itrfState.position.distance(testState.position) * 1000; assert(rDist <= 0.6); }); it("should convert to ITRF within 0.0004m/s", () => { const vDist = itrfState.velocity.distance(testState.velocity) * 1000; assert(vDist <= 0.0004); }); }); describe("ITRF", () => { const testState = itrfState.toJ2000(); it("should convert to J2000 within 0.6m", () => { const rDist = j2kState.position.distance(testState.position) * 1000; assert(rDist <= 0.6); }); it("should convert to J2000 within 0.0004m/s", () => { const vDist = j2kState.velocity.distance(testState.velocity) * 1000; assert(vDist <= 0.0004); }); }); describe("TEME", () => { const testState = temeState.toJ2000(); const expected = new J2000( EpochUTC.fromDateString("2017-04-28T12:45:00.000Z"), new Vector3D(12694.023495137, -40315.279590286, -304.820736794), new Vector3D(5.867428953, 1.848712469, -0.087403192) ); it("should convert to J2000 within 0.3m", () => { const rDist = expected.position.distance(testState.position) * 1000; assert(rDist <= 0.3); }); it("should convert to J2000 within 0.00005m/s", () => { const vDist = expected.velocity.distance(testState.velocity) * 1000; assert(vDist <= 0.00005); }); const convBack = temeState.toJ2000().toTEME(); it("should convert back to J2000 within 1e-8m.", () => { const rDist = temeState.position.distance(convBack.position) * 1000; assert(rDist <= 1e-8); }); it("should convert back to J2000 within 1e-11m/s.", () => { const vDist = temeState.velocity.distance(convBack.velocity) * 1000; assert(vDist <= 1e-11); }); }); <file_sep>/src/bodies/sun-body.ts import { EarthBody } from "../bodies/earth-body"; import { J2000 } from "../coordinates/j2000"; import { ASTRONOMICAL_UNIT, DEG2RAD, SPEED_OF_LIGHT } from "../math/constants"; import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; export class SunBody { /** Moon gravitational parameter, in km^3/s^2. */ public static readonly MU = 132712440017.987; /** Solar flux, in W/m^2 */ public static readonly SOLAR_FLUX = 1353; /** Solar Radiation Pressure, in N/m^2. */ public static readonly SOLAR_PRESSURE = SunBody.SOLAR_FLUX / SPEED_OF_LIGHT; /** Solar umbra angle, in radians. */ public static readonly UMBRA_ANGLE = 0.26411888 * DEG2RAD; /** Solar penumbra angle, in radians. */ public static readonly PENUMBRA_ANGLE = 0.26900424 * DEG2RAD; /** * Calculate the J2000 position of the Sun, in kilometers, at a given epoch. * * @param epoch satellite state epoch */ public static position(epoch: EpochUTC) { const jc = epoch.toUT1().toJulianCenturies(); const dtr = DEG2RAD; const lamSun = 280.46 + 36000.77 * jc; const mSun = 357.5277233 + 35999.05034 * jc; const lamEc = lamSun + 1.914666471 * Math.sin(mSun * dtr) + 0.019994643 * Math.sin(2 * mSun * dtr); const obliq = 23.439291 - 0.0130042 * jc; const rMag = 1.000140612 - 0.016708617 * Math.cos(mSun * dtr) - 0.000139589 * Math.cos(2 * mSun * dtr); const rI = rMag * Math.cos(lamEc * dtr); const rJ = rMag * Math.cos(obliq * dtr) * Math.sin(lamEc * dtr); const rK = rMag * Math.sin(obliq * dtr) * Math.sin(lamEc * dtr); return new Vector3D(rI, rJ, rK).scale(ASTRONOMICAL_UNIT); } /** * Return true if argument state is in eclipse. * * @param j2kState J2000 state vector */ public static shadow(j2kState: J2000) { const { epoch, position: posSat } = j2kState; const posSun = SunBody.position(epoch); let shadow = false; if (posSun.dot(posSat) < 0) { const angle = posSun.angle(posSat); const r = posSat.magnitude(); const satHoriz = r * Math.cos(angle); const satVert = r * Math.sin(angle); const penVert = EarthBody.RADIUS_EQUATOR + Math.tan(SunBody.PENUMBRA_ANGLE) * satHoriz; if (satVert <= penVert) { shadow = true; } } return shadow; } } <file_sep>/src/coordinates/ric.ts import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; import { IStateVector } from "./coordinate-interface"; import { J2000 } from "./j2000"; import { Matrix3D } from "../math/matrix-3d"; /** Class representing Radial-Intrack-Crosstrack (RIC) relative coordinates. */ export class RIC implements IStateVector { /** State UTC Epoch. */ public readonly epoch: EpochUTC; /** Relative position vector, in kilometers. */ public readonly position: Vector3D; /** Relative velocity vector, in kilometers per second. */ public readonly velocity: Vector3D; private reference: J2000 | null; private matrix: Matrix3D | null; /** * Create a new RIC object. * * @param epoch UTC epoch * @param position relative position, in kilometers * @param velocity relative velocity, in kilometers per second */ constructor(epoch: EpochUTC, position: Vector3D, velocity: Vector3D) { this.epoch = epoch; this.position = position; this.velocity = velocity; this.reference = null; this.matrix = null; } /** Return a string representation of this object. */ public toString(): string { const { epoch, position, velocity } = this; const output = [ "[RIC]", ` Epoch: ${epoch.toString()}`, ` Position: ${position.toString()} km`, ` Velocity: ${velocity.toString()} km/s` ]; return output.join("\n"); } /** * Create a RIC state for a J2000 state, relative to another J2000 state. * * This handles caching appropriate data for RIC to J2000 conversion. * * @param state J2000 state vector * @param reference target state for reference frame */ public static fromJ2kState(state: J2000, reference: J2000) { const ru = state.position.normalized(); const cu = state.position.cross(state.velocity).normalized(); const iu = cu.cross(ru); const matrix = new Matrix3D(ru, iu, cu); const dp = state.position.add(reference.position.negate()); const dv = state.velocity.add(reference.velocity.negate()); const ric = new RIC( state.epoch, matrix.multiplyVector3D(dp), matrix.multiplyVector3D(dv) ); ric.reference = reference; ric.matrix = matrix; return ric; } /** Convert this to a J2000 state vector object. */ public toJ2000() { this.matrix = this.matrix || Matrix3D.zeros(); this.reference = this.reference || new J2000(this.epoch, Vector3D.origin(), Vector3D.origin()); const ricMatrixT = this.matrix.transpose(); const dp = ricMatrixT.multiplyVector3D(this.position); const dv = ricMatrixT.multiplyVector3D(this.velocity); return new J2000( this.epoch, this.reference.position.add(dp), this.reference.velocity.add(dv) ); } /** * Create a new RIC object, with adjusted velocity. * * @param radial radial delta-V (km/s) * @param intrack intrack delta-V (km/s) * @param crosstrack crosstrack delta-V (km/s) */ public addVelocity(radial: number, intrack: number, crosstrack: number) { const deltaV = new Vector3D(radial, intrack, crosstrack); const ric = new RIC(this.epoch, this.position, this.velocity.add(deltaV)); ric.reference = this.reference; ric.matrix = this.matrix; return ric; } } <file_sep>/src/math/vector-3d.ts import { Vector6D } from "./vector-6d"; /** Class representing a vector of length 3. */ export class Vector3D { /** Vector x-axis component. */ public readonly x: number; /** Vector y-axis component. */ public readonly y: number; /** Vector z-axis component. */ public readonly z: number; /** * Create a new Vector3D object. * * @param x x-axis component * @param y y-axis component * @param z z-axis component */ constructor(x: number, y: number, z: number) { this.x = x; this.y = y; this.z = z; } /** * Create a new Vector3D object, containing zero for each state element. */ public static origin(): Vector3D { return new Vector3D(0, 0, 0); } /** Return a string representation of this vector. */ public toString(): string { const { x, y, z } = this; const xStr = x.toFixed(9); const yStr = y.toFixed(9); const zStr = z.toFixed(9); return `[ ${xStr}, ${yStr}, ${zStr} ]`; } /** Return the magnitude of this object. */ public magnitude(): number { const { x, y, z } = this; return Math.sqrt(x * x + y * y + z * z); } /** * Calculate the Euclidean distance between this and another Vector3D. * * @param v the other vector */ public distance(v: Vector3D): number { const { x, y, z } = this; var dx = x - v.x; var dy = y - v.y; var dz = z - v.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); } /** * Perform element-wise addition of this and another Vector. * * Returns a new Vector object containing the sum. * * @param v the other vector */ public add(v: Vector3D): Vector3D { const { x, y, z } = this; return new Vector3D(x + v.x, y + v.y, z + v.z); } /** * Linearly scale the elements of this. * * Returns a new Vector object containing the scaled state. * * @param n scalar value */ public scale(n: number): Vector3D { const { x, y, z } = this; return new Vector3D(x * n, y * n, z * n); } /** Return a new Vector3D object with all values negated. */ public negate() { return this.scale(-1); } /** * Return the normalized (unit vector) form of this as a new Vector3D object. */ public normalized(): Vector3D { const { x, y, z } = this; const m = this.magnitude(); return new Vector3D(x / m, y / m, z / m); } /** * Calculate the cross product of this and another Vector. * * Returns the result as a new Vector object. * * @param v the other vector */ public cross(v: Vector3D): Vector3D { const { x, y, z } = this; return new Vector3D( y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x ); } /** * Calculate the dot product this and another Vector. * * @param v the other vector */ public dot(v: Vector3D): number { const { x, y, z } = this; return x * v.x + y * v.y + z * v.z; } /** * Rotate the elements of this along the x-axis. * * @param theta rotation angle, in radians */ public rot1(theta: number): Vector3D { const cosT = Math.cos(theta); const sinT = Math.sin(theta); const { x, y, z } = this; return new Vector3D( 1 * x + 0 * y + 0 * z, 0 * x + cosT * y + sinT * z, 0 * x + -sinT * y + cosT * z ); } /** * Rotate the elements of this along the y-axis. * * @param theta rotation angle, in radians */ public rot2(theta: number): Vector3D { const cosT = Math.cos(theta); const sinT = Math.sin(theta); const { x, y, z } = this; return new Vector3D( cosT * x + 0 * y + -sinT * z, 0 * x + 1 * y + 0 * z, sinT * x + 0 * y + cosT * z ); } /** * Rotate the elements of this along the z-axis. * * @param theta rotation angle, in radians */ public rot3(theta: number): Vector3D { const cosT = Math.cos(theta); const sinT = Math.sin(theta); const { x, y, z } = this; return new Vector3D( cosT * x + sinT * y + 0 * z, -sinT * x + cosT * y + 0 * z, 0 * x + 0 * y + 1 * z ); } /** * Calculate the angle, in radians, between this and another Vector3D. * * @param v the other vector */ public angle(v: Vector3D): number { return Math.acos(this.dot(v) / (this.magnitude() * v.magnitude())); } /** * Change coordinates of this to the relative position from a new origin. * * @param origin new origin */ public changeOrigin(origin: Vector3D): Vector3D { const delta = origin.negate(); return this.add(delta); } /** * Join this and another Vector3D object into a single Vector6D object. * * @param v other vector */ public join(v: Vector3D) { const { x: a, y: b, z: c } = this; const { x, y, z } = v; return new Vector6D(a, b, c, x, y, z); } /** * Determine line of sight between two vectors and the radius of a central * object. Returns true if line-of-sight exists. * * @param v other vector * @param radius central body radius */ public sight(v: Vector3D, radius: number) { const r1Mag2 = Math.pow(this.magnitude(), 2); const r2Mag2 = Math.pow(v.magnitude(), 2); const rDot = this.dot(v); let los = false; const tMin = (r1Mag2 - rDot) / (r1Mag2 + r2Mag2 - 2 * rDot); if (tMin < 0 || tMin > 1) { los = true; } else { const c = (1 - tMin) * r1Mag2 + rDot * tMin; if (c >= radius * radius) { los = true; } } return los; } } <file_sep>/src/examples/propagator-example.ts import { EpochUTC, J2000, KeplerPropagator, RungeKutta4Propagator, Vector3D } from "../index"; //============================================================================== // define an initial state //============================================================================== // initial state in J2000 frame const initialState = new J2000( EpochUTC.fromDateString("2018-12-21T00:00:00.000Z"), // epoch (UTC) new Vector3D(-1117.913276, 73.093299, -7000.018272), // km new Vector3D(3.531365461, 6.583914964, -0.495649656) // km/s ); console.log(initialState.toString()); // => [J2000] // Epoch: 2018-12-21T00:00:00.000Z // Position: [ -1117.913276000, 73.093299000, -7000.018272000 ] km // Velocity: [ 3.531365461, 6.583914964, -0.495649656 ] km/s // real-world expected state (24-hours into the future) const expectedState = new J2000( EpochUTC.fromDateString("2018-12-22T00:00:00.000Z"), new Vector3D(-212.125533, -2464.351601, 6625.907454), new Vector3D(-3.618617698, -6.12677853, -2.38955619) ); console.log(expectedState.toString()); // => [J2000] // Epoch: 2018-12-22T00:00:00.000Z // Position: [ -212.125533000, -2464.351601000, 6625.907454000 ] km // Velocity: [ -3.618617698, -6.126778530, -2.389556190 ] km/s //============================================================================== // propagate state vector (numerical high-accuracy) //============================================================================== // create a propagator using J2000 state const hiAccProp = new RungeKutta4Propagator(initialState); // set step size hiAccProp.setStepSize(5); // seconds // add earth gravity hiAccProp.forceModel.setEarthGravity( 50, // degree 50 // order ); // add sun & moon gravity hiAccProp.forceModel.setThirdBody( true, // moon true // sun ); // add atmospheric drag hiAccProp.forceModel.setAtmosphericDrag( 2200, // mass (kg) 3.7, // area (m^2) 2.2 // drag coefficient ); // add solar radiation pressure hiAccProp.forceModel.setSolarRadiationPressure( 2200, // mass (kg) 3.7, // area (m^2) 1.2 // reflectivity coefficient ); // propagated state (24-hours into the future) const resultState = hiAccProp.propagate( EpochUTC.fromDateString("2018-12-22T00:00:00.000Z") ); console.log(resultState.toString()); // => [J2000] // Epoch: 2018-12-22T00:00:00.000Z // Position: [ -212.131159564, -2464.369431512, 6625.894946242 ] km // Velocity: [ -3.618619589, -6.126775239, -2.389579324 ] km/s // calculate the distance between result and expected, in kilometers const distance = resultState.position.distance(expectedState.position); console.log((distance * 1000).toFixed(3) + " meters"); // => 22.495 meters //============================================================================== // propagate state vector (numerical two-body) //============================================================================== const twoBodyProp = new RungeKutta4Propagator(initialState); twoBodyProp.forceModel.setEarthGravity(0, 0); twoBodyProp.propagate(EpochUTC.fromDateString("2018-12-22T00:00:00.000Z")); console.log(twoBodyProp.state.toString()); // => [J2000] // Epoch: 2018-12-22T00:00:00.000Z // Position: [ -1241.886675379, -3977.873474857, 5689.561067368 ] km // Velocity: [ -3.502813706, -5.085314761, -4.303326274 ] km/s //============================================================================== // propagate classical elements (analytical two-body) //============================================================================== // convert j2000 state to classical elements const ceState = initialState.toClassicalElements(); // create a propagator using classical elements, and propagate const keplerProp = new KeplerPropagator(ceState); keplerProp.propagate(EpochUTC.fromDateString("2018-12-22T00:00:00.000Z")); console.log(keplerProp.state.toString()); // => [J2000] // Epoch: 2018-12-22T00:00:00.000Z // Position: [ -1241.885644014, -3977.871988515, 5689.562370838 ] km // Velocity: [ -3.502814112, -5.085316082, -4.303324341 ] km/s <file_sep>/src/coordinates/coordinate-interface.ts import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; export interface IStateVector { /** Satellite state epoch. */ epoch: EpochUTC; /** Position vector, in kilometers. */ position: Vector3D; /** Velocity vector, in kilometers per second. */ velocity: Vector3D; } <file_sep>/src/index.ts // bodies export { EarthBody } from "./bodies/earth-body"; export { MoonBody } from "./bodies/moon-body"; export { SunBody } from "./bodies/sun-body"; // conjunction export { ConjunctionAssesment } from "./conjunction/conjunction-assessment"; // coordinates export { ClassicalElements } from "./coordinates/classical-elements"; export { Geodetic } from "./coordinates/geodetic"; export { ITRF } from "./coordinates/itrf"; export { J2000 } from "./coordinates/j2000"; // data export { DataHandler } from "./data/data-handler"; // math export { Matrix3D } from "./math/matrix-3d"; export { MonteCarlo } from "./math/monte-carlo"; export { Vector3D } from "./math/vector-3d"; // propagators export { InterpolatorPropagator } from "./propagators/interpolator-propagator"; export { KeplerPropagator } from "./propagators/kepler-propagator"; export { RungeKutta4Propagator } from "./propagators/runge-kutta-4-propagator"; // time export { EpochUTC } from "./time/epoch-utc"; <file_sep>/src/math/monte-carlo.ts import { Matrix3D } from "./matrix-3d"; import { Vector3D } from "./vector-3d"; import { RandomGaussian } from "./random-gaussian"; /** Class for performing Monte-Carlo simulations. */ export class MonteCarlo { /** simulation vector */ private readonly vector: Vector3D; /** simulation covariance */ private readonly covariance: Matrix3D; /** random gaussian generator */ private readonly random: RandomGaussian; /** * Create a new MonteCarlo object. * * @param vector simulation vector * @param covariance simulation covariance * @param sigma standard deviation */ constructor(vector: Vector3D, covariance: Matrix3D, sigma: number) { this.vector = vector; this.covariance = covariance.scale(sigma).cholesky(); this.random = new RandomGaussian(0, 1); } /** * Sample the simulation space, and return a new statistically * relevent vector. */ public sample() { const gauss = this.random.nextVector3D(); const offset = this.covariance.multiplyVector3D(gauss); return this.vector.add(offset); } } <file_sep>/src/coordinates/classical-elements.ts import { EarthBody } from "../bodies/earth-body"; import { RAD2DEG, TWO_PI } from "../math/constants"; import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; import { J2000 } from "./j2000"; /** Class representing Keplerian orbital elements. */ export class ClassicalElements { /** Satellite state epoch. */ public readonly epoch: EpochUTC; /** Semimajor axis, in kilometers. */ public readonly a: number; /** Orbit eccentricity (unitless). */ public readonly e: number; /** Inclination, in radians. */ public readonly i: number; /** Right ascension of the ascending node, in radians. */ public readonly o: number; /** Argument of perigee, in radians. */ public readonly w: number; /** True anomaly, in radians. */ public readonly v: number; /** * Create a new Keplerian object. * * @param epoch UTC epoch * @param a semimajor axis, in kilometers * @param e orbit eccentricity (unitless) * @param i inclination, in radians * @param o right ascension of the ascending node, in radians * @param w argument of perigee, in radians * @param v true anomaly, in radians */ constructor( epoch: EpochUTC, a: number, e: number, i: number, o: number, w: number, v: number ) { this.epoch = epoch; this.a = a; this.e = e; this.i = i; this.o = o; this.w = w; this.v = v; } /** Return a string representation of the object. */ public toString() { const { epoch, a, e, i, o, w, v } = this; const epochOut = epoch.toString(); const aOut = a.toFixed(3); const eOut = e.toFixed(6); const iOut = (i * RAD2DEG).toFixed(4); const oOut = (o * RAD2DEG).toFixed(4); const wOut = (w * RAD2DEG).toFixed(4); const vOut = (v * RAD2DEG).toFixed(4); return [ "[KeplerianElements]", ` Epoch: ${epochOut}`, ` (a) Semimajor Axis: ${aOut} km`, ` (e) Eccentricity: ${eOut}`, ` (i) Inclination: ${iOut}\u00b0`, ` (\u03a9) Right Ascension: ${oOut}\u00b0`, ` (\u03c9) Argument of Perigee: ${wOut}\u00b0`, ` (\u03bd) True Anomaly: ${vOut}\u00b0` ].join("\n"); } /** Calculate the satellite's mean motion, in radians per second. */ public meanMotion(): number { return Math.sqrt(EarthBody.MU / this.a ** 3); } /** Calculate the number of revolutions the satellite completes per day. */ public revsPerDay(): number { return this.meanMotion() * (86400 / TWO_PI); } /** Convert this to a J2000 state vector object. */ public toJ2000() { const { epoch, a, e, i, o, w, v } = this; const { cos, sin, sqrt } = Math; const rPQW = new Vector3D(cos(v), sin(v), 0).scale( (a * (1 - e ** 2)) / (1 + e * cos(v)) ); const vPQW = new Vector3D(-sin(v), e + cos(v), 0).scale( sqrt(EarthBody.MU / (a * (1 - e ** 2))) ); const rJ2k = rPQW .rot3(-w) .rot1(-i) .rot3(-o); const vJ2k = vPQW .rot3(-w) .rot1(-i) .rot3(-o); return new J2000(epoch, rJ2k, vJ2k); } } <file_sep>/README.MD # Pious Squid [![npm version](https://badge.fury.io/js/pious-squid.svg)](https://badge.fury.io/js/pious-squid) Orbital mechanics and satellite mission analysis library, for NodeJS and the browser. ## Features - **Coordinate Frames** - Classical Orbit Elements - Earth Centered Earth Fixed _(ITRF)_ - Geodetic - J2000 - Look Angles - True Equator Mean Equinox _(TEME)_ - Relative Motion _(RIC)_ - **Ephemeris Propagators** - 4th Order Runge-Kutta _(numerical)_ - Keplerian _(analytic)_ - Interpolator - **Celestial Bodies** - Earth Atmospheric Density - Earth Precession / Nutation - Moon Position - Solar Eclipse - Sun Position - **Epoch** - Barycentric Dynamical Time _(TDB)_ - Greenwich Mean Sidereal Time - International Atomic Time _(TAI)_ - Julian Centuries - Julian Date - Leap Seconds - Terrestrial Time _(TT)_ - UTC/UT1 Time - **Force Model** - Atmospheric Drag - Earth Geopotential _(70x70)_ - Moon Gravity - Solar Radiation Pressure - Sun Gravity - **Operations** - Satellite Maneuvers - Monte-Carlo Simulation - Conjunction Assesment ## Install To include `pious-squid` in your _NodeJS_ project: npm install pious-squid --save The browser library bundles (`pious-squid.js` or `pious-squid.min.js`) can be found under, the [Releases](https://github.com/david-rc-dayton/pious-squid/releases) tab on _GitHub_. ## Example To propagate a satellite from its position and velocity vectors: ```javascript import { EpochUTC, Geodetic, J2000, RungeKutta4Propagator, Vector3D } from "pious-squid"; // ============================================================================= // set initial state in J2000 frame // ============================================================================= const initialState = new J2000( EpochUTC.fromDateString("2018-12-21T00:00:00.000Z"), // epoch (UTC) new Vector3D(-1117.913276, 73.093299, -7000.018272), // km new Vector3D(3.531365461, 6.583914964, -0.495649656) // km/s ); console.log(initialState.toString()); // => [J2000] // Epoch: 2018-12-21T00:00:00.000Z // Position: [ -1117.913276000, 73.093299000, -7000.018272000 ] km // Velocity: [ 3.531365461, 6.583914964, -0.495649656 ] km/s // ============================================================================= // create a propagator object // ============================================================================= const propagator = new RungeKutta4Propagator(initialState); // set the step size propagator.setStepSize(5); // seconds // add Earth gravity acceleration propagator.forceModel.setEarthGravity( 50, // degree 50 // order ); // add third-body acceleration propagator.forceModel.setThirdBody( true, // moon gravity true // sun gravity ); // ============================================================================= // propagate ephemeris to a future time // ============================================================================= const finalState = propagator.propagate( EpochUTC.fromDateString("2018-12-22T00:00:00.000Z") ); console.log(finalState.toString()); // => [J2000] // Epoch: 2018-12-22T00:00:00.000Z // Position: [ -212.111629987, -2464.336270508, 6625.907441304 ] km // Velocity: [ -3.618621245, -6.126790740, -2.389539402 ] km/s // ============================================================================= // display information about the propagated state // ============================================================================= // Earth-fixed coordinates console.log(finalState.toITRF().toString()); // => [ITRF] // Epoch: 2018-12-22T00:00:00.000Z // Position: [ -2463.105532067, 235.348124556, 6625.580458844 ] km // Velocity: [ -6.093169860, 3.821763334, -2.395927109 ] km/s // geodetic coordinates console.log( finalState .toITRF() .toGeodetic() .toString() ); // => [Geodetic] // Latitude: 69.635° // Longitude: 174.542° // Altitude: 713.165 km // look angle from ground observer const observer = new Geodetic( 71.218 * (Math.PI / 180), // latitude (radians) 180.508 * (Math.PI / 180), // longitude (radians) 0.325 // altitude (km) ); console.log( finalState .toITRF() .toLookAngle(observer) .toString() ); // => [Look-Angle] // Azimuth: 234.477° // Elevation: 65.882° // Range: 773.318 km // relative position const actualState = new J2000( EpochUTC.fromDateString("2018-12-22T00:00:00.000Z"), new Vector3D(-212.125533, -2464.351601, 6625.907454), new Vector3D(-3.618617698, -6.12677853, -2.38955619) ); console.log(finalState.toRIC(actualState).toString()); // => [RIC] // Epoch: 2018-12-22T00:00:00.000Z // Position: [ -0.005770585, -0.019208198, 0.005105235 ] km // Velocity: [ 0.000020089, 0.000006319, 0.000000117 ] km/s ``` Additional examples can be found in the [examples](https://github.com/david-rc-dayton/pious-squid/tree/master/src/examples) directory in the project source directory. ## License **The MIT License (MIT)** Copyright © 2018 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <file_sep>/src/examples/basic-example.ts import { EpochUTC, Geodetic, J2000, RungeKutta4Propagator, Vector3D } from "../index"; // ============================================================================= // set initial state in J2000 frame // ============================================================================= const initialState = new J2000( EpochUTC.fromDateString("2018-12-21T00:00:00.000Z"), // epoch (UTC) new Vector3D(-1117.913276, 73.093299, -7000.018272), // km new Vector3D(3.531365461, 6.583914964, -0.495649656) // km/s ); console.log(initialState.toString()); // => [J2000] // Epoch: 2018-12-21T00:00:00.000Z // Position: [ -1117.913276000, 73.093299000, -7000.018272000 ] km // Velocity: [ 3.531365461, 6.583914964, -0.495649656 ] km/s // ============================================================================= // create a propagator object // ============================================================================= const propagator = new RungeKutta4Propagator(initialState); // set the step size propagator.setStepSize(5); // seconds // add Earth gravity acceleration propagator.forceModel.setEarthGravity( 50, // degree 50 // order ); // add third-body acceleration propagator.forceModel.setThirdBody( true, // moon gravity true // sun gravity ); // ============================================================================= // propagate ephemeris to a future time // ============================================================================= const finalState = propagator.propagate( EpochUTC.fromDateString("2018-12-22T00:00:00.000Z") ); console.log(finalState.toString()); // => [J2000] // Epoch: 2018-12-22T00:00:00.000Z // Position: [ -212.111629987, -2464.336270508, 6625.907441304 ] km // Velocity: [ -3.618621245, -6.126790740, -2.389539402 ] km/s // ============================================================================= // display information about the propagated state // ============================================================================= // Earth-fixed coordinates console.log(finalState.toITRF().toString()); // => [ITRF] // Epoch: 2018-12-22T00:00:00.000Z // Position: [ -2463.105532067, 235.348124556, 6625.580458844 ] km // Velocity: [ -6.093169860, 3.821763334, -2.395927109 ] km/s // geodetic coordinates console.log( finalState .toITRF() .toGeodetic() .toString() ); // => [Geodetic] // Latitude: 69.635° // Longitude: 174.542° // Altitude: 713.165 km // look angle from ground observer const observer = new Geodetic( 71.218 * (Math.PI / 180), // latitude (radians) 180.508 * (Math.PI / 180), // longitude (radians) 0.325 // altitude (km) ); console.log( finalState .toITRF() .toLookAngle(observer) .toString() ); // => [Look-Angle] // Azimuth: 234.477° // Elevation: 65.882° // Range: 773.318 km // relative position const actualState = new J2000( EpochUTC.fromDateString("2018-12-22T00:00:00.000Z"), new Vector3D(-212.125533, -2464.351601, 6625.907454), new Vector3D(-3.618617698, -6.12677853, -2.38955619) ); console.log(finalState.toRIC(actualState).toString()); // => [RIC] // Epoch: 2018-12-22T00:00:00.000Z // Position: [ -0.005770585, -0.019208198, 0.005105235 ] km // Velocity: [ 0.000020089, 0.000006319, 0.000000117 ] km/s <file_sep>/src/math/constants.ts /** Value of 2 times Pi. */ export const TWO_PI = Math.PI * 2; /** Unit for converting degrees to radians. */ export const DEG2RAD = Math.PI / 180; /** Unit for converting radians to degrees. */ export const RAD2DEG = 180 / Math.PI; /** Unit for converting 0.0001 arcseconds to radians. */ export const TTASEC2RAD = (1 / 60 / 60 / 10000) * DEG2RAD; /** Unit for converting arcseconds to radians. */ export const ASEC2RAD = (1 / 60 / 60) * DEG2RAD; /** Astronomical Unit, in kilometers. */ export const ASTRONOMICAL_UNIT = 149597870.0; /** Unit for converting seconds to days. */ export const SEC2DAY = 1 / 60 / 60 / 24; /** Unit for converting seconds to degrees. */ export const SEC2DEG = 1 / 60 / 60; /** Speed of light, in km/s. */ export const SPEED_OF_LIGHT = 299792458; <file_sep>/src/coordinates/teme.ts import { EarthBody } from "../bodies/earth-body"; import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; import { IStateVector } from "./coordinate-interface"; import { J2000 } from "./j2000"; /** Class representing True Equator Mean Equinox (TEME) coordinates. */ export class TEME implements IStateVector { /** Satellite state epoch. */ public readonly epoch: EpochUTC; /** Position vector, in kilometers. */ public readonly position: Vector3D; /** Velocity vector, in kilometers per second. */ public readonly velocity: Vector3D; /** * Create a new TEME object. * * @param epoch UTC epoch * @param position J2000 position, in kilometers * @param velocity J2000 velocity, in kilometers per second */ constructor(epoch: EpochUTC, position: Vector3D, velocity: Vector3D) { this.epoch = epoch; this.position = position; this.velocity = velocity || Vector3D.origin(); } /** Return a string representation of this object. */ public toString(): string { const { epoch, position, velocity } = this; const output = [ "[TEME]", ` Epoch: ${epoch.toString()}`, ` Position: ${position.toString()} km`, ` Velocity: ${velocity.toString()} km/s` ]; return output.join("\n"); } /** Convert this to a TEME state vector object. */ public toJ2000() { const { epoch, position, velocity } = this; const [dPsi, dEps, mEps] = EarthBody.nutation(epoch); const epsilon = mEps + dEps; const rMOD = position .rot3(-dPsi * Math.cos(epsilon)) .rot1(epsilon) .rot3(dPsi) .rot1(-mEps); const vMOD = velocity .rot3(-dPsi * Math.cos(epsilon)) .rot1(epsilon) .rot3(dPsi) .rot1(-mEps); const [zeta, theta, zed] = EarthBody.precession(epoch); const rJ2K = rMOD .rot3(zed) .rot2(-theta) .rot3(zeta); const vJ2K = vMOD .rot3(zed) .rot2(-theta) .rot3(zeta); return new J2000(this.epoch, rJ2K, vJ2K); } } <file_sep>/src/conjunction/conjunction-assessment.ts import { Vector3D } from "../math/vector-3d"; import { Matrix3D } from "../math/matrix-3d"; import { MonteCarlo } from "../math/monte-carlo"; /** Class for satellite conjunction operations. */ export class ConjunctionAssesment { /** * Simulate possible outcomes of a satellite conjunction, using information * found in a Conjunction Summary Message (CSM). * * @param posA asset position * @param covA asset covariance * @param posB satellite position * @param covB satellite covariance * @param sigma standard deviation * @param iterations number of samples */ public static simulateConjunctionMessage( posA: Vector3D, covA: Matrix3D, posB: Vector3D, covB: Matrix3D, sigma: number, iterations: number ) { const mcA = new MonteCarlo(posA, covA, sigma); const mcB = new MonteCarlo(posB, covB, sigma); const missDistances: number[] = []; for (let i = 0; i < iterations; i++) { const sampleA = mcA.sample(); const sampleB = mcB.sample(); missDistances.push(sampleA.distance(sampleB)); } return missDistances; } } <file_sep>/src/examples/conjunction-example.ts import { ConjunctionAssesment, Matrix3D, Vector3D } from "../index"; // ============================================================================= // simulate conjunction using Conjunction Summary Message (CSM) data // example data from: https://www.space-track.org/documents/CSM_Guide.pdf // ============================================================================= // load relative position and covariance from the report const posA = new Vector3D(27.4, -70.2, 711.8); // meters const covA = new Matrix3D( // asset covariance (meters) new Vector3D(4.142e1, -8.579, -2.312e1), new Vector3D(-8.579, 2.533e3, 1.336e1), new Vector3D(-2.312e1, 1.336e1, 7.098e1) ); const posB = Vector3D.origin(); // zero since relative position is used const covB = new Matrix3D( // satellite covariance (meters) new Vector3D(1.337e3, -4.806e4, -3.298e1), new Vector3D(-4.806e4, 2.492e6, -7.588e2), new Vector3D(-3.298e1, -7.588e2, 7.105e1) ); // run a monte-carlo simulation of the conjunction and generate miss-distances const missDists = ConjunctionAssesment.simulateConjunctionMessage( posA, // asset position covA, // asset covariance posB, // satellite position covB, // satellite covariance 3, // standard deviation (sigma) 1000000 // iterations (some big number) ); // ============================================================================= // NOTE: results may vary due to the random nature of monte-carlo simulation // ============================================================================= console.log(`Expected Miss-Distance: ${posA.distance(posB).toFixed(3)} meters`); // => Expected Miss-Distance: 715.778 meters console.log( `Smallest Simulated Miss-Distance: ${missDists .reduce((a, b) => (a < b ? a : b)) .toFixed(3)} meters` ); // => Smallest Simulated Miss-Distance: 633.235 meters console.log( `Largest Simulated Miss-Distance: ${missDists .reduce((a, b) => (a > b ? a : b)) .toFixed(3)} meters` ); // => Largest Simulated Miss-Distance: 13121.900 meters // generate a histogram of the miss distances (for illustrative purposes) console.log("\n----- Miss-Distance Probability -----"); const step = 250; for (let m = 0; m <= 2500; m += step) { const count = missDists.filter(dist => dist >= m && dist < m + step).length; const percent = (count / missDists.length) * 100; const hist: string[] = ["|"]; for (let i = 0; i < percent; i++) { hist.push("*"); } const rangeStr = (m.toLocaleString() + "m: ").substr(0, 7); const percentStr = (percent.toFixed(1) + "% ").substr(0, 5); console.log(` ${rangeStr} ${percentStr} ${hist.join("")}`); } // => // ----- Miss-Distance Probability ----- // 0m: 0.0% | // 250m: 0.0% | // 500m: 6.4% |******* // 750m: 13.8% |************** // 1,000m: 9.0% |********* // 1,250m: 7.8% |******** // 1,500m: 7.0% |******** // 1,750m: 6.4% |******* // 2,000m: 5.9% |****** // 2,250m: 5.5% |****** // 2,500m: 5.0% |***** <file_sep>/src/test/bodies-test.ts import * as assert from "assert"; import { EarthBody, EpochUTC, J2000, MoonBody, RungeKutta4Propagator, SunBody, Vector3D } from "../index"; const epoch = EpochUTC.fromDateString("2018-12-21T00:00:00.000Z"); const state = new J2000( epoch, new Vector3D(-1117.913276, 73.093299, -7000.018272), new Vector3D(3.531365461, 6.583914964, -0.495649656) ); const rk4Prop = new RungeKutta4Propagator(state); describe("MoonBody", () => { describe("position", () => { const actual = MoonBody.position(epoch); const expected = new Vector3D( 154366.09642497, 318375.615233499, 109213.672184026 ); it("should be within 300km of real-world magnitude", () => { const magnitude = Math.abs(expected.magnitude() - actual.magnitude()); assert(magnitude <= 300); }); it("should be within 0.25 degrees of real-world angle", () => { const angle = expected.angle(actual) * (180 / Math.PI); assert(angle <= 0.25); }); }); }); describe("SunBody", () => { describe("position", () => { const actual = SunBody.position(epoch); const expected = new Vector3D( -3092558.657913523, -134994294.84136814, -58520244.455122419 ); it("should be within 7000km of real-world magnitude", () => { const magnitude = Math.abs(expected.magnitude() - actual.magnitude()); assert(magnitude <= 7000); }); it("should be within 0.30 degrees of real-world angle", () => { const angle = expected.angle(actual) * (180 / Math.PI); assert(angle <= 0.3); }); }); describe("shadow", () => { rk4Prop.reset(); rk4Prop.setStepSize(30); rk4Prop.forceModel.clearModel(); rk4Prop.forceModel.setEarthGravity(0, 0); let propEpoch = epoch; let errorCount = 0; it("should approximately match inverted vector sight algorithm", () => { for (let i = 0; i < 1440; i++) { const satState = rk4Prop.propagate(propEpoch); const shadow = SunBody.shadow(satState); const satPos = satState.position; const sunPos = SunBody.position(propEpoch); const sight = satPos.sight(sunPos, EarthBody.RADIUS_MEAN); if (shadow === sight) { errorCount++; } propEpoch = propEpoch.roll(60); } assert(errorCount <= 3); }); }); }); <file_sep>/src/forces/earth-gravity.ts import { EarthBody } from "../bodies/earth-body"; import { ITRF } from "../coordinates/itrf"; import { J2000 } from "../coordinates/j2000"; import { DataHandler } from "../data/data-handler"; import { SphericalHarmonics } from "../math/spherical-harmonics"; import { Vector3D } from "../math/vector-3d"; import { AccelerationForce, AccelerationMap } from "./forces-interface"; /** Model of Earth gravity, for use in a ForceModel object. */ export class EarthGravity implements AccelerationForce { /** model aspherical gravity, if true. */ private earthAsphericalFlag: boolean; /** geopotential degree (max=70) */ private degree: number; /** geopotential order (max=70) */ private order: number; /** spherical harmonics manager */ private harmonics: SphericalHarmonics; /** * Create a new EarthGravity object. * * @param degree geopotential degree (max=70) * @param order geopotential order (max=70) */ constructor(degree: number, order: number) { this.earthAsphericalFlag = degree >= 2; this.degree = degree; this.order = order; this.harmonics = new SphericalHarmonics(degree); } /** * Calculate a cache of recurring values for the geopotential model: * * [ * sin(m * lambda), * cos(m * lambda), * tan(phi) * ] * * @param m m-index * @param lambda longitude, in radians * @param phi geocentric latitude, in radians */ private recurExp( m: number, lambda: number, phi: number ): [number, number, number] { var smLam = Math.sin(m * lambda); var cmLam = Math.cos(m * lambda); var mtPhi = m * Math.tan(phi); return [smLam, cmLam, mtPhi]; } /** * Calculate R, Phi, and Lambda acceleration derivatives. * * @param phi geocentric latitude, in radians * @param lambda longitude, in radians * @param r radius (km) */ private calcGradient( phi: number, lambda: number, r: number ): [number, number, number] { const { degree, order, harmonics, recurExp } = this; let sumR = 0; let sumPhi = 0; let sumLambda = 0; for (let l = 2; l <= degree; l++) { for (let m = 0; m <= Math.min(l, order); m++) { const { clm, slm } = DataHandler.getEgm96Coeffs(l, m); const [smLam, cmLam, mtPhi] = recurExp(m, lambda, phi); // r derivative const aR = Math.pow(EarthBody.RADIUS_EQUATOR / r, l) * (l + 1) * harmonics.getP(l, m); const bR = clm * cmLam + slm * smLam; sumR += aR * bR; // phi derivative const aPhi = Math.pow(EarthBody.RADIUS_EQUATOR / r, l) * (harmonics.getP(l, m + 1) - mtPhi * harmonics.getP(l, m)); const bPhi = clm * cmLam + slm * smLam; sumPhi += aPhi * bPhi; // lambda derivative const aLambda = Math.pow(EarthBody.RADIUS_EQUATOR / r, l) * m * harmonics.getP(l, m); const bLambda = slm * cmLam - clm * smLam; sumLambda += aLambda * bLambda; } } const dR = -(EarthBody.MU / (r * r)) * sumR; const dPhi = (EarthBody.MU / r) * sumPhi; const dLambda = (EarthBody.MU / r) * sumLambda; return [dR, dPhi, dLambda]; } /** * Calculate acceleration due to Earth's gravity, assuming a spherical Earth. * * @param j2kState J2000 state vector */ private earthSpherical(j2kState: J2000) { const { position } = j2kState; const rMag = position.magnitude(); return position.scale(-EarthBody.MU / (rMag * rMag * rMag)); } /** * Calculate the aspherical components of acceleration due to Earth's gravity. * * @param j2kState J2000 state vector */ private earthAspherical(j2kState: J2000) { const itrf = j2kState.toITRF(); const { x: ri, y: rj, z: rk } = itrf.position; const p = Math.sqrt(ri * ri + rj * rj); const phi = Math.atan2(rk, p); const lambda = Math.atan2(rj, ri); const r = itrf.position.magnitude(); this.harmonics.buildCache(phi); const [dR, dPhi, dLambda] = this.calcGradient(phi, lambda, r); const r2 = r * r; const ri2 = ri * ri; const rj2 = rj * rj; const p1 = (1 / r) * dR - (rk / (r2 * Math.sqrt(ri2 + rj2))) * dPhi; const p2 = (1 / (ri2 + rj2)) * dLambda; const ai = p1 * ri - p2 * rj; const aj = p1 * rj + p2 * ri; const ak = (1 / r) * dR * rk + (Math.sqrt(ri2 + rj2) / r2) * dPhi; const accVec = new ITRF(j2kState.epoch, new Vector3D(ai, aj, ak)); return accVec.toJ2000().position; } /** * Update the acceleration map argument with a calculated "earth_gravity" * value, for the provided state vector. * * @param j2kState J2000 state vector * @param accMap acceleration map (km/s^2) */ public acceleration(j2kState: J2000, accMap: AccelerationMap) { accMap["earth_gravity"] = this.earthSpherical(j2kState); if (this.earthAsphericalFlag) { accMap["earth_gravity"] = accMap["earth_gravity"].add( this.earthAspherical(j2kState) ); } } } <file_sep>/src/propagators/kepler-propagator.ts import { ClassicalElements } from "../coordinates/classical-elements"; import { J2000 } from "../coordinates/j2000"; import { TWO_PI } from "../math/constants"; import { matchHalfPlane } from "../math/operations"; import { EpochUTC } from "../time/epoch-utc"; import { IPropagator } from "./propagator-interface"; /** Satellite ephemeris propagator, using Kepler's method. */ export class KeplerPropagator implements IPropagator { /** Cache for last computed statellite state. */ public state: J2000; /** Keplerian element set. */ private readonly elements: ClassicalElements; /** * Create a new Kepler propagator object. This propagator only models * two-body effects on the orbiting object. * * @param elements Keplerian element set */ constructor(elements: ClassicalElements) { this.elements = elements; this.state = elements.toJ2000(); } /** Return a string representation of the object. */ public toString() { return ["[Kepler]", " Two-Body Propagator"].join("\n"); } /** * Restore cached state to initial propagator state. Doesn't really do much * for the Kepler propagator, since it doesn't rely on transient states. */ public reset(): KeplerPropagator { this.state = this.elements.toJ2000(); return this; } /** * Propagate satellite state to a new epoch. * * @param epoch UTC epoch */ public propagate(epoch: EpochUTC): J2000 { const { epoch: t, a, e, i, o, w, v } = this.elements; const delta = epoch.difference(t); const n = this.elements.meanMotion(); let eaInit = Math.acos((e + Math.cos(v)) / (1 + e * Math.cos(v))); eaInit = matchHalfPlane(eaInit, v); let maInit = eaInit - e * Math.sin(eaInit); maInit = matchHalfPlane(maInit, eaInit); const maFinal = (maInit + n * delta) % TWO_PI; let eaFinal = maFinal; for (let iter = 0; iter < 32; iter++) { const eaTemp = maFinal + e * Math.sin(eaFinal); if (Math.abs(eaTemp - eaFinal) < 1e-12) { break; } eaFinal = eaTemp; } let vFinal = Math.acos( (Math.cos(eaFinal) - e) / (1 - e * Math.cos(eaFinal)) ); vFinal = matchHalfPlane(vFinal, eaFinal); this.state = new ClassicalElements(epoch, a, e, i, o, w, vFinal).toJ2000(); return this.state; } /** * Propagate state by some number of seconds, repeatedly, starting at a * specified epoch. * * @param epoch UTC epoch * @param interval seconds between output states * @param count number of steps to take */ public step(epoch: EpochUTC, interval: number, count: number): J2000[] { const output: J2000[] = [this.propagate(epoch)]; let tempEpoch = epoch; for (let i = 0; i < count; i++) { tempEpoch = tempEpoch.roll(interval); output.push(this.propagate(tempEpoch)); } return output; } } <file_sep>/src/data/values/finals.ts export interface FinalsData { /** USNO modified julaian date */ mjd: number; /** polar motion x-component (degrees) */ pmX: number; /** polar motion y-component (degrees) */ pmY: number; /** delta ut1 time (seconds) */ dut1: number; /** length of day (seconds) */ lod: number; /** delta psi (degrees) */ dPsi: number; /** delta epsilon (degrees) */ dEps: number; } /** IERS finals.all data. */ export let FINALS: FinalsData[] = []; /** Clear cached finals.all data. */ export function clearFinals() { FINALS = []; } /** Sort finals.all data by modified julian date. */ export function sortFinals() { FINALS.sort((a, b) => a.mjd - b.mjd); } /** Return a finals entry with all values set to zero. */ export function zeroFinal(): FinalsData { return { mjd: 0, pmX: 0, pmY: 0, dut1: 0, lod: 0, dPsi: 0, dEps: 0 }; } <file_sep>/src/math/matrix-3d.ts import { Vector3D } from "./vector-3d"; /** Internal Matrix3D storage format. */ export type Matrix3DValues = [Vector3D, Vector3D, Vector3D]; /** Class representing a 3x3 matrix. */ export class Matrix3D { /** matrix data */ private readonly matrix: Matrix3DValues; /** * Create a new Matrix3D object. * * @param a first row * @param b second row * @param c third row */ constructor(a: Vector3D, b: Vector3D, c: Vector3D) { this.matrix = [a, b, c]; } /** Create a new object, containing all zeros. */ public static zeros() { return new Matrix3D( Vector3D.origin(), Vector3D.origin(), Vector3D.origin() ); } /** Return a string representation of this matrix. */ public toString(): string { const a0Str = this.get(0, 0).toExponential(9); const a1Str = this.get(0, 1).toExponential(9); const a2Str = this.get(0, 2).toExponential(9); const b0Str = this.get(1, 0).toExponential(9); const b1Str = this.get(1, 1).toExponential(9); const b2Str = this.get(1, 2).toExponential(9); const c0Str = this.get(2, 0).toExponential(9); const c1Str = this.get(2, 1).toExponential(9); const c2Str = this.get(2, 2).toExponential(9); return [ `[ ${a0Str}, ${a1Str}, ${a2Str} ]`, `[ ${b0Str}, ${b1Str}, ${b2Str} ]`, `[ ${c0Str}, ${c1Str}, ${c2Str} ]` ].join("\n"); } /** * Get matrix data by index. * * @param row row index (0-2) * @param column column index (0-2) */ public get(row: number, column: number) { const rowVal = this.matrix[row]; if (column === 0) { return rowVal.x; } else if (column === 1) { return rowVal.y; } else if (column === 2) { return rowVal.z; } return 0; } /** * Linearly scale all matrix values by a number. * * @param n scalar */ public scale(n: number) { return new Matrix3D( this.matrix[0].scale(n), this.matrix[1].scale(n), this.matrix[2].scale(n) ); } /** Calculate and return the transpose of this matrix. */ public transpose() { const a = new Vector3D(this.get(0, 0), this.get(1, 0), this.get(2, 0)); const b = new Vector3D(this.get(0, 1), this.get(1, 1), this.get(2, 1)); const c = new Vector3D(this.get(0, 2), this.get(1, 2), this.get(2, 2)); return new Matrix3D(a, b, c); } /** * Multiply this by the vector argument. * * @param v 3-vector */ public multiplyVector3D(v: Vector3D) { const { matrix } = this; return new Vector3D(matrix[0].dot(v), matrix[1].dot(v), matrix[2].dot(v)); } /** Return the Cholesky decomposition of this matrix. */ public cholesky() { const a = this; const l = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]; for (let i = 0; i < 3; i++) { for (let k = 0; k < i + 1; k++) { let sum = 0; for (let j = 0; j < k; j++) { sum += l[i][j] * l[k][j]; } l[i][k] = i === k ? Math.sqrt(a.get(i, i) - sum) : (1 / l[k][k]) * (a.get(i, k) - sum); } } return new Matrix3D( new Vector3D(l[0][0], l[0][1], l[0][2]), new Vector3D(l[1][0], l[1][1], l[1][2]), new Vector3D(l[2][0], l[2][1], l[2][2]) ); } } <file_sep>/src/bodies/earth-body.ts import { DataHandler } from "../data/data-handler"; import { IAU_1980 } from "../data/values/iau1980"; import { DEG2RAD, TTASEC2RAD } from "../math/constants"; import { evalPoly } from "../math/operations"; import { Vector3D } from "../math/vector-3d"; import { EpochUTC } from "../time/epoch-utc"; export class EarthBody { /** Earth gravitational parameter, in km^3/s^2. */ public static readonly MU = 398600.4415; /** Earth equatorial radius, in kilometers. */ public static readonly RADIUS_EQUATOR = 6378.1363; /** Earth coefficient of flattening. */ public static readonly FLATTENING = 1 / 298.257; /** Earth rotation vector, in radians per second. */ private static readonly ROTATION = new Vector3D(0, 0, 7.2921158553e-5); /** Earth polar radius, in kilometers. */ public static readonly RADIUS_POLAR = EarthBody.RADIUS_EQUATOR * (1 - EarthBody.FLATTENING); /** Earth mean radius, in kilometers. */ public static readonly RADIUS_MEAN = (2 * EarthBody.RADIUS_EQUATOR + EarthBody.RADIUS_POLAR) / 3; /** Earth eccentricity squared. */ public static readonly ECCENTRICITY_SQUARED = EarthBody.FLATTENING * (2 - EarthBody.FLATTENING); /** * Return Earth's rotation vector, in radians per second. * * The vector is adjusted for length of day (LOD) variations, assuming IERS * finals.all data is loaded in DataHandler. Otherwise, LOD corrections are * ignored. * * @param epoch UTC epoch */ public static getRotation(epoch: EpochUTC) { const finals = DataHandler.getFinalsData(epoch.toMjd()); return EarthBody.ROTATION.scale(1 - finals.lod / 86400); } /** * Calculate the [zeta, theta, zed] angles of precession, in radians. * * @param epoch satellite state epoch */ public static precession(epoch: EpochUTC): [number, number, number] { const t = epoch.toTDB().toJulianCenturies(); const zeta = evalPoly(t, [0.0, 0.6406161, 0.0000839, 5.0e-6]); const theta = evalPoly(t, [0.0, 0.556753, -0.0001185, -1.16e-5]); const zed = evalPoly(t, [0.0, 0.6406161, 0.0003041, 5.1e-6]); return [zeta * DEG2RAD, theta * DEG2RAD, zed * DEG2RAD]; } /** * Calculate the [deltaPsi, deltaEpsilon, meanEpsilon] angles of nutation, * in radians. * * @param epoch satellite state epoch * @param n number of coefficients (default=106) */ public static nutation(epoch: EpochUTC, n = 106): [number, number, number] { const r = 360; const t = epoch.toTDB().toJulianCenturies(); const moonAnom = evalPoly(t, [ 134.96340251, 1325.0 * r + 198.8675605, 0.0088553, 1.4343e-5 ]); const sunAnom = evalPoly(t, [ 357.52910918, 99.0 * r + 359.0502911, -0.0001537, 3.8e-8 ]); const moonLat = evalPoly(t, [ 93.27209062, 1342.0 * r + 82.0174577, -0.003542, -2.88e-7 ]); const sunElong = evalPoly(t, [ 297.85019547, 1236.0 * r + 307.1114469, -0.0017696, 1.831e-6 ]); const moonRaan = evalPoly(t, [ 125.04455501, -(5.0 * r + 134.1361851), 0.0020756, 2.139e-6 ]); let deltaPsi = 0; let deltaEpsilon = 0; IAU_1980.slice(0, n).map(iauLine => { let [a1, a2, a3, a4, a5, Ai, Bi, Ci, Di] = iauLine; const arg = (a1 * moonAnom + a2 * sunAnom + a3 * moonLat + a4 * sunElong + a5 * moonRaan) * DEG2RAD; const sinC = Ai + Bi * t; const cosC = Ci + Di * t; deltaPsi += sinC * Math.sin(arg); deltaEpsilon += cosC * Math.cos(arg); }); deltaPsi = deltaPsi * TTASEC2RAD; deltaEpsilon = deltaEpsilon * TTASEC2RAD; const meanEpsilon = evalPoly(t, [23.439291, -0.013004, -1.64e-7, 5.04e-7]) * DEG2RAD; return [deltaPsi, deltaEpsilon, meanEpsilon]; } }
80c8eb142f4af8ace9ff2a224cbb6a4335335d74
[ "Markdown", "TypeScript" ]
43
TypeScript
battyone/pious-squid
2e39c63c5a342a180e26b4d984c6ed58df937fd5
ee15074a107060a1103c6c6ca81481ac4902a919
refs/heads/master
<file_sep>package com.example.camera.application; import com.example.camera.domain.Camera; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.sql.SQLException; public interface CameraService { /* 서버 <-> 카메라 서비스 * 1. 서버->카메라 실행, 유저아이디 * 2. 사진이 찍힌후, 카메라에서 오는 유저아이디와 경로 저장 */ public Camera startCamera(String userId, String beaconid) throws IOException, ClassNotFoundException, SQLException; public void savePhoto(Long userId, String photoPath); public Camera setCameraDomain(HttpServletRequest request) throws SQLException, ClassNotFoundException; } <file_sep>package com.example.beacon.domain; import javax.persistence.Embeddable; /** * Created by User on 2016-07-07. */ @Embeddable public class BeaconNo { } <file_sep>package com.example.response.infra; import com.example.response.domain.Location; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * Created by User on 2016-06-18. */ @Repository public interface LocationRepository extends JpaRepository<Location, Long> { } <file_sep>package com.example.response.domain; import com.example.beacon.domain.Beacon; import javax.persistence.*; import java.util.Date; @Entity public class Location { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long locationid; @JoinColumn(name = "beaconid") @ManyToOne private Beacon beaconid; private String userId; private Date date; public Long getLocationid() { return locationid; } public void setLocationid(Long locationid) { this.locationid = locationid; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Beacon getBeaconid() { return beaconid; } public void setBeaconid(Beacon beaconid) { this.beaconid = beaconid; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } <file_sep>package com.example.camera.application; import com.example.camera.infra.CameraRepository; import com.example.camera.domain.Camera; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.sql.SQLException; @Service("CameraService") public class CameraServiceImpl implements CameraService { @Autowired private CameraRepository cameraRepository; @Override public Camera startCamera(String userId, String beaconid) throws IOException, ClassNotFoundException, SQLException { Camera camera = cameraRepository.findOne(beaconid); URL url = new URL(camera.getDomain() + "?userid=" + userId); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (urlConnection.getResponseCode() == 404) { // 해당 카메라에 접속이 안되면 모든 값을 null로 변경. camera.setDomain(null); camera.setBeaconid(null); } return camera; } @Override public void savePhoto(Long userId, String photoPath) { /* - 특정 URL로 파일이 저장되게. - 파일은 POST로 받는다. - image인지 아닌지 */ } @Override public Camera setCameraDomain(HttpServletRequest request) throws SQLException, ClassNotFoundException { return null; } // @Override // public Camera setCameraDomain(HttpServletRequest request) throws SQLException, ClassNotFoundException { // Camera camera = new Camera(); // camera.setBeaconid(request.getParameter("beaconid")); // camera.setDomain(request.getParameter("domain")); // // return cameraRepository.save(camera); // } } <file_sep>package com.example.camera.domain; import javax.persistence.Embeddable; /** * Created by User on 2016-07-07. */ @Embeddable public class CameraNo { } <file_sep>package com.example.beacon.domain; import javax.persistence.*; import java.io.Serializable; /** * Created by User on 2016-06-21. */ @Entity public class Beacon implements Serializable { @EmbeddedId private BeaconNo beaconid; @Column(name = "type") @Enumerated(EnumType.STRING) private BeaconType type; // 1, 2, 3으로 나뉨. 1 파파라치, 2 스토리, 3 경로 저장 @Embedded private BeaconLocation location; public BeaconType getType() { return type; } public void setType(BeaconType type) { this.type = type; } public BeaconLocation getLocation() { return location; } public void setLocation(BeaconLocation location) { this.location = location; } public BeaconNo getBeaconid() { return beaconid; } public void setBeaconid(BeaconNo beaconid) { this.beaconid = beaconid; } } <file_sep>package com.example.response.infra; import com.example.response.domain.RecommendedRoute; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by User on 2016-06-21. */ @Repository public interface RecommendedRouteRepository extends JpaRepository<RecommendedRoute, Long> { List<RecommendedRoute> findByUserid(String userid); }<file_sep>package com.example.response.infra; import com.example.response.domain.Photo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by User on 2016-06-18. */ @Repository public interface PhotoRepository extends JpaRepository<Photo, Long> { List<Photo> findByUserid(String userid); } <file_sep>package com.example.beacon.infra; import com.example.beacon.domain.Beacon; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * Created by User on 2016-06-21. */ @Repository public interface BeaconRepository extends JpaRepository<Beacon, String> { }<file_sep>package com.example.response.application; import com.example.user.domain.User; import com.example.user.infra.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.SQLException; @Service("UserService") public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override public User userInfo(String id) throws ClassNotFoundException, SQLException { return userRepository.findOne(id); } @Override public User add(String id) throws SQLException { User user = new User(); user.setId(id); return userRepository.save(user); } } <file_sep>group 'whatsuda.server.rest' version '1.0-SNAPSHOT' apply plugin: 'java' apply plugin: 'spring-boot' apply plugin: 'war' apply plugin: 'idea' buildscript { repositories { maven { url "http://repo.spring.io/libs-snapshot" } mavenCentral() jcenter() } dependencies { classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.3.2.RELEASE' classpath 'org.springframework:springloaded:1.2.4.RELEASE' } } sourceCompatibility = 1.8 idea { module { inheritOutputDirs = false outputDir = file("$buildDir/classes/main/") } } repositories { mavenCentral() jcenter() maven { url "http://repo.spring.io/libs-snapshot" } } configurations { providedRuntime } dependencies { compile("org.springframework.boot:spring-boot-starter-web:1.0.0.RC1") compile("org.springframework.boot:spring-boot-devtools") compile("org.springframework.boot:spring-boot-starter-web") compile('org.springframework.boot:spring-boot-starter-thymeleaf') compile("org.springframework.boot:spring-boot-starter-data-jpa") compile("org.springframework.boot:spring-boot-starter-ws") compile("org.springframework.cloud:spring-cloud-aws-context:1.0.2.RELEASE") compile('mysql:mysql-connector-java:5.1.37') compile group: 'org.codehaus.castor', name: 'castor-core', version: '1.3.3' compile group: 'org.codehaus.castor', name: 'castor-xml', version: '1.3.3' testCompile group: 'junit', name: 'junit', version: '4.11' } <file_sep>package com.example.response.application; import com.example.beacon.domain.Beacon; import com.example.beacon.infra.BeaconRepository; import com.example.response.domain.Location; import com.example.response.domain.Photo; import com.example.response.domain.RecommendedRoute; import com.example.response.infra.LocationRepository; import com.example.response.infra.PhotoRepository; import com.example.response.infra.RecommendedRouteRepository; import com.example.response.infra.StoryRepository; import com.example.camera.application.CameraService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.sql.SQLException; import java.util.Date; import java.util.List; /** * Created by User on 2016-06-21. */ @RestController public class AppController { @Autowired private CameraService cameraService; @Autowired private BeaconRepository beaconRepository; @Autowired private PhotoRepository photoRepository; @Autowired private RecommendedRouteRepository recommendedRouteRepository; @Autowired private StoryRepository storyRepository; @Autowired private LocationRepository locationRepository; @RequestMapping(value = "/", method = RequestMethod.GET) //beaconid, userid 가 파라미터로 들어온다. public Object event(HttpServletRequest request) throws SQLException, IOException, ClassNotFoundException { Beacon beacon = beaconRepository.findOne(request.getParameter("beaconid")); String userid = request.getParameter("userid"); if(beacon.getType() == 1){ return cameraService.startCamera(userid, beacon.getBeaconid()); }else if(beacon.getType() == 2){ return storyRepository.findByBeacon(beacon); }else if(beacon.getType() == 3){ Location location = new Location(); Date date = new Date(); location.setUserId(userid); location.setBeaconid(beacon); location.setDate(date); return locationRepository.save(location); } return null; } @RequestMapping(value = "/photo/{userid}", method = RequestMethod.GET) public List<Photo> getPhoto(@PathVariable String userid){ return photoRepository.findByUserid(userid); } @RequestMapping(value = "/path/{userid}") public List<RecommendedRoute> route(@PathVariable String userid){ System.out.println( recommendedRouteRepository.findByUserid(userid).get(0).getBeacon().getLocation()); return recommendedRouteRepository.findByUserid(userid); } } <file_sep>package com.example.response.infra; import com.example.beacon.domain.Beacon; import com.example.response.domain.Story; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * Created by User on 2016-06-21. */ @Repository public interface StoryRepository extends JpaRepository<Story, String> { Story findByBeacon(Beacon beacon); } <file_sep>rootProject.name = 'whatsuda' <file_sep>package com.example.response.domain; import com.example.beacon.domain.Beacon; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import java.io.Serializable; /** * Created by User on 2016-06-21. */ @Entity public class Story implements Serializable { @Id private String storyid; @JoinColumn(name = "beaconid") @ManyToOne private Beacon beacon; private String content; public String getStoryid() { return storyid; } public void setStoryid(String storyid) { this.storyid = storyid; } public Beacon getBeacon() { return beacon; } public void setBeacon(Beacon beacon) { this.beacon = beacon; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
c49fe6ec64c2a20e16a8b36e427093e606a11945
[ "Java", "Gradle" ]
16
Java
hst2570/whatSuda
fcf2416264be7d446eda478ca446bc03636bd7aa
7e7cd8896271bc2dfb53d37eed8225fa995d0779
refs/heads/master
<file_sep><?php include("includes/database.php"); include("includes/init.php"); include("includes/config.php"); session_start(); $_SESSION['last_active'] = time(); if (time() > $_SESSION['last_active'] + $config['session_timeout']) { //log out user session_destroy(); header("Location: login.php?timeout"); } //check authorization if ($Auth->checkLogStatus() == false) { $Template->setAlert('Required field', 'error'); $Template->redirect('login.php'); } $input['input_name'] = ''; $input['current_pass'] = ''; if (isset($_POST['submit'])) { //get data from form $Template->setData('input_name', $_POST['name']); $Template->setData('inputCurrent', $_POST['current_pass']); $Template->setData('input_pass', $_POST['password']); $Template->setData('input_pass2', $_POST['password2']); //validation data if ($_POST['name'] == '' || $_POST['password'] == '' || $_POST['password2'] == '' || $_POST['current_pass'] == '') { //show error msg if ($_POST['name'] == '') { $Template->setData('error_user', 'required field'); } if ($_POST['current_pass'] == '') { $Template->setData('error_current', 'required field'); } if ($_POST['password'] == '') { $Template->setData('error_pass', 'required field'); } if ($_POST['password2'] == '') { $Template->setData('error_pass2', 'required field'); } if ($Auth->validateLogin($Template->getData('input_name'), $Template->getData('inputCurrent')) == true ) { $Template->setAlert('Введите заново текущий пароль и введите новый', 'warning'); } if ($_POST['current_pass'] != '' AND $_POST['name'] != '' ) { if ($Auth->validateLogin($Template->getData('input_name'), $Template->getData('inputCurrent')) == false ) { $Template->setAlert('Неверный текущий пароль', 'warning'); } } } if (empty($_POST['current_pass'])) { $Template->redirect("change_password.php"); } if (!empty($_POST['password']) && $_POST['password2']) { if ($_POST['password'] != $_POST['password2']) { $Template->setAlert('Пароли не совпадают, введите заново', 'warning'); } if ($Auth->validateLogin($Template->getData('input_name'), $Template->getData('inputCurrent')) == true &&($_POST['password']) ==($_POST['password2'])) { ($Auth->updatePassword($Template->getData('input_name'), $Template->getData('input_pass'))); $Template->setAlert('Поздравляем с успешной сменой пароля', 'success'); } } } $Template->load("views/v_change.php");<file_sep><?php include("includes/database.php"); include("includes/init.php"); include("includes/config.php"); session_start(); $_SESSION['last_active'] = time(); if (time() > $_SESSION['last_active'] + $config['session_timeout']) { //log out user session_destroy(); header("Location: login.php?timeout"); } //check authorization if ($Auth->checkLogStatus() == false) { $Template->setAlert('Вы не авторизированы', 'error'); $Template->redirect('login.php'); } if (isset($_POST['submit'])) { //get data from form $Template->setData('input_user', $_POST['username']); $Template->setData('input_email', $_POST['email']); $Template->setData('input_pass', $_POST['password']); $Template->setData('input_pass2', $_POST['password2']); //validation data if ($_POST['username'] == '' || $_POST['email'] == '' || $_POST['password'] == '' || $_POST['password2'] == '') { //show error msg if ($_POST['username'] == '') { $Template->setData('error_user', 'required field'); } if ($_POST['email'] == '') { $Template->setData('error_email', 'required field'); } if ($_POST['password'] == '') { $Template->setData('error_pass', 'required field'); } if ($_POST['password2'] == '') { $Template->setData('error_pass', 'required field'); } $Template->setAlert('Заполните обязательные поля', 'error'); $Template->load("views/v_register.php"); } elseif ($_POST['password'] != $_POST['password2']) { $Template->setAlert('Пароли не совпадают, повторите попытку', 'warning'); $Template->load("views/v_register.php"); } elseif ($Auth->insertdb($Template->getData('input_user'), $Template->getData('input_email'), $Template->getData('input_pass'))) { $Template->redirect("register.php"); $Template->setAlert('Поздравляем с успешной регистрацией', 'success'); } } else { $Template->load("views/v_register.php"); }<file_sep><?php $server = 'mysql.hostinger.ru'; $user = '...'; $pass = '.......'; $db = '......'; $Database = new mysqli($server, $user, $pass, $db); mysqli_report(MYSQLI_REPORT_ERROR); <file_sep><?php include("models/m_template.php"); include("models/m_auth.php"); $Template = new Template(); $Template->setAlertTypes(array('success','warning','error')); $Auth = new Auth(); <file_sep><!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" href="views/style.css"/> </head> <body> <h1>Админка</h1> <div id="content"> <?php echo $this->getData('name'); ?> <?php $alerts = $this->getAlerts(); if ($alerts != ''){ echo '<ul class="alerts">' . $alerts . '</ul>';} ?> <p>Вы в админке</p> <a href="register.php">Регистрация</a> <a href="change_password.php">Изменить пароль</a> <a href="logout.php">Выйти</a> </div> </body> </html><file_sep><!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" href="views/style.css"/> </head> <body> <h1>Регистрация</h1> <div id="content"> <form action=""method="post"> <div> <?php echo $this->getData('name'); ?> <?php $alerts = $this->getAlerts(); if ($alerts != ''){ echo '<ul class="alerts">' . $alerts . '</ul>';} ?> <div class="row"> <label for="username">Username: </label> <input type="text" name="username" value="<?php echo $this->getData('input_user'); ?>"/> <div class="error"><? echo $this->getData('error_user'); ?></div> </div> <div class="row"> <label for="email">Email: *</label> <input type="text" name="email" value="<?php echo $this->getData('input_email'); ?>"/> <div class="error"><? echo $this->getData('error_email'); ?></div> </div> <div class="row"> <label for="password">Password: *</label> <input type="password" name="password" value="<?php echo $this->getData('input_pass'); ?>"/> <div class="error"><? echo $this->getData('error_pass'); ?></div> </div> <div class="row"> <label for="password2">Password again: *</label> <input type="password" name="password2" value="<?php echo $this->getData('input_pass2'); ?>"/> <div class="error"><? echo $this->getData('error_pass'); ?></div> </div> <div class="row"> <p class="required">* обязательно</p> <input type="submit" name="submit" class="submit" value="ОК"/> <p><a href="change_password.php">Изменить пароль</a></p> <p> <a href="logout.php">Выйти</a> </p> </div> </div> </form> <div class="row"> </div> </div> </body> </html><file_sep><?php include("includes/database.php"); include("includes/init.php"); session_start(); if (isset($_POST['submit'])) { //get data from form $Template->setData('input_user', $_POST['username']); $Template->setData('input_pass', $_POST['password']); //validation data if ($_POST['username'] == '' || $_POST['password'] == '') { //show error msg if ($_POST['username'] == '') { $Template->setData('error_user', 'required field'); } if ($_POST['password'] == '') { $Template->setData('error_pass', 'required field'); } $Template->setAlert('Заполните все поля', 'error'); $Template->load("views/v_login.php"); } else if ($Auth->validateLogin($Template->getData('input_user'), $Template->getData('input_pass')) == false) { //invalid login $Template->setAlert('Неправильный логин или пароль', 'error'); $Template->load("views/v_login.php"); } else { //successful login $_SESSION['username'] = $Template->getData('user_name'); $_SESSION['loggedin'] = true; $Template->setAlert('Welcome <i>' . $Template->getData('input_user').'</i>'); $Template->redirect("members.php"); } } else { $Template->load("views/v_login.php"); } <file_sep><?php session_start(); class Auth { private $salt = '<PASSWORD>'; function insertdb($user, $email, $pass) { global $Database; if ($stmt = $Database->prepare("insert users (username, email, password) values (?,?,?)")) { $stmt->bind_param("sss", $user, $email, md5($pass . $this->salt)); $stmt->execute(); $stmt->store_result(); $stmt->close(); } return true; } function getPass($current_pass) { global $mysqli; if ($check = $mysqli->prepare("SELECT password FROM users WHERE id = ?")) { $check->bind_param("s", $_SESSION['id']); $check->execute(); $check->bind_result($current_pass); $check->fetch(); $check->close(); } } function getTest() { global $mysqli; if ($check = $mysqli->prepare("SELECT password FROM users WHERE username = 'admin'")) { $check->execute(); $check->store_result(); $check->close(); echo $check; } } function updatePassword($username, $pass) { global $Database; if ($stmt = $Database->prepare("UPDATE users SET password = ? WHERE username = ?")) { $stmt->bind_param("ss", md5($pass . $this->salt), $username); $stmt->execute(); $stmt->store_result(); } return true; } function validateLogin($user,$pass) { //access to DB global $Database; if ($stmt = $Database->prepare("SELECT * FROM users WHERE username = ? AND password =?")) { $stmt->bind_param("ss", $user, md5($pass . $this->salt)); $stmt->execute(); $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->close(); return true; } else { $stmt->close(); return false; } } else { die("Error: can't prepare mysql"); } } function validatePass($pass) { //access to DB global $Database; if ($stmt = $Database->prepare("SELECT username FROM users WHERE password = ?")) { $stmt->bind_param("s", md5($pass . $this->salt)); $stmt->execute(); $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->close(); return true; } else { $stmt->close(); return false; } } else { die("Error: can't prepare mysql"); } } function validateName($username, $pass) { //access to DB global $Database; if ($stmt = $Database->prepare("SELECT username, password FROM users WHERE username = ? AND password = ?")) { $stmt->bind_param("ss", $username, md5($pass . $this->salt)); $stmt->execute(); $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->close(); return true; } else { $stmt->close(); return false; } } else { die("Error: can't prepare mysql"); } } function checkLogStatus() { if (isset($_SESSION['loggedin'])) { return true; } else { return false; } } function logout() { session_destroy(); session_start(); } }<file_sep><!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" href="views/style.css"/> </head> <body> <h1>Смена пароля</h1> <div id="content"> <form action="" method="post"> <div> <?php echo $this->getData('name'); ?> <?php $alerts = $this->getAlerts(); if ($alerts != ''){ echo '<ul class="alerts">' . $alerts . '</ul>';} ?> <div class="row"> <label for="username">Логин: </label> <input type="text" name="name" value="<?php echo $this->getData('input_name'); ?>"/> <div class="error"><? echo $this->getData('error_user'); ?></div> </div> <div class="row"> <label for="current_pass">Текущий пароль: </label> <input type="password" name="current_pass" value="<?php echo $this->getData('inputCurrent'); ?>"/> <div class="error"><? echo $this->getData('error_current'); ?></div> </div> <div class="row"> <label for="password">Новый пароль: *</label> <input type="password" name="password" value="<?php echo $this->getData('input_pass'); ?>"/> <div class="error"><? echo $this->getData('error_pass'); ?></div> </div> <div class="row"> <label for="password2">Повторить пароль *</label> <input type="password" name="password2" value="<?php echo $this->getData('input_pass2'); ?>"/> <div class="error"><? echo $this->getData('error_pass2'); ?></div> </div> <div class="row"> <p class="required">* обязательно</p> <input type="submit" name="submit" class="submit" value="ОК"/> <p> <a href="logout.php">Выйти</a> </p> </div> </div> </form> <div class="row"> </div> </div> </body> </html><file_sep><!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" href="views/style.css"/> </head> <body> <h1>LOG IN OOP + MVC</h1> <div id="content"> <form action="" method="post"> <div> <?php echo $this->getData('name'); ?> <?php $alerts = $this->getAlerts(); if ($alerts != ''){ echo '<ul class="alerts">' . $alerts . '</ul>';} ?> <div class="row"> <label for="username">Username: *</label> <input type="text" name="username" value="<?php echo $this->getData('input_user'); ?>"/> <div class="error"><? echo $this->getData('error_user'); ?></div> </div> <div class="row"> <label for="password">Password: *</label> <input type="<PASSWORD>" name="password" value="<?php echo $this->getData('input_pass'); ?>"/> <div class="error"><? echo $this->getData('error_pass'); ?></div> </div> <div class="row"> <a href="../files/my_source.zip">Скачать мои исходники</a> </div> <div class="row"> <p class="required">для доступа использовать логин - 'temp' пароль 'temp' </p> <input type="submit" name="submit" class="submit" value="Log In"/> </div> </div> </form> </div> </body> </html><file_sep><? include("includes/init.php"); session_start(); //check authorization if ($Auth->checkLogStatus() == false) { $Template->setAlert('Вы не авторизированы', 'error'); $Template->redirect('login.php'); } else { $Template->load('views/v_members.php'); }<file_sep><?php include("includes/init.php"); //log out $Auth->logout(); //redirect $Template->setAlert('Вы успешно разлогились'); $Template->redirect('login.php');<file_sep><? /* * config.php */ //user auth $config['salt'] = '<PASSWORD>'; $config['session_timeout'] = 500;//seconds //error report mysqli_report(MYSQLI_REPORT_ERROR); function is_admin() { if ($_SESSION['type'] == 'admin') { return true; } else { return false; } } ?> <file_sep><?php class Template { private $data; private $alertTypes; function load($url) { include($url); } function redirect($url) { header("Location: $url"); } /* * get or set data */ function setData($name, $value) { $this->data[$name]= htmlentities($value, ENT_QUOTES); } function getData($name) { if (isset($this->data[$name])) { return $this->data[$name]; } else { return ''; } } /* * get / set alerts */ function setAlertTypes($types) { $this->alertTypes = $types; } function setAlert($value, $type = null) { if ($type == '') { $type = $this->alertTypes[0]; } $_SESSION[$type][] = $value; } function getAlerts() { $data = ''; foreach($this->alertTypes as $alert) { if (isset($_SESSION[$alert])) { foreach($_SESSION[$alert] as $value) { $data .= '<li class="'. $alert . '">' . $value . '</li>'; } unset($_SESSION[$alert]); } } return $data; } }
2605749de254b6683ed54b06d99a100a88337afd
[ "PHP" ]
14
PHP
riderby/mvc-login-system
3de2730fc698ae559e59a3f8245cde443905fc05
43eba9b0b364f3545aab5a993dd99b6118913f92
refs/heads/master
<file_sep>#include <stdio.h> #include <math.h> float calculaDistancia(int x1, int y1, int x2, int y2){ return sqrt(pow(x2-x1,2) + pow(y2-y1,2)); int main() { int x1, y1, x2, y2; float distancia; printf("Informe as coordenadas do ponto A"); scanf("%i %i", &x1, &y1); printf("Informe as coordenadas do ponto B"); scanf("%i %i", &x2, &y2); distancia = calculaDistancia(x1,y1,x2,y2); printf("Distancia: %f", distancia); }
bf1016455d96db9e27d21a313ebce3529bb3d111
[ "C" ]
1
C
DiRenan/Projeto-Teste
2405f9bc929f5104ab9bf21e5f70a12a82cc7e68
e0499b141144723b7cfb0618534bda4b589fbc91
refs/heads/master
<repo_name>gusssar/table-gms<file_sep>/src/components/StringTable/index.js import React,{Component} from 'react' class StringTable extends Component{ render(){ const {obj} = this.props; return( <tr> <td> {obj.Name} </td> <td> {obj.Email} </td> <td> {obj.Phone} </td> <td> {obj.Company} </td> </tr> ) } } export default StringTable;
fb2595f5d93c0a55fa8bc135a164b70f54b4a22f
[ "JavaScript" ]
1
JavaScript
gusssar/table-gms
0ff15d0d9fd247a77924404e4d396de291e8304b
e66ba4b7d397e6b8b6cb981cbcc5ce507601e536
refs/heads/main
<file_sep>let btn = document.getElementById('btn'); let wave = document.getElementById('wave'); let ship = document.getElementById('ship'); let text = document.getElementById('text'); let Username = document.getElementById('Username'); let number = document.getElementById('number'); let rollNumber = document.getElementById('rollNumber'); btn.addEventListener("click" , ()=>{ // alert('hi'); if(rollNumber.value && number.value && Username.value ){ wave.classList.toggle('show'); ship.classList.toggle('show'); alert("Successfully submitted"); } else{ alert("Please fill the required details"); } getdataHere(); text.value=''; Username.value=''; number.value=''; rollNumber.value=''; }); // Temp storage // let str = []; const getdataHere = () =>{ const obj = [ { Username: Username.value, number: number.value, roll: rollNumber.value, message: text.value } ]; if( localStorage.getItem('data') === null){ let str = []; str.push([obj]); localStorage.setItem('data',JSON.stringify(str)); } else{ let newList =localStorage.getItem('data'); str = JSON.parse(newList); str.push(obj); // str.country = "str"; localStorage.setItem('data',JSON.stringify(str)); } }
6fc370e57e490e03865cd27ce7bbee84b58ca1ee
[ "JavaScript" ]
1
JavaScript
nancygos/TripForm
6df1fb8e1ac5ca21e26ce02838b43565a323dd8e
7fe732fdd02d0a2415b1e79437c6b7be171d9604
refs/heads/master
<repo_name>NorbertasL/TicTacToePy<file_sep>/Run.py class ScoreTracker: # Scoring class # Positive score is X, negative score is 0 # When a score of |3| a winner is announced grind = [[None, None, None], [None, None, None], [None, None, None]] def __init__(self): self.row = [0, 0, 0] self.col = [0, 0, 0] self.diag = [0, 0] def add_score(self, x, y, _player): player_value = 1 if _player == 'X' else -1 self.row[x-1] += player_value self.col[y-1] += player_value if x in (1, 3): if y == x: self.diag[0] += player_value elif y in (1, 3): self.diag[1] += player_value if x == 2 and y == 2: self.diag[0] += player_value self.diag[1] += player_value for r in self.row: if abs(r) == 3: return "X" if r == 3 else "O" for c in self.col: if abs(c) == 3: return "X" if c == 3 else "O" for d in self.diag: if abs(d) == 3: return "X" if d == 3 else "O" return None # Main Game Class score_tracker = ScoreTracker() def print_grid(grid): for i in grid: for j in i: if j is None: print(" ", end='') else: print(j, end='') print("|", end='') # New Line print("") def quit_game(): print("Thank you for playing Tic-Tac-Toe-Py") exit() print("Welcome To Tic-Tac-Toe-Py") if input("For rules press H, to start the game press any other key: ").lower() == "h": print("Rules are simple...") print("Get 3 of you symbol in a row vertically/horizontally or diagonally and you win") print("To select a box just enter the coordinates of the box starting from 1 1 at the top left corner") print("And ending on 3 3 at the bottom right corner") if input("Press any kay to continue or Q to quit: ").lower() == "q": quit_game() # Max turns a game can have is 9 for i in range(1, 9): # Odd turn is X, even is O player = 'O' if i % 2 == 0 else 'X' print(player, " turn") print_grid(score_tracker.grind) validInput = False while not validInput: try: user_input = [int(x) for x in input("Enter the square you want to use: ").split()] if len(user_input) != 2: raise ValueError if not 0 < user_input[0] < 4 or not 0 < user_input[1] < 4: raise ValueError if score_tracker.grind[user_input[0] - 1][user_input[1] - 1] is not None: print("Grid space occupied, please try again") continue except ValueError as e: print("Bad Value please try again, you can only use values 1-3 inclusive") print("Used x y format for the coordinate separated by space") print("Example: 2 3") continue validInput = True score_tracker.grind[user_input[0] - 1][user_input[1] - 1] = player print(player, " has picked: ", user_input, "\n") winner = score_tracker.add_score(user_input[0], user_input[1], player) if winner is not None: print_grid(score_tracker.grind) print("The winner is player ", winner, "!!!!!") break
ee12e1987de09e2563b424c887ede8710381cb15
[ "Python" ]
1
Python
NorbertasL/TicTacToePy
2a01fc2261754e79bfb9d03b1f8d978730214303
e9995292dbcb5103e19a0de517f6bf99212378d0
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "sqlite3.h" #define CREATE_TABLE_PERSONA \ "CREATE TABLE IF NOT EXISTS persona " \ "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" \ ", nombre TEXT NOT NULL" \ ", edad INTEGER NOT NULL)" typedef struct Persona Persona; struct Persona { char nombre[500]; int edad; int id; Persona *siguiente; }; void muestraLista(const Persona *lista) { if (lista == NULL) { printf("[Lista vacia]\n"); return; } Persona *ix = lista; while (ix != NULL) { printf("ID: %d;Nombre: %s;Edad: %d\n", ix->id, ix->nombre, ix->edad); ix = ix->siguiente; } } Persona *personaNueva(const Persona *persona) { Persona *p = (Persona *) malloc(sizeof(Persona)); strcpy(p->nombre, persona->nombre); p->edad = persona->edad; p->id = persona->id; p->siguiente = NULL; return p; } void agregaPersona(Persona **lista, const Persona *persona) { if (lista == NULL) { return; } if (*lista == NULL) { *lista = personaNueva(persona); return; } Persona *ix = *lista; while (ix->siguiente != NULL) { ix = ix->siguiente; } ix->siguiente = personaNueva(persona); } int gestionaError(sqlite3 *db) { fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db)); return sqlite3_errcode(db); } void introduceDatos(const Persona *lista, sqlite3 *db) { if (lista == NULL) { return; } Persona *ix = lista; char sql[100]; while (ix != NULL) { sprintf(sql, "INSERT INTO persona (nombre, edad) VALUES ('%s', %d)", ix->nombre, ix->edad); if (sqlite3_exec(db, sql, NULL, NULL, NULL) != SQLITE_OK) { gestionaError(db); return; } ix = ix->siguiente; } } int callback(void *ptr, int numeroDeColumnas, char **valoresCeldas, char **nombresDeColumnas) { (void) ptr; int ix; for (ix = 0; ix < numeroDeColumnas; ++ix) { printf("%s: %s\n", nombresDeColumnas[ix], valoresCeldas[ix]); } printf("\n"); return 0; } void leeBaseDatos(sqlite3 *db) { sqlite3_exec(db, "SELECT * FROM persona", callback, NULL, NULL); } int main(void) { FILE *file = NULL; Persona persona; Persona *lista = NULL; sqlite3 *db = NULL; const char *filenameDatabase = "C:/users/cedo/desktop/MiBaseDatos.db"; const char *filenameLista = "C:/users/cedo/desktop/datos.txt"; persona.id = -1; // abre base de datos if (sqlite3_open(filenameDatabase, &db) != SQLITE_OK) { return gestionaError(db); } // configura base de datos if (sqlite3_exec(db, CREATE_TABLE_PERSONA, NULL, NULL, NULL) != SQLITE_OK) { return gestionaError(db); } // lee lista file = fopen(filenameLista, "r"); if (file != NULL) { while (!feof(file)) { fscanf(file, "%s%d", persona.nombre, &persona.edad); agregaPersona(&lista, &persona); } fclose(file); } else { fprintf(stderr, "Error de archivo\n"); } muestraLista(lista); // introduce datos a la base de datos introduceDatos(lista, db); // lectura de base de datos leeBaseDatos(db); // cerramos sqlite sqlite3_close(db); return 0; }
ff6dd28156401b88abf59a1a03ff2a0707449cac
[ "C" ]
1
C
cedoduarte/EjemploBaseDatosSQLite
af11a581c247350ee6f5298d0e08ad837494da96
3dca09b2e95b235ccb00ac46d5d5e9ccad4a756a
refs/heads/master
<file_sep>var bio = { 'name': '<NAME>', 'role': 'Software Developer', 'contacts': { 'mobile': '(319) 331-4863', 'email': '<EMAIL>', 'github': 'mullans', 'location': 'Iowa City, IA' }, 'welcomeMessage': 'Hi, my name is Sean!', 'skills': ['JS', 'CSS', 'HTML', 'Responsive Web Design', 'Objective-C (OSX and iOS)', 'Swift', 'Java', 'Python', 'Adobe Creative Suite'], 'biopic': 'images/myPhoto.jpg', display: function() { var formattedName = HTMLheaderName.replace('%data%', bio.name); $('.header-top').append(formattedName); var formattedRole = HTMLheaderRole.replace('%data%', bio.role); $('.header-top').append(formattedRole); var formattedBioPic = HTMLbioPic.replace('%data%', bio.biopic); $('#header').append(formattedBioPic); var formattedWelcomeMsg = HTMLwelcomeMsg.replace('%data%', bio.welcomeMessage); $('#header').append(formattedWelcomeMsg); var formattedMobile = HTMLmobile.replace('%data%', bio.contacts.mobile); var formattedEmail = HTMLemail.replace('%data%', bio.contacts.email); var formattedGithub = HTMLgithub.replace('%data%', bio.contacts.github); var formattedLocation = HTMLlocation.replace('%data%', bio.contacts.location); $('#topContacts, #footerContacts').append(formattedMobile + formattedEmail + formattedGithub + formattedLocation); if (bio.skills.length > 0) { $('#header').append(HTMLskillsStart); var formattedSkill; for (var i = 0; i < bio.skills.length; i++) { formattedSkill = HTMLskills.replace('%data%', bio.skills[i]); $('#skills').append(formattedSkill); } } } }; var education = { 'schools': [{ 'name': '<NAME>', 'location': 'Northfield, MN', 'degree': 'Bachelor of Arts', 'majors': ['Computer Science'], 'minors': ['Cognitive Science'], 'dates': '2012 - 2016', 'url': 'http://www.carleton.edu' }], 'onlineCourses': [{ 'title': 'Front End Web Developer', 'school': 'Udacity', 'dates': '2016', 'url': 'https://www.udacity.com/course/front-end-web-developer-nanodegree--nd001' }], display: function() { for (var index = 0; index < education.schools.length; index++) { var school = education.schools[index]; var node = $(HTMLschoolStart); $('#education').append(node); var formattedName = HTMLschoolName.replace('%data%', school.name); formattedName = formattedName.replace('#', school.url); var formattedDegree = HTMLschoolDegree.replace('%data%', school.degree); node.append(formattedName + formattedDegree); var formattedDates = HTMLschoolDates.replace('%data%', school.dates); node.append(formattedDates); var formattedLocation = HTMLschoolLocation.replace('%data%', school.location); node.append(formattedLocation); for (var majorIndex = 0; majorIndex < school.majors.length; majorIndex++) { var formattedMajor = HTMLschoolMajor.replace('%data%', school.majors[majorIndex]); node.append(formattedMajor); } for (var minorIndex = 0; minorIndex < school.minors.length; minorIndex++) { var formattedMinor = '<em><br>Minor: %data%</em>'.replace('%data%', school.minors[minorIndex]); node.append(formattedMinor); } } if (education.onlineCourses.length !== 0) { $('#education').append(HTMLonlineClasses); } for (var onlineIndex = 0; onlineIndex < education.onlineCourses.length; onlineIndex++) { var onlineNode = $(HTMLschoolStart); $('#education').append(onlineNode); var onlineSchool = education.onlineCourses[onlineIndex]; var formattedOnlineTitle = HTMLonlineTitle.replace('%data%', onlineSchool.title); formattedOnlineTitle = formattedOnlineTitle.replace('#', 'https://www.udacity.com/'); formattedOnlineSchool = HTMLonlineSchool.replace('%data%', onlineSchool.school); onlineNode.append(formattedOnlineTitle + formattedOnlineSchool); var formattedOnlineDates = HTMLonlineDates.replace('%data%', onlineSchool.dates); onlineNode.append(formattedOnlineDates); var formattedOnlineURL = HTMLonlineURL.replace('%data%', onlineSchool.url); onlineNode.append(formattedOnlineURL); } } }; var work = { 'jobs': [{ 'employer': 'Sil<NAME> LLC', 'title': 'Founder', 'location': 'Iowa City, Iowa', 'dates': 'June 2013 - Present', 'description': 'Founded the company in the state of Iowa. Consulted and assisted with digitizing records for Kylemore Center LLC. Developed a POS/Inventory management application for Kylemore Center LLC.' }, { 'employer': '<NAME>', 'title': 'Assisstant to the Academic Technologist', 'location': 'Northfield, MN', 'dates': 'June 2014 - June 2015', 'description': 'Used Python and Objective-C to work with data management and refinement projects. Created a web-to-pdf archiving system for Carleton’s Moodle course pages. Used Python to clean data from Carleton digital library archives. Developed an application to split an image archive based on blank TIFF images into individual segments.' }, { 'employer': '<NAME>', 'title': 'Grader', 'location': 'Northfield, MN', 'dates': 'March 2015 - June 2016', 'description': 'Chosen to grade assignments for Evolutionary Computing, Introduction to Computer Science, Data Structures, Natural Language Processing, and Operating System classes from the Spring 2015 term to the Spring 2016 term based on familiarity with the relevant coursework.' }, { 'employer': '<NAME>', 'title': 'Technical Intern', 'location': 'San Francisco, CA', 'dates': 'November 2015 - December 2015', 'description': 'Worked as part of a front-end development team for the Stroll Health website. Worked on investor research for Series A funding.' }, { 'employer': 'QCI', 'title': 'Test Automation Developer', 'location': 'Des Moines, IA', 'dates': 'September 2016 - Present', 'description': 'Test automation developer contracted by QCI to work with <NAME> on extending the existing application that supports the Global Field Seed Management processes. Work including taking part as a member of a Scrum team, working with the QA test lead and the team tech lead to identify test scripts to automate new development. ' }], display: function() { var formattedEmployer; var formattedTitle; var formattedLocation; var formattedDates; var formattedDescription; for (var job = 0; job < work.jobs.length; job++) { $('#workExperience').append(HTMLworkStart); formattedEmployer = HTMLworkEmployer.replace('%data%', work.jobs[job].employer); formattedTitle = HTMLworkTitle.replace('%data%', work.jobs[job].title); formattedLocation = HTMLworkLocation.replace('%data%', work.jobs[job].location); formattedDates = HTMLworkDates.replace('%data%', work.jobs[job].dates); formattedDescription = HTMLworkDescription.replace('%data%', work.jobs[job].description); $('.work-entry:last').append(formattedEmployer + formattedTitle); $('.work-entry:last').append(formattedLocation); $('.work-entry:last').append(formattedDates); $('.work-entry:last').append(formattedDescription); } } }; var projects = { 'projects': [{ 'title': 'upwardPOS', 'dates': 'July 2015 - Present', 'description': 'An integrated inventory and POS system for small businesses. Tracks invoices, clients, inventory, and can handle payments by connecting the user\'s Stripe account.', 'images': ['images/Upward.png'], 'url': 'http://upwardpos.com' }, { 'title': 'Text to Speech', 'dates': 'October 2015', 'description': 'Written in Java as a final project for a Natural Language Processing course, this program takes in text and converts it into spoken phonemes. This program uses the Carnegie Mellon phoneme dictionary for known words, but also has an algorithm that lets it pronounce any gibberish that is entered as well.', 'images': ['images/typewriter.jpg'], 'url': 'https://github.com/Mullans/NLPFinal' }, { 'title': 'Evolutionary Stock Trader', 'dates': 'February 2016 - March 2016', 'description': 'A genetic algorithm to trade S&P500 stocks. Uses genetically created and refined decision trees to optimize stock trading using a variety of different features of the stocks and their companies over the course of a variable period of trading time. It is in Java and utilizes the jpgpp library for genetic algorithms. This was made as my senior project at Carleton College and was written as a team of 3 people.', 'images': ['images/stocks.jpg'], 'url': 'https://github.com/tdquang/Genetic-Programming-Stock-Trading' }, { 'title': 'Lithograph Generator', 'dates': 'January 2014', 'description': 'Takes in an image and either entered text or text file, then overlays the text on the image to create a beautiful lithographic picture. This was written in Java and was written purely for the fun of making it.', 'images': ['images/words.jpg'], 'url': 'https://github.com/Mullans/Lithograph' }], display: function() { for (var index = 0; index < projects.projects.length; index++) { $('#projects').append(HTMLprojectStart); var project = projects.projects[index]; var formattedTitle = HTMLprojectTitle.replace('%data%', project.title); formattedTitle = formattedTitle.replace('#', project.url); var formattedDates = HTMLprojectDates.replace('%data%', project.dates); var formattedDescription = HTMLprojectDescription.replace('%data%', project.description); $('.project-entry:last').append(formattedTitle); $('.project-entry:last').append(formattedDates); $('.project-entry:last').append(formattedDescription); for (var imageIndex = 0; imageIndex < project.images.length; imageIndex++) { var formattedImage = HTMLprojectImage.replace('%data%', project.images[imageIndex]); $('.project-entry:last').append(formattedImage); } } } }; bio.display(); work.display(); education.display(); projects.display(); $('#mapDiv').append(googleMap);
a5400a59f99cc1c92e6619de69cf2233d30ccd5f
[ "JavaScript" ]
1
JavaScript
Mullans/frontend-nanodegree-resume
9188bdc8997ff5b8471f0023a18174b4dd5ac789
8cef722c8b54165efb143d2b45cfe7c972eb2edd
refs/heads/master
<repo_name>drat/sharedcount-daily-reports<file_sep>/scripts/sharedcount.py #!/usr/bin/python import sys, os, getopt, csv, datetime, errno from datetime import timedelta import xml.dom.minidom as minidom import urllib, urllib2, socket import json, re, string from urlparse import urlparse def fetch_sitemap_url( url, domains, limit, i=0 ) : print url + '...' urls = {} xml = urllib2.urlopen( url ) sitemap = minidom.parse(xml) links = sitemap.getElementsByTagName("loc") for link in links : if limit is None or i < limit : i += 1 url = str( link.firstChild.data ) if url.endswith('.xml') : urls.update( fetch_sitemap_url(url, domains, limit, i) ) else : u = urlparse(url) page = u.path + u.params + u.query; scheme = u.scheme urls[ page ] = [] for domain in domains : url_variant = scheme+'://'+domain+page urls[ page ].append( url_variant ) if scheme is not 'https' and check_https : ssl_variant = 'https://'+domain+page urls[ page ].append( ssl_variant ) return urls def get_urls_list( sitemaps, domains, limit ) : urls = {} for sitemap_url in sitemaps : urls.update( fetch_sitemap_url(sitemap_url, domains, limit) ) return urls def check_args(argv) : global project_name, sitemaps, domains, limit, output_dir, apikey, force, yesterday, check_https def usage_and_die() : print 'sharedcount.py --name=project_name --apikey=xxxxx --domains=foo.be,www.foo.be,mirror.foo.fr --sitemap=sitemap_url[,sitemap2.url] [--output-dir=dirname] [--force] [--limit=n] [--yesterday]' sys.exit( errno.EINVAL ) try: opts, args = getopt.getopt( argv, "c:n:d:s:o:l:k:", ["name=", "apikey=", "domains=", "sitemap=", "output-dir=", "limit=", "force", "yesterday", "https"] ) except getopt.GetoptError as err: sys.stderr.write( str(err)+'\n' ) usage_and_die() for opt, arg in opts: if opt in ("-h", "--help"): usage_and_die() elif opt in ("-n", "--name") : project_name = arg elif opt in ("-k", "--apikey") : apikey = arg elif opt in ("-d", "--domains") : domains = string.split(arg, ',') elif opt in ("-s", "--sitemap") : sitemaps = string.split(arg, ',') elif opt in ("-o", "--output-dir") : output_dir = arg.strip('/') elif opt in ("-l", "--limit") : limit = int(arg) elif opt == '--force' : force = True elif opt == '--yesterday' : yesterday = True elif opt == '--https' : check_https = True if sitemaps is [] or domains is [] or project_name is None or apikey is None : usage_and_die() def get_csv(create=True) : global output_dir, project_name, metrics folder = output_dir+'/'+project_name if not os.path.exists( folder ) : os.makedirs( folder ) csv_file = folder+'/'+project_name+'.csv' if create and not os.path.isfile( csv_file ) : print 'Create ' + csv_file + '...' writer = csv.writer( open(csv_file, 'wb') ) writer.writerow( ['Date', 'Page'] + metrics ) return csv_file def csv_needs_update() : csv_file = get_csv() tmp_file = 'tmp_'+project_name+'.csv' reader = csv.reader( open(csv_file, 'rb'), delimiter=',' ) next(reader, None) # skip header last_date = None for row in reader : last_date = row[0] needs_update = last_date is None or datetime.date.today() > datetime.datetime.strptime(last_date, "%d/%m/%y").date() if not needs_update and force : # remove today's entries in csv reader = csv.reader( open(get_csv(), 'rb'), delimiter=',' ) writer = csv.writer( open(tmp_file, 'wb') ) for row in reader : if ( row[0] != last_date ) : writer.writerow( row ) os.rename( tmp_file, get_csv(False) ) needs_update = True return needs_update def get_cumulative_stats() : previous = {} reader = csv.reader( open(get_csv(), 'rb'), delimiter=',' ) next(reader, None) # skip header for row in reader : page = row[1] stats = map(int, row[2:]) if previous.has_key( page ) : previous[page] = [ sum(x) for x in zip(previous[page], stats) ] else : previous[page] = stats return previous def get_quota() : global apikey req = "http://plus.sharedcount.com/quota?apikey="+apikey stream = urllib2.urlopen( req ) data = json.load( stream ) used = data['quota_used_today'] remaining = data['quota_remaining_today'] return used, remaining import time from functools import wraps def retry( ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None ): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ExceptionToCheck: the exception to check. may be a tuple of exceptions to check :type ExceptionToCheck: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int :param logger: logger to use. If None, print :type logger: logging.Logger instance """ def deco_retry(f): def f_retry(*args, **kwargs): mtries, mdelay = tries, delay while mtries > 0: try: return f(*args, **kwargs) except ExceptionToCheck, e: print "%s, Retrying in %d seconds..." % (str(e), mdelay) time.sleep(mdelay) mtries -= 1 mdelay *= backoff lastException = e raise lastException return f_retry return deco_retry def fetch_sharedcount_data( urls ) : global result, apikey @retry( urllib2.URLError, tries=3, delay=5, backoff=1.5 ) def urlopen_with_retry( url ) : return urllib2.urlopen( url, timeout=60 ) def sharedcount_data( url ) : print url req = "http://plus.sharedcount.com/?url="+url+"&apikey="+apikey try : stream = urlopen_with_retry( req ) data = json.load( stream ) return data except urllib2.URLError as e: print '!!!!!! URL error !' return False except socket.timeout as e: print '!!!!!! Timeout error !' return False for page, variants in urls.items() : for variant in variants : data = sharedcount_data( variant ) if data : result[page]['FB comments'] += int( data['Facebook']['comment_count'] ) result[page]['FB likes'] += int( data['Facebook']['like_count'] ) result[page]['FB shares'] += int( data['Facebook']['share_count'] ) result[page]['Tweets'] += int( data['Twitter'] ) result[page]['Google+ shares'] += int( data['GooglePlusOne'] ) result[page]['Linkedin shares'] += int( data['LinkedIn'] ) result[page]['Pinterest pins'] += int( data['Pinterest'] ) def main(argv) : global domains, sitemaps, project_name, limit, output_dir, result, metrics, yesterday # CHECK PARAMETERS check_args( argv ) today = datetime.date.today().strftime("%d/%m/%y") if yesterday : today = ( datetime.date.today() - timedelta(days=1) ).strftime("%d/%m/%y") # DO WE NEED AN UPDATE ? if not csv_needs_update() : print 'CSV file is up to date, abort.' sys.exit( errno.EPERM ) # CALCULATE CUMULATIVE PREVIOUS RESULTS previous = get_cumulative_stats() # GET URLS FROM SITEMAP print 'Fetching sitemaps...' urls = get_urls_list( sitemaps, domains, limit ) print str(len(urls)) + ' links found.' # CHECK WE HAVE ENOUGH QUOTA FOR TODAY used, remaining = get_quota() if remaining < len(urls) : sys.stderr.write( 'Remaining quota ('+str(remaining)+') too small for request ('+str(len(urls))+' urls), exit.\n' ) sys.exit( errno.EDQUOT ) # INIT RESULTS for page in urls.keys() : stats = [0] * len(metrics) if ( previous.has_key(page) ) : stats = previous.get(page) stats = map( lambda k : -int(k), stats ) result[page] = dict( zip( metrics, stats ) ) # FETCH TODAY RESULTS print '\nFetching sharedcount results for '+str(len(urls))+' urls...' fetch_sharedcount_data( urls ) # APPEND TODAY RESULTS TO CSV print 'Updating CSV file...' f = open( get_csv(), 'ab' ) writer = csv.writer(f) for page, data in result.items() : row = [ today, page ] # date, page for metric in metrics : row.append( data[metric] ) writer.writerow( row ) f.close() # DISPLAY REMAINING QUOTA used, remaining = get_quota() print 'Finished, '+str(used)+' quota used today, '+str(remaining)+' quota remaining for today.' if __name__ == "__main__": limit = None force = False yesterday = False check_https = False sitemaps = [] project_name = None domains = [] output_dir = '.' apikey = None result = {} metrics = ['FB likes', 'FB shares', 'FB comments', 'Tweets', 'Google+ shares', 'Linkedin shares', 'Pinterest pins' ] main( sys.argv[1:] ) <file_sep>/do_it.py #!/usr/bin/python import json import subprocess if __name__ == "__main__": projects = json.loads( open('projects.json').read() ) options = json.loads( open('options.json').read() ) # SHAREDCOUNT API KEY APIKEY = str( options['sharedcount']['apikey'] ) # FETCH SHAREDCOUNT STATS for name, project in projects.items() : domains = ','.join( map( lambda s: str(s), project['domains'] ) ) sitemaps = ','.join( map( lambda s: str(s), project['sitemaps'] ) ) check_https = 'https' in project and project['https'] is True stats_cmd = 'python scripts/sharedcount.py' stats_cmd += ' --name=' + name stats_cmd += ' --sitemap=' + sitemaps stats_cmd += ' --domains=' + domains if check_https : stats_cmd += ' --https' stats_cmd += ' --output-dir=output/' stats_cmd += ' --apikey=' + APIKEY stats_cmd += ' --force' project['process'] = subprocess.Popen( stats_cmd, shell=True ) for name, project in projects.items() : project['exit_code'] = project['process'].wait() for name, project in projects.items() : if project['exit_code'] == 0 : print 'ok.' <file_sep>/README.md # Installation ```sh $ mv options.json.example options.json # Enter your Sharedcount API key ``` # Usage ## Manually Create CSV for today : ```sh $ python scripts/sharecount.py --apikey=xxxx --sitemap=http://website.com/fr/sitemap.xml,http://website.com/en/sitemap.xml --domains=website.com,www.website.com --name=website-name --output-dir=output/ ``` ## Projects presets ```sh $ mv projects.json.example projects.json # Enter here all the projects options ``` Runs the script for projects listed in `projets.json` : ```sh $ python ./do_it.py ``` This fetches social data and uploads it to tableau, according to the options listed in `options.json`. ## Cron schedule Schedule automatic fetch each day at 23:30 : ```sh $ crontab -e ``` ```sh MAILTO=<EMAIL> 30 23 * * * cd /path/to/app ; python do_it.py ```
8099472293cc386a118245fc9048b6ae1cd42edd
[ "Markdown", "Python" ]
3
Python
drat/sharedcount-daily-reports
5c812482c178224fa6eb5c41dc57a21cace54943
d878832ed552784d90b27a139ab69ee215770c4e
refs/heads/main
<repo_name>katevoskresenska/perfsys_test<file_sep>/api_files/postblobs.py import json import os import uuid import boto3 from botocore.client import Config from botocore.exceptions import ClientError dynamodb_client = boto3.client("dynamodb") BLOBS_TABLE = os.environ["BLOBS_TABLE"] response_bad_request = {"statusCode": 400, "body": json.dumps({"error": "Invalid callback url supplied"})} def _upload_url(uuid): clients = boto3.client("s3", config=Config(signature_version="s3v4"), region_name=os.environ["REGION_NAME"], aws_access_key_id=os.environ["ACCESS_KEY"], aws_secret_access_key=os.environ["SECRET_KEY"]) try: url = clients.generate_presigned_url( ClientMethod="put_object", Params={"Bucket": os.environ["BUCKET"], "Key": uuid}, ExpiresIn=1800) return url except ClientError as e: return e def create_blob(event, context): event_body = event.get("body") if not event_body: return response_bad_request request_body = json.loads(event_body) callback_url = request_body.get("callback_url") if not callback_url: return response_bad_request blob_id = str(uuid.uuid4()) dynamodb_client.put_item( TableName=BLOBS_TABLE, Item={"id": {"S": blob_id}, "callback_url": {"S": callback_url}} ) upload_url_create = _upload_url(uuid=blob_id) body = { "blob_id": blob_id, "callback_url": callback_url, "upload_url": upload_url_create } return { "statusCode": 201, "body": json.dumps(body) } <file_sep>/api_files/callbacks.py import requests callback_headers = {"Content-Type": "application/json"} def db_record_updated(event, _): print(event) for record in event.get("Records"): if record.get("eventName") != "MODIFY": continue blob = record.get("dynamodb").get("NewImage") labels_record = blob.get("labels") if not labels_record: continue labels = labels_record.get("S") callback_url = blob.get("callback_url").get("S") requests.post(url=callback_url, data=labels, headers=callback_headers) <file_sep>/api_files/rekognition_servicess.py import json import os import boto3 dynamodb_client = boto3.client("dynamodb") BLOBS_TABLE = os.environ["BLOBS_TABLE"] def _process_blob(uuid): client = boto3.client("rekognition", region_name= os.environ["REGION_NAME"], aws_access_key_id=os.environ["ACCESS_KEY"], aws_secret_access_key=os.environ["SECRET_KEY"] ) response = client.detect_labels( Image={ "S3Object": { "Bucket": os.environ["BUCKET"], 'Name': uuid } }, MaxLabels=200, MinConfidence=20 ) return response def uploaded_file(event, _): blob_id = event["Records"][0]["s3"]["object"]["key"] recognition_result = _process_blob(uuid=blob_id) _update_db_unit(blob_id=blob_id, labels=recognition_result.get("Labels")) def _update_db_unit(labels, blob_id): projections = [] for label in labels: parents = [] for parent in label.get("Parents"): parents.append(parent.get("Name")) projections.append({ "label": label.get("Name"), "confidence": label.get("Confidence"), "parents": parents }) projections_data = json.dumps(projections) dynamodb_client.update_item( TableName=BLOBS_TABLE, Key={ "id": {"S": blob_id} }, UpdateExpression="set labels=:value", ExpressionAttributeValues={ ":value": {"S": projections_data} } ) return projections_data <file_sep>/README.md <!-- title: 'AWS API for recognition of images' layout: Doc framework: v2 platform: AWS language: python authorLink: 'https://github.com/FlyOn21' authorName: '<NAME>' --> # AWS API for recognition of images ## Usage ### Deployment This example is made to work with the Serverless Framework dashboard which includes advanced features like CI/CD, monitoring, metrics, etc. ##MacOS/Linux - Create yourself AWS account using the [link](https://portal.aws.amazon.com/billing/signup?redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation&language=ru_ru#/start). - Use the [tutorial](https://www.serverless.com/framework/docs/providers/aws/guide/credentials/) to create a user. To install the latest version serverless, run this command in your terminal: ``` curl -o- -L https://slss.io/install | bash $ serverless login ``` Install the necessary plugins ``` $ serverless plugin install --name serverless-dotenv-plugin $ serverless plugin install --name serverless-python-requirements $ serverless plugin install --name serverless-s3-remover ``` In the api_files folder, rename the ```example.env``` file to ```.env```, after which we fill in the environment variables necessary for deployment ``` REGION_NAME=deploy_region ACCESS_KEY=your_access_key SECRET_KEY=your_secret_key USER_ARN=arn_your_user ``` > USER_ARN you can find on the page of the user AWS you created. > Launching the deployment api ``` $ serverless deploy ``` After running deploy, you should see output similar to: ```bash Serverless: Packaging service... Serverless: Excluding development dependencies... Serverless: Creating Stack... Serverless: Checking Stack create progress... ........ Serverless: Stack create finished... Serverless: Uploading CloudFormation file to S3... Serverless: Uploading artifacts... Serverless: Uploading service aws-python-rest-api.zip file to S3 (711.23 KB)... Serverless: Validating template... Serverless: Updating Stack... Serverless: Checking Stack update progress... ................................. Serverless: Stack update finished... Service Information service: aws-python-rest-api stage: dev region: us-east-1 stack: aws-python-rest-api-dev resources: 12 api keys: None endpoints: ANY - https://xxxxxxx.execute-api.us-east-1.amazonaws.com/dev/ functions: api: aws-python-rest-api-dev-hello layers: None ``` _Note_: In current form, after deployment, your API is public and can be invoked by anyone. For production deployments, you might want to configure an authorizer. For details on how to do that, refer to [http event docs](https://www.serverless.com/framework/docs/providers/aws/events/apigateway/). ### Invocation After successful deployment, you can call the created application via HTTP: ```bash curl https://xxxxxxx.execute-api.us-east-1.amazonaws.com/dev/ ``` Which should result in response similar to the following (removed `input` content for brevity): ```json { "message": "Go Serverless v2.0! Your function executed successfully!", "input": { } } ``` # Description API This api implements two endpoints - POST .../blobs - GET .../blobs/{blob_id} When use POST endpoint, the request body must contain a callback url where you expect the result of the service Examples: ```bash {"calback_url": "http://your_callback_url.com"} ``` Response API for POST request ```bash { "blob_id": "b1bb07b8-04c6-4f3e-9574-3c1d633f7a8e", "callback_url": "http://your_callback_url.com", "upload_url": "https://blobs.s3.eu-central-1.amazonaws.com/b1bb07b8-04c6-4f3e-9574-3c1d633f7a8e" } ``` >```"blob_id"```: id records in the DynamoDB database where the result of the work will be recorded images recognition ```"callback_url"```: url for callback when the result of image recognition is ready ```"upload_url"```: the link where the client uploaded image for recognition. Put request type. The link is valid for half an hour. > Response API for GET requests ```bash { "blob_id": "b1bb07b8-04c6-4f3e-9574-3c1d633f7a8e", "labels": [ { "label": "Plan", "confidence": 85.03274536132812, "parents": ["Plot"] }, ... ] } ``` > ```"blob_id"```: id of the requested entry in the database >```"labels"```: image recognition results ### API architecture ![API architecture](https://test-task-image-perfsys.s3.eu-central-1.amazonaws.com/Untitled+Diagram.png)
9edda951fc594463e25ae22e3f1edb20f805a53d
[ "Markdown", "Python" ]
4
Python
katevoskresenska/perfsys_test
71adc2ff165afd240242326fac8771039e954e92
52b1d0f42a2a782ed53306e0c7837303dc93bdf7
refs/heads/master
<file_sep>CC = g++ CXXFLAGS = -std=c++11 -Wall -O2 SOURCE_FILES = serv.o http.o event.o conf.o serv : $(SOURCE_FILES) $(CC) -o serv $(SOURCE_FILES) $(CXXFLAGS) %.o:%.cpp $(CC) -c $(CXXFLAGS) -o $@ $< clean: rm *.o rm serv <file_sep>A static HTTP server ==== a HTTP server implementation used by epoll ## Introduction This is a server that parses an HTTP message request and then find the resource(a static file in the configured directory) then responses it to the HTTP client. If not found, return the familiar 404 Not Found status. The accept event and read event are driven by epoll, so the main thread will not block when accepting or reading, which brings higher performance. Epoll are widely used in high performance server. ## Compile and run (only support Linux2.6+) ``` cd src make ./serv open the browser and visit http://127.0.0.1:3000/ ``` ## Thanks Thanks for google and Linux. And thank you for reading.<file_sep>#ifndef _HTTP_H_ #define _HTTP_H_ #include <string> #include <iostream> #include <vector> #include <unordered_map> namespace http { class request { friend request parse(std::string& req_buffer); public: std::string get_protocol() { return protocol;} std::string get_uri_name() const { auto begin = uri.find_first_of("/"); auto end= uri.find_last_of("?"); return uri.substr(begin, end - begin); } private: // Request-Line = Method SP Request-URI SP HTTP-Version CRLF std::string method; std::string uri; std::string protocol; // headers; std::unordered_map<std::string, std::string> headers; // message-body std::string body; }; // class request request parse(std::string& req_buffer); const std::unordered_map<int, std::string> code_msgs = { {200, "OK"}, {403, "Forbidden"}, {404, "Not Found"}, {500, "Internal Server Error"} }; class response; class handler { public: virtual bool do_req(const request& req, response& resp) = 0; }; class info_handler : public handler { public: bool do_req(const request& req, response& resp) override; }; class static_file_handler : public handler { public: static_file_handler(const std::string& root_dir) : root_dir(root_dir){} bool do_req(const request& req, response& resp) override; private: std::string root_dir; }; extern std::vector<http::handler*> req_handlers; class response { friend bool handler::do_req(const request& req, response& resp); friend bool info_handler::do_req(const request& req, response& resp); friend bool static_file_handler::do_req(const request& req, response& resp); public: response(std::string protocol) : protocol(protocol), status(200) {} bool send(int fd); private: std::string protocol; int status; std::vector<std::string> header_keys; std::unordered_map<std::string, std::string> headers; std::string body; }; } // namespace http #endif<file_sep>#include "conf.h" #include <iostream> int PORT; int MAX_EVENT; int BUF_BLOCK_SIZE; int MAX_ESTABLISHED_COUNT; void conf_init() { PORT = 3000; MAX_EVENT = 1000; BUF_BLOCK_SIZE = 512; MAX_ESTABLISHED_COUNT = 100; } <file_sep>// linux // socket setsockopt bind listen accept #include <sys/socket.h> // struct sockaddr_in #include <netinet/in.h> // htonl #include <arpa/inet.h> // epoll_create1 struct epoll_event epoll_ctl epoll_wait #include <sys/epoll.h> // read write close #include <unistd.h> // fcntl #include <fcntl.h> // stdc // memset #include <cstring> // perror #include <cstdio> // errno #include <cerrno> // cout #include <iostream> #include <string> #include <vector> #include "http.h" #include "event.h" #include "conf.h" int main() { conf_init(); int listen_fd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in serv_addr; std::memset(&serv_addr, 0, sizeof(struct sockaddr_in)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(PORT); int on = 1; setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)); bind(listen_fd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr_in)); // max of establishd but not accept connection listen(listen_fd, MAX_ESTABLISHED_COUNT); int epoll_fd = epoll_create1(0); struct epoll_event ev, events[MAX_EVENT]; // add accept event event::accept_event ac_ev(listen_fd, epoll_fd); ev.data.ptr = &ac_ev; ev.events = EPOLLIN; epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &ev); while (true) { int event_cnt = epoll_wait(epoll_fd, events, MAX_EVENT, -1); if (event_cnt <= 0) { std::perror("epoll_wait"); continue; } for (int i = 0; i < event_cnt; i++) { event::event *ready_event = static_cast<event::event*>(events[i].data.ptr); ready_event->deal(); } } }<file_sep>#ifndef _CONF_H_ #define _CONF_H_ #include <string> extern int PORT; extern int MAX_EVENT; extern int BUF_BLOCK_SIZE; extern int MAX_ESTABLISHED_COUNT; void conf_init(); #endif<file_sep>#include <sys/socket.h> #include <fcntl.h> #include <sys/epoll.h> #include <unistd.h> #include <errno.h> #include <cstdio> #include <string> #include "event.h" #include "conf.h" #include "http.h" namespace event { accept_event::accept_event(int listen_fd, int epoll_fd) : _listen_fd(listen_fd), _epoll_fd(epoll_fd){} void accept_event::deal() { int conn_fd = accept(_listen_fd, NULL, NULL); int flags = fcntl(conn_fd, F_GETFL, 0); fcntl(conn_fd, F_SETFL, flags | O_NONBLOCK); read_req_event *read_event = new read_req_event(_epoll_fd, conn_fd); epoll_event ev; ev.events = EPOLLIN; ev.data.ptr = read_event; epoll_ctl(_epoll_fd, EPOLL_CTL_ADD, conn_fd, &ev); } read_req_event::read_req_event(int epoll_fd, int conn_fd) : _epoll_fd(epoll_fd), _conn_fd(conn_fd) {} void read_req_event::deal() { // store http request(include head and body) into the buffer std::string buffer; char block_buffer[BUF_BLOCK_SIZE]; int readn ; while ((readn = read(_conn_fd, block_buffer, BUF_BLOCK_SIZE)) > 0 ) { buffer.append(block_buffer, readn); } if (readn == 0) { close(_conn_fd); epoll_event ev; epoll_ctl(_epoll_fd, EPOLL_CTL_DEL, _conn_fd, &ev); delete this; return ; } else { if (errno == EWOULDBLOCK) { errno = 0; } else { std::perror("read"); } } // parse buffer and get http::reqest; http::request req = http::parse(buffer); http::response resp(req.get_protocol()); for (const auto handler : http::req_handlers) { if (!handler->do_req(req, resp) ) { break; } } resp.send(_conn_fd); close(_conn_fd); delete this; } } // namespace event<file_sep>#include <iostream> #include <sstream> #include <string> #include <ctime> #include <cstdio> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "http.h" #include "conf.h" namespace http { std::vector<http::handler*> req_handlers = { new http::info_handler(), new http::static_file_handler("../html") }; request parse(std::string& req_buffer) { request req; std::istringstream req_in(req_buffer); std::string line; // Request-Line = Method SP Request-URI SP HTTP-Version CRLF // parse request line std::getline(req_in, line); std::istringstream req_line_stream(line); std::getline(req_line_stream, req.method, ' '); std::getline(req_line_stream, req.uri, ' '); std::getline(req_line_stream, req.protocol, ' '); // parse headers std::string header_key, header_val; while (std::getline(req_in, line) && line != "\r") { std::istringstream header_line_stream(line); std::getline(header_line_stream, header_key, ':'); std::getline(header_line_stream, header_val); req.headers[header_key] = header_val; } // parse message body req_in >> req.body; return req; } bool response::send(int fd) { std::string header; std::string tmp_pro = "HTTP/1.1"; header = tmp_pro + " " + std::to_string(status) + " " + code_msgs.at(status) + "\r\n"; for (const auto& h_key : header_keys) { header += h_key + ": " + headers[h_key] + "\r\n"; } header += "\r\n"; int res = write(fd, header.c_str(), header.size()); if (res < 0) { std::perror("write header"); } res = write(fd, body.c_str(), body.size()); if (res < 0) { std::perror("write body"); } return true; } bool info_handler::do_req(const request& req, response& resp) { std::time_t now = std::time(0); std::tm* now_tm = std::localtime(&now); char time_str[30] = {0}; std::strftime(time_str, 30, "%a, %d %b %Y %H:%M:%S GMT", now_tm); resp.header_keys.push_back("Date"); resp.headers["Date"] = std::string(time_str); resp.header_keys.push_back("Server"); resp.headers["Server"] = "Jw-server/0.1"; return true; } // get the static file and put it to the resp.body bool static_file_handler::do_req(const request& req, response& resp) { std::string file_name = req.get_uri_name(); std::string file_path; if (file_name == "/") { file_name = "/index.html"; } file_path = root_dir + file_name; int fd = open(file_path.c_str(), O_RDONLY); if (fd < 0) { resp.status = 404; file_path = root_dir + "/404.html"; fd = open(file_path.c_str(), O_RDONLY); } std::string& buffer = resp.body; char block_buffer[1024]; int readn ; while ((readn = read(fd, block_buffer, 1024)) > 0 ) { buffer.append(block_buffer, readn); } close(fd); return true; } } // namespace http<file_sep>#ifndef _EVENT_H_ #define _EVENT_H_ namespace event { class event { public: virtual void deal(){} virtual ~event() = default; }; // class event // to accept the new connection class accept_event : public event { public: accept_event(int listen_fd, int epoll_fd); virtual void deal() override; ~accept_event() {} private: int _listen_fd; int _epoll_fd; }; // accept_event // to read the tcp message into the buffer and deal the request class read_req_event : public event { public: read_req_event(int epoll_fd, int conn_fd); virtual void deal() override; ~read_req_event() {} private: int _epoll_fd; int _conn_fd; }; } // namespace ev #endif
1dc5ed5d3904fb540244b3a94e24324fa041fe2a
[ "Markdown", "Makefile", "C++" ]
9
Makefile
jwFon/static_server
7599d603538e5c8d3fda165c13c50881ecef3ca7
67761d75c6ec1f0cc26d89eb53292778d23d122c
refs/heads/master
<repo_name>mjyc/tabletrobotface-userstudy<file_sep>/lib/cycle-chartjs.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.mockStreamingChartSource = mockStreamingChartSource; exports.makeStreamingChartDriver = makeStreamingChartDriver; var _xstream = require("xstream"); var _xstream2 = _interopRequireDefault(_xstream); var _chart = require("chart.js"); var _chart2 = _interopRequireDefault(_chart); require("chartjs-plugin-streaming"); var _fromEvent = require("xstream/extra/fromEvent"); var _fromEvent2 = _interopRequireDefault(_fromEvent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function mockStreamingChartSource() { return _xstream2.default.never(); } function makeStreamingChartDriver(config) { var instance = null; // lazy initialize chart on first stream event var createChart = function createChart(el) { var ctx = el.getContext("2d"); instance = new _chart2.default(ctx, config); }; var updateChart = function updateChart(datasets) { if (!instance) { console.warn("Chart is not initialized yet; skipping updating chart"); return; } datasets.map(function (dataset, i) { Object.keys(dataset).map(function (k) { instance.data.datasets[i][k] = dataset[k]; }); }); instance.update({ preservation: true }); }; var addDataset = function addDataset(dataset) { if (!instance) { console.warn("Chart is not initialized yet; skipping adding dataset"); return; } dataset.map(function (data, i) { instance.data.datasets[i].data.push((typeof data === "undefined" ? "undefined" : _typeof(data)) !== "object" ? { x: new Date().getTime(), y: data } : data); }); instance.update({ preservation: true }); }; var createEvent = function createEvent(evName) { if (!instance) { console.error("Chart is not initialized yet; returning null"); return null; } return (0, _fromEvent2.default)(el, evName).filter(function () { return instance; }).map(function (ev) { return instance.getElementsAtEvent(ev); }); }; var streamingChartDriver = function streamingChartDriver(sink$) { sink$.filter(function (s) { return s.type === "CREATE"; }).addListener({ next: function next(s) { return createChart(s.value); } }); sink$.filter(function (s) { return s.type === "UPDATE"; }).addListener({ next: function next(s) { return updateChart(s.value); } }); sink$.filter(function (s) { return s.type === "ADD"; }).addListener({ next: function next(s) { return addDataset(s.value); } }); return { events: createEvent }; }; return streamingChartDriver; }<file_sep>/apps/robot/src/StateChart.js import xs from "xstream"; import { div, canvas, span, input } from "@cycle/dom"; const chartColors = { red: "rgb(255, 99, 132)", orange: "rgb(255, 159, 64)", yellow: "rgb(255, 205, 86)", green: "rgb(75, 192, 192)", blue: "rgb(54, 162, 235)", purple: "rgb(153, 102, 255)", grey: "rgb(201, 203, 207)" }; const color = Chart.helpers.color; export const config = { type: "line", data: { datasets: [ { label: "isVisible", backgroundColor: color(chartColors.red) .alpha(0.5) .rgbString(), borderColor: chartColors.red, fill: false, lineTension: 0, steppedLine: true, data: [], hidden: false }, { label: "vadState", backgroundColor: color(chartColors.orange) .alpha(0.5) .rgbString(), borderColor: chartColors.orange, fill: false, lineTension: 0, steppedLine: true, data: [], hidden: false } ] }, options: { title: { display: true, text: "Line chart (hotizontal scroll) sample" }, scales: { xAxes: [ { type: "realtime", realtime: { duration: 20000, ttl: undefined } } ], yAxes: [ { scaleLabel: { display: true, labelString: "value" } } ] }, tooltips: { mode: "nearest", intersect: false }, hover: { mode: "nearest", intersect: false }, plugins: { streaming: { frameRate: 15 } } } }; export default function StateChart(sources) { const vdom$ = xs.of( div(".stateChart", { style: { margin: "auto", width: "75%" } }, [ canvas(".myStateChart"), div({ style: { textAlign: "center" } }, [ span([ input(".isVisible", { attrs: { type: "checkbox", checked: "" } }), "isVisible" ]), span([ input(".vadState", { attrs: { type: "checkbox", checked: "" } }), "vadState" ]) ]) ]) ); const chartElem$ = sources.DOM.select(".myStateChart") .element() .take(1); const chartData$ = xs .combine(sources.isVisible, sources.vadState) .map(([iv, vs]) => [iv, vs]); const chart$ = xs.merge( chartElem$.map(elem => ({ type: "CREATE", value: elem })), chartData$.map(data => ({ type: "ADD", value: data })), sources.DOM.select(".isVisible") .events("change") .map(ev => ev.target.checked) .map(v => ({ type: "UPDATE", value: [{ hidden: !v }] })), sources.DOM.select(".vadState") .events("change") .map(ev => ev.target.checked) .map(v => ({ type: "UPDATE", value: [{}, { hidden: !v }] })) ); return { DOM: vdom$, Chart: chart$ }; } <file_sep>/apps/scripts/convert_questionset_to_transition.js if (process.argv.length < 3) { console.error("usage: node convert_questions_to_transition.js story.txt"); process.exit(1); } const fs = require("fs"); const defaultParams = { timeoutCm: 300, minSpeakDurationCm: 100, minTurnDurationCm: 500, engagedMinNoseAngle: -10, engagedMaxNoseAngle: 10, engagedMaxMaxNoseAngle1Sec: 20, sets: { passive: { timeoutCm: -1, minSpeakDurationCm: -1, minTurnDurationCm: -1, engagedMaxMaxNoseAngle1Sec: -1, engagedMinNoseAngle: -90, engagedMaxNoseAngle: 90 }, proactive: { timeoutCm: 300, minSpeakDurationCm: 100, minTurnDurationCm: 500, engagedMinNoseAngle: -10, engagedMaxNoseAngle: 10 } } }; let output = `// NOTE: might be called twice if transition and emission fncs are called separately function transition(stateStamped, inputD, inputC, params) {` + Object.keys(defaultParams) .filter(key => key !== "sets") .map(key => { return ` var ${key} = params.${key};`; }) .join("") + ` // Happy path if (stateStamped.state === "S0" && inputD.type === "START") { return { state: "S1", outputs: { RobotSpeechbubbleAction: 'Tap "Hello" when you are ready', HumanSpeechbubbleAction: ["Hello"] } };`; const lines = fs .readFileSync(process.argv[2]) .toString() .split("\n") .map(line => { return line.trim(); }); lines.map((line, i) => { output += ` } else if ( stateStamped.state === "S${i + 1}" && ${ i === 0 ? `inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Hello"` : `inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next"` } ) { return { state: "S${i + 2}", outputs: { RobotSpeechbubbleAction: ${JSON.stringify(line)}, HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: ${JSON.stringify(line)} } }; } else if (stateStamped.state === "S${i + 2}" && inputD.type === "Features") { if ( timeoutCm >= 0 && minSpeakDurationCm >= 0 && minTurnDurationCm >= 0 && engagedMaxMaxNoseAngle1Sec >= 0 && inputC.voice.vadState === "INACTIVE" && inputC.history.stateStamped[0].state === "S${i + 2}" && inputC.history.vadStateStamped[0].vadState === "INACTIVE" && inputC.history.stateStamped[0].stamp < inputC.history.vadStateStamped[1].stamp && inputC.history.vadStateStamped[0].stamp - inputC.history.vadStateStamped[1].stamp > minSpeakDurationCm * 10 && inputC.face.stamp - inputC.history.stateStamped[0].stamp > minTurnDurationCm * 10 && inputC.face.stamp - inputC.history.vadStateStamped[0].stamp > timeoutCm * 10 && (inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec) ) { return {${ i !== lines.length - 1 ? ` state: "S${i + 3}", outputs: { RobotSpeechbubbleAction: ${JSON.stringify(lines[i + 1])}, HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: ${JSON.stringify(lines[i + 1])} }` : ` state: "S${i + 3}", outputs: { RobotSpeechbubbleAction: "We are all done!", HumanSpeechbubbleAction: "", SpeechSynthesisAction: "We are all done!" }` } }; } else { return { state: stateStamped.state, outputs: null }; }`; }); output += ` } else if ( stateStamped.state === "S${lines.length + 1}" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S${lines.length + 2}", outputs: { RobotSpeechbubbleAction: "We are all done!", HumanSpeechbubbleAction: "", SpeechSynthesisAction: "We are all done!" } };`; output += ` } else { return { state: stateStamped.state, outputs: null }; } } var defaultParams = ${JSON.stringify(defaultParams, null, 2)}; module.exports = { transition: transition, defaultParams: defaultParams };`; console.log(output); <file_sep>/src/index.js export { mockStreamingChartSource, makeStreamingChartDriver } from "./cycle-chartjs"; export { mockMediaRecorderSource, makeMediaRecorderDriver, mockDownloadDataSource, makeDownloadDataDriver, DataDownloader } from "./cycle-media"; export { VADState, default as makeVoiceActivityDetectionDriver, adapter as vadAdapter } from "./makeVoiceActivityDetectionDriver"; export { maxDiff, maxDiffReverse, defaultFaceFeatures, extractFaceFeatures, defaultVoiceFeatures, extractVoiceFeatures } from "./features"; export { input, transitionReducer, output, RobotApp } from "./RobotApp"; <file_sep>/apps/dataplayer/src/Replayer.js import { intent, makeTime$, timeTravelStreams, timeTravelBarView, scopedDOM } from "@mjyc/cycle-time-travel"; export default function Replayer(DOM, Time, recordedStreams) { const name = ".time-travel"; const { timeTravelPosition$, playing$ } = intent(scopedDOM(DOM, name)); const time$ = makeTime$(Time, playing$, timeTravelPosition$); const timeTravel = timeTravelStreams(recordedStreams, time$); return { DOM: timeTravelBarView( name, time$, playing$, recordedStreams.filter(s => !s.hidden) ), timeTravel, time: time$ }; } <file_sep>/apps/settings_helper.js var settings = require("./settings.json"); var defaultVal = { dataplayer: { fileprefix: "test" }, robot: { name: "demo", withTabletFaceRobotActionsOptions: { styles: { robotSpeechbubble: { styles: { img: { height: "75vmin" } } }, humanSpeechbubble: { styles: { button: { fontSize: "8vmin" } } } } }, recording: { enabled: true }, charts: { enabled: true }, parameters: { setName: "" } } }; settings = (function defaults(s, dVal) { if (typeof dVal !== "object" && typeof dVal !== null) { return typeof s === "undefined" ? dVal : s; } else { if (Array.isArray(dVal)) { return dVal.map(function(k) { return defaults(typeof s === "undefined" ? s : s[k], dVal[k]); }); } else { return Object.keys(dVal).reduce(function(prev, k) { prev[k] = defaults(typeof s === "undefined" ? s : s[k], dVal[k]); return prev; }, {}); } } })(typeof settings === "undfined" ? {} : settings, defaultVal); module.exports = settings; <file_sep>/apps/robot/src/transitions/qa_set1.js // NOTE: might be called twice if transition and emission fncs are called separately function transition(stateStamped, inputD, inputC, params) { var timeoutCm = params.timeoutCm; var minSpeakDurationCm = params.minSpeakDurationCm; var minTurnDurationCm = params.minTurnDurationCm; var engagedMinNoseAngle = params.engagedMinNoseAngle; var engagedMaxNoseAngle = params.engagedMaxNoseAngle; var engagedMaxMaxNoseAngle1Sec = params.engagedMaxMaxNoseAngle1Sec; // Happy path if (stateStamped.state === "S0" && inputD.type === "START") { return { state: "S1", outputs: { RobotSpeechbubbleAction: 'Tap "Hello" when you are ready', HumanSpeechbubbleAction: ["Hello"] } }; } else if ( stateStamped.state === "S1" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Hello" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: "Are you a morning person or a night owl?", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "Are you a morning person or a night owl?" } }; } else if (stateStamped.state === "S2" && inputD.type === "Features") { if ( timeoutCm >= 0 && minSpeakDurationCm >= 0 && minTurnDurationCm >= 0 && engagedMaxMaxNoseAngle1Sec >= 0 && inputC.voice.vadState === "INACTIVE" && inputC.history.stateStamped[0].state === "S2" && inputC.history.vadStateStamped[0].vadState === "INACTIVE" && inputC.history.stateStamped[0].stamp < inputC.history.vadStateStamped[1].stamp && inputC.history.vadStateStamped[0].stamp - inputC.history.vadStateStamped[1].stamp > minSpeakDurationCm * 10 && inputC.face.stamp - inputC.history.stateStamped[0].stamp > minTurnDurationCm * 10 && inputC.face.stamp - inputC.history.vadStateStamped[0].stamp > timeoutCm * 10 && (inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec) ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: "Is there anything you don't eat? and why?", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "Is there anything you don't eat? and why?" } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: "Is there anything you don't eat? and why?", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "Is there anything you don't eat? and why?" } }; } else if (stateStamped.state === "S3" && inputD.type === "Features") { if ( timeoutCm >= 0 && minSpeakDurationCm >= 0 && minTurnDurationCm >= 0 && engagedMaxMaxNoseAngle1Sec >= 0 && inputC.voice.vadState === "INACTIVE" && inputC.history.stateStamped[0].state === "S3" && inputC.history.vadStateStamped[0].vadState === "INACTIVE" && inputC.history.stateStamped[0].stamp < inputC.history.vadStateStamped[1].stamp && inputC.history.vadStateStamped[0].stamp - inputC.history.vadStateStamped[1].stamp > minSpeakDurationCm * 10 && inputC.face.stamp - inputC.history.stateStamped[0].stamp > minTurnDurationCm * 10 && inputC.face.stamp - inputC.history.vadStateStamped[0].stamp > timeoutCm * 10 && (inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec) ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "What does a typical day look like for you?", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "What does a typical day look like for you?" } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "What does a typical day look like for you?", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "What does a typical day look like for you?" } }; } else if (stateStamped.state === "S4" && inputD.type === "Features") { if ( timeoutCm >= 0 && minSpeakDurationCm >= 0 && minTurnDurationCm >= 0 && engagedMaxMaxNoseAngle1Sec >= 0 && inputC.voice.vadState === "INACTIVE" && inputC.history.stateStamped[0].state === "S4" && inputC.history.vadStateStamped[0].vadState === "INACTIVE" && inputC.history.stateStamped[0].stamp < inputC.history.vadStateStamped[1].stamp && inputC.history.vadStateStamped[0].stamp - inputC.history.vadStateStamped[1].stamp > minSpeakDurationCm * 10 && inputC.face.stamp - inputC.history.stateStamped[0].stamp > minTurnDurationCm * 10 && inputC.face.stamp - inputC.history.vadStateStamped[0].stamp > timeoutCm * 10 && (inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec) ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: "What odd talent do you have?", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "What odd talent do you have?" } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: "What odd talent do you have?", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "What odd talent do you have?" } }; } else if (stateStamped.state === "S5" && inputD.type === "Features") { if ( timeoutCm >= 0 && minSpeakDurationCm >= 0 && minTurnDurationCm >= 0 && engagedMaxMaxNoseAngle1Sec >= 0 && inputC.voice.vadState === "INACTIVE" && inputC.history.stateStamped[0].state === "S5" && inputC.history.vadStateStamped[0].vadState === "INACTIVE" && inputC.history.stateStamped[0].stamp < inputC.history.vadStateStamped[1].stamp && inputC.history.vadStateStamped[0].stamp - inputC.history.vadStateStamped[1].stamp > minSpeakDurationCm * 10 && inputC.face.stamp - inputC.history.stateStamped[0].stamp > minTurnDurationCm * 10 && inputC.face.stamp - inputC.history.vadStateStamped[0].stamp > timeoutCm * 10 && (inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec) ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: "What's the most spontaneous thing you've done?", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "What's the most spontaneous thing you've done?" } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S5" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: "What's the most spontaneous thing you've done?", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "What's the most spontaneous thing you've done?" } }; } else if (stateStamped.state === "S6" && inputD.type === "Features") { if ( timeoutCm >= 0 && minSpeakDurationCm >= 0 && minTurnDurationCm >= 0 && engagedMaxMaxNoseAngle1Sec >= 0 && inputC.voice.vadState === "INACTIVE" && inputC.history.stateStamped[0].state === "S6" && inputC.history.vadStateStamped[0].vadState === "INACTIVE" && inputC.history.stateStamped[0].stamp < inputC.history.vadStateStamped[1].stamp && inputC.history.vadStateStamped[0].stamp - inputC.history.vadStateStamped[1].stamp > minSpeakDurationCm * 10 && inputC.face.stamp - inputC.history.stateStamped[0].stamp > minTurnDurationCm * 10 && inputC.face.stamp - inputC.history.vadStateStamped[0].stamp > timeoutCm * 10 && (inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec) ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: "We are all done!", HumanSpeechbubbleAction: "", SpeechSynthesisAction: "We are all done!" } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S6" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: "We are all done!", HumanSpeechbubbleAction: "", SpeechSynthesisAction: "We are all done!" } }; } else { return { state: stateStamped.state, outputs: null }; } } var defaultParams = { timeoutCm: 300, minSpeakDurationCm: 100, minTurnDurationCm: 500, engagedMinNoseAngle: -10, engagedMaxNoseAngle: 10, engagedMaxMaxNoseAngle1Sec: 20, sets: { passive: { timeoutCm: -1, minSpeakDurationCm: -1, minTurnDurationCm: -1, engagedMaxMaxNoseAngle1Sec: -1, engagedMinNoseAngle: -90, engagedMaxNoseAngle: 90 }, proactive: { timeoutCm: 300, minSpeakDurationCm: 100, minTurnDurationCm: 500, engagedMinNoseAngle: -10, engagedMaxNoseAngle: 10 } } }; module.exports = { transition: transition, defaultParams: defaultParams }; <file_sep>/apps/robot/src/transitions/storytelling_test.js // NOTE: might be called twice if transition and emission fncs are called separately function transition(stateStamped, inputD, inputC, params) { var engagedMinNoseAngle = params.engagedMinNoseAngle; var engagedMaxNoseAngle = params.engagedMaxNoseAngle; var disengagedMinNoseAngle = params.disengagedMinNoseAngle; var disengagedMaxNoseAngle = params.disengagedMaxNoseAngle; var disengagedTimeoutIntervalMs = params.disengagedTimeoutIntervalMs; // Happy path if (stateStamped.state === "S0" && inputD.type === "START") { return { state: "S1", outputs: { RobotSpeechbubbleAction: 'Tap "Hello" when you are ready', HumanSpeechbubbleAction: ["Hello"] } }; } else if ( stateStamped.state === "S1" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Hello" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: "PROFESS<NAME> MAKES A BANG", HumanSpeechbubbleAction: ["Pause"], SpeechSynthesisAction: "PROFESS<NAME> MAKES A BANG" } }; } else if ( stateStamped.state === "S2" && inputD.type === "SpeechSynthesisAction" && inputD.status === "SUCCEEDED" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: "<NAME> thinks a lot. He thinks of things to make.", HumanSpeechbubbleAction: ["Pause"], SpeechSynthesisAction: "<NAME> thinks a lot. He thinks of things to make." } }; } else if ( stateStamped.state === "S3" && inputD.type === "SpeechSynthesisAction" && inputD.status === "SUCCEEDED" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "He thinks as he brushes his teeth. He thinks at his desk. He even thinks in bed. Then, it clicks.", HumanSpeechbubbleAction: ["Pause"], SpeechSynthesisAction: "He thinks as he brushes his teeth. He thinks at his desk. He even thinks in bed. Then, it clicks." } }; } else if ( stateStamped.state === "S4" && inputD.type === "SpeechSynthesisAction" && inputD.status === "SUCCEEDED" ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: "The END", HumanSpeechbubbleAction: "", SpeechSynthesisAction: "The END" } }; // Handle Pause } else if ( stateStamped.state === "S2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP2", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP3", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP4", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; // Handle Resume } else if ( stateStamped.state === "SP2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: "<NAME> MAKES A BANG", HumanSpeechbubbleAction: ["Pause"], SpeechSynthesisAction: "<NAME> MAKES A BANG" } }; } else if ( stateStamped.state === "SP3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: "<NAME> thinks a lot. He thinks of things to make.", HumanSpeechbubbleAction: ["Pause"], SpeechSynthesisAction: "<NAME> thinks a lot. He thinks of things to make." } }; } else if ( stateStamped.state === "SP4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "He thinks as he brushes his teeth. He thinks at his desk. He even thinks in bed. Then, it clicks.", HumanSpeechbubbleAction: ["Pause"], SpeechSynthesisAction: "He thinks as he brushes his teeth. He thinks at his desk. He even thinks in bed. Then, it clicks." } }; // Proactive Pause } else if (stateStamped.state === "S2" && inputD.type === "Features") { if ( (inputC.face.isVisible && (inputC.face.noseAngle > disengagedMaxNoseAngle || inputC.face.noseAngle < disengagedMinNoseAngle)) || (!inputC.face.isVisible && inputC.face.stamp - inputC.face.stampLastDetected > disengagedTimeoutIntervalMs) ) { return { state: "SP2", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S3" && inputD.type === "Features") { if ( (inputC.face.isVisible && (inputC.face.noseAngle > disengagedMaxNoseAngle || inputC.face.noseAngle < disengagedMinNoseAngle)) || (!inputC.face.isVisible && inputC.face.stamp - inputC.face.stampLastDetected > disengagedTimeoutIntervalMs) ) { return { state: "SP3", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S4" && inputD.type === "Features") { if ( (inputC.face.isVisible && (inputC.face.noseAngle > disengagedMaxNoseAngle || inputC.face.noseAngle < disengagedMinNoseAngle)) || (!inputC.face.isVisible && inputC.face.stamp - inputC.face.stampLastDetected > disengagedTimeoutIntervalMs) ) { return { state: "SP4", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } // Proactive Resume } else if (stateStamped.state === "SP2" && inputD.type === "Features") { if ( inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: "PROFESS<NAME> MAKES A BANG", HumanSpeechbubbleAction: ["Pause"], SpeechSynthesisAction: "PROFESS<NAME> MAKES A BANG" } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP3" && inputD.type === "Features") { if ( inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: "<NAME> thinks a lot. He thinks of things to make.", HumanSpeechbubbleAction: ["Pause"], SpeechSynthesisAction: "<NAME> thinks a lot. He thinks of things to make." } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP4" && inputD.type === "Features") { if ( inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "He thinks as he brushes his teeth. He thinks at his desk. He even thinks in bed. Then, it clicks.", HumanSpeechbubbleAction: ["Pause"], SpeechSynthesisAction: "He thinks as he brushes his teeth. He thinks at his desk. He even thinks in bed. Then, it clicks." } }; } else { return { state: stateStamped.state, outputs: null }; } } else { return { state: stateStamped.state, outputs: null }; } } var defaultParams = { engagedMinNoseAngle: -0.001, engagedMaxNoseAngle: 0.001, disengagedMinNoseAngle: -90, disengagedMaxNoseAngle: 90, disengagedTimeoutIntervalMs: 10000 }; module.exports = { transition: transition, defaultParams: defaultParams }; <file_sep>/src/RobotApp.js import xs from "xstream"; import dropRepeats from "xstream/extra/dropRepeats"; import pairwise from "xstream/extra/pairwise"; import sampleCombine from "xstream/extra/sampleCombine"; import throttle from "xstream/extra/throttle"; import { initGoal, isEqualGoalID } from "@cycle-robot-drivers/action"; import { defaultFaceFeatures } from "./features"; export function input({ command, fsmUniqueStateStamped, actionResults, faceFeatures, voiceFeatures, temporalFeatures }) { const command$ = command.filter(cmd => cmd.type === "LOAD_FSM"); const inputD$ = xs.merge( command .filter(cmd => cmd.type === "START_FSM") .mapTo({ type: "START" }), actionResults ); // extract history features const stateStampedHistory$ = fsmUniqueStateStamped .compose(pairwise) // IMPORTANT! assumes first two unique states are S0 and S1 .map(([x, y]) => [y, x]) .startWith([...Array(2)].map(_ => ({ state: "", stamp: 0 }))); const isVisibleStampedHistory$ = xs .merge( faceFeatures // for filling up pairwise .map(ff => ({ isVisible: ff.isVisible, stamp: ff.stamp })) .take(2), faceFeatures .map(ff => ({ isVisible: ff.isVisible, stamp: ff.stamp })) .compose(dropRepeats((x, y) => x.isVisible === y.isVisible)) ) .compose(pairwise) .map(([x, y]) => [y, x]); const vadStateStampedHistory$ = xs .merge( voiceFeatures // for filling up pairwise .map(vf => ({ vadState: vf.vadState, stamp: vf.stamp })) .take(2), voiceFeatures .map(vf => ({ vadState: vf.vadState, stamp: vf.stamp })) .compose(dropRepeats((x, y) => x.vadState === y.vadState)) ) .compose(pairwise) .map(([x, y]) => [y, x]); const humanSpeechbubbleActionResultStamped$ = inputD$ .filter(inputD => inputD.type === "HumanSpeechbubbleAction") .map(inputD => ({ stamp: Date.now(), ...inputD })) .compose( dropRepeats( (x, y) => x.status === y.status && isEqualGoalID(x.goal_id, y.goal_id) ) ) .startWith({ type: "", goal_id: { stamp: 0, id: "" }, status: "", result: "" }); const speechSynthesisActionResultStamped$ = inputD$ .filter(inputD => inputD.type === "SpeechSynthesisAction") .map(inputD => ({ stamp: Date.now(), ...inputD })) .compose( dropRepeats( (x, y) => x.status === y.status && isEqualGoalID(x.goal_id, y.goal_id) ) ) .startWith({ type: "", goal_id: { stamp: 0, id: "" }, status: "", result: "" }); const inputC$ = xs .combine( faceFeatures, voiceFeatures, temporalFeatures, stateStampedHistory$, isVisibleStampedHistory$, vadStateStampedHistory$, humanSpeechbubbleActionResultStamped$, speechSynthesisActionResultStamped$, faceFeatures.filter(ff => !!ff.isVisible).startWith(defaultFaceFeatures) ) .map( ([ faceFeatures, voiceFeatures, temporalFeatures, stateStampedHistory, isVisibleStampedHistory, vadStateStampedHistory, humanSpeechbubbleActionResultStamped, speechSynthesisActionResultStamped, lastVisibleFaceFeatures ]) => ({ face: faceFeatures, voice: voiceFeatures, history: { stateStamped: stateStampedHistory, isVisibleStamped: isVisibleStampedHistory, vadStateStamped: vadStateStampedHistory, humanSpeechbubbleActionResultStamped: [ humanSpeechbubbleActionResultStamped ], speechSynthesisActionResultStamped: [ speechSynthesisActionResultStamped ], lastVisibleFaceFeatures }, temporal: temporalFeatures }) ); return xs.merge( command$, inputD$.compose(sampleCombine(inputC$)).map(([inputD, inputC]) => ({ type: "FSM_INPUT", discrete: inputD, continuous: inputC })), inputC$ .map(inputC => ({ type: "FSM_INPUT", discrete: { type: "Features" }, continuous: inputC })) .compose(throttle(100)) // 10hz ); } export function transitionReducer(input$) { const initReducer$ = xs.of(prev => { return { fsm: null, outputs: null }; }); const wrapOutputs = (outputs = {}) => { return outputs !== null ? Object.keys(outputs).reduce( (prev, name) => ({ ...prev, [name]: outputs[name].hasOwnProperty("goal") && outputs[name].hasOwnProperty("cancel") ? { ...outputs[name], goal: initGoal(outputs[name].goal) } : { goal: initGoal(outputs[name]) // no cancel } }), {} ) : outputs; }; const inputReducer$ = input$.map(input => prev => { if (input.type === "LOAD_FSM") { const stamp = Date.now(); return { ...prev, fsm: { stateStamped: { stamp, state: input.value.S0 }, transition: input.value.T, emission: input.value.G }, trace: null, outputs: null }; } else if (input.type === "FSM_INPUT") { if (prev.fsm === null) { console.warn(`FSM not loaded; skipping`); return { ...prev, outputs: null }; } const prevStateStamped = prev.fsm.stateStamped; const inputD = input.discrete; const inputC = input.continuous; const state = prev.fsm.transition(prevStateStamped, inputD, inputC); const stamp = Date.now(); const stateStamped = { // new state state, stamp }; const outputs = wrapOutputs( prev.fsm.emission(prevStateStamped, inputD, inputC) ); return { ...prev, fsm: { ...prev.fsm, stateStamped }, outputs, trace: { prevStateStamped, input, stateStamped, outputs } }; } else { console.warn(`Unknown input.type=${input.type}; skipping`); return { ...prev, outputs: null }; } }); return xs.merge(initReducer$, inputReducer$); } export function output(reducerState$) { const outputs$ = reducerState$ .filter(rs => !!rs.outputs) .map(rs => rs.outputs); return { FacialExpressionAction: { goal: outputs$ .filter( o => !!o.FacialExpressionAction && !!o.FacialExpressionAction.goal ) .map(o => o.FacialExpressionAction.goal), cancel: outputs$ .filter( o => !!o.FacialExpressionAction && !!o.FacialExpressionAction.cancel ) .map(o => o.FacialExpressionAction.cancel) }, RobotSpeechbubbleAction: { goal: outputs$ .filter( o => !!o.RobotSpeechbubbleAction && !!o.RobotSpeechbubbleAction.goal ) .map(o => o.RobotSpeechbubbleAction.goal), cancel: outputs$ .filter( o => !!o.RobotSpeechbubbleAction && !!o.RobotSpeechbubbleAction.cancel ) .map(o => o.RobotSpeechbubbleAction.cancel) }, HumanSpeechbubbleAction: { goal: outputs$ .filter( o => !!o.HumanSpeechbubbleAction && !!o.HumanSpeechbubbleAction.goal ) .map(o => o.HumanSpeechbubbleAction.goal), cancel: outputs$ .filter( o => !!o.HumanSpeechbubbleAction && !!o.HumanSpeechbubbleAction.cancel ) .map(o => o.HumanSpeechbubbleAction.cancel) }, AudioPlayerAction: { goal: outputs$ .filter(o => !!o.AudioPlayerAction && !!o.AudioPlayerAction.goal) .map(o => o.AudioPlayerAction.goal), cancel: outputs$ .filter(o => !!o.AudioPlayerAction && !!o.AudioPlayerAction.canel) .map(o => o.AudioPlayerAction.cancel) }, SpeechSynthesisAction: { goal: outputs$ .filter( o => !!o.SpeechSynthesisAction && !!o.SpeechSynthesisAction.goal ) .map(o => o.SpeechSynthesisAction.goal), cancel: outputs$ .filter( o => !!o.SpeechSynthesisAction && !!o.SpeechSynthesisAction.cancel ) .map(o => o.SpeechSynthesisAction.cancel) }, SpeechRecognitionAction: { goal: outputs$ .filter( o => !!o.SpeechRecognitionAction && !!o.SpeechRecognitionAction.goal ) .map(o => o.SpeechRecognitionAction.goal), cancel: outputs$ .filter( o => !!o.SpeechRecognitionAction && !!o.SpeechRecognitionAction.cancel ) .map(o => o.SpeechRecognitionAction.cancel) } }; } export function RobotApp(sources) { // sources.state.stream.addListener({next: s => console.debug('RobotApp state', s)}); const input$ = input(sources); const reducer = transitionReducer(input$); const outputs = output(sources.state.stream); return { state: reducer, ...outputs }; } <file_sep>/lib/makeVoiceActivityDetectionDriver.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.VADState = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; // adapted from https://github.com/Jam3/voice-activity-detection/blob/master/test/test.js exports.default = makeVoiceActivityDetectionDriver; exports.adapter = adapter; var _xstream = require("xstream"); var _xstream2 = _interopRequireDefault(_xstream); var _voiceActivityDetection = require("@mjyc/voice-activity-detection"); var _voiceActivityDetection2 = _interopRequireDefault(_voiceActivityDetection); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function makeVoiceActivityDetectionDriver(options) { var audioContext; return function voiceActivityDetectionDriver() { var output$ = _xstream2.default.create({ start: function start(listener) { function handleUserMediaError() { listener.error("Mic input is not supported by the browser."); } function handleMicConnectError() { listener.error("Could not connect microphone. Possible rejected by the user or is blocked by the browser."); } function requestMic() { try { window.AudioContext = window.AudioContext || window.webkitAudioContext; audioContext = new AudioContext(); // https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#audiovideo_elements if (audioContext.state === "suspended") { console.warn("audioContext.state is \"suspended\"; will attempt to resume every 1s"); var handle = setInterval(function () { if (!!audioContext && audioContext.state === "suspended") { audioContext.resume(); } else if (audioContext.state === "running") { console.debug("audioContext.state is \"running\"; stopping resuming attempts"); clearInterval(handle); } }, 1000); } navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; navigator.getUserMedia({ audio: true }, startUserMedia, handleMicConnectError); } catch (e) { handleUserMediaError(); } } function startUserMedia(stream) { var opts = _extends({}, options, { onVoiceStart: function onVoiceStart() { listener.next({ type: "START" }); }, onVoiceStop: function onVoiceStop() { listener.next({ type: "STOP" }); }, onUpdate: function onUpdate(val) { listener.next({ type: "UPDATE", value: val }); } }); (0, _voiceActivityDetection2.default)(audioContext, stream, opts); } requestMic(); }, stop: function stop() {} }); return output$; }; } var VADState = exports.VADState = { INACTIVE: 0, ACTIVE: 1 }; function adapter(output$) { var state$ = output$.filter(function (_ref) { var type = _ref.type; return type === "START" || type === "STOP"; }).fold(function (prev, _ref2) { var type = _ref2.type; return type === "START" ? "ACTIVE" : type === "STOP" ? "INACTIVE" : prev; }, "INACTIVE"); var level$ = output$.filter(function (_ref3) { var type = _ref3.type; return type === "UPDATE"; }).map(function (_ref4) { var value = _ref4.value; return value; }); return { events: function events(name) { return name === "state" ? state$ : name === "level" ? level$ : _xstream2.default.never(); } }; }<file_sep>/apps/robot/src/transitions/neck_exercise.js // NOTE: might be called twice if transition and emission fncs are called separately function transition(stateStamped, inputD, inputC, params) { var rotateRightNoseAngle = params.rotateRightNoseAngle; var rotateLeftNoseAngle = params.rotateLeftNoseAngle; var touchRighFaceAngle = params.touchRighFaceAngle; var touchLeftFaceAngle = params.touchLeftFaceAngle; var nextMaxMaxNoseAngle1Sec = params.nextMaxMaxNoseAngle1Sec; if (stateStamped.state === "S0" && inputD.type === "START") { return { state: "S1", outputs: { RobotSpeechbubbleAction: 'Tap "Hello" when you are ready', HumanSpeechbubbleAction: ["Hello"] } }; } else if ( (stateStamped.state === "S1" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Hello") || (inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Repeat") ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: "Let's start from looking forward", HumanSpeechbubbleAction: "", SpeechSynthesisAction: { goal_id: { id: "Let's start from looking forward", stamp: Date.now() }, goal: "Let's start from looking forward" } } }; // Rotete right and left } else if ( stateStamped.state === "S2" && inputD.type === "SpeechSynthesisAction" && inputD.status === "SUCCEEDED" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your right", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your right", stamp: Date.now() }, goal: "and now slowly rotate to your right" } } }; } else if (stateStamped.state === "S3" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now slowly rotate to your right" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && ((inputC.face.isVisible && inputC.face.noseAngle < rotateRightNoseAngle) || (!inputC.face.isVisible && inputC.history.lastVisibleFaceFeatures.noseAngle < rotateRightNoseAngle)) ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your left", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your left", stamp: Date.now() }, goal: "and now slowly rotate to your left" } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your left", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your left", stamp: Date.now() }, goal: "and now slowly rotate to your left" } } }; } else if (stateStamped.state === "S4" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now slowly rotate to your left" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && ((inputC.face.isVisible && inputC.face.noseAngle > rotateLeftNoseAngle) || (!inputC.face.isVisible && inputC.history.lastVisibleFaceFeatures.noseAngle > rotateLeftNoseAngle)) ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your right", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your right", stamp: Date.now() }, goal: "and now slowly rotate to your right" } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your right", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your right", stamp: Date.now() }, goal: "and now slowly rotate to your right" } } }; } else if (stateStamped.state === "S5" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now slowly rotate to your right" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && ((inputC.face.isVisible && inputC.face.noseAngle < rotateRightNoseAngle) || (!inputC.face.isVisible && inputC.history.lastVisibleFaceFeatures.noseAngle < rotateRightNoseAngle)) ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your left", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your left", stamp: Date.now() }, goal: "and now slowly rotate to your left" } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S5" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your left", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your left", stamp: Date.now() }, goal: "and now slowly rotate to your left" } } }; } else if (stateStamped.state === "S6" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now slowly rotate to your left" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && ((inputC.face.isVisible && inputC.face.noseAngle > rotateLeftNoseAngle) || (!inputC.face.isVisible && inputC.history.lastVisibleFaceFeatures.noseAngle > rotateLeftNoseAngle)) ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch right shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch right shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch right shoulder" } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S6" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch right shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch right shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch right shoulder" } } }; } else if (stateStamped.state === "S7" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now take your ear and act like trying to touch right shoulder" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && inputC.face.faceAngle > touchRighFaceAngle ) { return { state: "S8", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch left shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch left shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch left shoulder" } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S7" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S8", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch left shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch left shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch left shoulder" } } }; } else if (stateStamped.state === "S8" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now take your ear and act like trying to touch left shoulder" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && inputC.face.faceAngle < touchLeftFaceAngle ) { return { state: "S9", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch right shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch right shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch right shoulder" } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S8" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S9", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch right shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch right shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch right shoulder" } } }; } else if (stateStamped.state === "S9" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now take your ear and act like trying to touch right shoulder" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && inputC.face.faceAngle > touchRighFaceAngle ) { return { state: "S10", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch left shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch left shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch left shoulder" } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S9" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S10", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch left shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch left shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch left shoulder" } } }; } else if (stateStamped.state === "S10" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now take your ear and act like trying to touch left shoulder" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && inputC.face.faceAngle < touchLeftFaceAngle ) { return { state: "S11", outputs: { RobotSpeechbubbleAction: "Great job!", HumanSpeechbubbleAction: ["Repeat"], SpeechSynthesisAction: { goal_id: { id: "Great job!", stamp: Date.now() }, goal: "Great job!" } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S10" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S11", outputs: { RobotSpeechbubbleAction: "Great job!", HumanSpeechbubbleAction: ["Repeat"], SpeechSynthesisAction: "Great job!" } }; } else { return { state: stateStamped.state, outputs: null }; } } var defaultParams = { rotateRightNoseAngle: -20, rotateLeftNoseAngle: 20, touchRighFaceAngle: 30, touchLeftFaceAngle: -30, nextMaxMaxNoseAngle1Sec: 20, sets: { passive: { rotateRightNoseAngle: -60, rotateLeftNoseAngle: 60, touchRighFaceAngle: 90, touchLeftFaceAngle: -90, nextMaxMaxNoseAngle1Sec: -1 }, proactive: { rotateRightNoseAngle: -20, rotateLeftNoseAngle: 20, touchRighFaceAngle: 30, touchLeftFaceAngle: -30, nextMaxMaxNoseAngle1Sec: 20 } } }; module.exports = { transition: transition, defaultParams: defaultParams }; <file_sep>/apps/robot/src/transitions/storytelling_professor_archie_makes_a_bang.js // NOTE: might be called twice if transition and emission fncs are called separately function transition(stateStamped, inputD, inputC, params) { var engagedMinNoseAngle = params.engagedMinNoseAngle; var engagedMaxNoseAngle = params.engagedMaxNoseAngle; var disengagedMinNoseAngle = params.disengagedMinNoseAngle; var disengagedMaxNoseAngle = params.disengagedMaxNoseAngle; var disengagedMaxMaxNoseAngle1Sec = params.disengagedMaxMaxNoseAngle1Sec; var disengagedTimeoutIntervalCs = params.disengagedTimeoutIntervalCs; // Happy path if (stateStamped.state === "S0" && inputD.type === "START") { return { state: "S1", outputs: { RobotSpeechbubbleAction: 'Tap "Hello" when you are ready', HumanSpeechbubbleAction: ["Hello"] } }; } else if ( stateStamped.state === "S1" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Hello" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-1.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "PROFESSOR ARCHIE MAKES A BANG by <NAME>", stamp: Date.now() }, goal: { text: "PROFESSOR ARCHIE MAKES A BANG by <NAME>", rate: 0.8, afterpauseduration: 3000 } } } }; } else if (stateStamped.state === "S2" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "PROFESSOR ARCHIE MAKES A BANG by <NAME>" && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-2.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "<NAME> thinks a lot. He thinks of things to make.", stamp: Date.now() }, goal: { text: "<NAME> thinks a lot. He thinks of things to make.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP3", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S3" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "<NAME> thinks a lot. He thinks of things to make." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-3.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "He thinks as he brushes his teeth. He thinks at his desk.", stamp: Date.now() }, goal: { text: "He thinks as he brushes his teeth. He thinks at his desk.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP4", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S4" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "He thinks as he brushes his teeth. He thinks at his desk." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-4.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "He even thinks in bed. Then, it clicks.", stamp: Date.now() }, goal: { text: "He even thinks in bed. Then, it clicks.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP5", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S5" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "He even thinks in bed. Then, it clicks." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-5.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes bots that can help. The bots make toast for Archie.", stamp: Date.now() }, goal: { text: "Archie makes bots that can help. The bots make toast for Archie.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP6", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S6" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Archie makes bots that can help. The bots make toast for Archie." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-6.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes a pen that can do art by itself. What do you think of it?", stamp: Date.now() }, goal: { text: "Archie makes a pen that can do art by itself. What do you think of it?", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP7", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S7" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Archie makes a pen that can do art by itself. What do you think of it?" && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S8", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-7.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes it so that his bike can run his laptop.", stamp: Date.now() }, goal: { text: "Archie makes it so that his bike can run his laptop.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP8", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S8" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Archie makes it so that his bike can run his laptop." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S9", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-8.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie even makes it so that cars can sail.", stamp: Date.now() }, goal: { text: "Archie even makes it so that cars can sail.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP9", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S9" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Archie even makes it so that cars can sail." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S10", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-9.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie has a lot of plans. He never stops inventing.", stamp: Date.now() }, goal: { text: "Archie has a lot of plans. He never stops inventing.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP10", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S10" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Archie has a lot of plans. He never stops inventing." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S11", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-10.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "What would you make if you were Archie?", stamp: Date.now() }, goal: { text: "What would you make if you were Archie?", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP11", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S11" && inputD.type === "SpeechSynthesisAction" && inputD.status === "SUCCEEDED" ) { return { state: "S12", outputs: { RobotSpeechbubbleAction: "The END", HumanSpeechbubbleAction: "", SpeechSynthesisAction: { goal_id: { id: "The END", stamp: Date.now() }, goal: { text: "The END", rate: 0.8, afterpauseduration: 3000 } } } }; // Handle Next } else if ( stateStamped.state === "S1" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-1.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "PROFESSOR ARCHIE MAKES A BANG by <NAME>", stamp: Date.now() }, goal: { text: "PROFESSOR ARCHIE MAKES A BANG by <NAME>", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-2.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "<NAME> thinks a lot. He thinks of things to make.", stamp: Date.now() }, goal: { text: "<NAME> thinks a lot. He thinks of things to make.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-3.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "He thinks as he brushes his teeth. He thinks at his desk.", stamp: Date.now() }, goal: { text: "He thinks as he brushes his teeth. He thinks at his desk.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-4.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "He even thinks in bed. Then, it clicks.", stamp: Date.now() }, goal: { text: "He even thinks in bed. Then, it clicks.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S5" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-5.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes bots that can help. The bots make toast for Archie.", stamp: Date.now() }, goal: { text: "Archie makes bots that can help. The bots make toast for Archie.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S6" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-6.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes a pen that can do art by itself. What do you think of it?", stamp: Date.now() }, goal: { text: "Archie makes a pen that can do art by itself. What do you think of it?", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S7" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S8", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-7.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes it so that his bike can run his laptop.", stamp: Date.now() }, goal: { text: "Archie makes it so that his bike can run his laptop.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S8" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S9", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-8.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie even makes it so that cars can sail.", stamp: Date.now() }, goal: { text: "Archie even makes it so that cars can sail.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S9" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S10", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-9.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie has a lot of plans. He never stops inventing.", stamp: Date.now() }, goal: { text: "Archie has a lot of plans. He never stops inventing.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S10" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S11", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-10.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "What would you make if you were Archie?", stamp: Date.now() }, goal: { text: "What would you make if you were Archie?", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S11" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S12", outputs: { RobotSpeechbubbleAction: "The END", HumanSpeechbubbleAction: "", SpeechSynthesisAction: { goal_id: { id: "The END", stamp: Date.now() }, goal: { text: "The END", rate: 0.8, afterpauseduration: 3000 } } } }; // Handle Pause } else if ( stateStamped.state === "S2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP2", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP3", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP4", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S5" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP5", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S6" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP6", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S7" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP7", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S8" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP8", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S9" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP9", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S10" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP10", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S11" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP11", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; // Handle Resume } else if ( stateStamped.state === "SP2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-1.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "PROFESSOR ARCHIE MAKES A BANG by <NAME>", stamp: Date.now() }, goal: { text: "PROFESSOR ARCHIE MAKES A BANG by <NAME>", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-2.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "<NAME> thinks a lot. He thinks of things to make.", stamp: Date.now() }, goal: { text: "<NAME> thinks a lot. He thinks of things to make.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-3.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "He thinks as he brushes his teeth. He thinks at his desk.", stamp: Date.now() }, goal: { text: "He thinks as he brushes his teeth. He thinks at his desk.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP5" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-4.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "He even thinks in bed. Then, it clicks.", stamp: Date.now() }, goal: { text: "He even thinks in bed. Then, it clicks.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP6" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-5.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes bots that can help. The bots make toast for Archie.", stamp: Date.now() }, goal: { text: "Archie makes bots that can help. The bots make toast for Archie.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP7" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-6.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes a pen that can do art by itself. What do you think of it?", stamp: Date.now() }, goal: { text: "Archie makes a pen that can do art by itself. What do you think of it?", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP8" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S8", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-7.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes it so that his bike can run his laptop.", stamp: Date.now() }, goal: { text: "Archie makes it so that his bike can run his laptop.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP9" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S9", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-8.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie even makes it so that cars can sail.", stamp: Date.now() }, goal: { text: "Archie even makes it so that cars can sail.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP10" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S10", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-9.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie has a lot of plans. He never stops inventing.", stamp: Date.now() }, goal: { text: "Archie has a lot of plans. He never stops inventing.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP11" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S11", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-10.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "What would you make if you were Archie?", stamp: Date.now() }, goal: { text: "What would you make if you were Archie?", rate: 0.8, afterpauseduration: 3000 } } } }; // Proactive Resume } else if (stateStamped.state === "SP2" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-1.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "PROFESSOR ARCHIE MAKES A BANG by <NAME>", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... PROFESSOR ARCHIE MAKES A BANG by <NAME>", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP3" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-2.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "<NAME> thinks a lot. He thinks of things to make.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... <NAME> thinks a lot. He thinks of things to make.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP4" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-3.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "He thinks as he brushes his teeth. He thinks at his desk.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... He thinks as he brushes his teeth. He thinks at his desk.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP5" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-4.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "He even thinks in bed. Then, it clicks.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... He even thinks in bed. Then, it clicks.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP6" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-5.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes bots that can help. The bots make toast for Archie.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Archie makes bots that can help. The bots make toast for Archie.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP7" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-6.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes a pen that can do art by itself. What do you think of it?", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Archie makes a pen that can do art by itself. What do you think of it?", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP8" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S8", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-7.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie makes it so that his bike can run his laptop.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Archie makes it so that his bike can run his laptop.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP9" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S9", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-8.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie even makes it so that cars can sail.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Archie even makes it so that cars can sail.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP10" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S10", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-9.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Archie has a lot of plans. He never stops inventing.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Archie has a lot of plans. He never stops inventing.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP11" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S11", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/professor_archie_makes_a_bang-10.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "What would you make if you were Archie?", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... What would you make if you were Archie?", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else { return { state: stateStamped.state, outputs: null }; } } var defaultParams = { engagedMinNoseAngle: -10, engagedMaxNoseAngle: 10, disengagedMinNoseAngle: -15, disengagedMaxNoseAngle: 15, disengagedMaxMaxNoseAngle1Sec: 20, disengagedTimeoutIntervalCs: 200, sets: { passive: { engagedMinNoseAngle: 0, engagedMaxNoseAngle: 0, disengagedMinNoseAngle: -90, disengagedMaxNoseAngle: 90, disengagedMaxMaxNoseAngle1Sec: -1, disengagedTimeoutIntervalCs: -1 }, proactive: { engagedMinNoseAngle: -10, engagedMaxNoseAngle: 10, disengagedMinNoseAngle: -15, disengagedMaxNoseAngle: 15, disengagedMaxMaxNoseAngle1Sec: 20, disengagedTimeoutIntervalCs: 200 } } }; module.exports = { transition: transition, defaultParams: defaultParams }; <file_sep>/apps/robot/src/transitions/recipeinsts_breakfast.js // NOTE: might be called twice if transition and emission fncs are called separately function transition(stateStamped, inputD, inputC, params) { var nextTimeoutIntervalCs = params.nextTimeoutIntervalCs; // Happy path if (stateStamped.state === "S0" && inputD.type === "START") { return { state: "S1", outputs: { RobotSpeechbubbleAction: 'Tap "Hello" when you are ready', HumanSpeechbubbleAction: ["Hello"] } }; } else if ( stateStamped.state === "S1" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Hello" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: "Please prepare 1 yogurt", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "Please prepare 1 yogurt" } }; } else if (stateStamped.state === "S2" && inputD.type === "Features") { if ( inputC.face.isVisible && nextTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.face.stamp - inputC.history.stateStamped[0].stamp > inputC.face.stamp - inputC.history.isVisibleStamped[1].stamp && inputC.history.isVisibleStamped[1].isVisible === false && inputC.face.stamp - inputC.history.isVisibleStamped[1].stamp > nextTimeoutIntervalCs * 10 ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: "Please prepare 1 orange juice", HumanSpeechbubbleAction: ["Go back", "Next"], SpeechSynthesisAction: "Please prepare 1 orange juice" } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: "Please prepare 1 orange juice", HumanSpeechbubbleAction: ["Go back", "Next"], SpeechSynthesisAction: "Please prepare 1 orange juice" } }; } else if (stateStamped.state === "S3" && inputD.type === "Features") { if ( inputC.face.isVisible && nextTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.face.stamp - inputC.history.stateStamped[0].stamp > inputC.face.stamp - inputC.history.isVisibleStamped[1].stamp && inputC.history.isVisibleStamped[1].isVisible === false && inputC.face.stamp - inputC.history.isVisibleStamped[1].stamp > nextTimeoutIntervalCs * 10 ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "Please prepare 1 tomato", HumanSpeechbubbleAction: ["Go back", "Next"], SpeechSynthesisAction: "Please prepare 1 tomato" } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "Please prepare 1 tomato", HumanSpeechbubbleAction: ["Go back", "Next"], SpeechSynthesisAction: "Please prepare 1 tomato" } }; } else if (stateStamped.state === "S4" && inputD.type === "Features") { if ( inputC.face.isVisible && nextTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.face.stamp - inputC.history.stateStamped[0].stamp > inputC.face.stamp - inputC.history.isVisibleStamped[1].stamp && inputC.history.isVisibleStamped[1].isVisible === false && inputC.face.stamp - inputC.history.isVisibleStamped[1].stamp > nextTimeoutIntervalCs * 10 ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: "You are done!", HumanSpeechbubbleAction: "", SpeechSynthesisAction: "You are done!" } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S4" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: "You are done!", HumanSpeechbubbleAction: "", SpeechSynthesisAction: "You are done!" } }; // Handle Go back } else if ( stateStamped.state === "S3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Go back" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: "Please prepare 1 yogurt", HumanSpeechbubbleAction: ["Go back", "Next"], SpeechSynthesisAction: "Please prepare 1 yogurt" } }; } else if ( stateStamped.state === "S4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Go back" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: "Please prepare 1 orange juice", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: "Please prepare 1 orange juice" } }; } else if ( stateStamped.state === "S5" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Go back" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "Please prepare 1 tomato", HumanSpeechbubbleAction: ["Go back", "Next"], SpeechSynthesisAction: "Please prepare 1 tomato" } }; } else { return { state: stateStamped.state, outputs: null }; } } var defaultParams = { nextTimeoutIntervalCs: 100, sets: { passive: { nextTimeoutIntervalCs: 0 }, proactive: { nextTimeoutIntervalCs: 100 } } }; module.exports = { transition: transition, defaultParams: defaultParams }; <file_sep>/apps/robot/prestart.sh #!/usr/bin/env bash test -e ../settings.json || echo {} > ../settings.json test -e ../data/parameters || mkdir -p ../data/parameters; for f in $(find ./src/transitions -type f -name '*.js' -not -name 'index.js'); do \ FILENAME=../data/parameters/"`basename $f .js`".json; test -e $FILENAME || echo "{}" > $FILENAME; done; <file_sep>/apps/scripts/create_neck_exercise_transition.js var numRepeats = !process.argv[2] ? 2 : process.argv[2]; var rotateOnly = process.argv[3] === "undefined" || process.argv[3] == "true" ? true : false; var defaultParams = { rotateRightNoseAngle: -20, rotateLeftNoseAngle: 20, touchRighFaceAngle: 30, touchLeftFaceAngle: -30, nextMaxMaxNoseAngle1Sec: 20, sets: { passive: { rotateRightNoseAngle: -60, rotateLeftNoseAngle: 60, touchRighFaceAngle: 90, touchLeftFaceAngle: -90, nextMaxMaxNoseAngle1Sec: -1 }, proactive: { rotateRightNoseAngle: -20, rotateLeftNoseAngle: 20, touchRighFaceAngle: 30, touchLeftFaceAngle: -30, nextMaxMaxNoseAngle1Sec: 20 } } }; var output = `// NOTE: might be called twice if transition and emission fncs are called separately function transition(stateStamped, inputD, inputC, params) {` + Object.keys(defaultParams) .filter(key => key !== "sets") .map(key => { return ` var ${key} = params.${key};`; }) .join("") + ` if (stateStamped.state === "S0" && inputD.type === "START") { return { state: "S1", outputs: { RobotSpeechbubbleAction: 'Tap "Hello" when you are ready', HumanSpeechbubbleAction: ["Hello"] } }; } else if ( (stateStamped.state === "S1" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Hello") || (inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Repeat") ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: "Let's start from looking forward", HumanSpeechbubbleAction: "", SpeechSynthesisAction: { goal_id: { id: "Let's start from looking forward", stamp: Date.now() }, goal: "Let's start from looking forward" } } };`; output += ` // Rotete right and left`; var idx = 2; for (var i = 0; i < numRepeats; i++) { output += `${ i === 0 ? ` } else if ( stateStamped.state === "S${idx}" && inputD.type === "SpeechSynthesisAction" && inputD.status === "SUCCEEDED" ) { return { state: "S${idx + 1}", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your right", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your right", stamp: Date.now() }, goal: "and now slowly rotate to your right" } } };` : ` } else if ( stateStamped.state === "S${idx}" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S${idx + 1}", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your right", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your right", stamp: Date.now() }, goal: "and now slowly rotate to your right" } } };` } } else if (stateStamped.state === "S${idx + 1}" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now slowly rotate to your right" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && (inputC.face.isVisible && (inputC.face.noseAngle < rotateRightNoseAngle) || !inputC.face.isVisible && inputC.history.lastVisibleFaceFeatures.noseAngle < rotateRightNoseAngle) ) { return { state: "S${idx + 2}", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your left", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your left", stamp: Date.now() }, goal: "and now slowly rotate to your left" } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S${idx + 1}" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S${idx + 2}", outputs: { RobotSpeechbubbleAction: "and now slowly rotate to your left", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now slowly rotate to your left", stamp: Date.now() }, goal: "and now slowly rotate to your left" } } }; } else if (stateStamped.state === "S${idx + 2}" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now slowly rotate to your left" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && (inputC.face.isVisible && (inputC.face.noseAngle > rotateLeftNoseAngle) || !inputC.face.isVisible && inputC.history.lastVisibleFaceFeatures.noseAngle > rotateLeftNoseAngle) ) { return { state: "S${idx + 3}", outputs: { RobotSpeechbubbleAction: "${ i !== numRepeats - 1 ? !rotateOnly ? `and now slowly rotate to your right` : `Great job!` : `and now take your ear and act like trying to touch right shoulder` }", HumanSpeechbubbleAction: ${!rotateOnly ? `["Next"]` : `["Repeat"]`}, SpeechSynthesisAction: { goal_id: { id: "${ i !== numRepeats - 1 ? !rotateOnly ? `and now slowly rotate to your right` : `Great job!` : `and now take your ear and act like trying to touch right shoulder` }", stamp: Date.now() }, goal: "${ i !== numRepeats - 1 ? !rotateOnly ? `and now slowly rotate to your right` : `Great job!` : `and now take your ear and act like trying to touch right shoulder` }" } } }; } else { return { state: stateStamped.state, outputs: null }; }`; idx += 2; } if (!!rotateOnly) output += ` // Touch right and left shoulders`; for (var i = 0; i < numRepeats; i++) { output += ` } else if ( stateStamped.state === "S${idx}" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S${idx + 1}", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch right shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch right shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch right shoulder" } } }; } else if (stateStamped.state === "S${idx + 1}" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now take your ear and act like trying to touch right shoulder" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && inputC.face.faceAngle > touchRighFaceAngle ) { return { state: "S${idx + 2}", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch left shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch left shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch left shoulder" } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S${idx + 1}" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S${idx + 2}", outputs: { RobotSpeechbubbleAction: "and now take your ear and act like trying to touch left shoulder", HumanSpeechbubbleAction: ["Next"], SpeechSynthesisAction: { goal_id: { id: "and now take your ear and act like trying to touch left shoulder", stamp: Date.now() }, goal: "and now take your ear and act like trying to touch left shoulder" } } }; } else if (stateStamped.state === "S${idx + 2}" && inputD.type === "Features") { if ( nextMaxMaxNoseAngle1Sec >= 0 && inputC.temporal.maxNoseAngle1Sec < nextMaxMaxNoseAngle1Sec && inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "and now take your ear and act like trying to touch left shoulder" && inputC.face.stamp - inputC.history.speechSynthesisActionResultStamped[0].stamp > 3000 && inputC.face.faceAngle < touchLeftFaceAngle ) { return { state: "S${idx + 3}", outputs: { RobotSpeechbubbleAction: "${ i !== numRepeats - 1 ? `and now take your ear and act like trying to touch right shoulder` : `Great job!` }", HumanSpeechbubbleAction: ${ i !== numRepeats - 1 ? `["Next"]` : `["Repeat"]` }, SpeechSynthesisAction: { goal_id: { id: "${ i !== numRepeats - 1 ? `and now take your ear and act like trying to touch right shoulder` : `Great job!` }", stamp: Date.now(), }, goal: "${ i !== numRepeats - 1 ? `and now take your ear and act like trying to touch right shoulder` : `Great job!` }" } } }; } else { return { state: stateStamped.state, outputs: null }; }`; idx += 2; } output += ` } else if ( stateStamped.state === "S${idx}" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S${idx + 1}", outputs: { RobotSpeechbubbleAction: "Great job!", HumanSpeechbubbleAction: ["Repeat"], SpeechSynthesisAction: "Great job!" } };`; output += ` } else { return { state: stateStamped.state, outputs: null }; } } var defaultParams = ${JSON.stringify(defaultParams, null, 2)}; module.exports = { transition: transition, defaultParams: defaultParams };`; console.log(output); <file_sep>/lib/features.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ function maxDiff(arr) { var n = arr.length; var maxDiff = -1; var maxRight = arr[n - 1]; for (var i = n - 2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i];else { var diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } function maxDiffReverse(arr) { var n = arr.length; var maxDiff = -1; var maxLeft = arr[0]; for (var i = 1; i < n; i++) { if (arr[i] > maxLeft) maxLeft = arr[i];else { var diff = maxLeft - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } var defaultFaceFeatures = { stamp: 0, isVisible: false, faceSize: 0, faceHeight: 0, faceCenterX: 0, faceCenterY: 0, faceAngle: 0, noseAngle: 0 }; function norm(pt) { return Math.sqrt(pt.x * pt.x + pt.y * pt.y); } function rotate(pt, theta) { return { x: pt.x * Math.cos(theta) - pt.y * Math.sin(theta), y: pt.x * Math.sin(theta) + pt.y * Math.cos(theta) }; } function extractFaceFeatures(poses) { if (poses.length === 0 || !poses[0].keypoints.find(function (kpt) { return kpt.part === "nose"; }) || !poses[0].keypoints.find(function (kpt) { return kpt.part === "leftEye"; }) || !poses[0].keypoints.find(function (kpt) { return kpt.part === "rightEye"; })) { return { stamp: Date.now(), isVisible: false, faceSize: defaultFaceFeatures.faceSize, faceHeight: defaultFaceFeatures.faceHeight, faceCenterX: defaultFaceFeatures.faceCenterX, faceCenterY: defaultFaceFeatures.faceCenterY, faceAngle: defaultFaceFeatures.faceAngle, noseAngle: defaultFaceFeatures.noseAngle }; } var ns = poses[0].keypoints.filter(function (kpt) { return kpt.part === "nose"; })[0].position; var le = poses[0].keypoints.filter(function (kpt) { return kpt.part === "leftEye"; })[0].position; var re = poses[0].keypoints.filter(function (kpt) { return kpt.part === "rightEye"; })[0].position; var dnsre = Math.sqrt(Math.pow(ns.x - le.x, 2) + Math.pow(ns.y - le.y, 2)); var dnsle = Math.sqrt(Math.pow(ns.x - re.x, 2) + Math.pow(ns.y - re.y, 2)); var drele = Math.sqrt(Math.pow(re.x - le.x, 2) + Math.pow(re.y - le.y, 2)); var s = 0.5 * (dnsre + dnsle + drele); var faceSize = Math.sqrt(s * (s - dnsre) * (s - dnsle) * (s - drele)); var faceCenterX = (ns.x + le.x + re.x) / 3; var faceCenterY = (ns.y + le.y + re.y) / 3; // a point between two eyes var bw = { x: (le.x + re.x) * 0.5, y: (le.y + re.y) * 0.5 }; // a vector from the point between two eyes to the right eye var vbl = { x: le.x - bw.x, y: le.y - bw.y }; var faceRotation = Math.atan2(vbl.y, vbl.x); var vbn = { x: ns.x - bw.x, y: ns.y - bw.y }; var dvbl = Math.sqrt(Math.pow(vbl.x, 2) + Math.pow(vbl.y, 2)); var dvbn = Math.sqrt(Math.pow(vbn.x, 2) + Math.pow(vbn.y, 2)); var noseRotation = Math.acos((vbl.x * vbn.x + vbl.y * vbn.y) / (dvbl * dvbn)); var faceAngle = faceRotation / Math.PI * 180; var noseAngle = (noseRotation - Math.PI / 2) / Math.PI * 180; return { stamp: Date.now(), isVisible: true, faceSize: faceSize, faceHeight: norm(vbn), faceCenterX: faceCenterX, faceCenterY: faceCenterY, faceAngle: faceAngle, noseAngle: noseAngle }; } var defaultVoiceFeatures = { stamp: 0, vadLevel: 0, vadState: "INACTIVE" }; function extractVoiceFeatures(state) { return { stamp: Date.now(), vadState: state }; } exports.maxDiff = maxDiff; exports.maxDiffReverse = maxDiffReverse; exports.defaultFaceFeatures = defaultFaceFeatures; exports.extractFaceFeatures = extractFaceFeatures; exports.defaultVoiceFeatures = defaultVoiceFeatures; exports.extractVoiceFeatures = extractVoiceFeatures;<file_sep>/README.md # Tablet Robot Face User Study A collection of [tabletrobotface](https://github.com/mjyc/tablet-robot-face) apps for running a human robot interaction user study. # Demos - Robot apps - [Neck exercise](https://codesandbox.io/s/github/mjyc/tabletrobotface-userstudy/tree/codesandbox_neck_exercise/apps/robot) - [Recipe instructions](https://codesandbox.io/s/github/mjyc/tabletrobotface-userstudy/tree/codesandbox_recipeinsts_breakfast/apps/robot) - [Questions](https://codesandbox.io/s/github/mjyc/tabletrobotface-userstudy/tree/codesandbox_qa_set1/apps/robot) # Getting started 1. Install the latest version of node using [nvm](https://github.com/nvm-sh/nvm). NOTE: the maintainer is using `nvm=0.33.2`, `node=v8.11.0`, and `npm=5.6.0` 1. Build pkgs: ``` cd {path/to/tabletrobotface-userstudy} npm install npm build cd apps/{appname} npm install # repeat the last two steps for remaining apps ``` 1. Run [`robot`](./apps/robot) app: ``` npm run robot ``` <!-- 1. Run [`instructor`](./apps/instructor) app (for giving instructions to participants): ``` npm run instructor ``` --> <file_sep>/apps/robot/src/FeatureChart.js import xs from "xstream"; import { div, canvas, span, input } from "@cycle/dom"; const chartColors = { red: "rgb(255, 99, 132)", orange: "rgb(255, 159, 64)", yellow: "rgb(255, 205, 86)", green: "rgb(75, 192, 192)", blue: "rgb(54, 162, 235)", purple: "rgb(153, 102, 255)", grey: "rgb(201, 203, 207)" }; const color = Chart.helpers.color; export const config = { type: "line", data: { datasets: [ { label: "faceSize", backgroundColor: color(chartColors.red) .alpha(0.5) .rgbString(), borderColor: chartColors.red, fill: false, lineTension: 0, data: [], hidden: true }, { label: "faceHeight", backgroundColor: color(chartColors.orange) .alpha(0.5) .rgbString(), borderColor: chartColors.orange, fill: false, lineTension: 0, data: [], hidden: true }, { label: "faceCenterX", backgroundColor: color(chartColors.blue) .alpha(0.5) .rgbString(), borderColor: chartColors.blue, fill: false, lineTension: 0, data: [], hidden: true }, { label: "faceCenterY", backgroundColor: color(chartColors.green) .alpha(0.5) .rgbString(), borderColor: chartColors.green, fill: false, lineTension: 0, data: [], hidden: true }, { label: "faceAngle", backgroundColor: color(chartColors.purple) .alpha(0.5) .rgbString(), borderColor: chartColors.purple, fill: false, lineTension: 0, data: [], hidden: false }, { label: "noseAngle", backgroundColor: color(chartColors.yellow) .alpha(0.5) .rgbString(), borderColor: chartColors.yellow, fill: false, lineTension: 0, data: [], hidden: false } ] }, options: { title: { display: true, text: "Line chart (hotizontal scroll) sample" }, scales: { xAxes: [ { type: "realtime", realtime: { duration: 20000, ttl: undefined } } ], yAxes: [ { scaleLabel: { display: true, labelString: "value" } } ] }, tooltips: { mode: "nearest", intersect: false }, hover: { mode: "nearest", intersect: false }, plugins: { streaming: { frameRate: 15 } } } }; export default function FeatureChart(sources) { const vdom$ = xs.of( div(".chart", { style: { margin: "auto", width: "75%" } }, [ canvas(".myChart"), div({ style: { textAlign: "center" } }, [ span([input(".faceSize", { attrs: { type: "checkbox" } }), "faceSize"]), span([ input(".faceHeight", { attrs: { type: "checkbox" } }), "faceHeight" ]), span([ input(".faceCenterX", { attrs: { type: "checkbox" } }), "faceCenterX" ]), span([ input(".faceCenterY", { attrs: { type: "checkbox" } }), "faceCenterY" ]), span([ input(".faceAngle", { attrs: { type: "checkbox", checked: "" } }), "faceAngle" ]), span([ input(".noseAngle", { attrs: { type: "checkbox", checked: "" } }), "noseAngle" ]) ]) ]) ); const chartElem$ = sources.DOM.select(".myChart") .element() .take(1); const chartData$ = sources.features.map(features => [ features.faceSize, features.faceHeight, features.faceCenterX, features.faceCenterY, features.faceAngle, features.noseAngle ]); const chart$ = xs.merge( chartElem$.map(elem => ({ type: "CREATE", value: elem })), chartData$.map(data => ({ type: "ADD", value: data })), sources.DOM.select(".faceSize") .events("change") .map(ev => ev.target.checked) .map(v => ({ type: "UPDATE", value: [{ hidden: !v }] })), sources.DOM.select(".faceHeight") .events("change") .map(ev => ev.target.checked) .map(v => ({ type: "UPDATE", value: [{}, { hidden: !v }] })), sources.DOM.select(".faceCenterX") .events("change") .map(ev => ev.target.checked) .map(v => ({ type: "UPDATE", value: [{}, {}, { hidden: !v }] })), sources.DOM.select(".faceCenterY") .events("change") .map(ev => ev.target.checked) .map(v => ({ type: "UPDATE", value: [{}, {}, {}, { hidden: !v }] })), sources.DOM.select(".faceAngle") .events("change") .map(ev => ev.target.checked) .map(v => ({ type: "UPDATE", value: [{}, {}, {}, {}, { hidden: !v }] })), sources.DOM.select(".noseAngle") .events("change") .map(ev => ev.target.checked) .map(v => ({ type: "UPDATE", value: [{}, {}, {}, {}, {}, { hidden: !v }] })) ); return { DOM: vdom$, Chart: chart$ }; } <file_sep>/apps/robot/src/index.js document.body.style.backgroundColor = "white"; document.body.style.margin = "0px"; import xs from "xstream"; import delay from "xstream/extra/delay"; import dropRepeats from "xstream/extra/dropRepeats"; import throttle from "xstream/extra/throttle"; import { div } from "@cycle/dom"; import isolate from "@cycle/isolate"; import { run } from "@cycle/run"; import { withState } from "@cycle/state"; import { timeDriver } from "@cycle/time"; import { makeTime$, recordStreams } from "@mjyc/cycle-time-travel"; import { makeTabletFaceDriver } from "@cycle-robot-drivers/screen"; import { makePoseDetectionDriver } from "cycle-posenet-driver"; import { initializeTabletFaceRobotDrivers, withTabletFaceRobotActions } from "@cycle-robot-drivers/run"; import { mockMediaRecorderSource, makeMediaRecorderDriver, mockDownloadDataSource, makeDownloadDataDriver, mockStreamingChartSource, makeStreamingChartDriver, DataDownloader, VADState, makeVoiceActivityDetectionDriver, vadAdapter, defaultFaceFeatures, extractFaceFeatures, defaultVoiceFeatures, extractVoiceFeatures, RobotApp } from "tabletrobotface-userstudy"; import settings from "../../settings_helper"; import transitions from "./transitions"; import FeatureChart, { config as featureChartConfig } from "./FeatureChart"; import StateChart, { config as stateChartConfig } from "./StateChart"; const postDetectionFPS = 10; function TabletRobotFaceApp(sources) { // sources.state.stream.addListener({next: s => console.debug('reducer state', s)}); const appName = Object.keys(transitions).indexOf(settings.robot.name) !== -1 ? settings.robot.name : "demo"; const transition = transitions[appName].transition; const params = settings.robot.parameters.setName !== "" && typeof transitions[appName].params.sets === "object" && typeof transitions[appName].params.sets[ settings.robot.parameters.setName ] === "object" ? transitions[appName].params.sets[settings.robot.parameters.setName] : transitions[appName].params; const S0 = "S0"; const T = (...args) => transition(...args, params).state; const G = (...args) => transition(...args, params).outputs; const command$ = xs.merge( sources.TabletFace.events("load").mapTo({ type: "LOAD_FSM", value: { S0, T, G } }), sources.TabletFace.events("load") .compose(delay(0)) .mapTo({ type: "START_FSM" }) ); const actionResults$ = xs.merge( sources.FacialExpressionAction.result.map(r => ({ type: "FacialExpressionAction", goal_id: r.status.goal_id, status: r.status.status, result: r.result })), sources.RobotSpeechbubbleAction.result.map(r => ({ type: "RobotSpeechbubbleAction", goal_id: r.status.goal_id, status: r.status.status, result: r.result })), sources.HumanSpeechbubbleAction.result.map(r => ({ type: "HumanSpeechbubbleAction", goal_id: r.status.goal_id, status: r.status.status, result: r.result })), sources.AudioPlayerAction.result.map(r => ({ type: "AudioPlayerAction", goal_id: r.status.goal_id, status: r.status.status, result: r.result })), sources.SpeechSynthesisAction.result.map(r => ({ type: "SpeechSynthesisAction", goal_id: r.status.goal_id, status: r.status.status, result: r.result })), sources.SpeechRecognitionAction.result.map(r => ({ type: "SpeechRecognitionAction", goal_id: r.status.goal_id, status: r.status.status, result: r.result })) ); const fsmUniqueStateStamped$ = sources.state.stream .filter( s => !!s.RobotApp && !!s.RobotApp.fsm && !!s.RobotApp.fsm.stateStamped ) .map(s => s.RobotApp.fsm.stateStamped) .compose(dropRepeats((x, y) => x.state === y.state)); // extract face features const poses$ = sources.PoseDetection.events("poses"); const faceFeatures$ = poses$ .map(poses => extractFaceFeatures(poses)) .startWith(defaultFaceFeatures); // extract voice features const vadState$ = sources.VAD.events("state").compose(throttle(100)); // 10hz const voiceFeatures$ = vadState$ .map(state => extractVoiceFeatures(state)) .startWith(defaultVoiceFeatures); const maxNoseAngle1Sec$ = faceFeatures$ .fold((prev, val) => { prev.unshift(!val.isVisible ? null : val.noseAngle); if (prev.length > postDetectionFPS * 1) prev.pop(); return prev; }, []) .map(val => { val.filter(v => v !== null); if (val.length < 2) return 0; const sorted = val.slice(0).sort((x, y) => x - y); return sorted[sorted.length - 1] - sorted[0]; }); const maxNoseAngle2Sec$ = faceFeatures$ .fold((prev, val) => { prev.unshift(!val.isVisible ? null : val.noseAngle); if (prev.length > postDetectionFPS * 2) prev.pop(); return prev; }, []) .map(val => { val.filter(v => v !== null); if (val.length < 2) return 0; const sorted = val.slice(0).sort((x, y) => x - y); return sorted[sorted.length - 1] - sorted[0]; }); const robotSinks = isolate(RobotApp, "RobotApp")({ state: sources.state, command: command$, fsmUniqueStateStamped: fsmUniqueStateStamped$, actionResults: actionResults$, faceFeatures: faceFeatures$, voiceFeatures: voiceFeatures$, temporalFeatures: xs .combine(maxNoseAngle1Sec$, maxNoseAngle2Sec$) .map(([maxNoseAngle1Sec, maxNoseAngle2Sec]) => ({ maxNoseAngle1Sec, maxNoseAngle2Sec })) }); return { ...robotSinks, command: command$, actionResults: actionResults$, fsmUniqueStateStamped: fsmUniqueStateStamped$, poses: poses$, faceFeatures: faceFeatures$, vadState: vadState$, voiceFeatures: voiceFeatures$ }; } function main(sources) { const options = settings.robot.withTabletFaceRobotActionsOptions; const sinks = withState( withTabletFaceRobotActions(TabletRobotFaceApp, options) )(sources); // to save the first event; it gets fired before recording starts sinks.DOM = sinks.DOM.remember(); const featureChart = settings.robot.charts.enabled ? isolate(FeatureChart)({ DOM: sources.DOM, features: sinks.faceFeatures }) : { DOM: xs.of(""), Chart: xs.never() }; const stateChart = settings.robot.charts.enabled ? isolate(StateChart)({ DOM: sources.DOM, isVisible: sinks.faceFeatures .map(faceFeatures => faceFeatures.isVisible) .compose(throttle(100)), vadState: sinks.vadState.compose(throttle(100)).map(s => VADState[s]) }) : { DOM: xs.of(""), Chart: xs.never() }; if (!settings.robot.recording.enabled) { return { ...sinks, DOM: xs .combine(sinks.DOM, featureChart.DOM, stateChart.DOM) .map(vdoms => div(vdoms)), Chart: featureChart.Chart, Chart2: stateChart.Chart }; } const dataProxy$ = xs.create(); const dataDownloader = DataDownloader(sources, dataProxy$); const vdom$ = xs .combine(sinks.DOM, featureChart.DOM, stateChart.DOM, dataDownloader.DOM) .map(vdoms => div(vdoms)); const videoRecorder$ = xs.merge( sources.VideoRecorder.filter(v => v.type === "READY").mapTo("START"), dataDownloader.VideoRecorder ); const videoStart$ = sources.VideoRecorder.filter(v => v.type === "START"); const time$ = makeTime$(sources.Time, xs.of(true), xs.of(0)); const recordedStreams = recordStreams( [ { stream: sinks.DOM || xs.never(), label: "DOM" }, { stream: sinks.TabletFace || xs.never(), label: "TabletFace" }, { stream: sinks.AudioPlayer || xs.never(), label: "AudioPlayer" }, { stream: sinks.SpeechSynthesis || xs.never(), label: "SpeechSynthesis" }, { stream: sinks.SpeechRecognition || xs.never(), label: "SpeechRecognition" }, { stream: sinks.PoseDetection || xs.never(), label: "PoseDetection" }, { stream: sinks.command, label: "command" }, { stream: sinks.actionResults, label: "actionResults" }, { stream: sinks.fsmUniqueStateStamped, label: "fsmUniqueStateStamped" }, { stream: sinks.poses, label: "poses" }, { stream: sinks.vadState, label: "vadState" } ], time$ ); const data$ = xs.combine.apply(null, recordedStreams).map(recorded => { const labels = recorded.map(r => r.label); const combined = recorded.reduce((out, data, i) => { out[labels[i]] = data; return out; }, {}); return combined; }); dataProxy$.imitate(data$); return { ...sinks, DownloadData: dataDownloader.DownloadData, DOM: vdom$, VideoRecorder: videoRecorder$, Chart: featureChart.Chart, Chart2: stateChart.Chart }; } const drivers = { TabletFace: makeTabletFaceDriver(), PoseDetection: makePoseDetectionDriver({ fps: postDetectionFPS }), VAD: makeVoiceActivityDetectionDriver({ useNoiseCapture: false, activityCounterThresh: 10, activityCounterMax: 30, useDefaultActivityCounting: false }), Time: timeDriver, VideoRecorder: settings.robot.recording.enabled ? makeMediaRecorderDriver() : mockMediaRecorderSource, DownloadData: settings.robot.recording.enabled ? makeDownloadDataDriver() : mockDownloadDataSource, Chart: settings.robot.charts.enabled ? makeStreamingChartDriver(featureChartConfig) : mockStreamingChartSource, Chart2: settings.robot.charts.enabled ? makeStreamingChartDriver(stateChartConfig) : mockStreamingChartSource }; function withAdapters(main, adapters) { return sources => main( Object.keys(sources).reduce((prev, key) => { prev[key] = !!adapters[key] ? adapters[key](sources[key]) : sources[key]; return prev; }, {}) ); } run(withAdapters(main, { VAD: vadAdapter }), { ...initializeTabletFaceRobotDrivers(), ...drivers }); <file_sep>/apps/scripts/printsettings.js #!/usr/bin/env node console.log(JSON.stringify(require("../settings_helper"))); <file_sep>/apps/robot/update.sh #!/usr/bin/env bash rsync -av ../data/parameters ./src/transitions/ sed -i 's|"../../../data/parameters|"./parameters|g' ./src/transitions/index.js ../scripts/printsettings.js | echo {\"robot\": `npx json robot`} | npx json> ./src/settings.json sed -i 's|"../../settings_helper"|"./settings.json"|g' src/index.js npx json -I -f package.json -e 'this.dependencies["tabletrobotface-userstudy"]="~0.0.0"' rm -rf node_modules package-lock.json npm install <file_sep>/apps/robot/src/transitions/demo.js // NOTE: might be called twice if transition and emission fncs are called separately function transition(stateStamped, inputD, inputC, params) { if (stateStamped.state === "S0" && inputD.type === "START") { return { state: "S1", outputs: { RobotSpeechbubbleAction: 'Tap "Hello" when you are ready', HumanSpeechbubbleAction: ["Hello"] } }; } else if ( (stateStamped.state === "S1" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Hello") || (stateStamped.state === "S5" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Again") ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: "How are you?", HumanSpeechbubbleAction: ["Great!", "Meh"], SpeechSynthesisAction: "How are you?" } }; } else if ( stateStamped.state === "S2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Great!" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: "I'm happy to hear that!", HumanSpeechbubbleAction: "", SpeechSynthesisAction: "I'm happy to hear that!" } }; } else if ( stateStamped.state === "S2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Meh" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: "I'm sorry to hear that...", HumanSpeechbubbleAction: "", SpeechSynthesisAction: "I'm sorry to hear that..." } }; } else if ( (stateStamped.state === "S3" || stateStamped.state === "S4") && inputD.type === "SpeechSynthesisAction" && inputD.status === "SUCCEEDED" ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: 'Tap "Again" to repeat', HumanSpeechbubbleAction: ["Again"] } }; } else { return { state: stateStamped.state, outputs: null }; } } var defaultParams = {}; module.exports = { transition: transition, defaultParams: defaultParams }; <file_sep>/src/cycle-media.js import xs from "xstream"; import delay from "xstream/extra/delay"; import sampleCombine from "xstream/extra/sampleCombine"; import { adapt } from "@cycle/run/lib/adapt"; import { button } from "@cycle/dom"; export const isAndroid = () => { return /Android/i.test(navigator.userAgent); }; export const isiOS = () => { return /iPhone|iPad|iPod/i.test(navigator.userAgent); }; export const isMobile = () => { return isAndroid() || isiOS(); }; export const mockMediaRecorderSource = () => { return xs.never(); }; export const makeMediaRecorderDriver = options => { if (!options) { options = {}; } const videoRecorderDriver = sink$ => { const constraints = options.constraints ? options.constraints : { video: { facingMode: "user", width: isMobile() ? undefined : 640, height: isMobile() ? undefined : 480 }, audio: true }; let mediaRecorder = null; let blobs = []; const source$ = xs.create(); navigator.mediaDevices .getUserMedia(constraints) .then(stream => { source$.shamefullySendNext({ type: "READY" }); mediaRecorder = new MediaRecorder(stream); mediaRecorder.ondataavailable = evt => { blobs.push(evt.data); }; mediaRecorder.onstart = () => { source$.shamefullySendNext({ type: "START" }); }; mediaRecorder.onstop = _ => { source$.shamefullySendNext({ type: "BLOBS", value: blobs }); blobs = []; }; }) .catch(err => { console.error("Failed to get MediaStream"); throw err; }); const timeout = options.timeout || 60 * 10000; // 10mins const timeout$ = xs.of("STOP").compose(delay(timeout)); xs.merge(sink$, timeout$).addListener({ next: v => { if (v.type === "COMMAND" || typeof v === "string") { const cmd = typeof v === "string" ? v : v.value; if (cmd === "START") { if (mediaRecorder && mediaRecorder.state !== "recording") { mediaRecorder.start(); } else { console.warn(`mediaRecorder.start() not allowed`); } } else if (cmd === "STOP") { if (mediaRecorder && mediaRecorder.state !== "inactive") { mediaRecorder.stop(); } else { console.warn(`mediaRecorder.stop() not allowed`); } } } } }); return adapt(source$); }; return videoRecorderDriver; }; export function mockDownloadDataSource() { return { DOM: xs.never(), DownloadData: xs.never(), VideoRecorder: xs.never() }; } export function makeDownloadDataDriver({ filenamePrefix = "Data", recordVideo = true, jsonPostProcessFnc = data => data } = {}) { const downloadDataDriver = sink$ => { const createDownloadLinkElement = (id, href, filename) => { const a = document.createElement("a"); a.id = id; a.href = href; a.download = filename; return a; }; const jsonData$ = sink$.filter(v => v.type === "JSON").map(v => v.value); const videoData$ = sink$.filter(v => v.type === "VIDEO").map(v => v.value); if (recordVideo) { const data$ = xs.combine(jsonData$, videoData$); sink$ .filter(v => v.type === "DOWNLOAD") .compose(sampleCombine(data$)) .addListener({ next: ([_, data]) => { const filename = `${filenamePrefix}_${new Date() .toISOString() .replace(/-/g, "_") .replace(/:/g, "_") .replace("T", "_") .slice(0, -5)}`; const a1 = createDownloadLinkElement( "dl-json", window.URL.createObjectURL( new Blob([JSON.stringify(jsonPostProcessFnc(data[0]))], { type: "application/json" }) ), filename ); const a2 = createDownloadLinkElement( "dl-video", window.URL.createObjectURL( new Blob(data[1], { type: "video/mp4" }) ), filename ); a1.click(); a2.click(); } }); } else { sink$ .filter(v => v.type === "DOWNLOAD") .compose(sampleCombine(jsonData$)) .addListener({ next: ([_, jsonData]) => { const filename = `${filenamePrefix}_${new Date() .toISOString() .replace(/-/g, "_") .replace(/:/g, "_") .replace("T", "_") .slice(0, -5)}`; const a1 = createDownloadLinkElement("dl-json", jsonData, filename); a1.click(); } }); } }; return downloadDataDriver; } export function DataDownloader(sources, data$) { const downloadClick$ = sources.DOM.select(".download").events("click"); const vdom$ = !!sources.VideoRecorder ? downloadClick$ .take(1) .mapTo(true) .startWith(false) .map(disabled => button(".download", { props: { disabled } }, "Download") ) : xs.of(button(".download", "Download")); const downloadData$ = !!sources.VideoRecorder ? xs.merge( data$.map(v => ({ type: "JSON", value: v })), sources.VideoRecorder.filter(v => v.type === "BLOBS") // it expects VideoRecorder to run on start .map(v => ({ type: "VIDEO", value: v.value })), sources.VideoRecorder.filter(v => v.type === "BLOBS") // HACK! similar to setTimeout(..., 0) .mapTo({ type: "DOWNLOAD" }) .compose(delay(0)) ) : xs.merge( data$.map(v => ({ type: "JSON", value: v })), downloadClick$.mapTo({ type: "DOWNLOAD" }) ); const videoRecorder$ = !!sources.VideoRecorder ? downloadClick$.mapTo("STOP") : xs.never(); return { DOM: vdom$, DownloadData: downloadData$, VideoRecorder: videoRecorder$ }; } <file_sep>/apps/robot/src/transitions/storytelling_ranger_forester.js // NOTE: might be called twice if transition and emission fncs are called separately function transition(stateStamped, inputD, inputC, params) { var engagedMinNoseAngle = params.engagedMinNoseAngle; var engagedMaxNoseAngle = params.engagedMaxNoseAngle; var disengagedMinNoseAngle = params.disengagedMinNoseAngle; var disengagedMaxNoseAngle = params.disengagedMaxNoseAngle; var disengagedMaxMaxNoseAngle1Sec = params.disengagedMaxMaxNoseAngle1Sec; var disengagedTimeoutIntervalCs = params.disengagedTimeoutIntervalCs; // Happy path if (stateStamped.state === "S0" && inputD.type === "START") { return { state: "S1", outputs: { RobotSpeechbubbleAction: 'Tap "Hello" when you are ready', HumanSpeechbubbleAction: ["Hello"] } }; } else if ( stateStamped.state === "S1" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Hello" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-1.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "RANGER FORESTER by <NAME>", stamp: Date.now() }, goal: { text: "RANGER FORESTER by <NAME>", rate: 0.8, afterpauseduration: 3000 } } } }; } else if (stateStamped.state === "S2" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "RANGER FORESTER by <NAME>" && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-2.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Ranger Forester will check on the animals.", stamp: Date.now() }, goal: { text: "Ranger Forester will check on the animals.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP3", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S3" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Ranger Forester will check on the animals." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-3.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Forester sees insects. This sort of bee cannot sting.", stamp: Date.now() }, goal: { text: "Forester sees insects. This sort of bee cannot sting.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP4", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S4" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Forester sees insects. This sort of bee cannot sting." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-4.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Tweet! Forester can see soft fluff.", stamp: Date.now() }, goal: { text: "Tweet! Forester can see soft fluff.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP5", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S5" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Tweet! Forester can see soft fluff." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-5.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Hiss! A snake is looking for a rock to sit on in the sun.", stamp: Date.now() }, goal: { text: "Hiss! A snake is looking for a rock to sit on in the sun.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP6", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S6" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Hiss! A snake is looking for a rock to sit on in the sun." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-6.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The spiders need to fix the web to get insects.", stamp: Date.now() }, goal: { text: "The spiders need to fix the web to get insects.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP7", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S7" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "The spiders need to fix the web to get insects." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S8", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-7.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Here is the kangaroo family. Forester cannot see the little kangaroo.", stamp: Date.now() }, goal: { text: "Here is the kangaroo family. Forester cannot see the little kangaroo.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP8", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S8" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Here is the kangaroo family. Forester cannot see the little kangaroo." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S9", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-8.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The little kangaroo got stuck in a trap. Forester helps.", stamp: Date.now() }, goal: { text: "The little kangaroo got stuck in a trap. Forester helps.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP9", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S9" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "The little kangaroo got stuck in a trap. Forester helps." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S10", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-9.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The little roo is happy. Back to its family. Thanks Forester.", stamp: Date.now() }, goal: { text: "The little roo is happy. Back to its family. Thanks Forester.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP10", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S10" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "The little roo is happy. Back to its family. Thanks Forester." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S11", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-10.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Forester keeps the trap. He is very upset. He will tell the cops.", stamp: Date.now() }, goal: { text: "Forester keeps the trap. He is very upset. He will tell the cops.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP11", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "S11" && inputD.type === "Features") { if ( // Proactive Next disengagedMaxMaxNoseAngle1Sec >= 0 && // use disengagedMaxMaxNoseAngle1Sec < 0 to disable proactive next inputC.history.speechSynthesisActionResultStamped[0].goal_id.id === "Forester keeps the trap. He is very upset. He will tell the cops." && inputC.face.isVisible && inputC.face.noseAngle < disengagedMaxNoseAngle && inputC.face.noseAngle > disengagedMinNoseAngle && inputC.temporal.maxNoseAngle1Sec < disengagedMaxMaxNoseAngle1Sec ) { return { state: "S12", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-11.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The cops get the man that set the trap. The animals are safe.", stamp: Date.now() }, goal: { text: "The cops get the man that set the trap. The animals are safe.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( // Proactive Pause disengagedTimeoutIntervalCs >= 0 && // use disengagedTimeoutIntervalCs < 0 to disable proactive pause inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Resume" && // don't override human !inputC.history.isVisibleStamped[0].isVisible && // not visible inputC.face.stamp - inputC.history.isVisibleStamped[0].stamp > disengagedTimeoutIntervalCs * 10 ) { return { state: "SP12", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else { return { state: stateStamped.state, outputs: null }; } } else if ( stateStamped.state === "S12" && inputD.type === "SpeechSynthesisAction" && inputD.status === "SUCCEEDED" ) { return { state: "S13", outputs: { RobotSpeechbubbleAction: "The END", HumanSpeechbubbleAction: "", SpeechSynthesisAction: { goal_id: { id: "The END", stamp: Date.now() }, goal: { text: "The END", rate: 0.8, afterpauseduration: 3000 } } } }; // Handle Next } else if ( stateStamped.state === "S1" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-1.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "RANGER FORESTER by <NAME>", stamp: Date.now() }, goal: { text: "RANGER FORESTER by <NAME>", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-2.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Ranger Forester will check on the animals.", stamp: Date.now() }, goal: { text: "Ranger Forester will check on the animals.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-3.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Forester sees insects. This sort of bee cannot sting.", stamp: Date.now() }, goal: { text: "Forester sees insects. This sort of bee cannot sting.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-4.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Tweet! Forester can see soft fluff.", stamp: Date.now() }, goal: { text: "Tweet! Forester can see soft fluff.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S5" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-5.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Hiss! A snake is looking for a rock to sit on in the sun.", stamp: Date.now() }, goal: { text: "Hiss! A snake is looking for a rock to sit on in the sun.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S6" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-6.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The spiders need to fix the web to get insects.", stamp: Date.now() }, goal: { text: "The spiders need to fix the web to get insects.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S7" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S8", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-7.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Here is the kangaroo family. Forester cannot see the little kangaroo.", stamp: Date.now() }, goal: { text: "Here is the kangaroo family. Forester cannot see the little kangaroo.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S8" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S9", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-8.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The little kangaroo got stuck in a trap. Forester helps.", stamp: Date.now() }, goal: { text: "The little kangaroo got stuck in a trap. Forester helps.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S9" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S10", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-9.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The little roo is happy. Back to its family. Thanks Forester.", stamp: Date.now() }, goal: { text: "The little roo is happy. Back to its family. Thanks Forester.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S10" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S11", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-10.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Forester keeps the trap. He is very upset. He will tell the cops.", stamp: Date.now() }, goal: { text: "Forester keeps the trap. He is very upset. He will tell the cops.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S11" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S12", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-11.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The cops get the man that set the trap. The animals are safe.", stamp: Date.now() }, goal: { text: "The cops get the man that set the trap. The animals are safe.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "S12" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Next" ) { return { state: "S13", outputs: { RobotSpeechbubbleAction: "The END", HumanSpeechbubbleAction: "", SpeechSynthesisAction: { goal_id: { id: "The END", stamp: Date.now() }, goal: { text: "The END", rate: 0.8, afterpauseduration: 3000 } } } }; // Handle Pause } else if ( stateStamped.state === "S2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP2", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP3", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP4", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S5" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP5", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S6" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP6", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S7" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP7", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S8" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP8", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S9" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP9", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S10" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP10", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S11" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP11", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; } else if ( stateStamped.state === "S12" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Pause" ) { return { state: "SP12", outputs: { RobotSpeechbubbleAction: 'Tap "Resume" when you are ready', HumanSpeechbubbleAction: ["Resume"], SpeechSynthesisAction: " " } }; // Handle Resume } else if ( stateStamped.state === "SP2" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-1.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "RANGER FORESTER by <NAME>", stamp: Date.now() }, goal: { text: "RANGER FORESTER by <NAME>", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP3" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-2.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Ranger Forester will check on the animals.", stamp: Date.now() }, goal: { text: "Ranger Forester will check on the animals.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP4" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-3.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Forester sees insects. This sort of bee cannot sting.", stamp: Date.now() }, goal: { text: "Forester sees insects. This sort of bee cannot sting.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP5" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-4.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Tweet! Forester can see soft fluff.", stamp: Date.now() }, goal: { text: "Tweet! Forester can see soft fluff.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP6" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-5.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Hiss! A snake is looking for a rock to sit on in the sun.", stamp: Date.now() }, goal: { text: "Hiss! A snake is looking for a rock to sit on in the sun.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP7" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-6.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The spiders need to fix the web to get insects.", stamp: Date.now() }, goal: { text: "The spiders need to fix the web to get insects.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP8" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S8", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-7.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Here is the kangaroo family. Forester cannot see the little kangaroo.", stamp: Date.now() }, goal: { text: "Here is the kangaroo family. Forester cannot see the little kangaroo.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP9" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S9", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-8.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The little kangaroo got stuck in a trap. Forester helps.", stamp: Date.now() }, goal: { text: "The little kangaroo got stuck in a trap. Forester helps.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP10" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S10", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-9.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The little roo is happy. Back to its family. Thanks Forester.", stamp: Date.now() }, goal: { text: "The little roo is happy. Back to its family. Thanks Forester.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP11" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S11", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-10.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Forester keeps the trap. He is very upset. He will tell the cops.", stamp: Date.now() }, goal: { text: "Forester keeps the trap. He is very upset. He will tell the cops.", rate: 0.8, afterpauseduration: 3000 } } } }; } else if ( stateStamped.state === "SP12" && inputD.type === "HumanSpeechbubbleAction" && inputD.status === "SUCCEEDED" && inputD.result === "Resume" ) { return { state: "S12", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-11.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The cops get the man that set the trap. The animals are safe.", stamp: Date.now() }, goal: { text: "The cops get the man that set the trap. The animals are safe.", rate: 0.8, afterpauseduration: 3000 } } } }; // Proactive Resume } else if (stateStamped.state === "SP2" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S2", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-1.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "RANGER FORESTER by <NAME>", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... RANGER FORESTER by <NAME>", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP3" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S3", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-2.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Ranger Forester will check on the animals.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Ranger Forester will check on the animals.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP4" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S4", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-3.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Forester sees insects. This sort of bee cannot sting.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Forester sees insects. This sort of bee cannot sting.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP5" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S5", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-4.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Tweet! Forester can see soft fluff.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Tweet! Forester can see soft fluff.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP6" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S6", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-5.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Hiss! A snake is looking for a rock to sit on in the sun.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Hiss! A snake is looking for a rock to sit on in the sun.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP7" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S7", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-6.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The spiders need to fix the web to get insects.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... The spiders need to fix the web to get insects.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP8" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S8", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-7.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Here is the kangaroo family. Forester cannot see the little kangaroo.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Here is the kangaroo family. Forester cannot see the little kangaroo.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP9" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S9", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-8.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The little kangaroo got stuck in a trap. Forester helps.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... The little kangaroo got stuck in a trap. Forester helps.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP10" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S10", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-9.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The little roo is happy. Back to its family. Thanks Forester.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... The little roo is happy. Back to its family. Thanks Forester.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP11" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S11", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-10.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "Forester keeps the trap. He is very upset. He will tell the cops.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... Forester keeps the trap. He is very upset. He will tell the cops.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else if (stateStamped.state === "SP12" && inputD.type === "Features") { if ( inputC.history.humanSpeechbubbleActionResultStamped[0].result != "Pause" && // don't override human inputC.face.isVisible && (inputC.face.noseAngle < engagedMaxNoseAngle && inputC.face.noseAngle > engagedMinNoseAngle) ) { return { state: "S12", outputs: { RobotSpeechbubbleAction: { type: "IMAGE", value: "/public/img/ranger_forester-11.png" }, HumanSpeechbubbleAction: ["Pause", "Next"], SpeechSynthesisAction: { goal_id: { id: "The cops get the man that set the trap. The animals are safe.", stamp: Date.now() }, goal: { text: ", , , , , , Let's see... The cops get the man that set the trap. The animals are safe.", rate: 0.8, afterpauseduration: 3000 } } } }; } else { return { state: stateStamped.state, outputs: null }; } } else { return { state: stateStamped.state, outputs: null }; } } var defaultParams = { engagedMinNoseAngle: -10, engagedMaxNoseAngle: 10, disengagedMinNoseAngle: -15, disengagedMaxNoseAngle: 15, disengagedMaxMaxNoseAngle1Sec: 20, disengagedTimeoutIntervalCs: 200, sets: { passive: { engagedMinNoseAngle: 0, engagedMaxNoseAngle: 0, disengagedMinNoseAngle: -90, disengagedMaxNoseAngle: 90, disengagedMaxMaxNoseAngle1Sec: -1, disengagedTimeoutIntervalCs: -1 }, proactive: { engagedMinNoseAngle: -10, engagedMaxNoseAngle: 10, disengagedMinNoseAngle: -15, disengagedMaxNoseAngle: 15, disengagedMaxMaxNoseAngle1Sec: 20, disengagedTimeoutIntervalCs: 200 } } }; module.exports = { transition: transition, defaultParams: defaultParams }; <file_sep>/src/features.js // https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ function maxDiff(arr) { const n = arr.length; let maxDiff = -1; let maxRight = arr[n - 1]; for (let i = n - 2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { const diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } function maxDiffReverse(arr) { const n = arr.length; let maxDiff = -1; let maxLeft = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] > maxLeft) maxLeft = arr[i]; else { const diff = maxLeft - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } const defaultFaceFeatures = { stamp: 0, isVisible: false, faceSize: 0, faceHeight: 0, faceCenterX: 0, faceCenterY: 0, faceAngle: 0, noseAngle: 0 }; function norm(pt) { return Math.sqrt(pt.x * pt.x + pt.y * pt.y); } function rotate(pt, theta) { return { x: pt.x * Math.cos(theta) - pt.y * Math.sin(theta), y: pt.x * Math.sin(theta) + pt.y * Math.cos(theta) }; } function extractFaceFeatures(poses) { if ( poses.length === 0 || (!poses[0].keypoints.find(function(kpt) { return kpt.part === "nose"; }) || !poses[0].keypoints.find(function(kpt) { return kpt.part === "leftEye"; }) || !poses[0].keypoints.find(function(kpt) { return kpt.part === "rightEye"; })) ) { return { stamp: Date.now(), isVisible: false, faceSize: defaultFaceFeatures.faceSize, faceHeight: defaultFaceFeatures.faceHeight, faceCenterX: defaultFaceFeatures.faceCenterX, faceCenterY: defaultFaceFeatures.faceCenterY, faceAngle: defaultFaceFeatures.faceAngle, noseAngle: defaultFaceFeatures.noseAngle }; } const ns = poses[0].keypoints.filter(function(kpt) { return kpt.part === "nose"; })[0].position; const le = poses[0].keypoints.filter(function(kpt) { return kpt.part === "leftEye"; })[0].position; const re = poses[0].keypoints.filter(function(kpt) { return kpt.part === "rightEye"; })[0].position; const dnsre = Math.sqrt(Math.pow(ns.x - le.x, 2) + Math.pow(ns.y - le.y, 2)); const dnsle = Math.sqrt(Math.pow(ns.x - re.x, 2) + Math.pow(ns.y - re.y, 2)); const drele = Math.sqrt(Math.pow(re.x - le.x, 2) + Math.pow(re.y - le.y, 2)); const s = 0.5 * (dnsre + dnsle + drele); const faceSize = Math.sqrt(s * (s - dnsre) * (s - dnsle) * (s - drele)); const faceCenterX = (ns.x + le.x + re.x) / 3; const faceCenterY = (ns.y + le.y + re.y) / 3; // a point between two eyes const bw = { x: (le.x + re.x) * 0.5, y: (le.y + re.y) * 0.5 }; // a vector from the point between two eyes to the right eye const vbl = { x: le.x - bw.x, y: le.y - bw.y }; const faceRotation = Math.atan2(vbl.y, vbl.x); const vbn = { x: ns.x - bw.x, y: ns.y - bw.y }; const dvbl = Math.sqrt(Math.pow(vbl.x, 2) + Math.pow(vbl.y, 2)); const dvbn = Math.sqrt(Math.pow(vbn.x, 2) + Math.pow(vbn.y, 2)); let noseRotation = Math.acos((vbl.x * vbn.x + vbl.y * vbn.y) / (dvbl * dvbn)); const faceAngle = (faceRotation / Math.PI) * 180; const noseAngle = ((noseRotation - Math.PI / 2) / Math.PI) * 180; return { stamp: Date.now(), isVisible: true, faceSize: faceSize, faceHeight: norm(vbn), faceCenterX: faceCenterX, faceCenterY: faceCenterY, faceAngle: faceAngle, noseAngle: noseAngle }; } const defaultVoiceFeatures = { stamp: 0, vadLevel: 0, vadState: "INACTIVE" }; function extractVoiceFeatures(state) { return { stamp: Date.now(), vadState: state }; } export { maxDiff, maxDiffReverse, defaultFaceFeatures, extractFaceFeatures, defaultVoiceFeatures, extractVoiceFeatures }; <file_sep>/apps/dataplayer/prestart.sh #!/usr/bin/env bash test -e ../settings.json || echo {} > ../settings.json test -e ../data/fromrobot || mkdir -p ../data/fromrobot ln -sF ../data/fromrobot ./
b6ec567f47905906d457fa2b8589da7312e94a70
[ "JavaScript", "Markdown", "Shell" ]
26
JavaScript
mjyc/tabletrobotface-userstudy
17f08cbd3cb5bd4a90dec1befb979643c8061a5b
8cff7b5a69a8f605263c2e7460e93c9cc6ee84ae
refs/heads/master
<repo_name>kissinpublic/kissinpublic.github.io<file_sep>/js/scripts.js $(window).load(function(){ var $container = $('#isotope'); // init $container.isotope({ // options itemSelector: '.photo-link', masonry: { columnWidth: '.grid-sizer', gutter: 0 } }); });
d116c0249d62ebd0fc011140bb2a67df8a265e9b
[ "JavaScript" ]
1
JavaScript
kissinpublic/kissinpublic.github.io
6f69d8de2fd36b67f3885c8dc283dc166abc3985
e7ef910822ccc068289104d569d9e0e0111b5bcf
refs/heads/master
<repo_name>swilcox/omz-custom<file_sep>/home/.zshcustom/themes/scw.zsh-theme function prompt_char { git branch >/dev/null 2>/dev/null && echo 'λ' && return hg root >/dev/null 2>/dev/null && echo 'Њ' && return echo '$' } local ret_status="%(?:%{$fg_bold[green]%}●:%{$fg_bold[red]%}●%s)" PROMPT='[%{$FG[154]%}%n@$PROMPTHOST%{$fg[white]%}:%{$fg_bold[green]%}${PWD/#$HOME/~}%{$reset_color%}]$(parse_git_dirty)$(prompt_char)%{$reset_color%} ' ZSH_THEME_GIT_PROMPT_PREFIX="" ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}" ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[red]%}" ZSH_THEME_GIT_PROMPT_CLEAN="" <file_sep>/README.md omz-custom ========== oh-my-zsh custom stuff
cff9a13e6f44383a5eb2a3e523259d9599ca6f2d
[ "Markdown", "Shell" ]
2
Shell
swilcox/omz-custom
990d34b0b1ce9d176686a387a5d13de1b9d72d99
da96442b1f6c27c1f054bfe0c5d4352daf494cf7
refs/heads/master
<repo_name>ArmanSadri/coinme-node<file_sep>/src/js/data/Identity.js import CoreObject from "../CoreObject"; import Address from "../Address"; import Utility from "../Utility"; import URI from "urijs"; import Lodash from "lodash"; /** * This class represents a User pointer. * * One user could possibly have more than 1 identity associated with them. * * It is best to use a Natural Key for an Identity */ class Identity extends CoreObject { /** * @type {Address} */ _address; /** * @type {Object} */ _attributes; //region constructor /** * * @param {String|URI|{address:Address, attributes?:Object}} options */ constructor(options) { let address; let attributes = {}; if (Utility.isObject(options)) { address = Utility.take(options, 'address'); attributes = Utility.take(options, 'attributes', 'object'); } else { address = Address.toAddressWithDefaultScheme(options, 'identity'); } super(...arguments); this._address = Address.shouldBeInstance(address, 'address is required'); this._attributes = attributes; // this is optional } //endregion //region properties /** * * @return {Address} */ get address() { return this._address; } /** * Optional attributes * * @return {Object} */ get attributes() { return this._attributes; } //endregion toString() { /** @type {URI} */ var uri = this.address.uri.clone(); Lodash.each(this.attributes || {}, function(value, key) { uri = uri.addSearch(key, value); }); return uri.toString(); } toJson() { return super.toJson({ address: this.toString() }); } } export {Identity}; export default Identity;<file_sep>/src/js/Stopwatch.js 'use strict'; import Utility from "./Utility"; import TimeUnit from "./TimeUnit"; import CoreObject from './CoreObject'; import Logger from "winston"; import Preconditions from "./Preconditions"; import Ticker from './Ticker'; import NanoTimer from 'nanotimer'; const MILLISECONDS = TimeUnit.MILLISECONDS; const MICROSECONDS = TimeUnit.MICROSECONDS; const NANOSECONDS = TimeUnit.NANOSECONDS; /** * * @type {Ticker} */ let SYSTEM_TICKER = Ticker.systemTicker(); class Stopwatch extends CoreObject { /** * * @param {Object} [options] * @param {Ticker} [options.ticker] * @param {boolean} [options.start] */ constructor(options) { let shouldStart = Utility.take(options, 'start', { defaultValue: true }); let ticker = Utility.take(options, 'ticker') || SYSTEM_TICKER; super(...arguments); // options = options || {}; this._ticker = ticker; /** * @type {Number} nanoseconds * @private */ this._startTick = this.ticker.read(); if (shouldStart) { this.start(); } } /** * * @returns {Number} */ get startTick() { return this._startTick; } /** * @returns {Ticker} */ get ticker() { return this._ticker; } /** * Returns {@code true} if {@link #start()} has been called on this stopwatch, * and {@link #stop()} has not been called since the last call to {@code * start()}. */ get running() { return this._running; } get finalized() { return this._finalized; } /** * Starts the stopwatch. * * @return {Stopwatch} */ start() { Preconditions.shouldBeFalsey(this.running, "This stopwatch is already running."); Preconditions.shouldBeFalsey(this.finalized, "This stopwatch cannot be started, stopped, or reset."); this.reset(); this._running = true; this._startTick = this.ticker.read(); return this; } /** * Stops the stopwatch. Future reads will return the fixed duration that had * elapsed up to this point. * * @param {Object} [options] * @param {Boolean} [options.finalize] * @return {Stopwatch} instance * @throws IllegalStateException if the stopwatch is already stopped. */ stop(options) { Preconditions.shouldBeFalsey(this.finalized, "This stopwatch cannot be started, stopped, or reset."); Preconditions.shouldBeTrue(this.running, "This stopwatch is already stopped."); this._running = false; this._elapsedNanos += this.ticker.read() - this._startTick; this._finalized = Utility.take(options, 'finalized', { type: 'boolean', defaultValue: false, required: false }); return this; } /** * Sets the elapsed time for this stopwatch to zero, * and places it in a stopped state. * * @return {Stopwatch} instance */ reset() { Preconditions.shouldBeFalsey(this.finalized, "This stopwatch cannot be started, stopped, or reset."); if (this.running) { this.stop(); } this._elapsedNanos = 0; this._startTick = null; this._running = false; return this; } /** * @returns {Number} */ elapsedNanos() { return this.running ? this.ticker.read() - this._startTick + this._elapsedNanos : this._elapsedNanos; } elapsedMillis() { return this.elapsed(MILLISECONDS); } /** * @returns {Number} */ elapsedMicros() { return this.elapsed(MICROSECONDS); } /** * Returns the current elapsed time shown on this stopwatch, expressed * in the desired time unit, with any fraction rounded down. * * <p>Note that the overhead of measurement can be more than a microsecond, so * it is generally not useful to specify {@link TimeUnit#NANOSECONDS} * precision here. * * @param {TimeUnit} [timeUnit] * @return {Number} */ elapsed(timeUnit) { if (!timeUnit) { timeUnit = MILLISECONDS; } return timeUnit.convert(this.elapsedNanos(), timeUnit); } /** * Returns a string representation of the current elapsed time. */ toString() { let nanos = this.elapsedNanos(); let unit = this.chooseUnit(nanos); let value = nanos / TimeUnit.NANOSECONDS.convert(1, unit); // Too bad this functionality is not exposed as a regular method call return `${value} ${unit.shortName}`; } /** * @private * @param {Number} nanos * @return {TimeUnit} */ static chooseUnit(nanos) { if (TimeUnit.DAYS.convert(nanos, TimeUnit.NANOSECONDS) > 0) { return TimeUnit.DAYS; } if (TimeUnit.HOURS.convert(nanos, TimeUnit.NANOSECONDS) > 0) { return TimeUnit.HOURS; } if (TimeUnit.MINUTES.convert(nanos, TimeUnit.NANOSECONDS) > 0) { return TimeUnit.MINUTES; } if (TimeUnit.SECONDS.convert(nanos, TimeUnit.NANOSECONDS) > 0) { return TimeUnit.SECONDS; } if (TimeUnit.MILLISECONDS.convert(nanos, TimeUnit.NANOSECONDS) > 0) { return TimeUnit.MILLISECONDS; } if (TimeUnit.MICROSECONDS.convert(nanos, TimeUnit.NANOSECONDS) > 0) { return TimeUnit.MICROSECONDS; } return TimeUnit.NANOSECONDS; } } export {Ticker}; export {Stopwatch}; export default Stopwatch;<file_sep>/src/js/slack/AbstractNotificationTemplate.js 'use strict'; import Logger from "winston"; import CoreObject from "~/CoreObject"; import NotificationBuilder from "~/slack/NotificationBuilder"; import Promise from 'bluebird'; /** * * This class is intended to be instantiated early and (generally) once in your app. */ class AbstractNotificationTemplate extends CoreObject { constructor() { super(...arguments); // Utility.defaults(this, { // name: 'NotificationTemplate' // }); // Preconditions.shouldBeString(Ember.get(this, 'name'), 'You must define a name for this template'); } /** * @public * @param {NotificationBuilder} builder * @param {*|undefined} data * @returns {Promise} */ render(builder, data) { // Apply the template. Might be a promise though. let result = this.applyTemplate(builder, data); result = result || builder; return Promise.resolve(result); } /** * * @protected * @param {NotificationBuilder} builder * @param {Object} data * @return {Promise|NotificationBuilder|Object} */ applyTemplate(builder, data) { Logger.silly('Builder', builder); Logger.silly('Data', data); throw new Error('This method must be overridden by a subclass'); } } export default AbstractNotificationTemplate;<file_sep>/test/Errors.spec.js 'use strict'; /** * How to use Chai * @see http://chaijs.com/api/assert/ */ import chai from 'chai'; const assert = chai.assert; const expect = chai.expect; import {Utility, Preconditions} from '../src/js/index'; import {Errors, AbstractError, PreconditionsError, HttpError} from "../src/js/errors"; import {Currency, Bitcoin, Money, Satoshi, USD, Converter} from "../src/js/money"; import {it, describe} from "mocha"; describe('Errors', () => { it('Errors.isErrorClass(Error)', () => { assert.isTrue(Errors.isErrorClass(Error)); }); it('Errors.isErrorClass(AbstractError)', () => { assert.isTrue(Errors.isErrorClass(AbstractError)); }); it('Errors.isErrorInstance(Error)', () => { assert.isTrue(Errors.isErrorInstance(new Error())); }); it('Errors.isErrorInstance(AbstractError)', () => { assert.isTrue(Errors.isErrorInstance(new AbstractError('Abstract'))); }); it('Utility.isInstance(new PreconditionsError())', () => { let e = new PreconditionsError({}); assert.isTrue(Utility.isError(e)); assert.isTrue(Errors.isErrorInstance(e)); }); it('Preconditions.shouldBeType(error)', () => { Preconditions.shouldBeType('error', new PreconditionsError(), 'Should be error type'); Preconditions.shouldBeType('error', new Error(), 'Should be error type'); }) it('PreconditionsError.isInstance(new PreconditionsError())', () => { assert.isTrue(PreconditionsError.isInstance(new PreconditionsError())); }); it('AbstractError.isInstance(new AbstractError())', () => { assert.isTrue(AbstractError.isInstance(new AbstractError())); }); it('Preconditions.shouldBeError', () => { let e = new PreconditionsError({ message: 'message' }); Preconditions.shouldBeError(e, PreconditionsError, 'bad type: ' + e); }); }); describe('HttpError', () => { it('HttpError.isClass(true)', () => { assert.isTrue(HttpError.isClass(HttpError)); }); it('HttpError.isClass(false)', () => { assert.isFalse(HttpError.isClass(Error)); }); it('HttpError.isClass(null)', () => { assert.isFalse(HttpError.isClass(null)); }); it('HttpError.isClass(null)', () => { assert.isFalse(HttpError.isClass(undefined)); }); it('Errors.createBadRequestInstance(string, properties)', () => { let error = Errors.createBadRequestInstance('blah', { propertyName: 'propertyValue' }); assert.isTrue(error instanceof Error); assert.isTrue(error instanceof HttpError); assert.isTrue(HttpError.isInstance(error)); }); }); <file_sep>/src/js/Utility.js 'use strict'; import Lodash from "lodash"; /** @type {Preconditions} */ import Preconditions from "~/Preconditions"; /** @type {Ember} **/ import Ember from "~/Ember"; import CoreObject from "~/CoreObject"; import {Errors} from "./errors"; import Big from "big.js/big"; import URI from "urijs"; import Promise from "bluebird"; import osenv from "osenv"; import { Instant, LocalDate, ZonedDateTime, LocalDateTime, DateTimeFormatter, ZoneOffset, nativeJs, convert, TemporalQueries, LocalTime } from "js-joda"; let TEMPORALS = { 'Instant': Instant, 'LocalTime': LocalTime, 'LocalDate': LocalDate, 'LocalDateTime': LocalDateTime, 'ZonedDateTime': ZonedDateTime }; let EMAIL_PATTERN = /(?:\w)+(?:\w|-|\.|\+)*@(?:\w)+(?:\w|\.|-)*\.(?:\w|\.|-)+$/; /** * @class * @singleton */ class Utility { /** * * @param {URI|String|{baseUri:URI|String, uri:URI|String}} path * @return {URI} */ static getPath(path) { const input = path; let output; if (Utility.isNotExisting(path)) { output = undefined; } else if (Utility.isString(path)) { path = path.trim(); if (path.startsWith('~/')) { path = path.substring(2); output = URI.joinPaths(osenv.home(), path); } else { output = URI(path); } } else if (path instanceof URI) { output = path; } else if (path.uri || path.baseUri) { let baseUri = Utility.getPath(path.baseUri) || ''; let uri = Utility.getPath(path.uri) || ''; if (uri.toString().startsWith('/')) { // absolute uri output = uri; } else { output = URI.joinPaths(baseUri, uri).toString(); } } if (output) { return output; } throw new Error(`I don't know what to do here: ${input}`); } static isTemporal(value) { // Direct Subclass: // ChronoLocalDate, ChronoLocalDateTime, ChronoZonedDateTime, DateTimeBuilder, DayOfWeek, Instant, LocalTime, Month, MonthDay, src/format/DateTimeParseContext.js~Parsed, Year, YearMonth // Indirect Subclass: // LocalDate, LocalDateTime, ZonedDateTime // console.log(value.toString()); // console.log(value.prototype); // console.log(value.__proto__); // console.log(value.constructor); return !!TEMPORALS[value.constructor.name]; } /** * * @param {*} one * @param {*} two * @return {boolean} */ static isSameType(one, two) { let type1 = Utility.typeOf(one); let type2 = Utility.typeOf(two); return type1 === type2; } /** * * @param {String|null|undefined} string * @return {String|undefined} */ static optLowerCase(string) { if (Utility.isNullOrUndefined(string)) { return undefined; } return (Utility.optString(string) || '').toLowerCase(); } /** * * @param {String} string1 * @param {String} string2 * @return {Boolean} */ static isStringEqualIgnoreCase(string1, string2) { if (Utility.isNotExisting(string1) || Utility.isNotExisting(string2)) { return Utility.isSameType(string1, string2); } return Utility.isStringEqual( Utility.optLowerCase(string1), Utility.optLowerCase(string2)); } /** * (null, null) -> true * * @param {String|*} string1 * @param {String|*} string2 * @return {boolean} */ static isStringEqual(string1, string2) { if (Utility.isNotExisting(string1) || Utility.isNotExisting(string2)) { return Utility.isSameType(string1, string2); } string1 = Utility.optString(string1); string2 = Utility.optString(string2); if (!Utility.isSameType(string1, string2)) { return false; } else if (!Utility.isExisting(string1)) { return false; } return string1 === string2; } /** * @param {*} object * @returns {boolean} */ static isObject(object) { let type = Utility.typeOf(object); return 'object' === type || 'instance' === type; } /** * * @param {*} object * @returns {Class} */ static toClass(object) { if (Utility.isClass(object)) { return object; } else if (Utility.isObject(object)) { return object.toClass(); } Preconditions.fail('object|class', Utility.typeOf(object), 'Must be correct type'); } static isNumber(object) { return 'number' === Utility.typeOf(object); } static isClass(object) { return 'class' === Utility.typeOf(object); } static isInstance(object) { return 'instance' === Utility.typeOf(object); } static isError(object) { return 'error' === Utility.typeOf(object); } /** * * @param {*} object * @param {String} path * @param {*} [defaultValue] * @returns {*} */ static result(object, path, defaultValue) { return Lodash.get.apply(Lodash, arguments); } /** * @param {CoreObject|Class<CoreObject>} instance - Must be an instance of CoreObject (or subclass) */ static toClassOrFail(instance) { if (Utility.isInstance(instance)) { } else if (Utility.isClass(instance)) { } else { Preconditions.fail(CoreObject, instance, 'Was not an instance or class. Cannot continue'); } return instance.toClass(); } /** * * @param boolean * @returns {*} */ static ifBoolean(boolean) { if (Utility.isBoolean(boolean)) { return boolean; } return undefined; } /** * Uses Lodash.get, but then removes the key from the parent object. * * It takes properties off of an object and optionally does validation. * * var value = Utility.take(object, key, type); * * var value = Utility.take(object, { * key: String, * }); * * var {value1, value2} = Utility.take(object, [keyAsString1, keyAsString2]); * * var {value1} = Utility.take(object, [keyAsString1]); * * A ruleset is defined as: * * { * // return true to pass. false to fail. * validator: function(value) { return boolean; } throws Error, * type: String, * adapter: function(value) { return new_value; }, * required: true|false|undefined * } * * @param {Object} object * @param {String|Object|Array} keyAsStringObjectArray * @param {String|Function|Class|Object|{required:Boolean,type:String|Class,validator:Function,adapter:Function, [defaultValue]:*}} [optionalTypeDeclarationOrDefaults] - If you pass a function in, it must return true * @param {Boolean} [requiredByDefault] Default value for required. * @throws PreconditionsError * * @returns {*} */ static take(object, keyAsStringObjectArray, optionalTypeDeclarationOrDefaults, requiredByDefault) { if (!object) { object = {}; } Preconditions.shouldBeDefined(keyAsStringObjectArray, 'key must be defined'); //region utilities /** * * @param {{[scope]: Object, [adapter]: function, [validator]: function, [adapter]: function}} ruleset * @param {String} key * @param {*} value * @returns {*} */ function executeValidator(ruleset, key, value) { let fn = Lodash.get(ruleset, 'validator'); let scope = Lodash.get(ruleset, 'scope') || this; if (fn) { Preconditions.shouldBeFunction(fn, 'validator must be type of function'); Preconditions.shouldBeTrue(false !== fn.call(scope, value), 'Failed validation: {key:\'' + key + '\' value:\'' + value + '\''); } return value; } /** * If the ruleset requires, will throw. * * @throws PreconditionsError * @param {{[scope]: Object, [adapter]: function, [validator]: function, [adapter]: function}} ruleset * @param {String} key * @param {*} value * @returns {*} */ function executeAdapter(ruleset, key, value) { let fn = Lodash.get(ruleset, 'adapter'); let scope = Lodash.get(ruleset, 'scope') || this; if (fn) { Preconditions.shouldBeFunction(fn, 'Validator must be a function'); value = fn.call(scope, value); } return value; } /** * If the ruleset requires, will throw. * * @throws PreconditionsError * @param {{[scope]: Object, [adapter]: function, [validator]: function, [adapter]: function, [defaultValue]:*}} ruleset * @param {String} key * @param {*} value * @returns {*} */ function executeRequired(ruleset, key, value) { let required = Lodash.get(ruleset, 'required'); if (Utility.isDefined(ruleset.defaultValue)) { if (!value) { value = ruleset.defaultValue; } } if (true === required) { if (Utility.isNullOrUndefined(value)) { Preconditions.shouldBeExisting(value, `Utility.take(). 'key=${key}' is required`); } } return value; } /** * If the ruleset requires, will throw. * * @throws PreconditionsError * @param {{[scope]: Object, [adapter]: function, [validator]: function, [adapter]: function}} ruleset * @param {String} key * @param {*} value * @returns {*} */ function executeType(ruleset, key, value) { if (!ruleset.required && Utility.isUndefined(value)) { return; } let type = Lodash.get(ruleset, 'type'); if (type) { Preconditions.shouldBeType(type, value, `${key} was wrong type.`); } return value; } /** * Main entry point for checks. * * @param {{[adapter]: function, [validator]: function, [adapter]: function}} ruleset * @param {String} key * @param {*} value * @returns {*} */ function executeChecks(ruleset, key, value) { // console.log(`executeChecks with ruleset: ${JSON.stringify(ruleset)} and (key:${key}) (value:${value})`); value = executeAdapter(ruleset, key, value); value = executeRequired(ruleset, key, value); value = executeType(ruleset, key, value); value = executeValidator(ruleset, key, value); return value; } //endregion //region ruleset - defaults let global_defaults = {}; Preconditions.shouldNotBeInstance(optionalTypeDeclarationOrDefaults, 'the 3rd parameter cannot be an instance of a CoreObject field.'); if (Utility.isObject(optionalTypeDeclarationOrDefaults)) { if (Utility.isClass(optionalTypeDeclarationOrDefaults)) { global_defaults = { type: optionalTypeDeclarationOrDefaults }; } else { global_defaults = Lodash.assign(global_defaults, optionalTypeDeclarationOrDefaults); } optionalTypeDeclarationOrDefaults = null; } else if (Utility.isFunction(optionalTypeDeclarationOrDefaults)) { global_defaults = { validator: optionalTypeDeclarationOrDefaults }; optionalTypeDeclarationOrDefaults = null; } else if (Utility.isBoolean(optionalTypeDeclarationOrDefaults)) { global_defaults = { required: optionalTypeDeclarationOrDefaults }; optionalTypeDeclarationOrDefaults = null; Preconditions.shouldBeUndefined(requiredByDefault, 'You provided two booleans. That\'s strange.'); } else if (Utility.isString(optionalTypeDeclarationOrDefaults)) { global_defaults = { type: optionalTypeDeclarationOrDefaults }; } if (Utility.isBoolean(requiredByDefault)) { // global_defaults.required = global_defaults = Utility.defaults(global_defaults, { required: requiredByDefault }); } // if (Utility.isDefined(global_defaults.defaultValue)) { // throw new Error('has default value global'); // } /** * * @param {Object} [defaults] * @returns {{required:Boolean, validator:Function, type:String|Object, adapter:Function}} */ function toRuleset(defaults) { let ruleset = {}; ruleset = Lodash.defaults(ruleset, defaults || {}, global_defaults, { required: false, validator: null }); return ruleset; } //endregion let mode = Utility.typeOf(keyAsStringObjectArray); //region String Mode if ('string' === mode) { /** @type {String} */ let key = keyAsStringObjectArray; keyAsStringObjectArray = null; /** @type {*} */ let value = Utility.result(object, key); /** * @type {{validator?:function, required?:boolean, type?: string|object}} */ let ruleset = toRuleset(); // if (Utility.isClass(optionalTypeDeclarationOrDefaults)) { // ruleset = { // validator: Utility.typeMatcher(optionalTypeDeclarationOrDefaults), // required: false // }; // } else if (Utility.isFunction(optionalTypeDeclarationOrDefaults)) { // ruleset = { // validator: optionalTypeDeclarationOrDefaults, // required: false // }; // } else if (Utility.isNullOrUndefined(optionalTypeDeclarationOrDefaults)) { // ruleset = { // validator: Utility.yes, // required: false // }; // } else if (Utility.isObject(optionalTypeDeclarationOrDefaults) && !Utility.isInstance(optionalTypeDeclarationOrDefaults)) { // // TODO: apply global defaults. // ruleset = optionalTypeDeclarationOrDefaults; // } else { // throw new TypeError('Not sure how to interpret the rules.') // } if (-1 != key.indexOf('.')) { // It's an object path. let parentPath = key.substring(0, key.lastIndexOf('.')); let itemKey = key.substring(key.lastIndexOf('.') + 1); let parent = Utility.result(object, parentPath); delete parent[itemKey]; } else { delete object[key]; } return executeChecks(ruleset, key, value); } //endregion //region Array/Object mode if ('array' === mode || 'object' === mode) { let result = {}; let defaults = toRuleset(Utility.result(keyAsStringObjectArray, 'defaults', {})); Lodash.forEach(keyAsStringObjectArray, /** * * @param {String|Object|Function} rulesetOrObject * @param {String} [rulesetOrObject.key] * @param {Number|String} keyOrIndex */ function (rulesetOrObject, keyOrIndex) { /** * @type {String} */ let key; /** * @type {Object} */ let ruleset; if ('array' === mode) { if (Utility.isString(rulesetOrObject)) { key = rulesetOrObject; ruleset = Lodash.defaults({}, defaults); // if (Utility.isObject(optionalTypeDeclarationOrDefaults)) { // ruleset = Lodash.defaults(ruleset, optionalTypeDeclarationOrDefaults); // } } else if (Utility.isObject(rulesetOrObject)) { /** * @type {String} */ key = Preconditions.shouldBeString(Utility.result(rulesetOrObject, 'key'), 'key not defined'); ruleset = rulesetOrObject; } else if (Utility.isFunction(rulesetOrObject)) { ruleset = { validator: rulesetOrObject }; } else { throw new Error('Dont know what to do: ' + rulesetOrObject); } } else if ('object' === mode) { key = keyOrIndex; if (Utility.isString(rulesetOrObject)) { ruleset = { type: rulesetOrObject }; } else if (Utility.isObject(rulesetOrObject)) { ruleset = rulesetOrObject; } else if (Utility.isFunction(rulesetOrObject)) { ruleset = { validator: rulesetOrObject }; } else { throw new Error('Dont know what to do: ' + rulesetOrObject); } } else { Preconditions.fail('array|object', mode, 'Unknown mode'); } Preconditions.shouldNotBeBlank(key, 'Key must be defined by here in all situations.'); Preconditions.shouldBeObject(ruleset, 'Must have a valid ruleset: ' + ruleset); // if (Utility.isObject(ruleset)) { // // this is a ruleset that overrides our ruleset. // ruleset = Lodash.defaults({key: key}, ruleset, defaults); // } else if (Utility.isFunction(ruleset)) { // let fn = ruleset; // // ruleset = { // key: key, // validator: fn // }; // } else { // throw new Error('Cannot determine what to do with: ' + typeOfRuleset + ': ' + ruleset); // } ruleset = Lodash.defaults(ruleset, defaults); let requiredType = ruleset.type; // If we don't have a validator yet, check to see if we can get one. if (!ruleset.validator && Utility.isNotBlank(requiredType)) { if ('string' === requiredType) { ruleset.validator = Utility.isString; } else if ('number' === requiredType) { ruleset.validator = Utility.isNumber; } else if ('required' === requiredType) { ruleset.validator = Utility.isExisting; } else { throw new Error('I should add more types: ' + requiredType); } } if ('defaults' === key) { return; } result[key] = executeChecks(ruleset, key, Utility.take(object, key)); }); return result; } else { throw new Error('Not sure how to handle this case: ' + Utility.typeOf(keyAsStringObjectArray)); } //endregion } /** * Creates a test method. Uses Utility.typeOf() * * @param {String|Class} type * @return {function} */ static typeMatcher(type) { // Ember.typeOf(); // 'undefined' // Ember.typeOf(null); // 'null' // Ember.typeOf(undefined); // 'undefined' // Ember.typeOf('michael'); // 'string' // Ember.typeOf(new String('michael')); // 'string' // Ember.typeOf(101); // 'number' // Ember.typeOf(new Number(101)); // 'number' // Ember.typeOf(true); // 'boolean' // Ember.typeOf(new Boolean(true)); // 'boolean' // Ember.typeOf(Ember.makeArray); // 'function' // Ember.typeOf([1, 2, 90]); // 'array' // Ember.typeOf(/abc/); // 'regexp' // Ember.typeOf(new Date()); // 'date' // Ember.typeOf(Ember.Object.extend()); // 'class' // Ember.typeOf(Ember.Object.create()); // 'instance' // Ember.typeOf(new Error('teamocil')); // 'error' // // 'normal' JavaScript object // Ember.typeOf({ a: 'b' }); // 'object' let knownTypes = { 'undefined': true, 'null': true, 'string': true, 'number': true, 'boolean': true, 'function': true, 'array': true, 'instance': true, 'error': true, 'object': true, 'class': true, 'regexp': true, 'date': true }; /** * Should be string. */ { let typeOfType = Utility.typeOf(type); if (!('string' === typeOfType || 'class' === typeOfType)) { Preconditions.fail('string', type, `The type passed in was not a string|class. It was ${typeOfType}`); } } /** * Should be known type. */ { // This will cause an infinite loop. // Preconditions.shouldNotBeBlank(type, 'type missing'); // type = Utility.toLowerCase(type); if (Utility.isString(type)) { type = type.toLowerCase(); Preconditions.shouldBeTrue(knownTypes[type], 'unknown type: ' + type); return (function (/** @type {*} */ object) { let objectType = Utility.typeOf(object); if ('object' === type || 'instance' === type) { return ('object' === objectType) || ('instance' === objectType); } return type === objectType; }); } else if (Utility.isClass(type)) { /** * @type {Class<CoreObject>} */ return function (/** @type {*} */object) { return (type.isInstance(object)); }; } } } /** * Returns a consistent type for the passed item. * * Use this instead of the built-in `typeof` to get the type of an item. * It will return the same result across all browsers and includes a bit * more detail. Here is what will be returned: * * | Return Value | Meaning | * |---------------|------------------------------------------------------| * | 'string' | String primitive or String object. | * | 'number' | Number primitive or Number object. | * | 'boolean' | Boolean primitive or Boolean object. | * | 'null' | Null value | * | 'undefined' | Undefined value | * | 'function' | A function | * | 'array' | An instance of Array | * | 'regexp' | An instance of RegExp | * | 'date' | An instance of Date | * | 'class' | An Ember class (created using Ember.Object.extend()) | * | 'instance' | An Ember object instance | * | 'error' | An instance of the Error object | * | 'object' | A JavaScript object not inheriting from Ember.Object | * * Examples: * ```javascript Ember.typeOf(); // 'undefined' Ember.typeOf(null); // 'null' Ember.typeOf(undefined); // 'undefined' Ember.typeOf('michael'); // 'string' Ember.typeOf(new String('michael')); // 'string' Ember.typeOf(101); // 'number' Ember.typeOf(new Number(101)); // 'number' Ember.typeOf(true); // 'boolean' Ember.typeOf(new Boolean(true)); // 'boolean' Ember.typeOf(Ember.makeArray); // 'function' Ember.typeOf([1, 2, 90]); // 'array' Ember.typeOf(/abc/); // 'regexp' Ember.typeOf(new Date()); // 'date' Ember.typeOf(Ember.Object.extend()); // 'class' Ember.typeOf(Ember.Object.create()); // 'instance' Ember.typeOf(new Error('teamocil')); // 'error' // 'normal' JavaScript object Ember.typeOf({ a: 'b' }); // 'object' ``` * * @method typeOf * @for Ember * @param {Object} object the item to check * @return {String} the type * @public */ static typeOf(object) { let type = Ember.typeOf(object); if ('function' === type) { // Let's isClass a bit further. if (CoreObject.isClass(object) || Errors.isErrorClass(object)) { return 'class'; } else if (Errors.isErrorInstance(object)) { return 'error'; } } else if ('object' === type) { if (CoreObject.isInstance(object)) { return 'instance'; } else if (Utility.isTemporal(object)) { return 'temporal'; } } return type; } /** * @param {Date|*} value * @return {Boolean} */ static isDate(value) { return 'date' === Utility.typeOf(value); } /** * * @param {String} string * @returns {boolean} */ static isEmail(string) { Preconditions.shouldBeString(string, 'Should be string'); var type = Utility.typeOf(string); if (type !== 'string' || !string) { return false; } return EMAIL_PATTERN.test(string); } /** * * @param {*} object * @returns {boolean} */ static isArray(object) { return 'array' === Utility.typeOf(object); } /** * * @param {*} object * @returns {boolean} */ static isBoolean(object) { return 'boolean' === Utility.typeOf(object); } /** * * @param {*} object * @return {boolean} */ static isUndefined(object) { return 'undefined' === Utility.typeOf(object); } /** * * @param {*} object * @returns {boolean} */ static isDefined(object) { return !this.isUndefined(object); } /** * Shorthand: Utility.typeOf() === string * * This is for functional programming. * * @param {*} object * @returns {boolean} */ static isString(object) { return 'string' === Utility.typeOf(object); } /** * Determines if the argument is a Number, String, null, undefined * * @param {*} object * @returns {boolean} */ static isPrimitive(object) { if (Utility.isNullOrUndefined(object)) { return true; } let type = Utility.typeOf(object); let primitives = ['number', 'string']; return -1 !== primitives.indexOf(type); } /** * Determine if something is a promise * * @param {*} object * @return boolean */ static isPromise(object) { return Promise.is(object); } /** * * @param valueOrFn */ static isTruthy(valueOrFn) { let value; if (Utility.isFunction(valueOrFn)) { value = valueOrFn(); } else { value = valueOrFn; } return !!value; } /** * * @param fn * @returns {boolean} */ static isFunction(fn) { return 'function' === Utility.typeOf(fn); } /** * @param {*} object * @returns {boolean} */ static isNotFunction(object) { return 'function' !== Utility.typeOf(object); } /** * @param {*} object * @returns {boolean} */ static isNaN(object) { return Lodash.isNaN(object); } /** * * @param {*} anything * @returns {boolean} */ static isNull(anything) { return 'null' === Utility.typeOf(anything); } /** * * @param {CoreObject|Class} object * @returns {Class|*|Class.<CoreObject>} */ static getClass(object) { if (Utility.isClass(object)) { return object; } Preconditions.shouldBeInstance(object); return object.toClass(); } /** * @param {String|Number|Big|null|NaN|undefined} numberOrStringOrBig * @returns {Big} */ static toBigNumber(numberOrStringOrBig) { if (Utility.isNullOrUndefined(numberOrStringOrBig)) { numberOrStringOrBig = 0; } if (numberOrStringOrBig instanceof Big) { return numberOrStringOrBig; } else if (Utility.isString(numberOrStringOrBig) || Utility.isNumber(numberOrStringOrBig)) { return new Big(numberOrStringOrBig); } Preconditions.fail('Number|String|Big', numberOrStringOrBig, 'Unsupported type'); } /** * * @param {Class|CoreObject|null|undefined} object * @returns {Class|undefined} */ static optClass(object) { if (Utility.isInstance(object)) { return Utility.getClass(object); } else if (Utility.isClass(object)) { return object; } return undefined; } /** * Null-safe way to lowercase * @param {String} string * @returns {String} */ static toLowerCase(string) { if (Utility.isBlank(string)) { return string; } Preconditions.shouldBeString(string); return string.toLowerCase(); } /** * Null-safe way to uppercase. * * @param {String} string * @returns {String} */ static toUpperCase(string) { if (Utility.isBlank(string)) { return string; } Preconditions.shouldBeString(string); return string.toUpperCase(); } /** * * @param object */ static optString(object) { if (!Utility.isExisting(object)) { return undefined; } else { if (Utility.isFunction(object.toString)) { return object.toString(); } else { return '' + object; } } } /** * optJson(undefined) -> undefined * optJson(null) -> undefined * optJson(NaN) -> undefined * optJson(primitive) -> primitive * optJson(object) -> object.toJSON * optJson(object) -> object.toJson * optJson(object) -> object * * @param object * @return {*} */ static optJson(object) { if (!Utility.isExisting(object)) { return undefined; } else if (Utility.isPrimitive(object)) { return object; } else if (Utility.isFunction(object.toJson)) { return object.toJson(); } else if (Utility.isFunction(object.toJSON)) { return object.toJSON(); } else { return object; } } /** * Determines if the input is NotNull, NotNaN, and NotUndefined. * * @param {*} anything * @return {boolean} */ static isExisting(anything) { let u = Utility.isUndefined(anything); let n = Utility.isNaN(anything); let nu = Utility.isNull(anything); return !(u || n || nu); } /** * The opposite of existing. * * @param {*} anything * @returns {boolean} */ static isNotExisting(anything) { return !Utility.isExisting(anything); } /** * * @param {*} object * @returns {boolean} */ static isFalsey(object) { return !object; } /** * * @param object */ static isNotFalsey(object) { return !Utility.isFalsey(object); } /** * Shorthand for value * * @param value * @returns {boolean} */ static isNullOrUndefined(value) { return Utility.isNull(value) || Utility.isUndefined(value); } /** * A value is blank if it is empty or a whitespace string. * * ```javascript * Ember.isBlank(); // true * Ember.isBlank(null); // true * Ember.isBlank(undefined); // true * Ember.isBlank(''); // true * Ember.isBlank([]); // true * Ember.isBlank('\n\t'); // true * Ember.isBlank(' '); // true * Ember.isBlank({}); // false * Ember.isBlank('\n\t Hello'); // false * Ember.isBlank('Hello world'); // false * Ember.isBlank([1,2,3]); // false * ``` * @param {String|Array|Number} stringOrArrayOrNumber * @param {String|Array|Number} [stringOrArrayOrNumber.length] * @return {boolean} */ static isBlank(stringOrArrayOrNumber) { if (!stringOrArrayOrNumber) { return true; } if (Utility.isNotExisting(stringOrArrayOrNumber)) { return true; } let type = Utility.typeOf(stringOrArrayOrNumber); if ('number' === type) { return (0 == stringOrArrayOrNumber); } if (!('array' === type || 'string' === type || 'number' === type)) { Preconditions.fail('type|array', type, `isBlank does not support ${type}`); } return Ember.isBlank(stringOrArrayOrNumber); } /** * * @param {String} string * @return {boolean} */ static isNotBlank(string) { return !Utility.isBlank(string); } /** * @returns {Number} */ static defaultNumber() { let result = 0; Lodash.each(arguments, function (object) { if (Utility.isNumber(object)) { result = object; } }); return result; } /** * * @param {String|Number} value * @return {boolean} */ static isNumeric(value) { if (typeof value === 'number') return true; var str = (value || '').toString(); if (!str) return false; return !isNaN(str); } /** * * @param {*} value * @returns {Number} */ static toNumberOrFail(value) { if (Utility.isNullOrUndefined(value)) { return 0; } else if (Utility.isNumber(value)) { return value; } else if (Utility.isString(value)) { return Number.parseFloat(value); } else if (value instanceof Big) { // is this a risk? return Number.parseFloat(value.toFixed()); } throw new TypeError("unknown type: " + Utility.typeOf(value)); } /** * @param {Number|String|Big|BigJsLibrary.BigJS|Instant|null|undefined|ZonedDateTime} numberOrStringOrBig * @param {String|DateTimeFormatter} [optionalParserOrFormat] * * @return {Instant|undefined} */ static optInstant(numberOrStringOrBig, optionalParserOrFormat) { /** * @type {ZonedDateTime} */ let date = Utility.optDateTime(numberOrStringOrBig, optionalParserOrFormat); if (!date) { return undefined; } return date.toInstant(); } /** * @param {Number|String|Big|BigJsLibrary.BigJS|Instant|null|undefined} numberOrStringOrBig * @param {String|DateTimeFormatter} [optionalParserOrFormat] * * @return {Date|undefined} */ static optDate(numberOrStringOrBig, optionalParserOrFormat) { let date = Utility.optDateTime(numberOrStringOrBig, optionalParserOrFormat); if (!date) { return undefined; } return convert(date); } /** * * @param {String|ZoneOffset|undefined} value * @return {ZoneOffset} */ static toTimeZoneOffset(value) { if (Utility.isNotExisting(value)) { return ZoneOffset.UTC; } else if (Utility.isString(value)) { return ZoneOffset.of(value); } else if (value instanceof ZoneOffset) { return value; } Errors.throwNotSure(value); } /** * @param {Number|String|Big|BigJsLibrary.BigJS|Instant|null|undefined} numberOrStringOrBig * @param {String|DateTimeFormatter|ZoneOffset} [optionalDateFormatStringOrDateFormatter] * * @return {ZonedDateTime|undefined} */ static optDateTime(numberOrStringOrBig, optionalDateFormatStringOrDateFormatter) { if (!numberOrStringOrBig) { return Utility .now() .withZoneSameInstant(Utility.toTimeZoneOffset(optionalDateFormatStringOrDateFormatter)); } if (Utility.isDate(numberOrStringOrBig)) { return LocalDateTime .from(nativeJs(numberOrStringOrBig)) .atZone(Utility.toTimeZoneOffset(optionalDateFormatStringOrDateFormatter)); } if (Utility.isString(numberOrStringOrBig)) { return ZonedDateTime .parse(numberOrStringOrBig, Utility.toDateTimeFormatter(optionalDateFormatStringOrDateFormatter)); } if (Utility.isTemporal(numberOrStringOrBig)) { /** @type {ZoneOffset} */ let zone = numberOrStringOrBig.query(TemporalQueries.zone()); if (!zone) { zone = Utility.toTimeZoneOffset(optionalDateFormatStringOrDateFormatter); } if (numberOrStringOrBig instanceof ZonedDateTime) { return numberOrStringOrBig; } else if (numberOrStringOrBig instanceof Instant) { return ZonedDateTime.ofInstant(numberOrStringOrBig, zone); } /** @type {LocalTime} */ let localTime = numberOrStringOrBig.query(TemporalQueries.localTime()); /** @type {LocalDate} */ let localDate = numberOrStringOrBig.query(TemporalQueries.localDate()); if (!localTime) { localTime = LocalTime.now(zone).toLocalTime(); } if (!localDate) { localDate = LocalDate.now(zone); } return localTime .atDate(localDate) .atZone(zone); } } /** * * This is copied from https://js-joda.github.io/js-joda/esdoc/class/src/format/DateTimeFormatter.js~DateTimeFormatter.html * * |Symbol |Meaning |Presentation |Examples * |--------|----------------------------|------------------|---------------------------------------------------- * | G | era | number/text | 1; 01; AD; Anno Domini * | y | year | year | 2004; 04 * | D | day-of-year | number | 189 * | M | month-of-year | number/text | 7; 07; Jul; July; J * | d | day-of-month | number | 10 * | | | | * | Q | quarter-of-year | number/text | 3; 03; Q3 * | Y | week-based-year | year | 1996; 96 * | w | week-of-year | number | 27 * | W | week-of-month | number | 27 * | e | localized day-of-week | number | 2; Tue; Tuesday; T * | E | day-of-week | number/text | 2; Tue; Tuesday; T * | F | week-of-month | number | 3 * | | | | * | a | am-pm-of-day | text | PM * | h | clock-hour-of-am-pm (1-12) | number | 12 * | K | hour-of-am-pm (0-11) | number | 0 * | k | clock-hour-of-am-pm (1-24) | number | 0 * | | | | * | H | hour-of-day (0-23) | number | 0 * | m | minute-of-hour | number | 30 * | s | second-of-minute | number | 55 * | S | fraction-of-second | fraction | 978 * | A | milli-of-day | number | 1234 * | n | nano-of-second | number | 987654321 * | N | nano-of-day | number | 1234000000 * | | | | * | V | time-zone ID | zone-id | America/Los_Angeles; Z; -08:30 * | z | time-zone name | zone-name | Pacific Standard Time; PST * | X | zone-offset 'Z' for zero | offset-X | Z; -08; -0830; -08:30; -083015; -08:30:15; * | x | zone-offset | offset-x | +0000; -08; -0830; -08:30; -083015; -08:30:15; * | Z | zone-offset | offset-Z | +0000; -0800; -08:00; * | | | | * | p | pad next | pad modifier | 1 * | | | | * | ' | escape for text | delimiter | * | '' | single quote | literal | ' * | [ | optional section start | | * | ] | optional section end | | * | {} | reserved for future use | | * * @param {String|DateTimeFormatter|null} [stringOrFormatter] * @throws {TypeError} if not sure what to do. * @return {DateTimeFormatter} */ static toDateTimeFormatter(stringOrFormatter) { if (Utility.isNotExisting(stringOrFormatter)) { return DateTimeFormatter.ISO_ZONED_DATE_TIME; } else if (Utility.isString(stringOrFormatter)) { Preconditions.shouldNotBeBlank(stringOrFormatter); return DateTimeFormatter.ofPattern(stringOrFormatter); } Errors.throwNotSure(stringOrFormatter); } /** * Proxies to Utility.now() if you pass no arguments. * * This is copied from https://js-joda.github.io/js-joda/esdoc/class/src/format/DateTimeFormatter.js~DateTimeFormatter.html * * |Symbol |Meaning |Presentation |Examples * |--------|----------------------------|------------------|---------------------------------------------------- * | G | era | number/text | 1; 01; AD; <NAME> * | y | year | year | 2004; 04 * | D | day-of-year | number | 189 * | M | month-of-year | number/text | 7; 07; Jul; July; J * | d | day-of-month | number | 10 * | | | | * | Q | quarter-of-year | number/text | 3; 03; Q3 * | Y | week-based-year | year | 1996; 96 * | w | week-of-year | number | 27 * | W | week-of-month | number | 27 * | e | localized day-of-week | number | 2; Tue; Tuesday; T * | E | day-of-week | number/text | 2; Tue; Tuesday; T * | F | week-of-month | number | 3 * | | | | * | a | am-pm-of-day | text | PM * | h | clock-hour-of-am-pm (1-12) | number | 12 * | K | hour-of-am-pm (0-11) | number | 0 * | k | clock-hour-of-am-pm (1-24) | number | 0 * | | | | * | H | hour-of-day (0-23) | number | 0 * | m | minute-of-hour | number | 30 * | s | second-of-minute | number | 55 * | S | fraction-of-second | fraction | 978 * | A | milli-of-day | number | 1234 * | n | nano-of-second | number | 987654321 * | N | nano-of-day | number | 1234000000 * | | | | * | V | time-zone ID | zone-id | America/Los_Angeles; Z; -08:30 * | z | time-zone name | zone-name | Pacific Standard Time; PST * | X | zone-offset 'Z' for zero | offset-X | Z; -08; -0830; -08:30; -083015; -08:30:15; * | x | zone-offset | offset-x | +0000; -08; -0830; -08:30; -083015; -08:30:15; * | Z | zone-offset | offset-Z | +0000; -0800; -08:00; * | | | | * | p | pad next | pad modifier | 1 * | | | | * | ' | escape for text | delimiter | * | '' | single quote | literal | ' * | [ | optional section start | | * | ] | optional section end | | * | {} | reserved for future use | | * * @param {Temporal|LocalDateTime|ZonedDateTime|Number|String|Big|BigJsLibrary.BigJS|Instant|null|undefined} [value] * @param {String|DateTimeFormatter} [optionalDateFormatStringOrDateFormatter] * @return {ZonedDateTime} */ static toDateTime(value, optionalDateFormatStringOrDateFormatter) { if (Utility.isBlank(arguments.length)) { return Utility.now(); } let dateTime = Utility.optDateTime(value, optionalDateFormatStringOrDateFormatter); if (dateTime) { return dateTime; } Errors.throwNotSure(value); } /** * * @return {ZonedDateTime} */ static now() { return ZonedDateTime.now(); } /** * @param args * @return value */ static defaultValue(...args) { let result = null; Lodash.each(arguments, function (object) { if (Utility.isDefined(object)) { result = object; } }); return result; } /** * @returns {*|Object} */ static defaultObject() { let result = null; Lodash.each(arguments, function (object) { if (Utility.isObject(object)) { result = object; } }); return result; } /** * * @param {Object} target * @param {String|{}} propertyNameOrObject * @param {*} [propertyValueOrUndefined] * @returns {Object} */ set(target, propertyNameOrObject, propertyValueOrUndefined) { Preconditions.shouldBeObject(target); if (Utility.isString(propertyNameOrObject)) { let propertyName = propertyNameOrObject; let propertyValue = propertyValueOrUndefined; Preconditions.shouldBeString(propertyName); Preconditions.shouldNotBeBlank(propertyName); Preconditions.shouldBeDefined(propertyValue); return Ember.set(target, propertyName, propertyValue); } else if (Utility.isObject(propertyNameOrObject)) { Preconditions.shouldBeUndefined(propertyValueOrUndefined); Lodash.each(propertyNameOrObject, function (value, key) { Utility.set(target, key, value); }); } } /** * Applies all of the defaults onto the first object. * * @param {Object} object * @param {Object} defaults * @returns {Object} The original object. */ static defaults(object, defaults) { Preconditions.shouldBeObject(object, 'target object must be object.'); Preconditions.shouldBeObject(defaults, 'defaults object must be object.'); let updates = Object.keys(defaults); for (let i = 0, l = updates.length; i < l; i++) { let prop = updates[i]; let value = Ember.get(defaults, prop); Ember.set(object, prop, value); } return object; } /** * * @param {Object} object * @param {String|Array} stringOrArray * @param {String|Object} [defaults] */ static get(object, stringOrArray, defaults) { defaults = defaults || {}; let mode = Utility.isString(stringOrArray) ? 'single' : (Utility.isArray(stringOrArray) ? 'multiple' : 'error'); Preconditions.shouldBeTrue(mode != 'error', `I do not know what to do with ${stringOrArray}`); Preconditions.shouldBeObject(object, 'target object must be object.'); if ('single' === mode) { //noinspection UnnecessaryLocalVariableJS let path = stringOrArray; return Ember.getWithDefault(object, path, defaults); } else if ('multiple' === mode) { //noinspection UnnecessaryLocalVariableJS let array = stringOrArray; let result = Ember.getProperties(array); if (Utility.isDefined(defaults)) { return Utility.defaults(result, defaults); } else { return result; } } throw new Error(`Not sure what to do here`); } /** * * @param {Class} clazz * @return {String|undefined} */ static optClassName(clazz) { if (!clazz) { return undefined; } if (Utility.isClass(clazz)) { return clazz.toString() || clazz.constructor.name; } else if (Utility.isInstance(clazz)) { return Utility.optClassName(clazz.toClass()); } Errors.throwNotSure(clazz); } } export default Utility;<file_sep>/src/js/data/CertificateBundle.js "use strict"; import fs from "fs"; import Preconditions from "../Preconditions"; import Utility from "../Utility"; import CoreObject from "../CoreObject"; import URI from "urijs"; import osenv from "osenv"; import {ResourceLoader, FileResourceLoader, CachedResourceLoader} from "./"; import {LocalFileCache} from "../cache"; import Promise from "bluebird"; //region class Certificate extends CoreObject /** * @class */ class Certificate extends CoreObject { /** * @type {Promise|bluebird} */ _startedLatch; /** * * @param {Object} options * @param {String|URI} options.path */ constructor(options) { //region let uri /** @type {URI} */ let uri = Utility.take(options, 'path', { required: true, adapter(value) { return Utility.getPath(value); } }); //endregion //region let resourceLoader /** @type {ResourceLoader} */ let resourceLoader = Utility.take(options, 'resourceLoader', { adapter: function(value) { if (!value) { let directoryPath = uri.clone().filename(''); value = new CachedResourceLoader({ resourceLoader: new FileResourceLoader({ path: directoryPath, cache: new LocalFileCache({ path: directoryPath }) }) }); } return value; } }); //endregion super(...arguments); this._uri = uri; this._path = this.uri.toString(); this._name = this.uri.filename(); this._resourceLoader = resourceLoader; //region startedLatch let scope = this; this._startedLatch = new Promise((resolve, reject) => { let promise = Promise.resolve(); promise = promise.then(() => this.open()); resolve(promise); }); //endregion } //region getters/setters /** * @property * @readonly * @type {Boolean} * @return {Boolean} */ get started() { return this._startedLatch.isFulfilled(); } /** * @property * @readonly * @type {Promise} * @return {Promise} */ get startedLatch() { return this._startedLatch; } /** * @property * @readonly * @type {ResourceLoader} * @return {ResourceLoader} */ get resourceLoader() { return this._resourceLoader; } /** * @readonly * @property * @type {URI} * @return {URI} */ get uri() { return this._uri; } /** * @readonly * @property * @type {String} * @return {String} */ get path() { return this._path; } /** * @readonly * @property * @type {String} * @return {String} */ get name() { return this._name; } /** * @readonly * @property * @throws {Error} */ get value() { Preconditions.shouldBeTrue(this._started, 'is not started yet'); Preconditions.shouldBeTrue(this.startedLatch.isFulfilled(), 'must be started'); Preconditions.shouldBeFalsey(this.startedLatch.isCancelled(), 'must be started'); Preconditions.shouldBeFalsey(this.startedLatch.isRejected(), 'must not be rejected'); Preconditions.shouldBeTrue(this.startedLatch.isResolved(), 'must be resolved'); return this._value; } //endregion /** * @return {Buffer} */ open() { let scope = this; return this.resourceLoader.load(this.path) .then((value) => { scope._value = value; return value; }); } } //endregion //region class CertificateBundle extends CoreObject /** * System for bundling 3 keys together (key, cert, and ca) * * @class */ class CertificateBundle extends CoreObject { /** * * @param {Object} options * @param {Certificate} options.certificate * @param {Certificate} options.key * @param {Certificate} options.authority */ constructor(options) { function adapter(value) { if (Utility.isString(value) || value instanceof URI) { return new Certificate({path: value}); } return value; } /** @type {Certificate} */ let certificate = Utility.take(options, 'certificate', { required: true, adapter: adapter }); /** @type {Certificate} */ let key = Utility.take(options, 'key', { required: true, adapter: adapter }); /** @type {Certificate} */ let authority = Utility.take(options, 'authority', { required: true, adapter: adapter }); super(options); this._authority = authority; this._key = key; this._certificate = certificate; //region startedLatch this._startedLatch = new Promise((resolve, reject) => { let promise = Promise.resolve(); if (authority) { promise = promise.then(() => authority.open()) } if (key) { promise = promise.then(() => key.open()); } if (certificate) { promise = promise.then(() => certificate.open()); } resolve(promise); }); //endregion } //region getters/setters get startedLatch() { return this._startedLatch; } /** * @readonly * @property * @type {Certificate} * @return {Certificate} */ get certificate() { return this._certificate; } /** * @readonly * @property * @type {Certificate} * @return {Certificate} */ get key() { return this._key; } /** * @readonly * @property * @type {Certificate} * @return {Certificate} */ get authority() { return this._authority; } //endregion /** * coinme-node-key.pem * coinme-node-cert.pem * coinme-wallet-ca-cert.pem * * @param {String} path example ~/.coinme-node * @return {CertificateBundle} */ static fromFolder(path) { let uri = URI((Utility.getPath(path)).toString() + '/'); // fixes the bug when the folder has a leading dot. return new CertificateBundle({ key: uri.filename('coinme-node-key.pem').clone(), certificate: uri.filename('coinme-node-cert.pem').clone(), authority: uri.filename('coinme-wallet-ca-cert.pem').clone() }); } static fromHome() { return CertificateBundle.fromFolder('~/.coinme-node'); } } //endregion export {Certificate}; export {CertificateBundle}; export default CertificateBundle;<file_sep>/test/CoinmeWalletClient.spec.js 'use strict'; /** * How to use Chai * @see http://chaijs.com/api/assert/ */ import {expect, assert} from "chai"; // import {Converter} from "../src/js/money"; import {Identity} from "../src/js/data/Identity"; import {Address} from "../src/js/Address"; import {CoinmeWalletClient, CoinmeWalletClientConfiguration} from "../src/js/net/CoinmeWalletClient"; import Ember from "../src/js/Ember"; import { CertificateBundle, Certificate} from "../src/js/data/CertificateBundle"; import ResourceLoader from "../src/js/data/ResourceLoader"; import {Instant} from "js-joda"; import {Receipt, EndpointTypes, ReceiptEndpoint} from "../src/js/data/Receipt"; import USD from '../src/js/money/USD'; describe('CoinmeWalletClient', () => { // it('CertificateBundle', () => { // // CertificateBundle.fromHome(); // // CertificateBundle.fromFolder('~/.coinme-node'); // // }); // it('CoinmeWalletClientConfiguration.clone', () => { // let configuration = new CoinmeWalletClientConfiguration({ // identity: new Identity('library:/coinme-node') // }); // // let configuration2 = configuration.clone(); // // assert.equal(configuration.identity.toString(), configuration2.identity.toString()) // }); // it('CoinmeWalletClient.notifyReceipt', (done) => { // let source = new ReceiptEndpoint({ // timestamp: Instant.now(), // address: EndpointTypes.KIOSK.toAddress('kiosk:/southcenter'), // amount: USD.create('10000') // }); // // let destination = new ReceiptEndpoint({ // timestamp: Instant.now(), // address: 'bitcoin:/1F1tAaz5x1HUXrCNLbtMDqcw6o5GNn4xqX', // amount: EndpointTypes.WALLET.toMoney('10'), // fee: null // }); // // let receipt = new Receipt({ // identity: 'user:/SMYERMA170QE', // timestamp: Instant.now(), // source: source, // destination: destination // }); // // let client = new CoinmeWalletClient({ // configuration: new CoinmeWalletClientConfiguration({ // baseUrl: 'http://localhost:1339', // identity: new Identity('library:/coinme-node') // }) // }); // // client.notifyReceipt(receipt) // .then(() => { done(null) }) // .catch(done) // ; // }); // // it('CoinmeWalletClient.myself', (done) => { // let client = new CoinmeWalletClient({ // configuration: new CoinmeWalletClientConfiguration({ // certificate: CertificateBundle.fromFolder('~/.coinme-node'), // identity: new Identity('library:/coinme-node') // }) // }); // // client // .peek('SMYERMA170QE') // .then((/** @type {UserExistenceToken} */ user) => { // // assert.equal(user.username, 'SMYERMA170QE'); // assert.isTrue(user.exists); // // return user; // }) // .then(() => { // done(); // }) // .catch((err) => { // done(err); // }); // }); }); <file_sep>/src/js/slack/InlineNotificationTemplate.js import NotificationTemplate from './NotificationTemplate'; class InlineNotificationTemplate extends NotificationTemplate { /** * * @param {NotificationBuilder} builder * @param {*|Object} data * @return {NotificationBuilder} */ applyTemplate(builder, data) { return builder.mergeIntoPayload(data); } } export default InlineNotificationTemplate;<file_sep>/test/Preconditions.spec.js 'use strict'; /** * How to use Chai * @see http://chaijs.com/api/assert/ */ import {expect, assert} from "chai"; import Functions from "../src/js/Functions"; import {Errors, AbstractError, PreconditionsError} from "../src/js/errors"; import {Currency, Bitcoin, Money, Satoshi, USD, Converter} from "../src/js/money"; import "source-map-support/register"; import Preconditions from "../src/js/Preconditions"; import CoreObject from "../src/js/CoreObject"; describe('Preconditions', () => { it('should notice abstract', () => { class Abstract extends CoreObject { constructor() { super(...arguments); // if (this.constructor === Abstract) { // // } Preconditions.shouldBeAbstract(this, Abstract); } } class Concrete extends Abstract { constructor() { super(...arguments); } } // should not crash. new Concrete({}); // should crash. let failed = false; try { new Abstract({}); failed = true; } catch(e) { } assert.isFalse(failed); }); it('Should be undefined', () => { Preconditions.shouldBeUndefined(undefined); }); it('Should be preconditions error', () => { Preconditions.shouldBePreconditionsError(new PreconditionsError()); }); it('shouldNotBeInstance', ()=>{ Preconditions.shouldNotBeInstance(function() {}, 'the 3rd parameter cannot be an instance of a CoreObject field.'); }); it('shouldBeClass', ()=>{ Preconditions.shouldBeClass(CoreObject, 'the 3rd parameter cannot be an instance of a CoreObject field.'); Preconditions.shouldBeClass(CoreObject, CoreObject, 'the 3rd parameter cannot be an instance of a CoreObject field.'); Preconditions.shouldFailWithPreconditionsError(() => { Preconditions.shouldBeClass(Object, 'the 3rd parameter cannot be an instance of a CoreObject field.'); }); Preconditions.shouldFailWithPreconditionsError(() => { Preconditions.shouldBeClass(CoreObject, Bitcoin, 'the 3rd parameter cannot be an instance of a CoreObject field.'); }); }); it('Should be preconditions error', () => { try { Preconditions.shouldBePreconditionsError(new Error()); throw new TypeError("Must throw"); } catch (e) { if (!(e instanceof PreconditionsError)) { throw new TypeError("Was not correct type: " + e); } } }); }); <file_sep>/src/js/data/DelegatedConverter.js 'use strict'; import CoreObject from "../CoreObject"; import Preconditions from "../Preconditions"; import Utility from "../Utility"; import Adapter from "./Adapter"; import Converter from "./Converter"; //region class CoreObjectAdapter /** * Internal class used by DelegatedConverter * * @private */ class CoreObjectAdapter extends Adapter { /** * * @param {CoreObject|Class<CoreObject>} instanceOrClass */ supports(instanceOrClass) { return CoreObject.isInstanceOrClass(instanceOrClass); } /** * @param {CoreObject|*} instance * @returns {*} */ adapt(instance) { this.shouldSupport(instance); return instance.toClass(); } } //endregion /** * Supports different conversion directions. * * This is not tied to money. It supports simple converting. * * {<br> * 'Bitcoin->Satoshi' : function(value) { return value * satoshi_factor; },<br> * 'Satoshi->Bitcoin': function(value) { return value / satoshi_factor; }<br> * }<br> * * @class */ class DelegatedConverter extends Converter { //region constructor /** * @param {Object} options * @param {Object} options.conversions * @param {Adapter} [options.adapter] */ constructor(options) { let adapter = Utility.take(options, 'adapter', { type: Adapter, defaultValue: new CoreObjectAdapter() }); let conversions = Utility.take(options, 'conversions', true); super(...arguments); /** * @type {Object} * @private */ this._conversions = conversions || {}; /** * @type {Adapter} */ this._adapter = adapter; } //endregion //region properties /** * @return {Adapter} */ get adapter() { return this._adapter; } //endregion /** * @param instance * @param clazz * @return {boolean} */ supports(instance, clazz) { let adapter = this.adapter; if (!adapter.supports(instance) || !adapter.supports(clazz)) { return false; } let fn = this.getConversion(instance, clazz); return Utility.isFunction(fn); } /** * Executes the conversion. * * @param {CoreObject|*} input * @param {Class<CoreObject>|Class|*} outputClass * @returns {*} * * @throws {PreconditionsError} if the converter fails to convert into a valid number * @throws {PreconditionsError} if the destinationCurrency is not a valid currency * @throws {PreconditionsError} if converter cannot support the conversion */ convert(input, outputClass) { let fn = this.getConversion(input, outputClass); return fn.call(this, input, outputClass); } /** * Detects the conversion function, given the inputs. * * @param {Class<CoreObject>|Class|*} input * @param {Class<CoreObject>|Class|*} output * * @returns {Function|undefined} */ getConversion(input, output) { /** * @type {String} */ let conversionName = this.getConversionName(input, output); return Preconditions.shouldBeFunction( this._conversions[conversionName], `Converter not found for ${conversionName}`); } /** * * @param {*} input * @param {*} output * @returns {Function} */ optConversion(input, output) { let conversionName = this.optConversionName(input, output); return this._conversions[conversionName]; } /** * * @param {Class<CoreObject>|Class|*} input * @param {Class<CoreObject>|Class|*} output * @private * @return {string} */ getConversionName(input, output) { Preconditions.shouldBeDefined(input, 'param:input'); Preconditions.shouldBeDefined(output, 'param:output'); let adapter = this.adapter; input = Preconditions.shouldBeClass(adapter.adapt(input), 'inputClass must be a class'); output = Preconditions.shouldBeClass(adapter.adapt(output), 'outputClass must be a class'); return Preconditions.shouldNotBeBlank(this.optConversionName(input, output)); } /** * @param {*} input * @param {*} output * @return {string} */ optConversionName(input, output) { if (!input) { input = ''; } if (!output) { output = ''; } return `${input.toString()}->${output.toString()}`; } } export {CoreObjectAdapter}; export {DelegatedConverter}; export default DelegatedConverter;<file_sep>/src/js/slack/AttachmentBuilder.js 'use strict'; import Preconditions from "../Preconditions"; import AbstractBuilder from "../slack/AbstractBuilder"; import FieldBuilder from "../slack/FieldBuilder"; import Utility from "../Utility"; import NotificationBuilder from "./NotificationBuilder"; class AttachmentBuilder extends AbstractBuilder { /** * * @param {{parent: NotificationBuilder}} options */ constructor(options) { Preconditions.shouldBeObject(options, 'AttachmentBuilder constructor requires configuration.'); /** * @type {NotificationBuilder} */ let parent = Utility.take(options, 'parent', { type: NotificationBuilder, required: true }); super(options); this._parent = parent; let payload = Utility.defaults(this.payload, { mrkdwn_in: ['pretext', 'text', 'fields'], color: 'good' }); parent .attachments() .push(payload); } /** * * @returns {AttachmentBuilder} */ get parent() { return this._parent; } /** * * @param {String} value * @returns {AttachmentBuilder} */ title(value) { Preconditions.shouldBeString(value); return this.mergeIntoPayload({ title: value }); } /** * * @param color * @returns {AttachmentBuilder} */ color(color) { Preconditions.shouldBeString(color); return this.mergeIntoPayload({ color: color }); } /** * * @param {String} value * @returns {AttachmentBuilder} */ text(value) { Preconditions.shouldBeString(value); return this.mergeIntoPayload({ text: value }); } /** * @returns {FieldBuilder} */ field() { return new FieldBuilder({ parent: this }) .small(); } /** * * @returns {[]} */ fields() { let fields = this.get('payload.fields'); if (!fields) { fields = []; this.set('payload.fields', fields); } return fields; } } export default AttachmentBuilder; <file_sep>/src/js/errors/HttpError.js import AbstractError from "./AbstractError"; import Lodash from "lodash"; import Utility from "../Utility"; class HttpError extends AbstractError { /** * * @param {String|Object} options */ constructor(options) { if (Utility.isString(options)) { let message = options; options = { message: message }; } /** * @type {String} */ let message = Utility.take(options, 'message', Utility.isString); super(message); // optional this._statusCode = Utility.take(options, 'statusCode', Utility.isNumber); this._properties = Utility.take(options, 'properties', Utility.isNotFunction); } get properties() { return this._properties; } /** * @returns {Number} */ get statusCode() { return this._statusCode; } toJSON() { return Lodash.assign(super.toJSON(), { statusCode: this.statusCode, message: this.message, name: this.name, properties: this.properties }); } } export {HttpError}; export default HttpError;<file_sep>/src/js/CoreObject.js 'use strict'; import Ember from "./Ember"; import Lodash from "lodash"; import Preconditions from "./Preconditions"; import Utility from "./Utility"; import winston from "winston"; const Logger = winston.Logger; /** * This is the base class for all classes in our architecture. * * * @abstract * @class */ export default class CoreObject extends Ember.Object { constructor(options) { let logger; if (Utility.isNotExisting(options) || Utility.isObject(options)) { super(...arguments); logger = Utility.take(options, 'logger'); Lodash.merge(this, options); } else { super({}); } this._logger = logger || new Logger(); } /** * @return {winston.Logger|Logger} */ get logger() { return this._logger; } /** * * @param {string} key * @returns {*|Object} */ get(key) { return Ember.get(this, key); } /** * * @param {string} key * @param {*} value * @returns {CoreObject|*} */ set(key, value) { Ember.set(this, key, value); return this; } /** * @returns {string} */ toString() { return this.toClass().toString(); } /** * * @returns {Class<CoreObject>} */ toClass() { return this.constructor; } toJson(options) { return Lodash.assign({ _class: this.constructor.name }, options || {}); } /** * * @returns {Class<CoreObject>} */ static toClass() { return this; } /** * @returns {String} */ static toString() { return this.constructor.name; } /** * Determines if a class definition is a subclass of CoreObject * * @param {*} clazz * @returns {boolean} */ static isClass(clazz) { if ('function' !== typeof clazz) { return false; } while (clazz) { if (clazz === this) { return true; } clazz = Object.getPrototypeOf(clazz); } return false; } static equals(foreignClass) { return this.isClass(foreignClass); } /** * * @param {CoreObject|Class|*} instanceOrClass * @param {String} [message] * @returns {*} */ static shouldBeClassOrInstance(instanceOrClass, message) { if (!this.isInstance(instanceOrClass) && !this.isClass(instanceOrClass)) { Preconditions.fail(this.toClass(), CoreObject.optClass(instanceOrClass), message || 'Was not the correct class or instance') } return instanceOrClass; } /** * * @param {*|CoreObject} obj * @returns {boolean} */ static isInstance(obj) { return obj instanceof this; } /** * * @param {*|CoreObject} obj * @param {String} [message] * @returns {*|CoreObject} */ static shouldBeInstance(obj, message) { if (!this.isInstance(obj)) { Preconditions.fail(this.toClass(), Utility.optClass(obj), message || 'Was not the correct class') } return obj; } /** * * @param obj * @return {boolean} */ static isInstanceOrClass(obj) { return this.isInstance(obj) || this.isClass(obj); } }<file_sep>/src/js/errors/PreconditionsError.js import Utility from '../Utility'; import AbstractError from './AbstractError'; class PreconditionsError extends AbstractError { /** * * @param {*} options.expectedValue * @param {*} options.actualValue * @param {String} [options.message] * @param {Error} [options.cause] * @param {Error} [options.optionalCause] * @constructor */ constructor(options) { options = options || {}; let cause = options.optionalCause || options.cause; let expectedValue = options.expectedValue; let actualValue = options.actualValue; let message = options.message; super(`failure (expected: '${expectedValue}' [${Utility.typeOf(expectedValue)}]) (actual: '${actualValue}' [${Utility.typeOf(actualValue)}]) (message: ${message})`); this._innerMessage = message; this._cause = cause; this._expectedValue = expectedValue; this._actualValue = actualValue; } get innerMessage() { return this._innerMessage; } get actualValue() { return this._actualValue; } get expectedValue() { return this._expectedValue; } get cause() { return this._cause; } static toString() { return 'PreconditionsError'; } } // /** // * // // */ // function PreconditionsError(expectedValue, actualValue, message, optionalCause) { // // } // // PreconditionsError.prototype = Object.create(Error.prototype); // PreconditionsError.prototype.constructor = PreconditionsError; export {PreconditionsError}; export default PreconditionsError; <file_sep>/src/js/money/CurrencyAdapter.js 'use strict'; import Adapter from '../data'; import Money from './Money'; import Currency from './Currency'; class CurrencyAdapter extends Adapter { /** * @param {Money|Class<Money>|Currency|Class<Currency>} instanceOrClass * @return {Boolean} */ supports(instanceOrClass) { let money = Money.isInstance(instanceOrClass); let currency = Currency.isInstanceOrClass(instanceOrClass); return money || currency; } /** * * @param {Money|Currency} instance * @return {Currency} */ adapt(instance) { return Currency.optCurrency(instance); } } export {CurrencyAdapter}; export default CurrencyAdapter;<file_sep>/src/js/Coinme.js class Coinme { } export default Coinme;<file_sep>/src/js/money/Satoshi.js 'use strict'; import Currency from "./Currency"; import Money from "./Money"; import Bitcoin from "./Bitcoin"; /** * @class Satoshi */ export default class Satoshi extends Currency { /** * @param {Number|String|Big|BigJsLibrary.BigJS} valueInSatoshis * @return {Money} */ static create(valueInSatoshis) { /** * @type {Big} */ let value = Currency.toValueOrFail(valueInSatoshis); return new Money({ value: value, currency: this }); } /** * @param {Money|Number|String|Big|BigJsLibrary.BigJS} valueInSatoshis * @return {Money} */ static fromSatoshis(valueInSatoshis) { return Satoshi.create(valueInSatoshis); } /** * @param {Number|String|Money|Big|BigJsLibrary.BigJS} valueInBitcoinOrMoney * @return {Money} */ static fromBitcoin(valueInBitcoinOrMoney) { let bitcoin = Currency.toValueOrFail(valueInBitcoinOrMoney); return Satoshi.fromSatoshis(bitcoin.times(Bitcoin.SATOSHIS_PER_BITCOIN)); } static toString() { return 'Satoshi'; } }<file_sep>/src/js/index.js 'use strict'; import Coinme from "./Coinme"; import Ember from "./Ember"; import CoreObject from "./CoreObject"; import Functions from "./Functions"; import Preconditions from "./Preconditions"; import Utility from "./Utility"; import Address from "./Address"; import errors from "./errors/index"; import slack from "./slack/index"; import data from "./data/index"; import cache from "./cache/index"; import money from "./money/index"; export {slack} export {data} export {errors} export {cache} export {money} export {Ember}; export {Coinme}; export {CoreObject}; export {Functions}; export {Preconditions}; export {Utility}; export {Address}; export default { slack, data, errors, cache, money, Ember, Coinme, CoreObject, Functions, Preconditions, Utility, Address };<file_sep>/src/js/slack/FieldBuilder.js 'use strict'; import AbstractBuilder from "../slack/AbstractBuilder"; import AttachmentBuilder from "../slack/AttachmentBuilder"; import Preconditions from "../Preconditions"; import Utility from "../Utility"; class FieldBuilder extends AbstractBuilder { /** * * @param {{parent: AttachmentBuilder}} options */ constructor(options) { Preconditions.shouldBeObject(options, 'FieldBuilder constructor requires configuration.'); /** * @type {AttachmentBuilder} */ let parent = Utility.take(options, 'parent', { type: AttachmentBuilder, required: true }); super(options); this._parent = parent; this.parent .fields() .push(this.payload); } /** * @returns {AttachmentBuilder} */ get parent() { return this._parent; } /** * @param {String} value * @returns {FieldBuilder} */ title(value) { Preconditions.shouldBeString(value); return this.mergeIntoPayload({ title: value }); } /** * @param {String} value * @returns {FieldBuilder} */ text(value) { return this.mergeIntoPayload({ value: value }); } /** * * @returns {FieldBuilder} */ small() { return this.mergeIntoPayload({ short: true }); } /** * * @param {String} stringToAdd * @returns {FieldBuilder} */ add(stringToAdd) { var sb = this.get('payload.value') || ''; { sb += (`\n${stringToAdd}`); } return this.text(sb); } /** * * @param {String} key * @param {String} value * @returns {FieldBuilder} */ addKeyValuePair(key, value) { var sb = this.get('payload.value') || ''; { sb += (`\n_${key}:_ ${value}`); } return this.text(sb); } } export default FieldBuilder; <file_sep>/test/User.spec.js 'use strict'; /** * How to use Chai * @see http://chaijs.com/api/assert/ */ import {expect, assert} from "chai"; import Utility from "../src/js/Utility"; import Ember from "../src/js/Ember"; import Preconditions from "../src/js/Preconditions"; import Functions from "../src/js/Functions"; import UserBuilder from "../src/js/data/UserBuilder"; import CoreObject from "../src/js/CoreObject"; import {Errors, AbstractError, PreconditionsError} from "../src/js/errors"; import {Currency, Bitcoin, Money, Satoshi, USD, Converter} from "../src/js/money"; import "source-map-support/register"; // import { NotificationService, NotificationBuilder, NotificationTemplate, InlineNotificationTemplate, UserNotificationTemplate } from '../src/js/slack'; //sadf // Preconditions.shouldBe(function() { return true; }, 'expected', 'actual', 'message'); // NotificationService.url = 'https://hooks.slack.com/services/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'; // NotificationService.mergeIntoPayload({ // channel: '#events-test', // username: 'coinme-node/slack.spec.js' // }); describe('User', () => { it('UserBuilder', () => { let SPEC_VERSION_8 = { 'DBA': 'expirationDate', 'DAC': 'firstName', 'DCS': 'lastName', 'DAD': 'middleName', 'DBB': 'birthDate', 'DCB': 'gender', 'DAG': 'addressLine1', 'DAH': 'addressLine2', 'DAI': 'addressCity', 'DAJ': 'addressState', 'DAK': 'addressZipcode', 'DAQ': 'username', 'DCG': 'addressCountry', 'DCL': 'race' }; let user = UserBuilder.fromVersion8({ 'DBA': 'expirationDate', 'DAC': 'firstName', 'DCS': 'lastName', 'DAD': 'middleName', 'DBB': 'birthDate', 'DCB': 'gender', 'DAG': 'addressLine1', 'DAH': 'addressLine2', 'DAI': 'addressCity', 'DAJ': 'addressState', 'DAK': 'addressZipcode', 'DAQ': 'username', 'DCG': 'addressCountry', 'DCL': 'race' }); assert.equal(user.expirationDate, 'expirationDate'); assert.equal(user.username, 'username'); assert.equal(user.firstName, 'firstName'); assert.equal(user.lastName, 'lastName'); assert.equal(user.middleName, 'middleName'); assert.equal(user.birthDate, 'birthDate'); assert.equal(user.addressLine1, 'addressLine1'); assert.equal(user.addressLine2, 'addressLine2'); assert.equal(user.addressCity, 'addressCity'); assert.equal(user.addressState, 'addressState'); assert.equal(user.addressZipcode, 'addressZipcode'); assert.equal(user.addressCountry, 'addressCountry'); assert.equal(user.gender, 'gender'); assert.equal(user.race, 'race'); }); });<file_sep>/src/js/cache/Cache.js import CoreObject from "../CoreObject"; import Utility from "../Utility"; import URI from "urijs"; import Preconditions from "../Preconditions"; import Promise from "bluebird"; /** * @class Cache * @extends CoreObject * @abstract */ class Cache extends CoreObject { /** * @protected * @type {Promise} */ _startedLatch; //region constructor constructor(options) { super(options); Preconditions.shouldBeAbstract(this, Cache); } //endregion //region getters/setters /** * @readonly * @property * @return {Promise} */ get startedLatch() { return this._startedLatch; } //endregion /** * @abstract * @param {String|URI} path * @return {Promise} */ read(path) { let scope = this; return Promise.resolve() .then(() => scope.startedLatch) .then(() => { return Utility.getPath(path); }); } } export {Cache} export default Cache;<file_sep>/test/Address.spec.js 'use strict'; /** * How to use Chai * @see http://chaijs.com/api/assert/ */ import {expect, assert} from "chai"; import URI from "urijs"; import {Errors, AbstractError, PreconditionsError} from "../src/js/errors"; import {Currency, Bitcoin, Money, Satoshi, USD, Converter} from "../src/js/money"; import Address from "../src/js/Address"; import uuid from 'node-uuid'; describe('URI', () => { it('URI()', () => { /** * @type {URI} */ let uri = URI('bitcoin:asdf-asdf'); assert.equal(uri.scheme(), 'bitcoin'); assert.equal(uri.path(), 'asdf-asdf', 'path'); }); }); describe('Address', () => { it('Address.toUri', () => { assert.equal(Address.toUri('bitcoin://1FfmbHfnpaZjKFvyi1okTjJJusN455paPH').scheme(), 'bitcoin'); assert.equal(Address.toUri('bitcoin://1FfmbHfnpaZjKFvyi1okTjJJusN455paPH').host(), '1FfmbHfnpaZjKFvyi1okTjJJusN455paPH'); assert.equal(Address.toUri('bitcoin:/1FfmbHfnpaZjKFvyi1okTjJJusN455paPH').scheme(), 'bitcoin'); assert.equal(Address.toUri('bitcoin:/1FfmbHfnpaZjKFvyi1okTjJJusN455paPH').host(), '1FfmbHfnpaZjKFvyi1okTjJJusN455paPH'); }); it('Address.toAddress', () => { let u = uuid.v4(); let address = Address.toAddress('kiosk:/' + u); assert.equal(address.resource, 'kiosk', 'resource mismatch'); assert.equal(address.value, u, `value mismatch`); assert.equal(Address.toAddress('kiosk:/southcenter').resource, 'kiosk'); assert.equal(Address.toAddress('kiosk:/southcenter').value, 'southcenter'); }); it('Works', () => { let address = new Address('bitcoin:/1FfmbHfnpaZjKFvyi1okTjJJusN455paPH'); assert.equal(address.resource, 'bitcoin'); console.log(address.uri); assert.equal(address.value, '1FfmbHfnpaZjKFvyi1okTjJJusN455paPH'); }); it('Fail with incomplete address (with valid scheme)', () => { try { new Address('bitcoin'); } catch (e) { console.log(e); assert.isTrue(PreconditionsError.isInstance(e)); } }); it('Fail with incomplete address (with invalid scheme)', () => { try { new Address('asdfasdf:/host'); } catch (/** @type {PreconditionsError} */e) { console.log(e); assert.isTrue(PreconditionsError.isInstance(e)); assert.equal(e.innerMessage, 'validator not found for \'asdfasdf\''); } }); }); <file_sep>/src/js/data/CachedResourceLoader.js import Utility from "../Utility"; import URI from "urijs"; import {Cache, LocalFileCache} from "../cache"; import ResourceLoader from "./ResourceLoader"; /** * @class CachedResourceLoader * @extends ResourceLoader */ class CachedResourceLoader extends ResourceLoader { /** * * @param {Object} options * @param {ResourceLoader} options.resourceLoader * @param {Cache} [options.cache] */ constructor(options) { //region let cache /** @type {Cache} */ let cache = Utility.take(options, 'cache', { adapter(value) { if (!value) { value = new LocalFileCache(); } return value; } }); //endregion /** @type {ResourceLoader} */ let resourceLoader = Utility.take(options, 'resourceLoader', ResourceLoader, true); super(options); this._loader = resourceLoader; this._cache = cache; this._startedLatch = new Promise((resolve, reject) => { let promise = Promise.resolve(); promise = promise.then(() => cache.startedLatch); promise = promise.then(() => resourceLoader.startedLatch); resolve(promise); }); } //region getters/setters /** * @property * @readonly * @type {ResourceLoader} * @return {ResourceLoader} */ get resourceLoader() { return this._loader; } /** * @property * @readonly * @type {Cache} * @return {Cache} */ get cache() { return this._cache; } //endregion load(path) { let cache = this.cache; let resourceLoader = this.resourceLoader; return super .load(path) .then((/**@type {URI}*/path) => { return cache .read(path) .then((value) => { return value || resourceLoader.load(path); }); }); } } export {CachedResourceLoader}; export default CachedResourceLoader;<file_sep>/src/js/money/Ethereum.js 'use strict'; import Preconditions from "../Preconditions"; import Currency from "./Currency"; import Money from "./Money"; /** * Represents the Ethereum currency in memory. * * This class cannot be instantiated. Everything is static and the constructor throws, so treat it like a singleton. * * @beta * @class Ethereum */ class Ethereum extends Currency { /** * * @param {Money|String|Number|null|undefined} valueInEthereum * @returns {Money} */ static fromEthereum(valueInEthereum) { /** * @type {Number} */ let value = Currency.toValueOrFail(valueInEthereum); /** * @type {Class.<Currency>|undefined} */ let currency = Currency.optCurrency(valueInEthereum); if (currency) { Ethereum.shouldBeEthereum(currency); } return new Money({ value: value, currency: Ethereum }); } //region Detection /** * Detects if you pass in either Money or Currency of type Ethereum <br> * <br> * Ethereum -> true <br> * money<Ethereum> -> true <br> * * @param {Money|Currency|Class<Currency>} moneyOrCurrency * @return {Boolean} */ static isEthereum(moneyOrCurrency) { if (!moneyOrCurrency) { return false; } let currency = Currency.optCurrency(moneyOrCurrency); return Ethereum.isClass(currency) || Ethereum.isInstance(currency); } /** * If {@link Ethereum#isEthereum} returns false, will throw. * * @param {Money|Currency|Class<Currency>} moneyOrCurrency * @return {Class<Currency>} * @throws {PreconditionsError} if not an instance of Money (for Ethereum) or the Ethereum class itself. */ static shouldBeEthereum(moneyOrCurrency) { if (!Ethereum.isEthereum(moneyOrCurrency)) { Preconditions.fail(Ethereum, Currency.optCurrency(moneyOrCurrency) || moneyOrCurrency); } return moneyOrCurrency; } //endregion static toString() { return 'Ethereum'; } } // Currency.types.register('Ethereum', Ethereum); // Currency.types.register('ETH', Ethereum); export default Ethereum;<file_sep>/src/js/cache/LocalFileCache.js import Utility from "../Utility"; import URI from "urijs"; import filecache from "filecache"; import Promise from "bluebird"; import osenv from "osenv"; import mkdirp from "mkdirp"; import Cache from "./Cache"; /** * @class LocalFileCache * @extends Cache */ class LocalFileCache extends Cache { _config = { watchDirectoryChanges: true, watchFileChanges: false, hashAlgo: 'sha1', gzip: true, deflate: true, debug: true }; //region constructor /** * * @param {Object} options * @param {String|URI} [options.path] defaults to tmpdir * @param {{watchDirectoryChanges: boolean, watchFileChanges: boolean, hashAlgo: string, gzip: boolean, deflate: boolean, debug: boolean}} [options.config] */ constructor(options) { let path = Utility.take(options, 'path', { adapter(value) { return URI(value || (osenv.tmpdir() + '/coinme')); } }); let config = Utility.take(options, 'config', false); super(options); this._config = Utility.defaults(config || {}, this._config); this._fc = filecache(this.config); this._path = path; this._started = false; let fc = this.fc; let scope = this; if (this.config.watchDirectoryChanges && this.config.debug) { fc.on('change', function (d) { scope.logger.debug('! file changed'); scope.logger.debug(' full path: %s', d.p); scope.logger.debug(' relative path: %s', d.k); scope.logger.debug(' length: %s bytes', d.length); scope.logger.debug(' %s bytes (gzip)', d.gzip.length); scope.logger.debug(' %s bytes (deflate)', d.deflate.length); scope.logger.debug(' mime-type: %s', d.mime_type); scope.logger.debug(' mtime: %s', d.mtime.toUTCString()); }); } this._startedLatch = new Promise((resolve, reject) => { let cache_dir = scope.path.toString(); mkdirp(cache_dir, function (err) { if (err) { return reject(err); } fc.load(cache_dir, function (err, cache) { if (err) { reject(err); } else { scope._items = cache; resolve(); } }); fc.on('ready', function (cache) { scope._items = cache; }); }) }); this.startedLatch.catch((err) => { scope._error = err; }); this.startedLatch.finally(() => { scope._started = true; }); } //endregion //region getters/setters /** * @property * @readonly * @type {Promise} * @return {Promise} */ get startedLatch() { return this._startedLatch; } /** * @property * @readonly * @type {boolean} * @return {boolean} */ get started() { return this._started; } /** * @property * @readonly * @type {undefined|Error} * @return {boolean} */ get hasError() { return !!this.error; } /** * @property * @readonly * @type {undefined|Error} * @return {undefined|Error} */ get error() { return this._error; } /** * The items in the cache. * @readonly * @private * @type {Object} * @return {Object} */ get items() { return this._items; } /** * @private * @property * @readonly * @type {filecache} * @return {filecache} */ get fc() { return this._fc; } /** * @property * @readonly * @type {String} * @return {{watchDirectoryChanges: boolean, watchFileChanges: boolean, hashAlgo: string, gzip: boolean, deflate: boolean, debug: boolean}} */ get config() { return this._config; } /** * @property * @readonly * @type {URI} * @return {URI} */ get path() { return this._path; } //endregion /** * * @param {String|URI} path * @return {Promise} */ read(path) { /** @type {URI} */ let base_path = this.path; /** @type {winston.Logger} */ let logger = this.logger; let scope = this; return super .read(path) .then((/** @type {URI} */path) => { if (scope.error) { // an error here means that this cache is fucked. throw scope.error; } return path; }) .then((path) => { return URI.joinPaths(base_path, path); }) .then((/** @type {URI} */absolutePath) => { let pathString = absolutePath.toString().substring(base_path.toString().length); if (pathString.startsWith('/')) { pathString = pathString.substring(1); } return pathString; }) .then((/** @type {String} */filePath) => { let items = scope.items; let result = items[filePath]; if (!result) { logger.warn(`Not sure why, but ${filePath} was not found in ${items}`); } return result; }); } } export {LocalFileCache} export default LocalFileCache;<file_sep>/src/js/data/SignTool.js 'use strict'; import jwt from "jsonwebtoken"; import Preconditions from "../Preconditions"; import Utility from '../Utility'; import CoreObject from '../CoreObject' /** * @class SignTool */ class SignTool extends CoreObject { /** * * @param {Object} options * @param {String} [options.secret] * @param {String} [options.issuer] */ constructor(options) { let secret = Utility.take(options, 'secret', 'string', false); let issuer = Utility.take(options, 'issuer', 'string', false); super(...arguments); this._issuer = issuer; this._secret = secret; } /** * @readonly * @property * @type {String} * @return {String} */ get issuer() { return this._issuer; } /** * @readonly * @property * @type {String} * @returns {String} */ get secret() { return this._secret; } /** * * @param {String} token * @param {Object} options * @param {boolean|String} [options.issuer] * @param {boolean|String} [options.subject] * @param {boolean|String} [options.audience] * @static */ containsHeaders(token, options) { // Will crash if not valid let decodedObject = jwt.decode(token, { complete: true }); // let result = decodedObject.payload; let payload = decodedObject.payload; { let requiresAudience = Utility.isTrue(options.audience); let hasAudience = !Utility.isBlank(payload.aud); if (requiresAudience && !hasAudience) { return null; } } { let requiresIssuer = Utility.isTrue(options.issuer); let hasIssuer = !Utility.isBlank(payload.iss); if (requiresIssuer && !hasIssuer) { return null; } } { let requiredSubject = Utility.isTrue(options.subject); let hasSubject = !Utility.isBlank(payload.sub); if (requiredSubject && !hasSubject) { return null; } } // TODO: verify the signature somehow? return true; } /** * * @param {String} token * @param {Object} options * @param {String} [options.issuer] * @param {String} [options.subject] * @param {String} [options.audience] * @static */ read(token, options) { let secret = this.secret; // Will crash if not valid jwt.verify(token, secret, options); return jwt.decode(token, secret); } /** * * @param {Object} object * @param {Object} options * @param {String} [options.issuer] * @param {String} [options.subject] * @param {String} [options.audience] * @param {String} [options.secret] * @return {String} token * @static */ write(object, options) { let secret = Utility.defaultValue(options.secret, this.secret); Preconditions.shouldBeObject(object); return jwt.sign(object, secret, options); } } export {SignTool}; export default SignTool;<file_sep>/src/js/RateLimiter.js import Preconditions from "./Preconditions"; import TimeUnit from "./TimeUnit"; import Utility from "./Utility"; import CoreObject from "./CoreObject"; import Stopwatch from "./Stopwatch"; import Errors from "./errors/Errors"; import Logger from 'winston'; class RateLimiter extends CoreObject { _permitsPerSecond; constructor(options) { super(options); /** * @type {Stopwatch} * @private */ this._stopwatch = new Stopwatch({ start: true }); // /** // * @type {String} // * @private // */ // this._failAction = Utility.take(options, 'failAction', { // type: 'string', // required: false, // defaultValue: 'wait' // }); } //region property: {Stopwatch} stopwatch /** * @returns {Stopwatch} */ get stopwatch() { return this._stopwatch; } //endregion //region property: {Ticker} ticker /** * * @return {Ticker} */ get ticker() { return this.stopwatch.ticker; } //endregion //region property: {Number} permitsPerSecond /** * Updates the stable rate of this {@code RateLimiter}, that is, the * {@code permitsPerSecond} argument provided in the factory method that * constructed the {@code RateLimiter}. Currently throttled threads will <b>not</b> * be awakened as a result of this invocation, thus they do not observe the new rate; * only subsequent requests will. * * <p>Note though that, since each request repays (by waiting, if necessary) the cost * of the <i>previous</i> request, this means that the very next request * after an invocation to {@code setRate} will not be affected by the new rate; * it will pay the cost of the previous request, which is in terms of the previous rate. * * <p>The behavior of the {@code RateLimiter} is not modified in any other way, * e.g. if the {@code RateLimiter} was configured with a warmup period of 20 seconds, * it still has a warmup period of 20 seconds after this method invocation. * * @param {Number} permitsPerSecond the new stable rate of this {@code RateLimiter} * @throws IllegalArgumentException if {@code permitsPerSecond} is negative or zero */ set permitsPerSecond(permitsPerSecond) { Preconditions.shouldBeExisting(permitsPerSecond); Preconditions.shouldBeTrue(permitsPerSecond > 0.0 && !Utility.isNaN(permitsPerSecond), "rate must be positive"); this._permitsPerSecond = Preconditions.shouldBePositiveNumber(permitsPerSecond, 'Rate must be positive'); this.doSetRate(permitsPerSecond, this.stopwatch.elapsedMicros()); } /** * * @returns {Number} */ get permitsPerSecond() { return this._permitsPerSecond; } //endregion /** * Acquires a single permit from this {@code RateLimiter}. Returns a Promise that will resolve or reject. * The default maximum time to wait is 30 seconds. * * <p>This method is equivalent to {@code acquire(1)}. * * @param {Number} [permits] defaults to 1 * @param {Number} [timeout] defaults to 30 * @param {TimeUnit} [timeUnit] defaults to seconds * @return {Promise} time spent sleeping to enforce rate, in seconds; 0.0 if not rate-limited * @since 16.0 (present in 13.0 with {@code void} return type}) */ acquire(permits, timeout, timeUnit) { return this.tryAcquire(permits, timeout, timeUnit); } /** * Reserves the given number of permits from this {@code RateLimiter} for future use, returning * the number of microseconds until the reservation can be consumed. * * @param {Number} [permits] * @return {Number} time in microseconds to wait until the resource can be acquired, never negative */ reserve(permits) { permits = this.checkPermits(permits); return this.reserveAndGetWaitLength(permits, this.stopwatch.elapsedMicros()); } /** * Reserves next ticket and returns the wait time that the caller must wait for. * * @private * @param {Number} permits * @param {Number} nowMicros * @return {Number} the required wait time, never negative */ reserveAndGetWaitLength(permits, nowMicros) { let momentAvailable = this.reserveEarliestAvailable(permits, nowMicros); let waitLength = Math.max(momentAvailable - nowMicros, 0); return waitLength; } /** * @private * @param {Number} nowMicros * @param {Number} timeoutMicros * @returns {boolean} */ canAcquire(nowMicros, timeoutMicros) { return this.queryEarliestAvailable(nowMicros) - timeoutMicros <= nowMicros; } /** * Acquires the given number of permits from this {@code RateLimiter} if it can be obtained * without exceeding the specified {@code timeout}, or returns {@code false} * immediately (without waiting) if the permits would not have been granted * before the timeout expired. * * @param {Number} [permits] the number of permits to acquire * @param {Number} [timeout] the maximum time to wait for the permits. Negative values are treated as zero. * @param {TimeUnit} [unit] the time unit of the timeout argument * @return {Promise} if the permits were acquired * @throws IllegalArgumentException if the requested number of permits is negative or zero */ tryAcquire(permits, timeout, unit) { Preconditions.shouldBeNumber(this.permitsPerSecond, 'Rate must be defined.'); permits = RateLimiter.checkPermits(permits); timeout = Utility.defaultNumber(timeout, 30); unit = Utility.defaultObject(unit, TimeUnit.SECONDS); let timeoutMicros = Math.max(unit.toMicros(timeout), 0); let microsToWait; let nowMicros = this.stopwatch.elapsedMicros(); let goalMicros = this.queryEarliestAvailable(nowMicros); if (!this.canAcquire(nowMicros, timeoutMicros)) { return Promise.reject(new Error(`RateLimit exceeded: (rate:${this.permitsPerSecond}/sec) (timeoutMicros:${timeoutMicros}) (goalMicros: ${goalMicros}) (differenceMicros:${goalMicros - nowMicros})`)); } else { microsToWait = this.reserveAndGetWaitLength(permits, nowMicros); } Preconditions.shouldBeExisting(this.ticker, 'ticker'); return this.ticker.wait(microsToWait, TimeUnit.MICROSECONDS); } //region abstract /** * Returns the earliest time that permits are available (with one caveat). * * @param {Number} nowMicros * @return the time that permits are available, or, if permits are available immediately, an * arbitrary past or present time */ queryEarliestAvailable(nowMicros) { Errors.throwNotImplemented(); } /** * Reserves the requested number of permits and returns the time that those permits can be used * (with one caveat). * * @param {Number} permits * @param {Number} nowMicros * @return {Number} the time that the permits may be used, or, if the permits may be used immediately, an * arbitrary past or present time */ reserveEarliestAvailable(permits, nowMicros) { Errors.throwNotImplemented(); } //endregion //region statics /** * @private * @param {Number} [permits] * @returns {Number} */ static checkPermits(permits) { if (Utility.isNotExisting(permits)) { return 1; } Preconditions.shouldBeNumber(permits, `Requested permits (${permits}) must be positive`); Preconditions.shouldBeTrue(permits > 0, `Requested permits (${permits}) must be positive`); return permits; } //endregion } class SmoothRateLimiter extends RateLimiter { constructor(options) { super(options); /** * The currently stored permits. */ this._storedPermits = 0; /** * The maximum number of stored permits. * @type {Number} * @private */ this._maxPermits = 0; /** * The interval between two unit requests, at our stable rate. E.g., a stable rate of 5 permits * per second has a stable interval of 200ms. */ this._stableIntervalMicros = 0; /** * The time when the next request (no matter its size) will be granted. After granting a * request, this is pushed further in the future. Large requests push this further than small * requests. * @type {Number} * @private */ this._nextFreeTicketMicros = 0; // could be either in the past or future } /** * @protected * @param permitsPerSecond * @param nowMicros */ doSetRate(permitsPerSecond, nowMicros) { this.resync(nowMicros); let stableIntervalMicros = TimeUnit.SECONDS.toMicros(1) / permitsPerSecond; this._stableIntervalMicros = stableIntervalMicros; this.doSetRate2(permitsPerSecond, stableIntervalMicros); } /** * @protected * @param permitsPerSecond * @param stableIntervalMicros */ doSetRate2(permitsPerSecond, stableIntervalMicros) { Errors.throwNotImplemented(); } queryEarliestAvailable(nowMicros) { return Preconditions.shouldBeNumber(this._nextFreeTicketMicros); } reserveEarliestAvailable(requiredPermits, nowMicros) { this.resync(nowMicros); let nextFreeTicketMicros = this._nextFreeTicketMicros; let returnValue = nextFreeTicketMicros; let storedPermitsToSpend = Math.min(requiredPermits, this._storedPermits); let freshPermits = requiredPermits - storedPermitsToSpend; let waitMicros = this.storedPermitsToWaitTime(this._storedPermits, storedPermitsToSpend) + (freshPermits * this._stableIntervalMicros); this._nextFreeTicketMicros = nextFreeTicketMicros + waitMicros; this._storedPermits -= storedPermitsToSpend; return returnValue; } /** * Translates a specified portion of our currently stored permits which we want to * spend/acquire, into a throttling time. Conceptually, this evaluates the integral * of the underlying function we use, for the range of * [(storedPermits - permitsToTake), storedPermits]. * * <p>This always holds: {@code 0 <= permitsToTake <= storedPermits} */ storedPermitsToWaitTime(storedPermits, permitsToTake) { Errors.throwNotImplemented(); } /** * * @param {Number} nowMicros * @return {Number} */ resync(nowMicros) { if (Utility.isNullOrUndefined(nowMicros)) { nowMicros = this.stopwatch.elapsedMicros(); } // if nextFreeTicket is in the past, resync to now let nextFreeTicketMicros = this._nextFreeTicketMicros; if (nowMicros > nextFreeTicketMicros) { this._storedPermits = Math.min(this._maxPermits, this._storedPermits + (nowMicros - nextFreeTicketMicros) / this._stableIntervalMicros); nextFreeTicketMicros = this._nextFreeTicketMicros = nowMicros; } return nextFreeTicketMicros; } } /** * This implements a "bursty" RateLimiter, where storedPermits are translated to * zero throttling. The maximum number of permits that can be saved (when the RateLimiter is * unused) is defined in terms of time, in this sense: if a RateLimiter is 2qps, and this * time is specified as 10 seconds, we can save up to 2 * 10 = 20 permits. */ class SmoothBurstyRateLimiter extends SmoothRateLimiter { /** The work (permits) of how many seconds can be saved up if this RateLimiter is unused? */ maxBurstSeconds; /** * @param {Object} options * @param {Number} options.maxBurstSeconds * @param {Stopwatch} [options.stopwatch] */ constructor(options) { let maxBurstSeconds = Utility.take(options, 'maxBurstSeconds', 'number', true); // SleepingStopwatch stopwatch, double maxBurstSeconds super(...arguments); this.maxBurstSeconds = maxBurstSeconds; } /** * * @param {Number} permitsPerSecond * @param {Number} stableIntervalMicros */ doSetRate2(permitsPerSecond, stableIntervalMicros) { let oldMaxPermits = Utility.defaultNumber(this._maxPermits); let maxBurstSeconds = Utility.defaultNumber(this.maxBurstSeconds); this._maxPermits = maxBurstSeconds * permitsPerSecond; // if (oldMaxPermits == Double.POSITIVE_INFINITY) { // // if we don't special-case this, we would get storedPermits == NaN, below // this.storedPermits = maxPermits; // } else { this._storedPermits = (oldMaxPermits == 0.0) ? 0.0 // initial state : this._storedPermits * this._maxPermits / oldMaxPermits; // } Preconditions.shouldBeNumber(this._storedPermits, 'storedPermits'); Preconditions.shouldBeNumber(this._maxPermits, '_maxPermits'); } /** * * @param {Number} storedPermits * @param {Number} permitsToTake * @return {number} */ storedPermitsToWaitTime(storedPermits, permitsToTake) { return 0; } } class SmoothWarmingUpRateLimiter extends SmoothRateLimiter { warmupPeriodMicros; /** * The slope of the line from the stable interval (when permits == 0), to the cold interval * (when permits == maxPermits) */ slope; halfPermits; constructor(options) { // SleepingStopwatch stopwatch, long warmupPeriod, TimeUnit timeUnit let timeUnit = Utility.take(options, 'timeUnit', TimeUnit, true); let warmupPeriod = Utility.take(options, 'warmupPeriod', 'number', true); super(...arguments); this.warmupPeriodMicros = timeUnit.toMicros(warmupPeriod); } /** * @private * @param permitsPerSecond * @param stableIntervalMicros */ doSetRate2(permitsPerSecond, stableIntervalMicros) { let oldMaxPermits = this._maxPermits; this._maxPermits = this.warmupPeriodMicros / stableIntervalMicros; this.halfPermits = this._maxPermits / 2.0; // Stable interval is x, cold is 3x, so on average it's 2x. Double the time -> halve the rate let coldIntervalMicros = stableIntervalMicros * 3.0; this.slope = (coldIntervalMicros - stableIntervalMicros) / this.halfPermits; // if (oldMaxPermits == Number.POSITIVE_INFINITY) { // // if we don't special-case this, we would get storedPermits == NaN, below // this._storedPermits = 0.0; // } else { this._storedPermits = (oldMaxPermits == 0.0) ? this._maxPermits // initial state is cold : this._storedPermits * this._maxPermits / oldMaxPermits; // } } /** * @private * @param storedPermits * @param permitsToTake * @return {number} */ storedPermitsToWaitTime(storedPermits, permitsToTake) { let availablePermitsAboveHalf = storedPermits - this.halfPermits; let micros = 0; // measuring the integral on the right part of the function (the climbing line) if (availablePermitsAboveHalf > 0.0) { let permitsAboveHalfToTake = Math.min(availablePermitsAboveHalf, permitsToTake); micros = (permitsAboveHalfToTake * (this.permitsToTime(availablePermitsAboveHalf) + this.permitsToTime(availablePermitsAboveHalf - permitsAboveHalfToTake)) / 2.0); permitsToTake -= permitsAboveHalfToTake; } // measuring the integral on the left part of the function (the horizontal line) micros += (this._stableIntervalMicros * permitsToTake); return micros; } /** * @private * @param permits * @return {*} */ permitsToTime(permits) { return this._stableIntervalMicros + permits * this.slope; } } export {RateLimiter}; export {SmoothRateLimiter}; export {SmoothBurstyRateLimiter}; export {SmoothWarmingUpRateLimiter}; export default SmoothRateLimiter; <file_sep>/src/js/data/ResourceLoader.js import CoreObject from "../CoreObject"; import Utility from "../Utility"; import URI from "urijs"; import Preconditions from "../Preconditions"; import Promise from "bluebird"; /** * @class ResourceLoader * @extends CoreObject */ class ResourceLoader extends CoreObject { _startedLatch; constructor(options) { super(options); Preconditions.shouldBeAbstract(this, ResourceLoader); } /** * @abstract * @param {String|URI} path * @return {Promise|Promise<Buffer>|Promise<String>} */ load(path) { return Promise .resolve() .then(() => { return Utility.getPath(path); }); } /** * @property * @readonly * @type {Promise} * @return {Promise} */ get startedLatch() { return this._startedLatch; } } export {ResourceLoader}; export default ResourceLoader;<file_sep>/dist/docs/file/js/data/DelegatedConverter.js.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <base data-ice="baseUrl" href="../../../"> <title data-ice="title">js/data/DelegatedConverter.js | API Document</title> <link type="text/css" rel="stylesheet" href="css/style.css"> <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css"> <script src="script/prettify/prettify.js"></script> <script src="script/manual.js"></script> </head> <body class="layout-container" data-ice="rootContainer"> <header> <a href="./">Home</a> <a href="identifiers.html">Reference</a> <a href="source.html">Source</a> <a data-ice="repoURL" href="https://github.com/coinme/coinme-node.git" class="repo-url-github">Repository</a> <div class="search-box"> <span> <img src="./image/search.png"> <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span> </span> <ul class="search-result"></ul> </div> </header> <nav class="navigation" data-ice="nav"><div> <ul> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Address.js~Address.html">Address</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Coinme.js~Coinme.html">Coinme</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/CoreObject.js~CoreObject.html">CoreObject</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Environment.js~Environment.html">Environment</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Functions.js~Functions.html">Functions</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Preconditions.js~Preconditions.html">Preconditions</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/RateLimiter.js~RateLimiter.html">RateLimiter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/RateLimiter.js~SmoothBurstyRateLimiter.html">SmoothBurstyRateLimiter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/RateLimiter.js~SmoothRateLimiter.html">SmoothRateLimiter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/RateLimiter.js~SmoothWarmingUpRateLimiter.html">SmoothWarmingUpRateLimiter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Stopwatch.js~Stopwatch.html">Stopwatch</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Ticker.js~Ticker.html">Ticker</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/TimeUnit.js~TimeUnit.html">TimeUnit</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Utility.js~Utility.html">Utility</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">cache</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/cache/Cache.js~Cache.html">Cache</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/cache/LocalFileCache.js~LocalFileCache.html">LocalFileCache</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">data</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Adapter.js~Adapter.html">Adapter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/CachedResourceLoader.js~CachedResourceLoader.html">CachedResourceLoader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/CertificateBundle.js~Certificate.html">Certificate</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/CertificateBundle.js~CertificateBundle.html">CertificateBundle</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Conversion.js~Conversion.html">Conversion</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Converter.js~Converter.html">Converter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/DelegatedConverter.js~DelegatedConverter.html">DelegatedConverter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/FileResourceLoader.js~FileResourceLoader.html">FileResourceLoader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Identity.js~Identity.html">Identity</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~EndpointType.html">EndpointType</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~EndpointTypes.html">EndpointTypes</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~KioskEndpointType.html">KioskEndpointType</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~Receipt.html">Receipt</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~ReceiptBuilder.html">ReceiptBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~ReceiptEndpoint.html">ReceiptEndpoint</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~WalletEndpointType.html">WalletEndpointType</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/ResourceLoader.js~ResourceLoader.html">ResourceLoader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/SignTool.js~SignTool.html">SignTool</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/User.js~User.html">User</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/UserBuilder.js~UserBuilder.html">UserBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/UserExistenceToken.js~UserExistenceToken.html">UserExistenceToken</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">errors</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/errors/AbstractError.js~AbstractError.html">AbstractError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/errors/Errors.js~Errors.html">Errors</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/errors/HttpError.js~HttpError.html">HttpError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/errors/NotImplementedError.js~NotImplementedError.html">NotImplementedError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/errors/PreconditionsError.js~PreconditionsError.html">PreconditionsError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-ExtendableBuiltin">ExtendableBuiltin</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">money</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/Bitcoin.js~Bitcoin.html">Bitcoin</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/Currency.js~Currency.html">Currency</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/CurrencyAdapter.js~CurrencyAdapter.html">CurrencyAdapter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/Ethereum.js~Ethereum.html">Ethereum</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/Money.js~Money.html">Money</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/MoneyConverter.js~MoneyConverter.html">MoneyConverter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/Satoshi.js~Satoshi.html">Satoshi</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/USD.js~USD.html">USD</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">net</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/net/CoinmeWalletClient.js~CoinmeWalletClient.html">CoinmeWalletClient</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/net/CoinmeWalletClient.js~CoinmeWalletClientConfiguration.html">CoinmeWalletClientConfiguration</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">slack</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/AbstractBuilder.js~AbstractBuilder.html">AbstractBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/AbstractNotificationTemplate.js~AbstractNotificationTemplate.html">AbstractNotificationTemplate</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/AttachmentBuilder.js~AttachmentBuilder.html">AttachmentBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/FieldBuilder.js~FieldBuilder.html">FieldBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/InlineNotificationTemplate.js~InlineNotificationTemplate.html">InlineNotificationTemplate</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/NotificationBuilder.js~NotificationBuilder.html">NotificationBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/NotificationService.js~NotificationService.html">NotificationService</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/NotificationTemplate.js~NotificationTemplate.html">NotificationTemplate</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/UserNotificationTemplate.js~UserNotificationTemplate.html">UserNotificationTemplate</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-notificationService">notificationService</a></span></span></li> </ul> </div> </nav> <div class="content" data-ice="content"><h1 data-ice="title">js/data/DelegatedConverter.js</h1> <pre class="source-code line-number raw-source-code"><code class="prettyprint linenums" data-ice="content">&apos;use strict&apos;; import CoreObject from &quot;../CoreObject&quot;; import Preconditions from &quot;../Preconditions&quot;; import Utility from &quot;../Utility&quot;; import Adapter from &quot;./Adapter&quot;; import Converter from &quot;./Converter&quot;; //region class CoreObjectAdapter /** * Internal class used by DelegatedConverter * * @private */ class CoreObjectAdapter extends Adapter { /** * * @param {CoreObject|Class&lt;CoreObject&gt;} instanceOrClass */ supports(instanceOrClass) { return CoreObject.isInstanceOrClass(instanceOrClass); } /** * @param {CoreObject|*} instance * @returns {*} */ adapt(instance) { this.shouldSupport(instance); return instance.toClass(); } } //endregion /** * Supports different conversion directions. * * This is not tied to money. It supports simple converting. * * {&lt;br&gt; * &apos;Bitcoin-&gt;Satoshi&apos; : function(value) { return value * satoshi_factor; },&lt;br&gt; * &apos;Satoshi-&gt;Bitcoin&apos;: function(value) { return value / satoshi_factor; }&lt;br&gt; * }&lt;br&gt; * * @class */ class DelegatedConverter extends Converter { //region constructor /** * @param {Object} options * @param {Object} options.conversions * @param {Adapter} [options.adapter] */ constructor(options) { let adapter = Utility.take(options, &apos;adapter&apos;, { type: Adapter, defaultValue: new CoreObjectAdapter() }); let conversions = Utility.take(options, &apos;conversions&apos;, true); super(...arguments); /** * @type {Object} * @private */ this._conversions = conversions || {}; /** * @type {Adapter} */ this._adapter = adapter; } //endregion //region properties /** * @return {Adapter} */ get adapter() { return this._adapter; } //endregion /** * @param instance * @param clazz * @return {boolean} */ supports(instance, clazz) { let adapter = this.adapter; if (!adapter.supports(instance) || !adapter.supports(clazz)) { return false; } let fn = this.getConversion(instance, clazz); return Utility.isFunction(fn); } /** * Executes the conversion. * * @param {CoreObject|*} input * @param {Class&lt;CoreObject&gt;|Class|*} outputClass * @returns {*} * * @throws {PreconditionsError} if the converter fails to convert into a valid number * @throws {PreconditionsError} if the destinationCurrency is not a valid currency * @throws {PreconditionsError} if converter cannot support the conversion */ convert(input, outputClass) { let fn = this.getConversion(input, outputClass); return fn.call(this, input, outputClass); } /** * Detects the conversion function, given the inputs. * * @param {Class&lt;CoreObject&gt;|Class|*} input * @param {Class&lt;CoreObject&gt;|Class|*} output * * @returns {Function|undefined} */ getConversion(input, output) { /** * @type {String} */ let conversionName = this.getConversionName(input, output); return Preconditions.shouldBeFunction( this._conversions[conversionName], `Converter not found for ${conversionName}`); } /** * * @param {*} input * @param {*} output * @returns {Function} */ optConversion(input, output) { let conversionName = this.optConversionName(input, output); return this._conversions[conversionName]; } /** * * @param {Class&lt;CoreObject&gt;|Class|*} input * @param {Class&lt;CoreObject&gt;|Class|*} output * @private * @return {string} */ getConversionName(input, output) { Preconditions.shouldBeDefined(input, &apos;param:input&apos;); Preconditions.shouldBeDefined(output, &apos;param:output&apos;); let adapter = this.adapter; input = Preconditions.shouldBeClass(adapter.adapt(input), &apos;inputClass must be a class&apos;); output = Preconditions.shouldBeClass(adapter.adapt(output), &apos;outputClass must be a class&apos;); return Preconditions.shouldNotBeBlank(this.optConversionName(input, output)); } /** * @param {*} input * @param {*} output * @return {string} */ optConversionName(input, output) { if (!input) { input = &apos;&apos;; } if (!output) { output = &apos;&apos;; } return `${input.toString()}-&gt;${output.toString()}`; } } export {CoreObjectAdapter}; export {DelegatedConverter}; export default DelegatedConverter;</code></pre> </div> <footer class="footer"> Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(0.5.0-alpha)</span></a> </footer> <script src="script/search_index.js"></script> <script src="script/search.js"></script> <script src="script/pretty-print.js"></script> <script src="script/inherited-summary.js"></script> <script src="script/test-summary.js"></script> <script src="script/inner-link.js"></script> <script src="script/patch-for-local.js"></script> </body> </html> <file_sep>/test/Money.spec.js 'use strict'; /** * How to use Chai * @see http://chaijs.com/api/assert/ */ import {expect, assert} from "chai"; import {Currency, Bitcoin, Money, Satoshi, USD, Converter} from "../src/js/money"; import {Errors, AbstractError, PreconditionsError} from "../src/js/errors"; import Preconditions from "../src/js/Preconditions"; import Big from 'big.js'; describe('Money', () => { it('', () => { let b = Bitcoin.create(1); assert.isTrue(b.value instanceof Big); }); it('shouldBeMoney', () => { let money = Bitcoin.create(1); assert.equal(Money.shouldBeMoney(money), money); }); it('new Bitcoin() - fails', () => { try { new Money(); assert.isTrue(false, 'The Bitcoin constructor should have thrown.'); } catch (e) { Preconditions.shouldBeError(e, PreconditionsError, 'bad type: ' + e); } }); // it('Bitcoin.convert', () => { // // assert.equal(Bitcoin.create(1).convertTo(Satoshi, Bitcoin.SATOSHIS_PER_BITCOIN), Bitcoin.SATOSHIS_PER_BITCOIN); // // assert.equal(Satoshi.create(Bitcoin.SATOSHIS_PER_BITCOIN).convertTo(Bitcoin, Bitcoin.BITCOIN_PER_SATOSHI), 1); // // }); it('Bitcoin.add', () => { let bitcoin = Bitcoin.create(1); let bitcoin2 = bitcoin.plus(bitcoin); // assert.equal(bitcoin.value, 1); // assert.equal(bitcoin2.value, 2); /** * @type {Money} */ // let usd = USD.create(1); // usd.convertTo(Bitcoin, 1); // // usd.convertTo(Bitcoin, function (valueInUsd) { // return valueInUsd; // }); // // usd.convertTo(Bitcoin, new Converter({ // // conversionRate: 2, // // conversions: { // 'Bitcoin->USD': function (valueInBitcoin) { // return valueInBitcoin / this.conversionRate; // }, // 'USD->Bitcoin': function (valueInUsd) { // return valueInUsd * this.conversionRate; // } // } // })); // let bitcoin4 = usd.convertTo(Bitcoin); // // Currency.converter.register({ // 'Bitcoin->USD': 4, // 'USD->Bitcoin': 1/4 // }); }); it('Simple case', () => { let bitcoin1 = Bitcoin.create(1); /** * @type {Money} */ let satoshi = Satoshi.create(Bitcoin.SATOSHIS_PER_BITCOIN); let bitcoin2 = Bitcoin.fromSatoshi(satoshi); assert.isTrue(bitcoin1.equals(bitcoin1), 'eq0'); // equals does an internal convert assert.isTrue(bitcoin1.equals(bitcoin2), 'eq1'); // equals does an internal convert assert.isTrue(bitcoin2.equals(bitcoin1), 'eq2'); assert.equal(bitcoin1.value, 1); // Money.valueOf() returns a number, which can be compared. assert.equal(bitcoin2.value, 1); // Money.valueOf() returns a number, which can be compared. // The PLUS operator coerces into a number // assert.isTrue(bitcoin.plus(satoshi).equals(Bitcoin.create(2))); // assert.isTrue(bitcoin.plus(satoshi).equals(2)); // assert.equal(bitcoin.plus(satoshi) + 0, 2); // assert.equal(satoshi.convertTo(Bitcoin) + 1, 2); }); it('fromBitcoin', () => { let money = Bitcoin.fromBitcoin(1); assert.isFalse(Money.isClass(money), 'money is Money - static'); assert.isTrue(Money.isInstance(money), 'money is Money - instance'); assert.isTrue(Bitcoin.isCurrency(money.currency), 'money.currency is Currency'); assert.isTrue(Bitcoin.isBitcoin(money.currency), 'money.currency is Bitcoin'); Bitcoin.shouldBeBitcoin(money.currency); Bitcoin.shouldBeBitcoin(money); }); it('Example', () => { let money = Bitcoin.fromBitcoin(1); let money2 = Bitcoin.fromBitcoin(money); assert.equal(money.value, money2.value, money.value + ':' + money2.value); assert.isTrue(Bitcoin.isBitcoin(money)); assert.isTrue(Bitcoin.isBitcoin(money2)); }); it('Convert: manual ', () => { let bitcoin = Bitcoin.fromBitcoin(1); let satoshis = Satoshi.fromBitcoin(bitcoin); assert.equal(bitcoin.value, 1); assert.equal(satoshis.value, Bitcoin.SATOSHIS_PER_BITCOIN * bitcoin.value); }); it('Convert: bitcoin->satoshi', () => { let bitcoin = Bitcoin.create(1); let satoshis = Satoshi.fromBitcoin(bitcoin); assert.equal(bitcoin.value.toFixed(), '1', 'bitcoin.value'); assert.equal(satoshis.value.toFixed(), '100000000', 'Value should be a number'); assert.equal(satoshis.value.toFixed(), Bitcoin.SATOSHIS_PER_BITCOIN.times(bitcoin.value).toFixed(), 'conversion problem'); assert.equal(Satoshi.fromBitcoin(bitcoin).value.toFixed(), satoshis.value.toFixed(), '1'); assert.equal(Satoshi.fromBitcoin(bitcoin).value.toFixed(), bitcoin.value.times(Bitcoin.SATOSHIS_PER_BITCOIN).toFixed(), '2'); assert.equal(Satoshi.fromSatoshis(satoshis).value.toFixed(), satoshis.value.toFixed(), '4'); // assert.equal(bitcoin.plus(satoshis).value, 2, '5'); // assert.equal(bitcoin.plus(satoshis).convertTo(Satoshi).value, 200000000); // assert.equal( // bitcoin // .plus(bitcoin) // .plus(1) // .plus('1') // .plus(bitcoin) // .value, // 5); }); it('Currency.equals', () => { assert.isTrue(Currency.equals(Currency), 'Currency equals self'); assert.isTrue(Bitcoin.equals(Bitcoin)); assert.isTrue(USD.equals(USD)); assert.isFalse(USD.equals(Bitcoin)); assert.isFalse(USD.equals(Currency)); }); // it('Convert: bitcoin->fiat', () => { // let bitcoin = Bitcoin.create(1); // // // Should work for self // { // let usd1 = USD.create(1); // let usd2 = usd1.convertTo(USD); // // assert.equal(+usd1, +usd2); // assert.isTrue(usd1.value == usd2.value); // assert.isTrue(usd1.value === usd2.value); // assert.equal(usd1.valueOf(), usd2.valueOf()); // } // // { // // This only works because we passed in a converting function // let converterFn = function (valueInBitcoin) { // return valueInBitcoin * .5; // }; // // let usd = bitcoin.convertTo(USD, /* required because not registered */ converterFn); // // assert.equal(usd.value, bitcoin.value / 2); // } // // { // assert.equal(bitcoin.convertTo(USD, .5).value, bitcoin.value / 2); // } // // // Should fail, because no conversions registered. // { // try { // bitcoin.convertTo(USD); // // assert.isTrue(false, 'Should have failed earlier'); // } catch (e) { // } // } // // { // Currency.converter.register({ // 'Bitcoin->USD': function () { // return 2; // } // }); // // assert.equal(bitcoin.convertTo(USD).value, bitcoin.value * 2); // } // }); }); <file_sep>/src/js/money/Currency.js 'use strict'; import Utility from "../Utility"; import CoreObject from "../CoreObject"; import Preconditions from "../Preconditions"; import Money from "./Money"; import Big from "big.js/big"; // import {Utility, CoreObject, Preconditions} from '../index'; // import Converter from "./Converter"; // let _converter = new Converter({ // conversions: { // // } // }); // // let _types = { // // /** // * // * @param {String|Class} stringOrClass // * @param {Class} [clazz] // */ // register: function(stringOrClass, clazz) { // let name = (stringOrClass.toString().toLowerCase()); // // if (!clazz && Currency.isClass(stringOrClass)) { // clazz = stringOrClass; // } // // this[name] = clazz; // // return this; // } // }; /** * @class */ export default class Currency extends CoreObject { constructor() { super(); // if (this.constructor === Currency) { throw new TypeError('Cannot construct Currency instances directly'); // } } /** * @returns {String} */ toString() { return this.toClass().toString(); } // /** // * @return {Converter} // */ // get converter() { // return this.toClass().converter; // } static equals(currency) { currency = Currency.optCurrency(currency); if (!Currency.isCurrency(currency)) { return false; } let clazz1 = this.toClass(); let clazz2 = currency.toClass(); return (clazz1 === clazz2); } /** * * @param {Number|Money|String} value * @returns {Money} */ static create(value) { let money = Money.optMoney( Currency.toValueOrFail(value), Currency.optCurrency(value) || this.getChildCurrencyTypeOrFail()); Preconditions.shouldBeDefined(money, 'Money.optMoney has failed us.'); Money.shouldBeMoney(money); return money; // return money.convertTo(this.getChildCurrencyTypeOrFail(), optionalConversion); } /** * @returns {String} */ static toString() { return 'Currency'; } // /** // * @returns {Converter} // */ // static get converter() { // return _converter; // } // /** // * @returns {{register: function(name:string, type:Currency)}} // */ // static get types() { // return _types; // } // /** // * // * @param {Converter} value // */ // static set converter(value) { // _converter = value; // } // /** // * @param {Money} money // * @param {Number|Function|Converter} [optionalConversion] // * @return {Money} // * @throws {PreconditionsError} if money is not of the correct type. // */ // static convertFrom(money, optionalConversion) { // Money.shouldBeMoney(money); // Money.shouldBeInstance(money); // // return money.currency.converter.convert(money, this.getChildCurrencyTypeOrFail(), optionalConversion); // } // // static canConvertFrom(money, optionalConversion) { // return money.currency.canConvertFrom(money, optionalConversion); // } // // /** // * If you are using it statically on Currency, then the signature is Currency.convertTo(money, destinationCurrency); // * If you are using it on a subclass of Currency, then the signature is Currency.convertTo(money); // * // * @param {Number|Money|String} valueOrMoney // * @param {Currency} [destinationCurrency] // */ // static convertTo(valueOrMoney, destinationCurrency) { // if (!destinationCurrency) { // destinationCurrency = this.getChildCurrencyTypeOrFail(); // } else { // if (this.isChildCurrency()) { // // } // } // // Currency.shouldBeCurrency(destinationCurrency); // // /** // * @type {Currency} // */ // let sourceCurrency = (/** @type {Currency} */(destinationCurrency || this.getChildCurrencyTypeOrFail())); // // /** // * @type {Money} // */ // let money = sourceCurrency.create(valueOrMoney); // // return this.converter.convert(money, destinationCurrency); // } /** * @private * @returns {Currency} */ static getChildCurrencyTypeOrFail() { var currency = this; Currency.shouldBeCurrency(currency); Preconditions.shouldBeTrue(this.isChildCurrency(), 'Cannot be the Currency class directly. Use a subclass, like Bitcoin. You used: ' + this.toClass().toString()); return currency; } /** * @private * @returns {boolean} */ static isChildCurrency() { return this.toClass() !== Currency && Currency.isClass(this); } /** * * @param {Money|String|Number} valueOrMoney * @param {Class<Currency>|Currency} [defaultCurrency] * @returns {Money} */ static toMoney(valueOrMoney, defaultCurrency) { if (valueOrMoney instanceof Money) { return valueOrMoney; } let value = Currency.toValueOrFail(valueOrMoney); let currency = Currency.optCurrency(valueOrMoney) || Currency.optCurrency(defaultCurrency); if (!currency) { currency = this.getChildCurrencyTypeOrFail(); } Currency.shouldBeCurrency(currency); if (currency === Currency) { // if (Object.getPrototypeOf(currency) === Currency) { throw new Error(`Cannot have myself as a currency. Must use a subclass, like Bitcoin or USD. This is usually because I do Currency.toMoney() instead of Bitcoin.toMoney()`); } return new Money({ value: value, currency: currency }); } /** * @param {Class<Currency>|Currency|Object} objectOrCurrency * @return {Class<Currency>} * @throws error if not a currency type */ static getCurrency(objectOrCurrency) { let instance = Currency.optCurrency(objectOrCurrency); Currency.shouldBeCurrency(instance, 'Currency not found: ' + objectOrCurrency); return instance; } /** * @param {Class<Currency>|Currency|Object|Money|String} objectOrCurrency * @return {Class<Currency>|Currency|undefined} */ static optCurrency(objectOrCurrency) { if (Currency.isCurrency(objectOrCurrency)) { return objectOrCurrency; } else if (Currency.isInstance(objectOrCurrency)) { return objectOrCurrency.toClass(); } else if (Money.isInstance(objectOrCurrency)) { return objectOrCurrency.currency; } else if (Utility.isString(objectOrCurrency)) { // let string = objectOrCurrency.toLowerCase(); if (Utility.isNumeric(objectOrCurrency)) { return undefined; } throw new Error(`Not sure what to do with ${objectOrCurrency}`); } return undefined; } /** * * @param {*} clazz * @param {String} [message] * * @returns {Class<Currency>} */ static shouldBeCurrency(clazz, message) { Preconditions.shouldBeClass(clazz, Currency, 'Must be currency: ' + message); return clazz; } /** * * @param {Class<Currency>|Currency|Object|*} object * @returns {boolean} */ static isCurrency(object) { if (Currency.isClass(object)) { return true; } if (Currency.isInstance(object)) { return true; } return false; } /** * If the type is correct, will unwrap to the value. * If the type is not correct, will throw an exception. * * @type {Money|Number|String|undefined|null|Big|BigJsLibrary.BigJS} * @return {Big|BigJsLibrary.BigJS} * @throws err if not correct type. */ static toValueOrFail(numberOrMoney) { let value = this.optValue(numberOrMoney); if (value) { return value; } else { Preconditions.fail('Number|Currency', Utility.typeOf(numberOrMoney), `This method fails with the wrong type. You provided ${numberOrMoney} (type: ${Utility.typeOf(numberOrMoney)})`); } } /** * Will return undefined if it cannot figure out what to do. * Defaults to Zero. * * @param numberOrMoney * @return {Big|BigJsLibrary.BigJS|undefined} */ static optValue(numberOrMoney) { if (Utility.isNullOrUndefined(numberOrMoney)) { return new Big(0); } else if (Money.isInstance(numberOrMoney)) { return numberOrMoney.value; } else if (Utility.isNumber(numberOrMoney)) { return new Big(numberOrMoney); } else if (Utility.isString(numberOrMoney)) { return new Big(numberOrMoney); } else if (numberOrMoney instanceof Big) { return numberOrMoney; } else { return undefined; } } }<file_sep>/src/js/money/Bitcoin.js 'use strict'; import Preconditions from "../Preconditions"; import Currency from "./Currency"; import Money from "./Money"; import Big from "big.js/big"; // // /** // * @private // * @type {Converter} // */ // let conversions = { // // /** // * // * @param {Number} valueInBitcoin // * @returns {Number} // */ // 'Bitcoin->Satoshi': function (valueInBitcoin) { // Preconditions.shouldBeNumber(valueInBitcoin); // // return valueInBitcoin * Bitcoin.SATOSHIS_PER_BITCOIN // }, // // /** // * // * @param {Number} valueInSatoshi // * @returns {Number} // */ // 'Satoshi->Bitcoin': function (valueInSatoshi) { // Preconditions.shouldBeNumber(valueInSatoshi); // // return valueInSatoshi * Bitcoin.BITCOIN_PER_SATOSHI; // } // }; // // // Register our known conversions. // Currency.converter.register(conversions); /** * @type {Big|BigJsLibrary.BigJS} */ let STATIC_BITCOIN_PER_SATOSHI = new Big(0.00000001); /** * @type {Big|BigJsLibrary.BigJS} */ let STATIC_SATOSHI_PER_BITCOIN = new Big(100000000); /** * Represents the Bitcoin currency in memory. * * This class cannot be instantiated. Everything is static and the constructor throws, so treat it like a singleton. * * @class Bitcoin */ class Bitcoin extends Currency { /** * * @param {Money|String|Number|null|undefined|Big|BigJsLibrary.BigJS} valueInBitcoin * @returns {Money} */ static fromBitcoin(valueInBitcoin) { /** * @type {Big|BigJsLibrary.BigJS} */ let value = Currency.toValueOrFail(valueInBitcoin); /** * @type {Class.<Currency>|undefined} */ let currency = Currency.optCurrency(valueInBitcoin); if (currency) { Bitcoin.shouldBeBitcoin(currency); } return new Money({ value: value, currency: Bitcoin }); } /** * * @param {Money|String|Number|null|undefined} valueInSatoshis * @returns {Money} */ static fromSatoshi(valueInSatoshis) { return Bitcoin.fromBitcoin(Currency.toValueOrFail(valueInSatoshis).div(Bitcoin.SATOSHIS_PER_BITCOIN)); } /** * @return {BigJsLibrary.BigJS} * @readonly */ static get SATOSHIS_PER_BITCOIN() { return STATIC_SATOSHI_PER_BITCOIN; } /** * @return {BigJsLibrary.BigJS} * @readonly */ static get BITCOIN_PER_SATOSHI() { return STATIC_BITCOIN_PER_SATOSHI; } /** * @returns {Class<Bitcoin>} */ static toClass() { return this; } /** * @returns {String} */ static toString() { return 'Bitcoin'; } //region Detection /** * Detects if you pass in either Money or Currency of type Bitcoin <br> * <br> * Bitcoin -> true <br> * money<Bitcoin> -> true <br> * * @param {Money|Currency|Class<Currency>} moneyOrCurrency * @return {Boolean} */ static isBitcoin(moneyOrCurrency) { if (!moneyOrCurrency) { return false; } let currency = Currency.optCurrency(moneyOrCurrency); return Bitcoin.isClass(currency) || Bitcoin.isInstance(currency); } /** * If {@link Bitcoin#isBitcoin} returns false, will throw. * * @param {Money|Currency|Class<Currency>} moneyOrCurrency * @return {Class<Currency>} * @throws {PreconditionsError} if not an instance of Money (for Bitcoin) or the Bitcoin class itself. */ static shouldBeBitcoin(moneyOrCurrency) { if (!Bitcoin.isBitcoin(moneyOrCurrency)) { Preconditions.fail(Bitcoin, Currency.optCurrency(moneyOrCurrency) || moneyOrCurrency); } return moneyOrCurrency; } //endregion } // /** // * // * @param {Money} money // * @param {Number} [places] // * @returns {String} // */ // static serialize(money, places) { // let value = this.toBitcoin(); // // if (isNaN(value)) { // return 'NaN'; // } // // if (!places) { // places = 8; // } // // let parts = String(value).split('.'); // // if (parts.length === 1) { // parts.push('0'); // } // // let needed = places - parts[1].length; // // for (let i = 0; i < needed; i++) { // parts[1] += '0'; // } // // return parts[0] + '.' + parts[1]; // } // /** // * // * @param number // * @returns {Number} // */ // static calculateSatoshisFromBitcoin(number) { // Preconditions.shouldBeDefined(Currency); // number = Currency.toValueOrFail(number); // // if (isNaN(number)) { // return NaN; // } // // if (number === 0) { // return 0; // } // // let str = String(number); // let sign = (str.indexOf('-') === 0) ? '-' : ''; // // str = str.replace(/^-/, ''); // // if (str.indexOf('e') >= 0) { // return parseInt(sign + str.replace('.', '').replace(/e-8/, '').replace(/e-7/, '0'), 10); // } else { // if (!(/\./).test(str)) { // str += '.0'; // } // // let parts = str.split('.'); // // str = parts[0] + '.' + parts[1].slice(0, 8); // // while (!(/\.[0-9]{8}/).test(str)) { // str += '0'; // } // // return parseInt(sign + str.replace('.', '').replace(/^0+/, ''), 10); // } // } // Currency.types.register('Bitcoin', Bitcoin); // Currency.types.register('btc', Bitcoin); export default Bitcoin;<file_sep>/src/js/data/UserBuilder.js import CoreObject from "~/CoreObject"; import User from "~/data/User"; import Lodash from "lodash"; let SPEC_VERSION_8 = { 'DBA': 'expirationDate', 'DAC': 'firstName', 'DCS': 'lastName', 'DAD': 'middleName', 'DBB': 'birthDate', 'DCB': 'gender', 'DAG': 'addressLine1', 'DAH': 'addressLine2', 'DAI': 'addressCity', 'DAJ': 'addressState', 'DAK': 'addressZipcode', 'DAQ': 'username', 'DCG': 'addressCountry', 'DCL': 'race' }; class UserBuilder extends CoreObject { static get SPEC_VERSION_8() { return SPEC_VERSION_8; } /** * * @param {Object} options * @param {String} options.DBA expirationDate * @param {String} options.DAC firstName * @param {String} options.DCS lastName * @param {String} options.DAD middleName * @param {String} options.DBB birthDate * @param {String} options.DCB gender * @param {String} options.DAG addressLine1 * @param {String} options.DAH addressLine2 * @param {String} options.DAI addressCity * @param {String} options.DAJ addressState * @param {String} options.DAK addressZipcode * @param {String} options.DAQ username * @param {String} options.DCG addressCountry * @param {String} options.DCL race * * @returns {User} */ static fromVersion8(options) { return UserBuilder.fromSpec(UserBuilder.SPEC_VERSION_8, options); } static fromSpec(spec, options) { var object = {}; Lodash.forEach(spec, function(value, key) { object[value] = options[key]; }); return new User(object); } } export default UserBuilder;<file_sep>/src/js/data/Conversion.js import CoreObject from "../CoreObject"; import Utility from "../Utility"; import Stopwatch from "../Stopwatch"; import Converter from "./Converter"; class Conversion extends CoreObject { /** * * @param {Object} options * @param {*} options.input * @param {*} options.output * @param {Number} options.duration * @param {Stopwatch} options.stopwatch * @param {Converter} options.converter */ constructor(options) { let input = Utility.take(options, 'input', true); let output = Utility.take(options, 'output', true); let stopwatch = Utility.take(options, 'stopwatch', Stopwatch, true); let converter = Utility.take(options, 'converter', Converter, true); let requestor = Utility.take(options, 'requestor'); super(...arguments); this._input = input; this._output = output; this._stopwatch = stopwatch; this._converter = converter; this._requestor = requestor; } /** * * @return {Stopwatch} */ get stopwatch() { return this._stopwatch; } /** * @returns {*|undefined} */ get requestor() { return this._requestor; } /** * @returns {*} */ get input() { return this._input; } /** * @returns {*} */ get output() { return this._output; } /** * @returns {Converter} */ get converter() { return this._converter; } /** * * @return {*} */ valueOf() { if (Utility.isNullOrUndefined(output)) { return null; } if (this.output.valueOf) { return this.output.valueOf(); } else { return this.output; } } /** * @return {String} */ toString() { return `Conversion{ input:'${this.input}', output:'${this.output}' }`; } /** * * @return {String} */ static toString() { return 'Conversion'; } } export default Conversion;<file_sep>/src/js/money/USD.js 'use strict'; import {Utility, Preconditions} from "~/"; import Currency from "./Currency"; import Money from "./Money"; /** * @class USD */ class USD extends Currency { /** * * @returns {String} */ static toString() { return 'USD'; } /** * @returns {Class<USD>} */ static toClass() { return this; } //region Detection /** * Detects if * * @param {Money|Currency|Class<Currency>} moneyOrCurrency * @return {Boolean} */ static isUSD(moneyOrCurrency) { let currency = Currency.optCurrency(moneyOrCurrency) || moneyOrCurrency; return USD.isClass(currency) || USD.isInstance(currency); } /** * Determines if {@link USD#isUSD} returns true * * @param {Money|Currency|Class<Currency>} moneyOrCurrency * @throws {PreconditionsError} if not the right currency type */ static shouldBeUSD(moneyOrCurrency) { if (!this.isUSD(moneyOrCurrency)) { Preconditions.fail(USD, moneyOrCurrency, 'Must be USD'); } return moneyOrCurrency; } //endregion } // Currency.types.register('USD', USD); export default USD;<file_sep>/test/Exchange.spec.js // 'use strict'; // // /** // * How to use Chai // * @see http://chaijs.com/api/assert/ // */ // import {expect, assert} from "chai"; // import "source-map-support/register"; // import Promise from "bluebird"; // import Ember from "../src/js/Ember"; // import Preconditions from "../src/js/Preconditions"; // import Utility from "../src/js/Utility"; // import Conversion from "../src/js/data/Conversion"; // // import {Currency, Bitcoin, Money, Satoshi, USD, Exchange} from "../src/js/money"; // // describe('Exchange', function () { // // it('convert', (done) => { // let exchange = new Exchange(); // // exchange.register(new Converter({ // conversions: { // /** // * // * @param {Money} money // * @returns {Money} // */ // 'Bitcoin->Satoshi': function(money) { // return Satoshi.fromBitcoin(money); // }, // // 'Satoshi->Bitcoin': function(money) { // return Bitcoin.fromSatoshi(money); // } // } // })); // // let bitcoin = Bitcoin.create(1); // // exchange // .convert(bitcoin, Satoshi) // .then((/** @type {Conversion} */satoshi) => { // // // satoshi.currency; // // satoshi.value; // // assert.isTrue(Money.isInstance(satoshi), 'Satoshi should be an instance of Satoshi: ' + satoshi); // assert.isFalse(Bitcoin.isInstance(satoshi), 'Satoshi should not be an instance of Bitcoin'); // // assert.equal(satoshi.value.toFixed(), Bitcoin.SATOSHIS_PER_BITCOIN.toFixed()); // assert.equal(bitcoin.value.toFixed(), '1'); // assert.equal(Bitcoin.SATOSHIS_PER_BITCOIN.toFixed(), '100000000') // }) // .then(done) // .catch(done); // }); // });<file_sep>/src/js/Preconditions.js 'use strict'; import Utility from "./Utility"; import Lodash from "lodash/index"; import CoreObject from "./CoreObject"; import AbstractError from "./errors/AbstractError"; import {Errors, PreconditionsError} from "./errors"; import {ZonedDateTime} from 'js-joda'; // class PreconditionsError extends AbstractError { // // /** // * // * @param {*} actualValue // * @param {*} expectedValue // * @param {String} [message] // * @param {Error} [optionalCause] // * @constructor // */ // constructor(expectedValue, actualValue, message, optionalCause) { // super(message); // // // this.name = 'PreconditionsError'; // // this.stack = error.stack; // this.cause = optionalCause; // // this.expectedValue = expectedValue || ''; // this.actualValue = actualValue || ''; // this.message = `failure (expected: ${this.expectedValue}) (actual: ${this.actualValue}) (message: ${this.message})`; // } // } // /** // * // * @param {*} expectedValue // * @param {*} actualValue // * @param {String} [message] // * @param {Error} [optionalCause] // * @constructor // */ // function PreconditionsError(expectedValue, actualValue, message, optionalCause) { // var error = Error.call(this, message); // // this.name = 'PreconditionsError'; // this.stack = error.stack; // this.cause = optionalCause; // // this.expectedValue = expectedValue; // this.actualValue = actualValue; // this.message = `failure (expected: '${this.expectedValue}' [${Utility.typeOf(this.expectedValue)}]) (actual: '${this.actualValue}' [${Utility.typeOf(this.actualValue)}]) (message: ${this.message})`; // } // // PreconditionsError.prototype = Object.create(Error.prototype); // PreconditionsError.prototype.constructor = PreconditionsError; // // export { PreconditionsError } /** * @singleton * @class Preconditions */ export default class Preconditions { /** * * @param {*} expectedValue * @param {*} actualValue * @param {String} [message] */ static fail(expectedValue, actualValue, message) { throw new PreconditionsError({ expectedValue: expectedValue, actualValue: actualValue, message: message || 'Preconditions failure' }); } /** * * @param {*} object * @param {String} [message] * return {*} object */ static shouldBeUndefined(object, message) { return Preconditions.shouldBe(Utility.isUndefined, undefined, object, message || 'must be undefined'); } /** * * @param {*} object * @param {String} [message] * @returns {*} */ static shouldNotBeFalsey(object, message) { return Preconditions.shouldBe(Utility.isNotFalsey, true, object, message || 'must not be falsey') } /** * * @param {*} object * @param {String} [message] * @returns {*} */ static shouldBeFalsey(object, message) { return Preconditions.shouldBe(Utility.isFalsey, false, object, message || 'must be falsey') } /** * This method checks for UNDEFINED, NAN, and NULL * * @param {*} object * @param {String} [message] * @return {*} */ static shouldBeDefined(object, message) { if (Utility.isUndefined(object)) { Preconditions.fail('defined', undefined, message || 'must be defined.'); } return object; } /** * Make sure an object is not: undefined, null, NaN * * @param {*} object * @param {String} [message] */ static shouldBeExisting(object, message) { return Preconditions.shouldBe(Utility.isExisting, 'exist', object, message || 'must exist.'); } /** * * @param {*} string * @param {String} [message] * @return {String} */ static shouldNotBeBlank(string, message) { Preconditions.shouldBeString(string, message || 'not blank'); return Preconditions.shouldBe(Utility.isNotBlank, 'not blank', string, message || 'must not be blank.'); } /** * * @param {*} fn * @param {String} [message] * @return {function} */ static shouldBeFunction(fn, message) { return Preconditions.shouldBeType('function', fn, message); } /** * * @param {*} number * @param {String} [message] * @return {Number} */ static shouldBeNumber(number, message) { Preconditions.shouldBeType('number', number, message); Preconditions.shouldBeFinite(number, message); return number; } /** * * @param {function} testFn * @param {*} [expectedValue] * @param {*} actualValue * @param {String} [message] * @returns {*} */ static shouldBe(testFn, expectedValue, actualValue, message) { if (!Utility.isFunction(testFn)) { Preconditions.fail('function', testFn, `testFn must be function, but was ${Utility.typeOf(testFn)}.`); } if (!testFn.call(this, actualValue)) { Preconditions.fail(expectedValue, actualValue, message || 'must pass test.'); } return actualValue; } /** * Execute a function. The function should fail with a preconditions error. * * @param {function} fn * @param {*} [scope] */ static shouldFailWithPreconditionsError(fn, scope) { try { fn.call(scope || this); throw new Error('Did not crash'); } catch (e) { Preconditions.shouldBePreconditionsError(e); } } /** * * * @param {Class|Object} actualClass * @param {Class|String} [requiredClassOrMessage] * @param {String} [message] */ static shouldBeClass(actualClass, requiredClassOrMessage, message) { Preconditions.shouldBeDefined(actualClass, message || 'object must be defined'); let requiredClass; if (Utility.isString(requiredClassOrMessage)) { Preconditions.shouldBeUndefined(message); message = requiredClassOrMessage; requiredClassOrMessage = null; } else { requiredClass = requiredClassOrMessage; } if (!requiredClass) { requiredClass = CoreObject; } if (!CoreObject.isClass(requiredClass)) { Preconditions.fail(CoreObject, requiredClass, message || 'Class not a CoreObject class'); } if (!requiredClass.isClass(actualClass)) { Preconditions.fail(requiredClass, actualClass, message || `Class was of the wrong type.`); } return actualClass; } /** * * @param value * @param message * @return {*} */ static shouldBeDateTime(value, message) { Preconditions.shouldBeType('temporal', value, message); Preconditions.shouldBe(() => { return value instanceof ZonedDateTime; }, ZonedDateTime, value, message || 'Must be ZonedDateTime'); return value; } /** * * @param {Temporal|ZonedDateTime|Instant} value * @param {String} [message] * @return {*} */ static shouldBeTemporal(value, message) { Preconditions.shouldBeType('temporal', value, message || 'must be temporal'); return value; } /** * * @param {*} object * @param {Class} [clazz] * @param {String} [message] * @returns {Object} */ static shouldBeInstance(object, clazz, message) { Preconditions.shouldBeDefined(object, message || 'object must be defined'); if (!Utility.isInstance(object)) { Preconditions.fail(CoreObject, clazz, message || 'object not an instance'); } if (clazz) { if (!Utility.isClass(clazz)) { Preconditions.fail(CoreObject, clazz, message || 'clazz not a class'); } if (!clazz.isInstance(object)) { Preconditions.fail(object, clazz, message || 'Class not an instance of ' + clazz); } } return object; } /** * Less strict version of "shouldBeInstance" * * @param {*} object * @param {*} clazz * @param {String} [message] * @return {*} */ static shouldBeInstanceOf(object, clazz, message) { Preconditions.shouldBeDefined(object, message); Preconditions.shouldBeDefined(clazz, message); if (object instanceof clazz) { return object; } Preconditions.fail(true, false, message); } /** * * @param {*} object * @param {Class<CoreObject>|String} [classOrString] * @param {String} [message] * @returns {Object} */ static shouldNotBeInstance(object, classOrString, message) { if (!object) { return object; } let clazz; if (Utility.isString(classOrString)) { Preconditions.shouldBeUndefined(message); message = classOrString; } if (!clazz) { clazz = CoreObject.toClass(); } clazz = Preconditions.shouldBeClass(clazz); if (clazz.isInstance(object)) { Preconditions.fail(object, clazz, message || 'Class is an instance of ' + clazz); } return object; } /** * * @param {*} number * @param {String} [message] * @return {Number} */ static shouldBeFinite(number, message) { if (!Lodash.isFinite(number)) { Preconditions.fail('finite', number, message || 'must be finite.'); } return number; } /** * * @param {Object} object * @param {String} [message] * @return {Object} */ static shouldBeObject(object, message) { Preconditions.shouldBeExisting(object, message); let fn = Utility.typeMatcher('object'); return Preconditions.shouldBe(fn, 'object', object, message || 'shouldBeObject'); } /** * * @param {*} string * @param {String} [message] * @return {String} */ static shouldBeString(string, message) { Preconditions.shouldBeExisting(string); let fn = Utility.typeMatcher('string'); return Preconditions.shouldBe(fn, 'object', string, message); } /** * * @param {String} string * @param {RegExp} regexp * @param {String} [message] */ static shouldMatchRegexp(string, regexp, message) { Preconditions.shouldBeString(string, message); Preconditions.shouldBeRegExp(regexp, message); if (!string.match(regexp)) { Preconditions.fail(true, false, message); } return string; } /** * * @param {RegExp} regexp * @param {String} [message] * @return {RegExp} */ static shouldBeRegExp(regexp, message) { return Preconditions.shouldBeType('regexp', regexp, message); } /** * * @param {*} object * @param {AbstractError} [clazz] * @param {String} [message] * @returns Error */ static shouldBeError(object, clazz, message) { Preconditions.shouldBeType('error', object, message || 'Should be error type'); if (clazz) { if (!Errors.isErrorClass(clazz)) { Preconditions.fail(Error, clazz, message || 'must be error class'); } if (!clazz.isInstance(object)) { Preconditions.fail(clazz, object, message || 'must be error instance.'); } } return object; } /** * * @param {String} typeName * @param {*} value * @param {String} [message] * @returns {*} */ static shouldBeType(typeName, value, message) { return Preconditions.shouldBe(Utility.typeMatcher(typeName), typeName, value, message); } /** * * @param {*} boolean * @param {String} [message] * @return {boolean} */ static shouldBeTrue(boolean, message) { Preconditions.shouldBeBoolean(boolean, message || 'should be true'); if (true === boolean) { return boolean; } Preconditions.fail(boolean, true, message || 'was not true'); } /** * @param {*} target (pass this in exactly "new.target") * @param {Class} clazz * @return {*} */ static shouldBeAbstract(target, clazz) { if (target.constructor === clazz) { Errors.throwMustBeAbstract(clazz); } return target; } /** * * @param {*} number * @param {String} [message] * @returns {Number} */ static shouldNotBeNegativeNumber(number, message) { Preconditions.shouldBeDefined(number, message); Preconditions.shouldBeNumber(number, message); if (number < 0) { Preconditions.fail('positive', number, message || 'Number should be positive. Was: ' + number); } return number; } /** * * @param {boolean} boolean * @param {String} [message] */ static shouldBeBoolean(boolean, message) { Preconditions.shouldBeDefined(boolean, message || 'should be boolean'); if (!Utility.isBoolean(boolean)) { Preconditions.fail('boolean', boolean, message || 'was not boolean'); } return boolean; } /** * * @param {Array} array * @param {String} [message] */ static shouldBeArray(array, message) { Preconditions.shouldBeDefined(array); if (!Utility.isArray(array)) { Preconditions.fail('array', array, message || 'was not array'); } return array; } /** * * @param {*} number1 * @param {*} number2 * @param {String} [message] */ static shouldBeGreaterThan(number1, number2, message) { Preconditions.shouldBeNumber(number1, message); Preconditions.shouldBeNumber(number2, message); if (number1 <= number2) { Preconditions.fail('larger than ' + number2, number1, message); } return number1; } /** * * @param {*} number * @param {String} [message] * @return {Number} */ static shouldBePositiveNumber(number, message) { Preconditions.shouldBeNumber(number, message); if (number <= 0) { Preconditions.fail('positive', number, message || 'Number should be positive. Was: ' + number); } return number; } /** * @param {*|PreconditionsError} e * @param {String} [message] * * @return {PreconditionsError} */ static shouldBePreconditionsError(e, message) { if (!PreconditionsError.isInstance(e)) { Preconditions.fail(PreconditionsError, e, message || 'Should be a preconditions error. Was: ' + e); } return e; } }<file_sep>/src/js/money/MoneyConverter.js 'use strict'; import Money from "./Money"; import Currency from "./Currency"; import Preconditions from "../Preconditions"; import Utility from "../Utility"; import Lodash from "lodash"; import {Converter, DelegatedConverter} from "../data"; import CurrencyAdapter from './CurrencyAdapter'; /** * Supports different conversion directions. * * The conversion map uses the Currency name for directionality. The internal conversion map is stored like: * * {<br> * 'Bitcoin->Satoshi' : function(value) { return value * satoshi_factor; },<br> * 'Satoshi->Bitcoin': function(value) { return value / satoshi_factor; }<br> * }<br> * * @class */ class MoneyConverter extends DelegatedConverter { /** * @param {Object} options * @param {Object} options.conversions */ constructor(options) { Utility.defaults(options, { adapter: new CurrencyAdapter() }); super(...arguments); } /** * Determines if this Converter instance can convert between the two currencies. * * NOTE: The direction matters. * * @param {Class<Currency>|Currency|String} currency1 * @param {Class<Currency>|Currency|String} currency2 * @returns {boolean} */ supports(currency1, currency2) { currency1 = Currency.optCurrency(currency1); currency2 = Currency.optCurrency(currency2); let conversion = this.optConversion(currency1, currency2, optionalConversion); return Utility.isFunction(conversion); } /** * Executes the conversion. * * @param {Money} sourceMoney * @param {Class<Currency>|Currency} destinationCurrency * @returns {Money} * @throws {PreconditionsError} if the converter fails to convert into a valid number * @throws {PreconditionsError} if the destinationCurrency is not a valid currency * @throws {PreconditionsError} if converter cannot support the conversion */ convert(sourceMoney, destinationCurrency) { return Money.shouldBeMoney(super.convert(sourceMoney, destinationCurrency), destinationCurrency); } /** * Detects the conversion function, given the inputs. * * @param {Class<Currency>|Currency|String} sourceCurrency * @param {Class<Currency>|Currency|String} destinationCurrency * @param {Function|Number|String|Converter} [optionalConversion] * * @returns {Function} */ optConversion(sourceCurrency, destinationCurrency, optionalConversion) { sourceCurrency = Currency.optCurrency(sourceCurrency); destinationCurrency = Currency.optCurrency(destinationCurrency); if (!sourceCurrency || !destinationCurrency) { return null; } else if (sourceCurrency.equals(destinationCurrency)) { return function (value) { return value; } } else if (Utility.isFunction(optionalConversion)) { return optionalConversion; } else if (Utility.isNumber(optionalConversion)) { return function (value) { return value * optionalConversion; } } else if (Converter.isInstance(optionalConversion)) { return this._getConversion(optionalConversion, sourceCurrency, destinationCurrency); } else { return this._getConversion(this, sourceCurrency, destinationCurrency); } } /** * Register a conversion with this converter. This must be a valid object. * * Example: * * {<br> * 'USD->Bitcoin': function() ...<br> * }<br> * * @param {Object} conversions * @returns {Converter} */ register(conversions) { Preconditions.shouldBeObject(conversions); Lodash.assign(this.conversions, conversions); return this; } /** * @param {Converter} converter * @param {Money|Currency|Class<Currency>|String} sourceCurrency * @param {Money|Currency|Class<Currency>|String} destinationCurrency * @private * @return {Function} */ _getConversion(converter, sourceCurrency, destinationCurrency) { sourceCurrency = Currency.getCurrency(sourceCurrency); destinationCurrency = Currency.getCurrency(destinationCurrency); let converterName = sourceCurrency.toString() + '->' + destinationCurrency.toString(); let fn = converter.conversions[converterName]; Preconditions.shouldBeFunction(fn, 'Converter not found: ' + converterName); return fn; } } export {MoneyConverter}; export default MoneyConverter;<file_sep>/src/js/TimeUnit.js 'use strict'; import Utility from "./Utility"; import CoreObject from "./CoreObject"; import {ChronoUnit} from 'js-joda/dist/js-joda' import {Duration} from 'js-joda/dist/js-joda' import Preconditions from "./Preconditions"; import math from 'mathjs'; Preconditions.shouldBeDefined(ChronoUnit); Preconditions.shouldBeDefined(Duration); // Handy constants for conversions const C0 = 1; const C1 = C0 * 1000; const C2 = C1 * 1000; const C3 = C2 * 1000; const C4 = C3 * 60; const C5 = C4 * 60; const C6 = C5 * 24; const MAX = Number.MAX_SAFE_INTEGER; const MIN = Number.MIN_SAFE_INTEGER; /** * Scale value by m, checking for overflow. * This has a short name to make above covaluee more reavalueable. * @param {Number|String} value * @param {Number} m * @param {Number} over * @return {Number} */ function x(value, m, over) { value = Utility.toNumberOrFail(value); if (value > over) return MAX; if (value < -over) return MIN; return value * m; } //region specs const SPEC_NANOSECONDS = { /** * @type {ChronoUnit} */ unit: ChronoUnit.NANOS, shortName: 'ns', longName: 'nanos', /** * @param {Duration} duration * @return {Number|number} */ toNumber(duration) { return this.fromNanos(duration.toNanos()); }, toNanos(valueInNanos) { return valueInNanos; }, fromNanos(valueInNanos) { return valueInNanos; }, toMicros(valueInNanos) { return math.chain(valueInNanos) .divide( math.divide(C1, C0) ) .done(); // return valueInNanos / (C1 / C0); }, toMillis(valueInNanos) { return math.divide(valueInNanos, (math.divide(C2, C0))); // return valueInNanos / (C2 / C0); }, toSeconds(valueInNanos) { return math.divide(valueInNanos, (math.divide(C3, C0))); // return valueInNanos / (C3 / C0); }, toMinutes(valueInNanos) { return math.divide(valueInNanos, (math.divide(C4, C0))); // return valueInNanos / (C4 / C0); }, toHours(valueInNanos) { return math.divide(valueInNanos, (math.divide(C5, C0))); // return valueInNanos / (C5 / C0); }, toDays(valueInNanos) { return math.divide(valueInNanos, (math.divide(C6, C0))); // return valueInNanos / (C6 / C0); }, convert(value, timeUnit) { return timeUnit.toNanos(value); }, excessNanos(value, m) { return (value - (m * C2)); } }; const SPEC_MICROSECONDS = { unit: ChronoUnit.MICROS, shortName: "\u03bcs", // μs longName: 'micros', /** * @param {Duration} duration * @return {Number|number} */ toNumber(duration) { return this.fromNanos(duration.toNanos()); }, fromNanos(valueInNanos) { return SPEC_NANOSECONDS.toMicros(valueInNanos); }, toNanos(valueInMicros) { return x(valueInMicros, math.divide(C1, C0), math.divide(MAX, math.divide(C1, C0))); // return x(valueInMicros, C1 / C0, MAX / (C1 / C0)); }, // toMicros(valueInMicros) { // return valueInMicros; // }, // toMillis(valueInMicros) { // return valueInMicros / (C2 / C1); // }, // toSeconds(valueInMicros) { // return valueInMicros / (C3 / C1); // }, // toMinutes(valueInMicros) { // return valueInMicros / (C4 / C1); // }, // toHours(valueInMicros) { // return valueInMicros / (C5 / C1); // }, // toDays(valueInMicros) { // return valueInMicros / (C6 / C1); // }, // convert(value, timeUnit) { // return timeUnit.toMicros(value); // }, excessNanos(value, m) { return ((value * C1) - (m * C2)); } }; const SPEC_MILLISECONDS = { unit: ChronoUnit.MILLIS, shortName: "ms", // μs longName: 'millis', /** * @param {Duration} duration * @return {Number|number} */ toNumber(duration) { return this.fromNanos(duration.toNanos()); }, fromNanos(valueInNanos) { return SPEC_NANOSECONDS.toMillis(valueInNanos); }, toNanos(valueInMillis) { return x(valueInMillis, math.divide(C2, C0), math.divide(MAX, math.divide(C2, C0))); // return x(valueInMillis, C2 / C0, MAX / (C2 / C0)); }, // toMicros(valueInMillis) { // return x(valueInMillis, C2 / C1, MAX / (C2 / C1)); // }, // toMillis(valueInMillis) { // return valueInMillis; // }, // toSeconds(valueInMillis) { // return valueInMillis / (C3 / C2); // }, // toMinutes(valueInMillis) { // return valueInMillis / (C4 / C2); // }, // toHours(valueInMillis) { // return valueInMillis / (C5 / C2); // }, // toDays(valueInMillis) { // return valueInMillis / (C6 / C2); // }, // convert(value, timeUnit) { // return timeUnit.toMillis(value); // }, excessNanos(value, m) { return 0; } }; const SPEC_SECONDS = { unit: ChronoUnit.SECONDS, shortName: "s", longName: 'seconds', /** * @param {Duration} duration * @return {Number|number} */ toNumber(duration) { return this.fromNanos(duration.toNanos()); }, fromNanos(valueInNanos) { return SPEC_NANOSECONDS.toSeconds(valueInNanos); }, toNanos(valueInSeconds) { return x(valueInSeconds, math.divide(C3, C0), math.divide(MAX, math.divide(C3 / C0))); // return x(valueInSeconds, C3 / C0, MAX / (C3 / C0)); }, // toMicros(valueInSeconds) { // return x(valueInSeconds, C3 / C1, MAX / (C3 / C1)); // }, // toMillis(valueInSeconds) { // return x(valueInSeconds, C3 / C2, MAX / (C3 / C2)); // }, // toSeconds(valueInSeconds) { // return valueInSeconds; // }, // toMinutes(valueInSeconds) { // return valueInSeconds / (C4 / C3); // }, // toHours(valueInSeconds) { // return valueInSeconds / (C5 / C3); // }, // toDays(valueInSeconds) { // return valueInSeconds / (C6 / C3); // }, // convert(value, timeUnit) { // return timeUnit.toSeconds(value); // }, excessNanos(value, m) { return 0; } }; const SPEC_MINUTES = { unit: ChronoUnit.MINUTES, shortName: 'min', longName: 'minutes', /** * @param {Duration} duration * @return {Number|number} */ toNumber(duration) { return this.fromNanos(duration.toNanos()); }, fromNanos(valueInNanos) { return SPEC_NANOSECONDS.toMinutes(valueInNanos); }, toNanos(valueInMinutes) { return x(valueInMinutes, math.divide(C4, C0), math.divide(MAX, math.divide(C4 / C0))); // return x(valueInMinutes, C4 / C0, MAX / (C4 / C0)); }, // toMicros(valueInMinutes) { // return x(valueInMinutes, C4 / C1, MAX / (C4 / C1)); // }, // toMillis(valueInMinutes) { // return x(valueInMinutes, C4 / C2, MAX / (C4 / C2)); // }, // toSeconds(valueInMinutes) { // return x(valueInMinutes, C4 / C3, MAX / (C4 / C3)); // }, // toMinutes(valueInMinutes) { // return valueInMinutes; // }, // toHours(valueInMinutes) { // return valueInMinutes / (C5 / C4); // }, // toDays(valueInMinutes) { // return valueInMinutes / (C6 / C4); // }, // convert(value, timeUnit) { // return timeUnit.toMinutes(value); // }, excessNanos(value, m) { return 0; } }; const SPEC_HOURS = { shortName: "h", longName: 'hours', /** * @param {Duration} duration * @return {Number|number} */ toNumber(duration) { return this.fromNanos(duration.toNanos()); }, fromNanos(valueInNanos) { return SPEC_NANOSECONDS.toHours(valueInNanos); }, toNanos(valueInHours) { return x(valueInHours, C5 / C0, MAX / (C5 / C0)); }, // toMicros(valueInHours) { // return x(valueInHours, C5 / C1, MAX / (C5 / C1)); // }, // // toMillis(valueInHours) { // return x(valueInHours, C5 / C2, MAX / (C5 / C2)); // }, // // toSeconds(valueInHours) { // return x(valueInHours, C5 / C3, MAX / (C5 / C3)); // }, // // toMinutes(valueInHours) { // return x(valueInHours, C5 / C4, MAX / (C5 / C4)); // }, // // toHours(valueInHours) { // return valueInHours; // }, // // toDays(valueInHours) { // return valueInHours / (C6 / C5); // }, // convert(value, timeUnit) { // return timeUnit.toHours(value); // }, excessNanos(value, m) { return 0; } }; const SPEC_DAYS = { unit: ChronoUnit.DAYS, shortName: 'd', longName: 'days', toNanos(valueInDays) { return x(valueInDays, C6 / C0, MAX / (C6 / C0)); }, fromNanos(valueInNanos) { // TimeUnit.NANOS.toDays(valueInNanos) return SPEC_NANOSECONDS.toDays(valueInNanos); }, toMicros(valueInDays) { return x(valueInDays, C6 / C1, MAX / (C6 / C1)); }, toMillis(valueInDays) { return x(valueInDays, C6 / C2, MAX / (C6 / C2)); }, toSeconds(valueInDays) { return x(valueInDays, C6 / C3, MAX / (C6 / C3)); }, toMinutes(valueInDays) { return x(valueInDays, C6 / C4, MAX / (C6 / C4)); }, /** * @param {Number} valueInDays * @return {Number} hours */ toHours(valueInDays) { return x(valueInDays, C6 / C5, MAX / (C6 / C5)); }, toDays(valueInDays) { return valueInDays; }, /** * * @param {Number} value * @param {TimeUnit} timeUnit * @returns {Number|*} days */ convert(value, timeUnit) { return timeUnit.toDays(value); }, excessNanos(value, m) { return 0; } }; //endregion //region TimeUnit class TimeUnit extends CoreObject { //region static TimeUnits /** * @return {TimeUnit} */ static NANOSECONDS = new TimeUnit(SPEC_NANOSECONDS); /** * @return {TimeUnit} */ static MICROSECONDS = new TimeUnit(SPEC_MICROSECONDS); /** * @return {TimeUnit} */ static MILLISECONDS = new TimeUnit(SPEC_MILLISECONDS); /** * @return {TimeUnit} */ static SECONDS = new TimeUnit(SPEC_SECONDS); /** * @return {TimeUnit} */ static MINUTES = new TimeUnit(SPEC_MINUTES); /** * @return {TimeUnit} */ static HOURS = new TimeUnit(SPEC_HOURS); /** * @return {TimeUnit} */ static DAYS = new TimeUnit(SPEC_DAYS); //endregion /** * @protected * @param {Object} spec */ constructor(spec) { super(); /** * @type {{unit: ChronoUnit, toString:function, equals:function, excessNanos:function, shortName:String, longName:String, toNumber:function}} * @private */ this.spec = spec; } /** * @returns {string} */ toString() { return this.spec.shortName; } valueOf() { return this.toString(); } //region public methods /** * * @returns {String} */ get shortName() { return this.spec.shortName; } /** * * @returns {String} */ get longName() { return this.spec.longName; } /** * @return {ChronoUnit} */ toChronoUnit() { return this.spec.unit; } /** * * @param {Number} value - (the units of this number are assumed to be 'this.unit') * @returns {Duration} */ toDuration(value) { value = Utility.toNumberOrFail(value, 'TimeUnit.toDuration(value) - value required'); return Duration.of(value, this.toChronoUnit()); } //conversions /** * Converts from SOURCE value/units into DESTINATION (this) units. * * @param {Number} value The SOURCE value * @param {TimeUnit} timeUnit The SOURCE timeUnit * @returns {Number} The destination value/units */ convert(value, timeUnit) { Preconditions.shouldBeNumber(value); Preconditions.shouldBeInstance(timeUnit, TimeUnit); let duration = Duration.of(value, timeUnit.toChronoUnit()); return this.spec.fromNanos(duration.toNanos()); // let numberOfNanos = sourceDuration.toNanos(); // let destinationDuration = this.toDuration(0); // // return destinationDuration.plusNanos(numberOfNanos); } /** * @param {Number} value The value, in "our" units. If the unit is Millis, then your 'value' should be units. * * @return {Number} */ toValue(value) { return this.spec.fromNanos( this.toDuration(value) .toNanos()); } /** * @param {Number} value * @returns {Number} */ toNanos(value) { return SPEC_NANOSECONDS.toNumber(this.toDuration(value)); } /** * @param {Number} value * @returns {Number} */ toMicros(value) { // This library does not have support for micro return SPEC_MICROSECONDS.toNumber(this.toDuration(value)); } /** * @param {Number} value * @returns {Number} */ toMillis(value) { return SPEC_MILLISECONDS.toNumber(this.toDuration(value)); } /** * @param {Number} value * @returns {Number} */ toSeconds(value) { return SPEC_SECONDS.toNumber(this.toDuration(value)); } /** * @param {Number} value * @returns {Number} */ toMinutes(value) { return SPEC_MINUTES.toNumber(this.toDuration(value)); } /** * @returns {Number} */ toHours(value) { return SPEC_HOURS.toNumber(this.toDuration(value)); } /** * @param {Number} value * @returns {Number} */ toDays(value) { return SPEC_DAYS.toNumber(this.toDuration(value)); } /** * * @param {TimeUnit} timeUnit * @returns {boolean} */ equals(timeUnit) { if (!timeUnit) { return false; } return timeUnit.toString() === this.toString(); } //endregion } //endregion export {TimeUnit}; export default TimeUnit;<file_sep>/test/Utility.spec.js 'use strict'; /** * How to use Chai * @see http://chaijs.com/api/assert/ */ import "source-map-support/register"; import {expect, assert} from "chai"; import Utility from "../src/js/Utility"; import Preconditions from "../src/js/Preconditions"; import CoreObject from "../src/js/CoreObject"; import {Errors, AbstractError, PreconditionsError} from "../src/js/errors"; import {Currency, Bitcoin, Money, Satoshi, USD, Converter} from "../src/js/money"; import {Instant, ZonedDateTime, ZoneOffset, LocalDateTime, LocalTime, TemporalQueries} from "js-joda"; describe('Utility', function () { it('Utility.getPath()', () => { assert.equal('/home/michael/.coinme-node', Utility.getPath({ baseUri: '/home/michael', uri: '.coinme-node' })); assert.equal('/home/michael/.coinme-node/test', Utility.getPath({ baseUri: '/home/michael', uri: '.coinme-node/test' })); assert.equal('/.coinme-node/test', Utility.getPath({ baseUri: '/home/michael', uri: '/.coinme-node/test' })); }); it('toInstant(LocalTime)', () => { let time = LocalTime.now(ZoneOffset.UTC); /** * @type {ZonedDateTime} */ let dateTime = Utility.toDateTime(time); assert.isTrue(dateTime instanceof ZonedDateTime); assert.isTrue(dateTime.toLocalTime().equals(time)); }); it('isBlank', () => { assert.isTrue(Utility.isBlank('')); assert.isTrue(Utility.isBlank(null)); assert.isTrue(Utility.isBlank([])); assert.isTrue(Utility.isBlank(undefined)); assert.isTrue(Utility.isBlank(0)); assert.isTrue(Utility.isBlank(NaN)); }); it('toInstant', () => { Utility.toDateTime(); // assert.isTrue(Utility.toInstant() instanceof Instant); // assert.isTrue(Utility.toInstant(Instant.now()) instanceof Instant); // assert.isTrue(Utility.toInstant(Instant.now().toString()) instanceof Instant); // assert.isTrue(Utility.toInstant(LocalTime.now()) instanceof Instant); // assert.isTrue(Utility.toInstant(LocalTime.now().toString()) instanceof LocalTime); // assert.isTrue(Utility.toInstant(LocalTime.now().toString()) instanceof LocalTime); // assert.isTrue(Utility.toInstant(LocalTime.now().toString()) instanceof LocalTime); let i = Utility.now(); let s = i.toString(); assert.isTrue(Utility.isString(s)); assert.isTrue(Utility.toDateTime(s).equals(i)); }); it('isNumeric', () => { assert.isTrue(Utility.isNumeric(1)); assert.isTrue(Utility.isNumeric('1')); assert.isTrue(Utility.isNumeric('1.0')); assert.isTrue(Utility.isNumeric('1 ')); assert.isTrue(Utility.isNumeric('1.')); assert.isTrue(Utility.isNumeric('1.0 ')); assert.isFalse(Utility.isNumeric()); assert.isFalse(Utility.isNumeric(null)); assert.isFalse(Utility.isNumeric('')); assert.isFalse(Utility.isNumeric('a')); assert.isFalse(Utility.isNumeric(' a')); assert.isFalse(Utility.isNumeric('1.0 a')); assert.isFalse(Utility.isNumeric('1.0.')); }); it('isTemporal()', () => { assert.isTrue(Utility.isTemporal(LocalDateTime.now()), 'isTemporal'); }); it('typeOf(DateTime) -> temporal', () => { assert.equal(Utility.typeOf(LocalDateTime.now()), 'temporal'); }); it('typeOf', () => { assert.equal('class', Utility.typeOf(Currency), 'Currency'); assert.equal('class', Utility.typeOf(Error), 'Error'); // assert.equal('instance', Utility.typeOf(new Error()), 'Error'); // assert.equal('instance', Utility.typeOf(new PreconditionsError()), 'PreconditionsError'); }); it('Utility.toLowerCase', () => { assert.equal(Utility.toLowerCase('ASDf'), 'asdf'); assert.isTrue(Utility.isStringEqual(Utility.toLowerCase('ASDf'), 'asdf')); assert.isTrue(Utility.isStringEqualIgnoreCase(Utility.toLowerCase('ASDf'), 'asdf')); }); it('Utility.optString', () => { assert.isTrue(Utility.isUndefined(Utility.optString(null))); assert.isTrue(Utility.isUndefined(Utility.optString(undefined))); assert.isTrue(Utility.isUndefined(Utility.optString(NaN))); assert.isTrue(Utility.isString(Utility.optString('asdf'))); }); it('Utility.optLowerCase', () => { assert.equal(Utility.optLowerCase('ASDf'), 'asdf'); assert.isTrue(Utility.isStringEqual(Utility.toLowerCase('ASDf'), 'asdf')); assert.isTrue(Utility.isStringEqualIgnoreCase(Utility.toLowerCase('ASDf'), 'asdf')); assert.isTrue(Utility.isStringEqualIgnoreCase(Utility.toLowerCase('ASDf'), 'asdf')); }); it('Utility.isStringEqual', () => { assert.isTrue(Utility.isStringEqual('a', 'a'), '1'); assert.isFalse(Utility.isStringEqual('a', 'A'), '2'); assert.isTrue(Utility.isStringEqual('', ''), '2'); assert.isTrue(Utility.isStringEqual(NaN, NaN), 'NaN'); assert.isTrue(Utility.isStringEqual(null, null), 'null'); assert.isTrue(Utility.isStringEqual(undefined, undefined), 'undefined'); assert.isFalse(Utility.isStringEqual('', null, 'null and empy')); assert.isFalse(Utility.isStringEqual('', undefined, 'empty and undef')); assert.isFalse(Utility.isStringEqual(null, undefined, 'null and undef')); }) it('Utility.isEqualIgnoreCase', () => { assert.isTrue(Utility.isStringEqualIgnoreCase('a', 'A'), '1'); assert.isTrue(Utility.isStringEqualIgnoreCase('', ''), '2'); assert.isTrue(Utility.isStringEqualIgnoreCase(NaN, NaN), 'NaN'); assert.isTrue(Utility.isStringEqualIgnoreCase(null, null), 'null'); assert.isTrue(Utility.isStringEqualIgnoreCase(undefined, undefined), 'undefined'); assert.isFalse(Utility.isStringEqualIgnoreCase('', null, 'null and empy')); assert.isFalse(Utility.isStringEqualIgnoreCase('', undefined, 'empty and undef')); assert.isFalse(Utility.isStringEqualIgnoreCase(null, undefined, 'null and undef')); }); it('Utility.typeMatcher(Class)', () => { assert.equal('class', Utility.typeOf(Money), 'Money should be class'); assert.equal('instance', Utility.typeOf(new Money({ value: 1, currency: Bitcoin })), 'new Money() should be instance'); let matcherFn = Utility.typeMatcher(Money); assert.equal('function', Utility.typeOf(matcherFn), 'matcherFn should be function'); assert.isFalse(matcherFn(Money), 'matcherFn(Money) should be false'); assert.isFalse(matcherFn(Bitcoin), 'matcherFn(Bitcoin) is not Money'); assert.isTrue(matcherFn(new Money({ value: 1, currency: Bitcoin })), 'new Money() should be true'); }); it('CoreObject.toClass() (static)', () => { assert.equal(CoreObject.toClass(), CoreObject, 'CoreObject.toClass()'); }); it('(new CoreObject()).toClass() (instance)', () => { assert.equal(CoreObject, Utility.toClass(CoreObject), 'Utility.toClass(CoreObject) === CoreObject'); assert.equal(Currency, Utility.toClass(Currency), 'Utility.toClass(Currency) === Currency'); assert.equal(Utility.toClass(new CoreObject()), CoreObject, 'Utility.toClass(new CoreObject()) === CoreObject'); assert.isTrue((new CoreObject()).toClass() === CoreObject, '(new CoreObject()).toClass()'); }); it('Utility.typeOf(class)', () => { assert.equal('class', Utility.typeOf(CoreObject), 'CoreObject is type of class'); assert.equal('class', Utility.typeOf(Currency), 'Currency is type of class'); assert.equal('class', Utility.typeOf(Bitcoin), 'Bitcoin is type of class'); assert.equal('class', Utility.typeOf(Money), 'Money is type of class'); }); it('isClass', () => { assert.equal('class', Utility.typeOf(Money), 'Money is type of class'); assert.isTrue(Utility.isClass(Currency)); assert.isTrue(Currency.isClass(Bitcoin)); assert.isFalse(Money.isClass(Bitcoin)); }); it('isInstance', () => { assert.equal('instance', Utility.typeOf(new CoreObject())); }); it('function', () => { let fn = () => { }; assert.isFunction(fn); assert.isTrue(Utility.isFunction(fn)); assert.isFalse(Utility.isFunction(null)); assert.isFalse(Utility.isFunction('')); assert.isFalse(Utility.isFunction(NaN)); }); it('take - with defaultValue', () => { let object = { one: 'one', two: 'two', three: 'three' }; let objectWithValue1 = Utility.take(object, 'four', { defaultValue: 'four' }); assert.equal(Object.keys(object).length, 3); assert.equal(objectWithValue1, 'four', 'Should have returned an object'); }); it('take(object, array<String>)', () => { let object = { one: 'one', two: 'two', three: 'three' }; let objectWithValue1 = Utility.take(object, ['one']); Preconditions.shouldBeObject(objectWithValue1); Preconditions.shouldBeString(objectWithValue1.one); assert.equal(objectWithValue1.one, 'one', 'Should have returned an object'); assert.equal(1, Object.keys(objectWithValue1).length, 'Should have returned only one value'); }); it('take(object, array<Object>)', () => { let object = { one: 'one', two: 'two', three: 'three' }; let objectWithValue1 = Utility.take(object, [{key: 'one'}]); Preconditions.shouldBeObject(objectWithValue1); Preconditions.shouldBeString(objectWithValue1.one); assert.equal(objectWithValue1.one, 'one', 'Should have returned an object'); assert.equal(1, Object.keys(objectWithValue1).length, 'Should have returned only one value'); }); it('take(object, {{ key: "type" }})', () => { let object = { one: 'one', two: 'two', three: 'three' }; let objectWithValue1 = Utility.take(object, {one: 'string'}); Preconditions.shouldBeObject(objectWithValue1); Preconditions.shouldBeString(objectWithValue1.one); assert.equal(objectWithValue1.one, 'one', 'Should have returned an object'); assert.equal(1, Object.keys(objectWithValue1).length, 'Should have returned only one value'); }); it('take(object, {{ key: "type" }})', () => { let object = { one: 'one', two: 'two', three: 'three' }; let objectWithValue1 = Utility.take(object, { one: 'string', two: { adapter: function () { return 'CHANGED'; } } }); Preconditions.shouldBeObject(objectWithValue1); Preconditions.shouldBeString(objectWithValue1.one); Preconditions.shouldBeString(objectWithValue1.two); assert.equal(objectWithValue1.one, 'one', 'Should have returned an object'); assert.equal(objectWithValue1.two, 'CHANGED', 'Should have returned an object'); assert.equal(2, Object.keys(objectWithValue1).length, 'Should have returned only one value'); }); it('take - with function', () => { let expected = new CoreObject(); let object = {key: expected}; let value = Utility.take(object, 'key', Utility.yes); assert.equal(expected, value); assert.isTrue(expected === value); }); it('take - with type', () => { let expected = new CoreObject(); let object = {key: expected}; let value = Utility.take(object, 'key', CoreObject); assert.equal(expected, value); assert.isTrue(expected === value); }); it('take - with dots', function () { var object = {one: {two: 3}}; var three = Utility.take(object, 'one.two'); assert.equal(three, 3, 'Should be 3'); assert.isTrue(Utility.isUndefined(object.one.two)); }); it('take - without dots', function () { var object = {one: 2}; var two = Utility.take(object, 'one'); assert.equal(two, 2, 'Should be 2'); assert.isTrue(Utility.isUndefined(object.one), '\'one\' should be undefined'); }); it('existing', function () { assert.isTrue(Utility.isExisting('string')); assert.isTrue(Utility.isExisting({})); }); it('string', function () { assert.isFunction(Utility.typeMatcher('string')); assert.isTrue(Utility.typeMatcher('string')('string')); assert.isTrue(Utility.isString('asdfad')); }); it('shouldBe', function () { Preconditions.shouldBeFalsey(undefined); Preconditions.shouldBeFalsey(false); Preconditions.shouldBeFalsey(null); }); }); <file_sep>/src/js/cache/index.js "use strict"; import Cache from "./Cache"; import LocalFileCache from "./LocalFileCache"; export {Cache}; export {LocalFileCache}; export default { Cache, LocalFileCache };<file_sep>/test/CoreObject.spec.js 'use strict'; /** * How to use Chai * @see http://chaijs.com/api/assert/ */ import {expect, assert} from "chai"; import CoreObject from "../src/js/CoreObject"; import {Errors, AbstractError, PreconditionsError} from "../src/js/errors"; import {Currency, Bitcoin, Money, Satoshi, USD, Converter} from "../src/js/money"; import "source-map-support/register"; describe('CoreObject', () => { it('isClass - self', () => { assert.isTrue(CoreObject.isClass(CoreObject)); assert.isFalse(CoreObject.isClass(function () { })); assert.isFalse(CoreObject.isClass(new CoreObject())); assert.isFalse(CoreObject.isClass(new CoreObject({}))); assert.isTrue(CoreObject.isClass((new CoreObject({})).toClass())); }); it('isInstance - self', () => { assert.isFalse(CoreObject.isInstance(CoreObject)); assert.isTrue(CoreObject.isInstance(new CoreObject())); assert.isFalse(CoreObject.isInstance({})); }); it('isClass - subclass', () => { class Subclass extends CoreObject { } assert.isTrue(CoreObject.isClass(Subclass), 'Subclass should be a CoreObject'); assert.isFalse(CoreObject.isClass(new Subclass())); assert.isTrue(CoreObject.isInstance(new Subclass()), 'subclass is instance of CoreObject'); }); });<file_sep>/README.md # coinme-slack [![npm version](https://badge.fury.io/js/coinme-slack.svg)](https://badge.fury.io/js/coinme-slack) [![Travis Build Status](https://travis-ci.org/coinme/coinme-node.svg?branch=master)](https://travis-ci.org/coinme/coinme-node) * https://esdoc.org/config.html#full-config * https://api.slack.com/incoming-webhooks * https://api.slack.com/docs/attachments * https://github.com/request/request * https://www.npmjs.com/package/request-promise * https://quickleft.com/blog/creating-and-publishing-a-node-js-module/ * https://github.com/yeoman/generator-node * https://github.com/sohamkamani/generator-nm-es6#readme * https://docs.npmjs.com/cli/link * http://jamesknelson.com/the-complete-guide-to-es6-with-babel-6/ * https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.viewc4c8f * https://github.com/corybill/Preconditions * http://www.2ality.com/2015/02/es6-classes-final.html * https://babeljs.io/docs/learn-es2015/ * http://www.2ality.com/2015/07/es6-module-exports.html * http://www.2ality.com/2015/12/babel6-helpersstandard-library.html ## If you don't want to use anything fancy ```javascript var builder = new NotificationBuilder({ url: 'https://hooks.slack.com/services/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', payload: { 'username': 'Say my name again, mother fucker', 'text': 'this is text', 'attachments': [{ 'fallback': 'ReferenceError - UI is not defined: https://honeybadger.io/path/to/event/', 'text': '<https://honeybadger.io/path/to/event/|ReferenceError> - UI is not defined', 'fields': [{ 'title': 'Project', 'value': 'Awesome Project', 'short': true }, { 'title': 'Environment', 'value': 'production', 'short': true }], 'color': '#F35A00' }] } }); ``` ## If you want to be a bit fancy ```javascript var builder = new NotificationBuilder({ url: 'https://hooks.slack.com/services/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' }); { var attachment = builder.attachment() .text('This is validated text, it will throw an Error if not a string') .color('red'); { // Your first field attachment.field() .title('Project') .value('Awesome Project') .short() // Your second field attachment.field() .title('Project') .value('Awesome Project') .short() } } ``` ## NotificationService ```javascript /** * * @param {String} eventName * @param {NotificationTemplate|Object} template */ NotificationService.register('EVENT_NAME', { /** * The name of the template. Useful for debugging. * * @type {String} * @required */ name: 'InlineTemplate', /** * @type {Object} * @optional */ payload: { username: 'InlineTemplate' } }); /** * @param {String} eventName * @param {Object|undefined} data * @return undefined */ NotificationService.notify('EVENT_NAME', { text: 'text' }); ``` ## Install ``` $ npm install --save coinme-slack ``` ## License MIT © [msmyers](https://github.com/msmyers) --- ## CoinmeWalletClient requires signatures ### How to make your certificates For more information, check out [https://engineering.circle.com/https-authorized-certs-with-node-js-315e548354a2] #### Define the client certificate (signed by our Certificate Authority) You would use this certificate when you make requests to *coinme-wallet* ``` openssl genrsa -out client1-key.pem 4096 wget https://raw.githubusercontent.com/coinme/coinme-wallet/master/server/certificates/coinme-ca.pem openssl req -new -config client1.cnf -key client1-key.pem -out client1-csr.pem openssl x509 -req -extfile client1.cnf -days 999 -passin "<PASSWORD>" -in client1-csr.pem -CA ca-crt.pem -CAkey ca-key.pem -CAcreateserial -out client1-crt.pem ``` <file_sep>/src/js/data/User.js 'use strict'; import CoreObject from "~/CoreObject"; /** * This is the base class for all classes in our architecture. * * @abstract * @class */ class User extends CoreObject { /** * * @param {Object} config * @param {String} config.phoneNumber * @param {String} config.username * @param {String} config.firstName * @param {String} config.middleName * @param {String} config.lastName * @param {String} config.race * @param {String} config.gender * @param {String} config.addressLine1 * @param {String} config.addressLine2 * @param {String} config.addressCity * @param {String} config.addressState * @param {String} config.addressZipcode * @param {String} config.addressCountry * @param {String} config.birthDate * @param {String} config.expirationDate */ constructor(config) { super(config); /** @type {String} */ this.firstName = config.firstName; /** @type {String} */ this.lastName = config.lastName; /** @type {String} */ this.middleName = config.middleName; /** @type {String} */ this.addressLine1 = config.addressLine1; /** @type {String} */ this.addressLine2 = config.addressLine2; /** @type {String} */ this.addressCity = config.addressCity; /** @type {String} */ this.addressState = config.addressState; /** @type {String} */ this.addressCountry = config.addressCountry; /** @type {String} */ this.expirationDate = config.expirationDate; /** @type {String} */ this.birthDate = config.birthDate; /** @type {String} */ this.gender = config.gender; /** @type {String} */ this.race = config.race; /** @type {String} */ this.addressZipcode = config.addressZipcode; /** @type {String} */ this.username = config.username; /** @type {String} */ this.phoneNumber = config.phoneNumber; } } export default User;<file_sep>/src/js/slack/NotificationTemplate.js 'use strict'; import Lodash from 'lodash/index'; import Logger from 'winston'; import Preconditions from '~/Preconditions'; import NotificationBuilder from '~/slack/NotificationBuilder'; import AbstractNotificationTemplate from '~/slack/AbstractNotificationTemplate'; class NotificationTemplate extends AbstractNotificationTemplate { constructor(options) { super(options); Lodash.defaults(this, { name: 'NotificationTemplate' }); Preconditions.shouldBeString(this.name, 'You must define a name for this template'); } /** * * @param {NotificationBuilder} builder * @param {*|Object} data * @return {NotificationBuilder} */ applyTemplate(builder, data) { if (Lodash.isObject(this.get('payload'))) { builder.mergeIntoPayload(this.get('payload')); } Logger.silly('Data', data); // This is actually not useful 'by default' // It's useful if you want to do inline stuff, but if we do this in the common base-class, // then we are actually prevented from ever using this.super() in subclasses that use strongly // typed objects instead of slack formatted json. Since the architecture of this project is to // abstract away the slack parts, applying the "data" to the slack payload was a limiting design mistake. // //if (this.Lodash.isObject(data)) { // notificationBuilder.mergeIntoPayload(data); //} // The default implementation // This is where you would modify your builder. return builder; } } export default NotificationTemplate;<file_sep>/src/js/data/Licenses.js import CoreObject from "../CoreObject"; import Errors from "../errors/Errors"; import Preconditions from "../Preconditions"; /******************************************************** * @DESCRIPTION: validation for the format of a driver's * license list as of 2012 US Driver's Licenses formats * @author: <NAME> * @date: 04/04/2013 * * @PARAM: $string, automatic input from form_validation() * @EXPECTED-INPUT: alpha-numeric, trimmed * * @REQUIREMENTS: It is required to validate the DL State * field FIRST in order for us to choose which regex rules * we will use. * @FIELD: 'dl_state' * @FIELD-VALUE: 2 uppercase character state abbreviation ********************************************************/ let format = { 'AL': /^[0-9]{1,7}$/, //1-7Numbers 'AK': /^[0-9]{1,7}$/, //1-7Numbers 'AZ': /(^[a-zA-Z]{1}[0-9]{8}$)|(^[a-zA-Z]{2}[0-9]{2,5}$)|(^[0-9]{9}$)/, //1Alpha+1-8Numeric or 2Alpha+2-5Numeric or 9Numeric 'AR': /^[0-9]{4,9}$/, //4-9Numeric 'CA': /^[a-zA-Z]{1}[0-9]{7}$/, //1Alpha+7Numeric 'CO': /(^[0-9]{9}$)|(^[a-zA-Z]{1}[0-9]{3,6}$)|(^[a-zA-Z]{2}[0-9]{2,5}$)/, //9Numeric or 1Alpha+3-6Numeric or 2Alpha+2-5Numeric 'CT': /^[0-9]{9}$/, //9Numeric 'DE': /^[0-9]{1,7}$/, //1-7Numeric 'DC': /(^[0-9]{7}$)|(^[0-9]{9}$)/, //7Numeric or 9Numeric 'FL': /^[a-zA-Z]{1}[0-9]{12}$/, //1Alpha+12Numeric 'GA': /^[0-9]{7,9}$/, //7-9Numeric 'HI': /(^[a-zA-Z]{1}[0-9]{8}$)|(^[0-9]{9}$)/, //1Alpha+8Numeric or 9Numeric 'ID': /(^[a-zA-Z]{2}[0-9]{6}[a-zA-Z]{1}$)|(^[0-9]{9}$)/, //2Alpha+6Numeric+1Alpha or 9Numeric 'IL': /^[a-zA-Z]{1}[0-9]{11,12}$/, //1Alpha+11-12Numeric 'IN': /(^[a-zA-Z]{1}[0-9]{9}$)|(^[0-9]{9,10}$)/, //1Alpha+9Numeric or 9-10Numeric 'IA': /^[0-9]{9}|([0-9]{3}[a-zA-Z]{2}[0-9]{4}$)/, //9Numeric or 3Numeric+2Alpha+4Numeric 'KS': /(^([a-zA-Z]{1}[0-9]{1}){2}[a-zA-Z]{1}$)|(^[a-zA-Z]{1}[0-9]{8}$)|(^[0-9]{9}$)/, //1Alpha+1Numeric+1Alpha+1Numeric+1Alpha or 1Alpha+8Numeric or 9Numeric 'KY': /(^[a-zA_Z]{1}[0-9]{8,9}$)|(^[0-9]{9}$)/, //1Alpha+8-9Numeric or 9Numeric 'LA': /^[0-9]{1,9}$/, //1-9Numeric 'ME': /(^[0-9]{7,8}$)|(^[0-9]{7}[a-zA-Z]{1}$)/, //7-8Numeric or 7Numeric+1Alpha 'MD': /^[a-zA-Z]{1}[0-9]{12}$/, //1Alpha+12Numeric 'MA': /(^[a-zA-Z]{1}[0-9]{8}$)|(^[0-9]{9}$)/, //1Alpha+8Numeric or 9Numeric 'MI': /(^[a-zA-Z]{1}[0-9]{10}$)|(^[a-zA-Z]{1}[0-9]{12}$)/, //1Alpha+10Numeric or 1Alpha+12Numeric 'MN': /^[a-zA-Z]{1}[0-9]{12}$/, //1Alpha+12Numeric 'MS': /^[0-9]{9}$/, //9Numeric 'MO': /(^[a-zA-Z]{1}[0-9]{5,9}$)|(^[a-zA-Z]{1}[0-9]{6}[R]{1}$)|(^[0-9]{8}[a-zA-Z]{2}$)|(^[0-9]{9}[a-zA-Z]{1}$)|(^[0-9]{9}$)/, //1Alpha+5-9Numeric or 1Alpha+6Numeric+R or 8Numeric+2Alpha or 9Numeric+1Alpha or 9Numeric 'MT': /(^[a-zA-Z]{1}[0-9]{8}$)|(^[0-9]{13}$)|(^[0-9]{9}$)|(^[0-9]{14}$)/, //1Alpha+8Numeric or 13Numeric or 9Numeric or 14Numeric 'NE': /^[0-9]{1,7}$/, //1-7Numeric 'NV': /(^[0-9]{9,10}$)|(^[0-9]{12}$)|(^[X]{1}[0-9]{8}$)/, //9Numeric or 10Numeric or 12Numeric or X+8Numeric 'NH': /^[0-9]{2}[a-zA-Z]{3}[0-9]{5}$/, //2Numeric+3Alpha+5Numeric 'NJ': /^[a-zA-Z]{1}[0-9]{14}$/, //1Alpha+14Numeric 'NM': /^[0-9]{8,9}$/, //8Numeric or 9Numeric 'NY': /(^[a-zA-Z]{1}[0-9]{7}$)|(^[a-zA-Z]{1}[0-9]{18}$)|(^[0-9]{8}$)|(^[0-9]{9}$)|(^[0-9]{16}$)|(^[a-zA-Z]{8}$)/, //1Alpha+7Numeric or 1Alpha+18Numeric or 8Numeric or 9Numeric or 16 Numeric or 8Alpha 'NC': /^[0-9]{1,12}$/, //1-12Numeric 'ND': /(^[a-zA-Z]{3}[0-9]{6}$)|(^[0-9]{9}$)/, //3Alpha+6Numeric or 9Numeric 'OH': /(^[a-zA-Z]{1}[0-9]{4,8}$)|(^[a-zA-Z]{2}[0-9]{3,7}$)|(^[0-9]{8}$)/, //1Alpha+4-8Numeric or 2Alpha+3-7Numeric or 8Numeric 'OK': /(^[a-zA-Z]{1}[0-9]{9}$)|(^[0-9]{9}$)/, //1Alpha+9Numeric or 9Numeric 'OR': /^[0-9]{1,9}$/, //1-9Numeric 'PA': /^[0-9]{8}$/, //8Numeric 'RI': /^([0-9]{7}$)|(^[a-zA-Z]{1}[0-9]{6}$)/, //7Numeric or 1Alpha+6Numeric 'SC': /^[0-9]{5,11}$/, //5-11Numeric 'SD': /(^[0-9]{6,10}$)|(^[0-9]{12}$)/, //6-10Numeric or 12Numeric 'TN': /^[0-9]{7,9}$/, //7-9Numeric 'TX': /^[0-9]{7,8}$/, //7-8Numeric 'UT': /^[0-9]{4,10}$/, //4-10Numeric 'VT': /(^[0-9]{8}$)|(^[0-9]{7}[A]$)/, //8Numeric or 7Numeric+A 'VA': /(^[a-zA-Z]{1}[0-9]{9,11}$)|(^[0-9]{9}$)/, //1Alpha+9Numeric or 1Alpha+10Numeric or 1Alpha+11Numeric or 9Numeric 'WA': /^(?=.{12}$)[a-zA-Z]{1,7}[a-zA-Z0-9\*]{4,11}$/, //1-7Alpha+any combination of Alpha, Numeric, or * for a total of 12 characters 'WV': /(^[0-9]{7}$)|(^[a-zA-Z]{1,2}[0-9]{5,6}$)/, //7Numeric or 1-2Alpha+5-6Numeric 'WI': /^[a-zA-Z]{1}[0-9]{13}$/, //1Alpha+13Numeric 'WY': /^[0-9]{9,10}$/ //9-10Numeric }; class Licenses extends CoreObject { constructor() { super(...arguments); // throw new TypeError('Licenses is abstract'); Preconditions.shouldBeAbstract(Licenses); } static detectStateFromDriverLicense(string) { var match = false; var matchingState = ''; if (string && string.length > 5) { // For performance Ember.$.each(format, function(state, regex) { if (!match && regex.test(string)) { match = true; matchingState = state; } }); } if (!match) { return undefined; } Ember.Logger.warn('Did an expensive query for ' + string); return {state: matchingState}; } }<file_sep>/src/js/money/index.js 'use strict'; import Money from "./Money"; import Bitcoin from "./Bitcoin"; import Currency from "./Currency"; import Satoshi from "./Satoshi"; import USD from "./USD"; import Ethereum from "./Ethereum"; // import Exchange from "./Exchange"; export {Currency}; // export {Exchange}; export {Money}; export {Bitcoin}; export {Ethereum}; export {Satoshi}; export {USD}; export default { Currency, // Exchange, Money, Bitcoin, Ethereum, Satoshi, USD };<file_sep>/src/js/net/CoinmeWalletClient.js "use strict"; import CoreObject from "../CoreObject"; import Promise from "bluebird"; import request from "request-promise"; import Receipt from "../data/Receipt"; import Utility from "../Utility"; import Preconditions from "../Preconditions"; import URI from "urijs"; import request_debug from "request-debug"; import SignTool from "../data/SignTool"; import uuid from "node-uuid"; import Identity from "../data/Identity"; import Address from "../Address"; import Lodash from "lodash"; import UserExistenceToken from "../data/UserExistenceToken"; import CertificateBundle from "../data/CertificateBundle"; request_debug(request); const VERSION_REGEXP = /^\/api\/v(?:\d+\.?\d*)+$/; const METHOD_REGEXP = /(?:POST)|(?:GET)|(?:DELETE)|(?:PUT)/; //region function customPromiseFactory /** * @param {Function} resolver The promise resolver function * @return {Object} The promise instance */ function customPromiseFactory(resolver) { return new Promise(resolver); } //endregion //region class CoinmeWalletClientConfiguration /** * Certificates are required! * * The default value for certificates are found in CertificateBundle.fromHome() */ class CoinmeWalletClientConfiguration extends CoreObject { //region constructor /** * * @param {CoinmeWalletClientConfiguration|Object} [options] * @param {CertificateBundle} [options.certificate] * @param {String|URI} [options.baseUrl] defaults to https://www.coinmewallet.com * @param {String} [options.version] defaults to /api/v1 * @param {SignTool} [options.signTool] defaults to null * @param {String|Address|Identity} [options.identity] defaults to null */ constructor(options) { //region let certificate /** @type {CertificateBundle} */ let certificate = Utility.take(options, 'certificate', { type: CertificateBundle, adapter: function (value) { if (!value) { return CertificateBundle.fromHome(); } else if (Utility.isString(value)) { return CertificateBundle.fromFolder(value); } return value; } }); //endregion //region let timeout let timeout = Utility.take(options, 'timeout', { type: 'number', defaultValue: 30000 }); //endregion //region let baseUrl /** @type {URI} */ let baseUrl = Utility.take(options, 'baseUrl', { required: false, defaultValue: URI('https://www.coinmewallet.com/'), // adapter goes first. adapter: function (value) { if (Utility.isString(value)) { return URI(value); } return value; }, validator: function (uri) { Preconditions.shouldBeInstanceOf(uri, URI, `value must be string or URI. (value:${uri}) (type:${Utility.typeOf(uri)})`); Preconditions.shouldBeTrue(uri.is('absolute'), 'uri must be absolute'); return true; } }); //endregion //region let version let version = Utility.take(options, 'version', { type: 'string', defaultValue: '/api/v1', required: false, validator: function (value) { Preconditions.shouldBeString(value, 'version must be a string'); Preconditions.shouldMatchRegexp(value, VERSION_REGEXP, `version must match pattern: ${VERSION_REGEXP}. Was ${value}`); return true; } }); //endregion //region let sessionId let sessionId = Utility.take(options, 'sessionId', 'string', false); //endregion //region let identity let identity = Utility.take(options, 'identity', { defaultValue: new Identity('library:/coinme-node'), adapter(value) { if (Utility.isString(value)) { return new Identity(value); } else if (Address.isInstance(value)) { return new Identity(value); } else { return value; } }, validator(value) { Preconditions.shouldBeInstance(value, Identity, `identity ${JSON.stringify(value)}`); } }); //endregion //region let signTool let signTool = Utility.take(options, 'signTool', { type: SignTool, defaultValue: new SignTool({ secret: identity.toString(), issuer: identity.toString() }) }); //endregion super(...arguments); this._identity = identity; this._sessionId = sessionId; this._baseUrl = baseUrl; this._version = version; this._signTool = signTool; this._certificate = certificate; this._startedLatch = new Promise((resolve, reject) => { let promise = Promise.resolve(); promise = promise.then(() => certificate.startedLatch); resolve(promise); }); } //endregion //region properties /** * @return {Promise} */ get startedLatch() { return this._startedLatch; } /** * @readonly * @property * @type {CertificateBundle} * @return {CertificateBundle} */ get certificate() { return this._certificate; } /** * * @readonly * @property * @type {Identity} * @return {Identity} */ get identity() { return this._identity; } /** * @readonly * @property * @type {String|undefined} * @return {String|undefined} */ get sessionId() { return this._sessionId; } /** * Example: /api/v1 * * @property * @readonly * @type {String} * @return {String} */ get version() { return this._version; } /** * @property * @readonly * @type {Number} * @return {Number} */ get timeout() { return this._timeout; } /** * Example: https://www.coinmewallet.com/ * * @readonly * @property * @type {URI} * @return {URI} */ get baseUrl() { return this._baseUrl } /** * @property * @readonly * @type {SignTool} * @return {SignTool} */ get signTool() { return this._signTool; } //endregion toJson() { return super.toJson({ version: this.version, identity: Utility.optJson(this.identity.toJson()), signTool: Utility.optJson(this.signTool), sessionId: this.sessionId, baseUrl: Utility.optString(this.baseUrl) }); } /** * * @param {String} sessionId * @return {CoinmeWalletClientConfiguration} */ withSessionId(sessionId) { Preconditions.shouldBeString(sessionId, 'sessionId'); return new CoinmeWalletClientConfiguration(this.clone({ sessionId: sessionId })); } /** * * @param {Object} overrides * @return {CoinmeWalletClientConfiguration} */ clone(overrides) { return new CoinmeWalletClientConfiguration(Lodash.assign({}, this, overrides)); } } //endregion //region class CoinmeWalletClient /** * */ class CoinmeWalletClient extends CoreObject { //region constructor /** * * @param {Object} options * @param {CoinmeWalletClientConfiguration} options.configuration */ constructor(options) { /** @type {CoinmeWalletClientConfiguration} */ let configuration = Utility.take(options, 'configuration', CoinmeWalletClientConfiguration, true); super(...arguments); this._configuration = configuration; this._startedLatch = new Promise((resolve, reject) => { let promise = Promise.resolve(); promise = promise.then(() => configuration.startedLatch); resolve(promise); }); } //endregion //region properties /** * @property * @readonly * @type {Promise} * @return {Promise} */ get startedLatch() { return this._startedLatch; } /** * @property * @readonly * @return {CoinmeWalletClientConfiguration} */ get configuration() { return this._configuration; } //endregion /** * Creates a brand new copy/clone of this client with a sessionId attached. * * @param {String} sessionId * @return {CoinmeWalletClient} */ withSession(sessionId) { return new CoinmeWalletClient({ configuration: this.configuration.withSessionId(sessionId) }); } /** * * @param {Receipt} receipt * @return {Promise} */ notifyReceipt(receipt) { return this._execute({ uri: '/receipt', method: 'POST', data: receipt.toJson() }); } /** * * @param {String} username * @return {Promise.<UserExistenceToken>|Promise} */ peek(username) { Preconditions.shouldNotBeBlank(username, 'username'); return this._execute({ uri: '/user/peek', method: 'GET', data: { username: username }, type: UserExistenceToken }); } /** * * @private * * @param {Object} options * @param {String|URI} options.uri * @param {String} options.method * @param {Object} [options.data] * @param {Function} [options.adapter] * @param {Class} [options.type] * * @return {Promise} */ _execute(options) { var scope = this; return Promise.resolve() .then(() => this.startedLatch) .then(function () { let configuration = scope.configuration; /** * @type {String} */ let method = Preconditions.shouldMatchRegexp(options.method, METHOD_REGEXP, 'Must be GET|POST|PUT|DELETE'); /** * @type {URI} */ let uri = scope._getUrl(options.uri); /** * @type {Object} */ let data = options.data || {}; data.transactionId = uuid.v1(); data.timestamp = (new Date()).getTime(); data.signature = scope._sign(uri.path(), data); let request_args = { url: uri.toString(), method: method, headers: { 'X-Transaction-ID': data.transactionId, 'X-Timestamp': data.timestamp, 'X-Signature': data.signature }, // --- json: true, httpSignature: { keyId: configuration.certificate.key.name, key: configuration.certificate.key.value }, timeout: scope.configuration.timeout, promiseFactory: customPromiseFactory, fullResponse: true // (default) To resolve the promise with the full response or just the body }; if ('GET' === method && data) { request_args.qs = data; } else if ('POST' === method) { request_args.data = data; } return request(request_args, function (err, res, body) { // console.log('REQUEST RESULTS:', err, res.statusCode, body); }) .then((result) => { if (options.adapter) { return options.adapter.call(scope, result); } else if (options.type) { return new options.type(result) } else { return result; } }); }); } /** * * @private * @return {undefined|String} */ _sign(relativeUri, parameters) { return this.configuration.signTool.write(parameters || {}, { issuer: this.configuration.identity.toString(), audience: 'coinme-wallet', subject: relativeUri.toString() }); } /** * @param {String|URI} stringOrUri * @return {URI} * @private */ _getUrl(stringOrUri) { /** @type {URI} */ let uri = URI(stringOrUri); /** @type {CoinmeWalletClientConfiguration} */ let configuration = this.configuration; let baseUrl = configuration.baseUrl; let version = configuration.version; Preconditions.shouldBeTrue(uri.is('relative'), `Must be relative. Was ${stringOrUri}`); return URI .joinPaths(baseUrl, version, uri) .absoluteTo(baseUrl); } } //endregion export {CoinmeWalletClientConfiguration}; export {CoinmeWalletClient}; export default CoinmeWalletClient;<file_sep>/src/js/data/Receipt.js 'use strict'; import CoreObject from "../CoreObject"; import Preconditions from "../Preconditions"; import Utility from "../Utility"; import {NotImplementedError} from "../errors/NotImplementedError"; import {Instant} from "js-joda/dist/js-joda"; import {Currency, USD, Money, Bitcoin} from "../money"; import {Address} from "../Address"; import Identity from "./Identity"; //region class EndpointType class EndpointType extends CoreObject { /** * * @param {String|Money} stringOrMoney * @return {Money} */ toMoney(stringOrMoney) { if (!stringOrMoney) { stringOrMoney = '0'; } Currency.shouldBeCurrency(this.currency); let money = Currency.toMoney(stringOrMoney, this.currency); let currencyClass1 = this.currency.toClass(); let currencyClass2 = money.currency.toClass(); Preconditions.shouldBeClass(currencyClass2, currencyClass1); return money; } /** * * @param {String|Address|URI|ReceiptEndpoint} stringOrAddressOrUri * @return {Address} */ toAddress(stringOrAddressOrUri) { if (stringOrAddressOrUri instanceof ReceiptEndpoint) { /** * @type {ReceiptEndpoint} */ let endpoint = stringOrAddressOrUri; return endpoint.address; } let address = Address.toAddressWithDefaultScheme(stringOrAddressOrUri, this.name); Preconditions.shouldBeInstance(address, Address, 'Wrong type'); Preconditions.shouldBeTrue( Utility.isStringEqualIgnoreCase(address.resource, this.name), `Wrong resource type. Actual:${this.name} Expected:${address.resource}`); Preconditions.shouldBeDefined(address.valid); Preconditions.shouldBeTrue(address.valid, 'Address is not valid: ' + address); return address; } toJson() { return super.toJson({ currency: Utility.optString(this.currency), name: this.name }); } /** * @return {Class<Currency>} */ get currency() { throw new NotImplementedError('type'); } /** * @return {String} */ get name() { throw new NotImplementedError('type'); } } class KioskEndpointType extends EndpointType { /** * @return {Currency} */ get currency() { return USD; } /** * @return {String} */ get name() { return 'kiosk' } static create(options) { let fee = Utility.take(options, 'fee', { validator: function (value) { Preconditions.shouldBeNumber(value, 'Must be number'); Preconditions.shouldBeTrue(value < 1, 'Fee should be less than 1'); return value; } }); let id = Utility.take(options, 'id', { type: 'String', required: true }); return new KioskEndpointType({ fee: fee, id: id }); } } class WalletEndpointType extends EndpointType { /** * @return {Class<Currency>|Currency} */ get currency() { return Bitcoin; } /** * @return {String} */ get name() { return 'bitcoin'; } } //endregion let ENDPOINT_INSTANCE_KIOSK = new KioskEndpointType(); let ENDPOINT_INSTANCE_WALLET = new WalletEndpointType(); let endpointTypes = {}; endpointTypes[ENDPOINT_INSTANCE_WALLET.name] = ENDPOINT_INSTANCE_WALLET; endpointTypes[ENDPOINT_INSTANCE_KIOSK.name] = ENDPOINT_INSTANCE_KIOSK; //region class EndpointTypes class EndpointTypes { static types = endpointTypes; /** * @return {KioskEndpointType} */ static get KIOSK() { return ENDPOINT_INSTANCE_KIOSK; } /** * @return {WalletEndpointType} */ static get WALLET() { return ENDPOINT_INSTANCE_WALLET; } /** * @param {Address|String|EndpointType} nameOrInstance * @return {EndpointType} */ static getEndpointTypeOrFail(nameOrInstance) { if (Address.isInstance(nameOrInstance)) { nameOrInstance = Preconditions.shouldNotBeBlank(nameOrInstance.resource, `Name suspiciously blank ${nameOrInstance}`); } else if (EndpointType.isInstance(nameOrInstance)) { return nameOrInstance; } else if (Utility.isString(nameOrInstance)) { } else { throw new NotImplementedError(`Cannot work with ${nameOrInstance}`); } let type = EndpointTypes.types[nameOrInstance]; Preconditions.shouldBeInstance(type, EndpointType, `EndpointType not found with name: '${nameOrInstance}'`); return type; } } //endregion //region class ReceiptEndpoint class ReceiptEndpoint extends CoreObject { //region fields /** * @type {Money} */ _amount; /** * @type {Money} */ _fee; /** * @type {Address} */ _address; /** * @type {EndpointType} */ _type; /** * @type {Instant} */ _timestamp; //endregion /** * * @param {Object} options * @param {Address|String} options.address * @param {Money|String|Number|Big|BigJsLibrary.BigJS} options.amount * @param {Money|String|Number|Big|BigJsLibrary.BigJS} [options.fee] * @param {Instant|String|Number} options.timestamp If number, is assumed to be millis. */ constructor(options) { /** * @type {Address} */ let address = Address.toAddress(Utility.take(options, 'address', { type: Address, required: true, adapter: Address.toAddressWithDefaultScheme })); /** * @type {Instant} */ let timestamp = Utility.take(options, 'timestamp', { required: true, validator: function (value) { return value instanceof Instant; } }); /** * @type {Money} */ let amount = Utility.take(options, 'amount', Money, true); let fee = Utility.take(options, 'fee', Money, false); super(...arguments); this._type = EndpointTypes.getEndpointTypeOrFail(address); this._address = address; this._amount = this.type.toMoney(amount); this._fee = this.type.toMoney(fee); this._timestamp = Utility.toDateTime(timestamp); } /** * @type {Address} */ get address() { return this._address; } /** * @type {EndpointType} */ get type() { return this._type; } /** * @type {Money} */ get amount() { return this._amount; } /** * @return {Money} */ get fee() { return this._fee; } toJson() { return super.toJson({ currency: Utility.optString(this.type.currency), fee: Utility.optString(Money.optValue(this.fee)), amount: Utility.optJson(Money.optValue(this.amount)), address: Utility.optString(this.address), }); } } //endregion //region class Receipt class Receipt extends CoreObject { /** * @type Instant */ _timestamp; /** * @type {ReceiptEndpoint} */ _source; /** * @type {ReceiptEndpoint} */ _destination; /** * @type {Identity} */ _identity; /** * @param {Object} options * @param {ReceiptEndpoint} options.source * @param {ReceiptEndpoint} options.destination * @param {Instant} options.timestamp */ constructor(options) { let source = Utility.take(options, 'source', ReceiptEndpoint, true); let destination = Utility.take(options, 'destination', ReceiptEndpoint, true); let identity = Utility.take(options, 'identity', Identity, true); let timestamp = Utility.take(options, 'timestamp', { required: true, adapter: function(value) { return Utility.optInstant(Utility.optDateTime(value)); }, validator: function (value) { return value instanceof Instant; } }); super(...arguments); this._timestamp = timestamp; this._source = source; this._destination = destination; this._identity = identity; } /** * @return {Instant} */ get timestamp() { return this._timestamp; } /** * @type {ReceiptEndpoint} */ get source() { return this._source; } /** * @type {ReceiptEndpoint} */ get destination() { return this._destination; } /** * @return {Identity} */ get identity() { return this._identity; } toJson() { return super.toJson({ identity: Utility.optString(this.identity), timestamp: Utility.optString(this.timestamp), source: Utility.optJson(this.source), destination: Utility.optJson(this.destination) }); } } //endregion //region class ReceiptBuilder (incomplete) class ReceiptBuilder extends CoreObject { constructor(options) { super(...arguments); } from(kioskName, money) { } to() { } at() { } } //endregion export {KioskEndpointType}; export {WalletEndpointType}; export {ReceiptBuilder}; export {EndpointTypes}; export {EndpointType}; export {ReceiptEndpoint}; export {Receipt}; export default Receipt; <file_sep>/src/js/Ticker.js 'use strict'; import TimeUnit from "./TimeUnit"; import Promise from 'bluebird'; import NanoTimer from 'nanotimer'; /** * * @type {Ticker} */ var SYSTEM_TICKER; class Ticker { /** * Constructor for use by subclasses. */ constructor(options) { this._timer = new NanoTimer(); } /** * * @return {NanoTimer} */ get timer() { return this._timer; } /** * Returns the number of nanoseconds elapsed since this ticker's fixed * point of reference. * * @return {Number} nanoseconds */ read() { let time = process.hrtime(); let timeInSeconds = time[0]; let timeInNanos = time[1]; return TimeUnit.SECONDS.toNanos(timeInSeconds) + timeInNanos; } /** * Returns a promise that will finish in the given time. * * @param {Number} value * @param {TimeUnit} timeUnit * @return {Promise} */ wait(value, timeUnit) { let scope = this; return new Promise((resolve, reject) => { let numberOfNanos = TimeUnit.NANOSECONDS.convert(value, timeUnit); //.setTimeout(task, args, timeout, [callback]) scope.timer.setTimeout(function() { resolve(); }, null, numberOfNanos + 'n'); }); } /** * A ticker that reads the current time using nanoseconds. * * @return {Ticker} */ static systemTicker() { return SYSTEM_TICKER; } } SYSTEM_TICKER = new Ticker(); export {Ticker}; export default Ticker;<file_sep>/src/js/errors/NotImplementedError.js import Utility from '../Utility'; import AbstractError from './AbstractError'; class NotImplementedError extends AbstractError { /** * * @param {String|Object} [options] * @param {String} [options.message] * @param {Error} [options.cause] * @constructor */ constructor(options) { if (Utility.isString(options)) { options = {message: options}; } options = options || {}; options.message = options.message || 'This method is not implemented'; super(options); } /** * @return {String} */ static toString() { return 'PreconditionsError'; } } export {NotImplementedError}; export default NotImplementedError; <file_sep>/test/TimeUnit.spec.js 'use strict'; /** * How to use Chai * @see http://chaijs.com/api/assert/ */ import {expect, assert} from "chai"; import TimeUnit from "../src/js/TimeUnit"; import {Errors, AbstractError, PreconditionsError} from "../src/js/errors"; import {Stopwatch} from "../src/js/Stopwatch"; import {SmoothBurstyRateLimiter, SmoothWarmingUpRateLimiter} from "../src/js/RateLimiter"; describe('TimeUnit', () => { it('Seconds -> Nanos', () => { assert.equal(TimeUnit.NANOSECONDS.convert(1, TimeUnit.SECONDS), 1000000000); }); it('Seconds -> Micros', () => { assert.equal(TimeUnit.MICROSECONDS.convert(1, TimeUnit.SECONDS), 1000000); }); it('Seconds -> Millis', () => { assert.equal(TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS), 1000); }); it('Seconds -> Seconds', () => { assert.equal(TimeUnit.SECONDS.convert(1, TimeUnit.SECONDS), 1); }); it('Seconds -> Minutes', () => { assert.equal(TimeUnit.MINUTES.convert(1, TimeUnit.SECONDS), 0.016666666666666666); }); it('Seconds -> Hours', () => { assert.equal(TimeUnit.HOURS.convert(1, TimeUnit.SECONDS), 0.0002777777777777778); }); it('Seconds -> Days', () => { assert.equal(TimeUnit.DAYS.convert(1, TimeUnit.SECONDS), 0.000011574074074074073); }); it('Stopwatch', (cb) => { let rateLimiter = new SmoothWarmingUpRateLimiter({ maxBurstSeconds: 3, warmupPeriod: 2, timeUnit: TimeUnit.SECONDS }); rateLimiter.permitsPerSecond = .001; rateLimiter .acquire(10000, 0, TimeUnit.SECONDS) .then(cb) }) }); <file_sep>/src/js/errors/index.js 'use strict'; import Errors from "./Errors"; import AbstractError from "./AbstractError"; import PreconditionsError from "./PreconditionsError"; import HttpError from './HttpError'; import NotImplementedError from './NotImplementedError'; export {Errors}; export {HttpError}; export {AbstractError}; export {PreconditionsError}; export {NotImplementedError}; export default { Errors: Errors, HttpError: HttpError, AbstractError: AbstractError, PreconditionsError: PreconditionsError, NotImplementedError: NotImplementedError }<file_sep>/src/js/Functions.js 'use strict'; /** * This class should contain all of our reusable functions */ export default class Functions { /** * Returns the current scope that you're calling from. * * @returns {Functions} */ static identity() { return this; } /** * Always returns true * * @returns {boolean} true */ static yes() { return true; } static emptyFn() { } /** * Always returns false * * @returns {boolean} false */ static no() { return false; } static ok() { return this; } static identityFn() { return this; } static passthroughFn(arg) { return arg; } }<file_sep>/src/js/slack/NotificationBuilder.js 'use strict'; import Promise from 'bluebird'; import Logger from 'winston'; import Preconditions from './../Preconditions'; import request from 'request-promise'; import CoreObject from '~/CoreObject'; import AbstractBuilder from './AbstractBuilder'; import AttachmentBuilder from './AttachmentBuilder'; import Ember from '~/Ember'; /** * @class NotificationBuilder * @extends AbstractBuilder */ class NotificationBuilder extends AbstractBuilder { /** * * @param {String} value * @returns {NotificationBuilder} */ channel(value) { Preconditions.shouldBeString(value); return this.set('payload.channel', value); } /** * * * @param text * @returns {NotificationBuilder} */ text(text) { Preconditions.shouldBeString(text); return this.set('payload.text', text); } /** * * @param icon * @returns {icon} */ icon(icon) { Preconditions.shouldBeString(icon); return this.set('payload.icon_emoji', icon); } username(username) { Preconditions.shouldBeString(username); return this.set('payload.username', username); } /** * @returns {Array} */ attachments() { let attachments = this.get('payload.attachments'); if (!attachments) { attachments = []; this.set('payload.attachments', attachments); } return attachments; } /** * @returns {AttachmentBuilder} */ attachment() { return new AttachmentBuilder({ parent: this }); } /** * @returns {Object} */ toPayload() { return this.get('payload'); } /** * @returns {String} */ toJson() { return JSON.stringify(this.toPayload()); } /** * * @return {Promise} */ execute() { let scope = this; let url = this.url; let payload = this.toPayload(); Preconditions.shouldBeString(scope.url, 'NotificationBuilder.execute(): url must be a string'); return Promise.resolve() .then(() => { // // https://www.npmjs.com/package/request-promise // // var options = { // method: 'POST', // uri: 'http://posttestserver.com/post.php', // body: { // some: 'payload' // }, // json: true // Automatically stringifies the body to JSON // }; let requestOptions = { uri: url, method: 'POST', body: payload, json: true }; Logger.debug(`[SLACK:${scope.name}] webhook `, JSON.stringify(payload)); return Promise.resolve(request(requestOptions)) .then(function(value) { Logger.debug(`[SLACK:${scope.name}] webhook succeeded.`, arguments); return value; }) .catch(function(err) { Logger.warn(`[SLACK:${scope.name}] webhook failed.`, arguments); throw err; }); }); } /** * Do not insert a Promise into this method. * * @param {Object|NotificationBuilder} object * @param {Object|undefined} deps * @param {Preconditions|undefined} deps.Preconditions * @return {Promise<NotificationBuilder>} */ static innerCast(object, deps) { deps = CoreObject.toDependencyMap(deps); let Preconditions = deps.Preconditions; Preconditions.shouldBeDefined(object); return Promise.resolve(object) .then(function(result) { Preconditions.shouldBeDefined(object, 'Casted object must be defined.'); Preconditions.shouldNotBeArray(object, 'Casted object must NOT be an array.'); Preconditions.shouldBeObject(object, 'Casted object must be an object.'); if (result instanceof NotificationBuilder) { return result; } return new NotificationBuilder(object); }); } } export default NotificationBuilder;<file_sep>/src/js/slack/AbstractBuilder.js 'use strict'; import Logger from 'winston'; import Lodash from 'lodash'; import Ember from '../Ember'; import Utility from '../Utility'; import Preconditions from '../Preconditions'; import CoreObject from '../CoreObject'; // winston : https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/ class AbstractBuilder extends CoreObject { constructor() { super(...arguments); Utility.defaults(this, { name: this.toClass().toString(), payload: { } }); } /** * @public * @param object * @return {*|AbstractBuilder} */ mergeIntoPayload(object) { Preconditions.shouldBeDefined(object, 'Cannot merge null'); Preconditions.shouldBeObject(object, 'Should be object'); Lodash.assign(this.payload, object); return this; } } export default AbstractBuilder;<file_sep>/dist/docs/file/js/cache/LocalFileCache.js.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <base data-ice="baseUrl" href="../../../"> <title data-ice="title">js/cache/LocalFileCache.js | API Document</title> <link type="text/css" rel="stylesheet" href="css/style.css"> <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css"> <script src="script/prettify/prettify.js"></script> <script src="script/manual.js"></script> </head> <body class="layout-container" data-ice="rootContainer"> <header> <a href="./">Home</a> <a href="identifiers.html">Reference</a> <a href="source.html">Source</a> <a data-ice="repoURL" href="https://github.com/coinme/coinme-node.git" class="repo-url-github">Repository</a> <div class="search-box"> <span> <img src="./image/search.png"> <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span> </span> <ul class="search-result"></ul> </div> </header> <nav class="navigation" data-ice="nav"><div> <ul> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Address.js~Address.html">Address</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Coinme.js~Coinme.html">Coinme</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/CoreObject.js~CoreObject.html">CoreObject</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Environment.js~Environment.html">Environment</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Functions.js~Functions.html">Functions</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Preconditions.js~Preconditions.html">Preconditions</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/RateLimiter.js~RateLimiter.html">RateLimiter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/RateLimiter.js~SmoothBurstyRateLimiter.html">SmoothBurstyRateLimiter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/RateLimiter.js~SmoothRateLimiter.html">SmoothRateLimiter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/RateLimiter.js~SmoothWarmingUpRateLimiter.html">SmoothWarmingUpRateLimiter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Stopwatch.js~Stopwatch.html">Stopwatch</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Ticker.js~Ticker.html">Ticker</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/TimeUnit.js~TimeUnit.html">TimeUnit</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/Utility.js~Utility.html">Utility</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">cache</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/cache/Cache.js~Cache.html">Cache</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/cache/LocalFileCache.js~LocalFileCache.html">LocalFileCache</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">data</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Adapter.js~Adapter.html">Adapter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/CachedResourceLoader.js~CachedResourceLoader.html">CachedResourceLoader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/CertificateBundle.js~Certificate.html">Certificate</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/CertificateBundle.js~CertificateBundle.html">CertificateBundle</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Conversion.js~Conversion.html">Conversion</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Converter.js~Converter.html">Converter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/DelegatedConverter.js~DelegatedConverter.html">DelegatedConverter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/FileResourceLoader.js~FileResourceLoader.html">FileResourceLoader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Identity.js~Identity.html">Identity</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~EndpointType.html">EndpointType</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~EndpointTypes.html">EndpointTypes</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~KioskEndpointType.html">KioskEndpointType</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~Receipt.html">Receipt</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~ReceiptBuilder.html">ReceiptBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~ReceiptEndpoint.html">ReceiptEndpoint</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/Receipt.js~WalletEndpointType.html">WalletEndpointType</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/ResourceLoader.js~ResourceLoader.html">ResourceLoader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/SignTool.js~SignTool.html">SignTool</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/User.js~User.html">User</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/UserBuilder.js~UserBuilder.html">UserBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/data/UserExistenceToken.js~UserExistenceToken.html">UserExistenceToken</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">errors</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/errors/AbstractError.js~AbstractError.html">AbstractError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/errors/Errors.js~Errors.html">Errors</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/errors/HttpError.js~HttpError.html">HttpError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/errors/NotImplementedError.js~NotImplementedError.html">NotImplementedError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/errors/PreconditionsError.js~PreconditionsError.html">PreconditionsError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-ExtendableBuiltin">ExtendableBuiltin</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">money</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/Bitcoin.js~Bitcoin.html">Bitcoin</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/Currency.js~Currency.html">Currency</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/CurrencyAdapter.js~CurrencyAdapter.html">CurrencyAdapter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/Ethereum.js~Ethereum.html">Ethereum</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/Money.js~Money.html">Money</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/MoneyConverter.js~MoneyConverter.html">MoneyConverter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/Satoshi.js~Satoshi.html">Satoshi</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/money/USD.js~USD.html">USD</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">net</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/net/CoinmeWalletClient.js~CoinmeWalletClient.html">CoinmeWalletClient</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/net/CoinmeWalletClient.js~CoinmeWalletClientConfiguration.html">CoinmeWalletClientConfiguration</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">slack</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/AbstractBuilder.js~AbstractBuilder.html">AbstractBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/AbstractNotificationTemplate.js~AbstractNotificationTemplate.html">AbstractNotificationTemplate</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/AttachmentBuilder.js~AttachmentBuilder.html">AttachmentBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/FieldBuilder.js~FieldBuilder.html">FieldBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/InlineNotificationTemplate.js~InlineNotificationTemplate.html">InlineNotificationTemplate</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/NotificationBuilder.js~NotificationBuilder.html">NotificationBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/NotificationService.js~NotificationService.html">NotificationService</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/NotificationTemplate.js~NotificationTemplate.html">NotificationTemplate</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/js/slack/UserNotificationTemplate.js~UserNotificationTemplate.html">UserNotificationTemplate</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-notificationService">notificationService</a></span></span></li> </ul> </div> </nav> <div class="content" data-ice="content"><h1 data-ice="title">js/cache/LocalFileCache.js</h1> <pre class="source-code line-number raw-source-code"><code class="prettyprint linenums" data-ice="content">import Utility from &quot;../Utility&quot;; import URI from &quot;urijs&quot;; import filecache from &quot;filecache&quot;; import Promise from &quot;bluebird&quot;; import osenv from &quot;osenv&quot;; import mkdirp from &quot;mkdirp&quot;; import Cache from &quot;./Cache&quot;; /** * @class LocalFileCache * @extends Cache */ class LocalFileCache extends Cache { _config = { watchDirectoryChanges: true, watchFileChanges: false, hashAlgo: &apos;sha1&apos;, gzip: true, deflate: true, debug: true }; //region constructor /** * * @param {Object} options * @param {String|URI} [options.path] defaults to tmpdir * @param {{watchDirectoryChanges: boolean, watchFileChanges: boolean, hashAlgo: string, gzip: boolean, deflate: boolean, debug: boolean}} [options.config] */ constructor(options) { let path = Utility.take(options, &apos;path&apos;, { adapter(value) { return URI(value || (osenv.tmpdir() + &apos;/coinme&apos;)); } }); let config = Utility.take(options, &apos;config&apos;, false); super(options); this._config = Utility.defaults(config || {}, this._config); this._fc = filecache(this.config); this._path = path; this._started = false; let fc = this.fc; let scope = this; if (this.config.watchDirectoryChanges &amp;&amp; this.config.debug) { fc.on(&apos;change&apos;, function (d) { scope.logger.debug(&apos;! file changed&apos;); scope.logger.debug(&apos; full path: %s&apos;, d.p); scope.logger.debug(&apos; relative path: %s&apos;, d.k); scope.logger.debug(&apos; length: %s bytes&apos;, d.length); scope.logger.debug(&apos; %s bytes (gzip)&apos;, d.gzip.length); scope.logger.debug(&apos; %s bytes (deflate)&apos;, d.deflate.length); scope.logger.debug(&apos; mime-type: %s&apos;, d.mime_type); scope.logger.debug(&apos; mtime: %s&apos;, d.mtime.toUTCString()); }); } this._startedLatch = new Promise((resolve, reject) =&gt; { let cache_dir = scope.path.toString(); mkdirp(cache_dir, function (err) { if (err) { return reject(err); } fc.load(cache_dir, function (err, cache) { if (err) { reject(err); } else { scope._items = cache; resolve(); } }); fc.on(&apos;ready&apos;, function (cache) { scope._items = cache; }); }) }); this.startedLatch.catch((err) =&gt; { scope._error = err; }); this.startedLatch.finally(() =&gt; { scope._started = true; }); } //endregion //region getters/setters /** * @property * @readonly * @type {Promise} * @return {Promise} */ get startedLatch() { return this._startedLatch; } /** * @property * @readonly * @type {boolean} * @return {boolean} */ get started() { return this._started; } /** * @property * @readonly * @type {undefined|Error} * @return {boolean} */ get hasError() { return !!this.error; } /** * @property * @readonly * @type {undefined|Error} * @return {undefined|Error} */ get error() { return this._error; } /** * The items in the cache. * @readonly * @private * @type {Object} * @return {Object} */ get items() { return this._items; } /** * @private * @property * @readonly * @type {filecache} * @return {filecache} */ get fc() { return this._fc; } /** * @property * @readonly * @type {String} * @return {{watchDirectoryChanges: boolean, watchFileChanges: boolean, hashAlgo: string, gzip: boolean, deflate: boolean, debug: boolean}} */ get config() { return this._config; } /** * @property * @readonly * @type {URI} * @return {URI} */ get path() { return this._path; } //endregion /** * * @param {String|URI} path * @return {Promise} */ read(path) { /** @type {URI} */ let base_path = this.path; /** @type {winston.Logger} */ let logger = this.logger; let scope = this; return super .read(path) .then((/** @type {URI} */path) =&gt; { if (scope.error) { // an error here means that this cache is fucked. throw scope.error; } return path; }) .then((path) =&gt; { return URI.joinPaths(base_path, path); }) .then((/** @type {URI} */absolutePath) =&gt; { let pathString = absolutePath.toString().substring(base_path.toString().length); if (pathString.startsWith(&apos;/&apos;)) { pathString = pathString.substring(1); } return pathString; }) .then((/** @type {String} */filePath) =&gt; { let items = scope.items; let result = items[filePath]; if (!result) { logger.warn(`Not sure why, but ${filePath} was not found in ${items}`); } return result; }); } } export {LocalFileCache} export default LocalFileCache;</code></pre> </div> <footer class="footer"> Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(0.5.0-alpha)</span></a> </footer> <script src="script/search_index.js"></script> <script src="script/search.js"></script> <script src="script/pretty-print.js"></script> <script src="script/inherited-summary.js"></script> <script src="script/test-summary.js"></script> <script src="script/inner-link.js"></script> <script src="script/patch-for-local.js"></script> </body> </html> <file_sep>/test/Ember.spec.js 'use strict'; /** * How to use Chai * @see http://chaijs.com/api/assert/ */ import {expect, assert} from "chai"; import Ember from "../src/js/Ember"; import CoreObject from "../src/js/CoreObject"; import {Errors, AbstractError, PreconditionsError} from "../src/js/errors"; import {Currency, Bitcoin, Money, Satoshi, USD, Converter} from "../src/js/money"; import "source-map-support/register"; describe('Ember', () => { it('computed properties', () => { var Record = CoreObject.extend({ thong: Ember.computed('thingy', function () { return this.get('thingy') + 'thong'; }) }); var record = new Record({ thingy: false, believesInHumanity: false }); assert.equal(record.get('believesInHumanity'), false); assert.equal(record.get('thingy'), false); assert.equal(record.get('thong'), 'falsethong'); record.set('thingy', true); assert.equal(record.get('thingy'), true); assert.equal(record.get('thong'), 'truethong'); }); }); <file_sep>/src/js/data/Adapter.js 'use strict'; import CoreObject from '../CoreObject'; import Errors from '../errors/Errors'; import NotImplementedError from '../errors/NotImplementedError'; import Preconditions from "../Preconditions"; class Adapter extends CoreObject { /** * * @param {CoreObject|Class<CoreObject>} instanceOrClass */ supports(instanceOrClass) { throw new NotImplementedError(); } /** * @param {CoreObject|*} instance * @returns {*} */ adapt(instance) { throw new NotImplementedError(); } /** * * @param {CoreObject|Class|Class<CoreObject>|*} instanceOrClass * @throws {PreconditionsError} if the instanceOrClass is not supported. * @return {*} */ shouldSupport(instanceOrClass) { if (!this.supports(instanceOrClass)) { Preconditions.fail(true, false, `Do not support ${instanceOrClass}`); } return instanceOrClass; } /** * * @return {Function} */ toFunction() { let self = this; return function() { return self.adapt.apply(self, arguments); } } } export {Adapter}; export default Adapter;
c8c7d825139e20dab46c58b05b2c9b1160a623e0
[ "JavaScript", "HTML", "Markdown" ]
59
JavaScript
ArmanSadri/coinme-node
b8bc43c41fa08cfdc3818c2aaea95e8461c06203
e1c92dced00bcb23049609e9d2686cbaa582a909
refs/heads/master
<file_sep>source 'https://rubygems.org' ruby '2.6.6' gem 'rails', '6.1.1' gem 'pg' gem 'sass-rails' gem 'uglifier', '>= 1.3.0' gem 'jquery-rails' gem 'rack-cors', :require => 'rack/cors' gem 'rack-timeout' gem 'rails_12factor', group: :production gem 'puma', group: :production
4a4e7e0fe0c8964d93b95cce725197e43f8c5037
[ "Ruby" ]
1
Ruby
simboutin/lewagon-chat
ec587b42d7d39d4a6d31fd7b1d79d6e9190222cc
dd21ce10e5288427b7a06a06ef53a6da1ecdf7c8
refs/heads/master
<repo_name>abdullahturel/mvc<file_sep>/Application/models/uye.php <?php class uye extends Model { public function uyeListe() { $query = $this->db->prepare("SELECT * FROM uyeler"); $query->execute(); return $query->fetchAll(PDO::FETCH_ASSOC); } } ?><file_sep>/System/Core/Model.php <?php class Model { public $db; public function __construct() { $this->db = new PDO("mysql:host=". DB_HOST .";dbname=". DB_NAME .";charset=utf8", DB_USERNAME, DB_PASSWORD); } } ?><file_sep>/crud.sql -- phpMyAdmin SQL Dump -- version 4.7.9 -- https://www.phpmyadmin.net/ -- -- Anamakine: 127.0.0.1:3306 -- Üretim Zamanı: 02 Tem 2018, 10:14:44 -- Sunucu sürümü: 5.7.21 -- PHP Sürümü: 7.2.4 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 */; -- -- Veritabanı: `crud` -- -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `uyeler` -- DROP TABLE IF EXISTS `uyeler`; CREATE TABLE IF NOT EXISTS `uyeler` ( `uye_id` int(11) NOT NULL AUTO_INCREMENT, `uye_kadi` varchar(100) NOT NULL, `uye_sifre` varchar(100) NOT NULL, `uye_eposta` varchar(100) NOT NULL, `uye_il` varchar(100) NOT NULL, `uye_rutbe` int(1) NOT NULL, PRIMARY KEY (`uye_id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4; -- -- Tablo döküm verisi `uyeler` -- INSERT INTO `uyeler` (`uye_id`, `uye_kadi`, `uye_sifre`, `uye_eposta`, `uye_il`, `uye_rutbe`) VALUES (1, 'Admin', '123456', '<EMAIL>', 'Ankara', 1), (2, 'Abdullah', '32165', '<EMAIL>', 'Ankara', 1); 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>/index.php <?php require_once 'System/init.php'; $system = new System(); ?><file_sep>/Application/controllers/home.php <?php class home extends Controller { public function index() { $a = new dene; $data = [ 'datax' => $a ]; $this->view->render("static/header"); $this->view->render("home/index",$data); $this->view->render("static/footer"); } } ?><file_sep>/Application/views/uyeler/index.php <div class="container"> <div class="card mt-5"> <div class="card-header">ÜYE LİSTESİ</div> <table class="table table-bordered mb-0"> <thead class="thead-light"> <tr> <th>Kullanıcı Adı</th> <th>Şifre</th> <th>E-posta</th> <th>İl</th> <th>Rutbe</th> </tr> </thead> <tbody> <?php foreach($data as $v){ echo '<tr> <td>'.$v["uye_kadi"].'</td> <td>'.$v["uye_sifre"].'</td> <td>'.$v["uye_eposta"].'</td> <td>'.$v["uye_il"].'</td> <td>'.$v["uye_rutbe"].'</td> </tr>'; } ?> </tbody> </table> </div> <?php echo "<br>".$this->deneme; echo "<br>".$ok; ?> </div><file_sep>/System/Core/Controller.php <?php class Controller { function __construct() { $this->view = new View(); } public function model($file) { if( file_exists(MODELS_PATH . "/" . $file .".php") ) { require_once MODELS_PATH . "/" . $file .".php"; if( class_exists($file) ) { return new $file; }else{ exit($file . " bir class değil!"); } } else { exit($file . " model dosyası bulunamadı!"); } } } ?><file_sep>/Application/views/home/index.php Burası Anasayfa <?php $datax->vv(); ?><file_sep>/README.md # MVC Basit MVC Yapısı <file_sep>/Application/classes/dene.php <?php class dene{ public function vv(){ echo "<br>Class otomatik yükleme denemesi."; } } ?><file_sep>/System/Core/System.php <?php class System { protected $controller; protected $method; public function __construct() { $this->controller = "home"; $this->method = "index"; /* Adres Verilerini Alma */ if(isset($_GET['act'])){ $url = explode('/', filter_var( rtrim($_GET['act'], '/'), FILTER_SANITIZE_URL) ); } else { $url[0] = $this->controller; $url[1] = $this->method; } /* Controller Bulma */ if( file_exists(CONTROLLERS_PATH . "/" . $url[0] .".php") ) { $this->controller = $url[0]; }else { exit($url[0] . " controller'ı bulunamadı!"); } require_once CONTROLLERS_PATH . "/" . $this->controller .".php"; if( class_exists($this->controller) ) { $this->controller = new $this->controller; array_shift($url); } else { exit($this->controller . " class'ı bulunamadı!"); } /* Method Bulma */ if( isset($url[0]) ){ if( method_exists($this->controller, $url[0]) ) { $this->method = $url[0]; array_shift($url); } else { exit($url[0] . " method'u bulunamadı!"); } } call_user_func_array([$this->controller, $this->method], $url); } } ?><file_sep>/Application/controllers/uyeler.php <?php class uyeler extends Controller { public function index() { $list = $this->model("uye")->uyeListe(); $this->view->deneme ="Merhaba dünya!"; $this->view->render("static/header"); $data = [ 'data' => $list, 'ok' => "oldu bu iş" ]; $this->view->render("uyeler/index", $data); $this->view->render("static/footer"); } } ?><file_sep>/System/Config/Config.php <?php define('PATH', realpath('.')); define("CONTROLLERS_PATH","Application/controllers"); define("VIEWS_PATH","Application/views"); define("MODELS_PATH","Application/models"); define("HELPERS_PATH","Application/helpers"); define("CLASSES_PATH","Application/classes"); define("DB_HOST","localhost"); define("DB_NAME","crud"); define("DB_USERNAME","root"); define("DB_PASSWORD",""); ?><file_sep>/System/init.php <?php session_start(); ob_start(); require_once 'Config/Config.php'; // MVC Çekirdek Dosyalarını Yükler foreach (glob(__DIR__ . '/Core/*.php') as $coreFile){ require_once strtolower($coreFile); } /* Application Classes Dosyalarını Yükler foreach (glob(PATH .'/'. strtolower(CLASSES_PATH) .'/*.php') as $className){ require_once strtolower($className); }*/ //Application Classes Dosyalarını Class Çağrıldığında Yükler function appClasses($className) { require PATH .'/'. strtolower(CLASSES_PATH) .'/'. strtolower($className) . '.php'; } spl_autoload_register('appClasses'); // Application Helper Dosyalarını Yükler foreach (glob(PATH .'/'. strtolower(HELPERS_PATH) .'/*.php') as $helperFile){ require_once strtolower($helperFile); } ?> <file_sep>/Application/controllers/kategoriler.php <?php class kategoriler extends Controller { public function index() { echo "kategori"; } } ?>
0ff8ed8b80d9f56aa87c0537d7c8abbb94441b8f
[ "Markdown", "SQL", "PHP" ]
15
PHP
abdullahturel/mvc
0f9c1bbc854ba5e11f9dfda07f953e502a587de5
bae8cebcd3e2fe197074db5bf88ea559f9c63f9e
refs/heads/master
<file_sep>package com.mybank.logic; /** * Created by <NAME> on 07.01.18. */ public class TransferException extends Exception { public TransferException(String message) { super(message); } } <file_sep># myBank myBank-Demo <file_sep>package com.mybank.logic; /** * Created by <NAME> on 08.01.18. */ public interface BankAPIInterface { public void transferMoney(long accountIdDst, long accountIdSrc, long transferAmount) throws TransferException ; public long createBankAccount(String name, String surname, long amount); } <file_sep>package com.mybank.logic; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by <NAME> on 07.01.18. */ public class TransferTests { @Test public void transferMoneyTest(){ AccountManager accountManager = new AccountManager(); TransferPool transferPool = new TransferPool(); long accountId = accountManager.createAccount("Adam","Małysz"); assertEquals(accountId,accountManager.getAccount(accountId).get().getAccountID()); accountManager.getAccount(accountId).get().setSaldo(1000000); long accountId2 = accountManager.createAccount("Kamil","Stoch"); assertEquals(accountId,accountManager.getAccount(accountId).get().getAccountID()); accountManager.getAccount(accountId2).get().setSaldo(200000); TransferPool transferPool1 = new TransferPool(); try { transferPool1.performTransfer(new Transfer(accountId,accountId2,50000),accountManager); transferPool1.performTransfer(new Transfer(accountId,accountId2,50000),accountManager); transferPool1.performTransfer(new Transfer(accountId,accountId2,50000),accountManager); transferPool1.performTransfer(new Transfer(accountId,accountId2,40000),accountManager); } catch (TransferException e) { e.printStackTrace(); } assertEquals(1190000,accountManager.getAccount(accountId).get().getSaldo()); assertEquals(10000,accountManager.getAccount(accountId2).get().getSaldo()); for(String item: accountManager.getAccount(accountId).get().getStatementHistory().printAll().split(";")) System.out.println(item); for(String item: accountManager.getAccount(accountId2).get().getStatementHistory().printAll().split(";")) System.out.println(item); } } <file_sep>package com.mybank.logic; import com.mybank.logic.Parameters.StatementType; import java.time.LocalDateTime; /** * Created by <NAME> on 07.01.18. */ public class Statement { private LocalDateTime dateOfOpertion; private long amountOfOperation; private long balance; private StatementType statementType; public Statement(LocalDateTime dateOfOpertion, long amountOfOperation, long balance, StatementType statementType) { this.dateOfOpertion = dateOfOpertion; this.amountOfOperation = amountOfOperation; this.balance = balance; this.statementType = statementType; } public LocalDateTime getDateOfOpertion() { return dateOfOpertion; } public long getAmountOfOperation() { return amountOfOperation; } public long getBalance() { return balance; } public StatementType getStatementType() { return statementType; } @Override public String toString() { return "Statement{" + "dateOfOpertion=" + dateOfOpertion + ", amountOfOperation=" + amountOfOperation + ", balance=" + balance + '}'; } } <file_sep>package com.mybank.logic; /** * Created by <NAME> on 07.01.18. */ public class AccountOwnerData{ private String name; private String surname; public AccountOwnerData(String name, String surname) { this.name = name; this.surname = surname; } public String getName() { return name; } public String getSurname() { return surname; } @Override public String toString() { return "AccountOwnerData{" + "name='" + name + '\'' + ", surname='" + surname + '\'' + '}'; } }
fd1263a29155c61a3bd3983276b49c34ce66fc15
[ "Markdown", "Java" ]
6
Java
StanislawLeja/myBank
9ad88c6d79a1a5fa8a38611f3f451a19e08749e5
6bed7252244be2e87ec1731386ec10a015d1c719
refs/heads/master
<file_sep># moodyReact: React Boilerplate Check [ONLINE VERSION](https://moody-react.netlify.com/) React Boilerplate with React Router and Webpack with Hot Reloading and precommit hook with linter and prettier to force clean code Added Docker example for production deployments Follow [Installation Guide](INSTALL.md) for local setup ## Starting service You can enter command below to start service ``` npm start || make start ``` For build info, to check package sizes, resources they take, duplicates, you can run dashboard mode ``` npm start:dashboard ``` ### Configuration If you need configuration object within the app, you can just call it with `settings` keyword Configuration is defined in `/config/config.[env].js` ### Hashing CSS files There is currently no css hashing as a preference, but if you wan to add it, change it in `webpack/webpack.[env].js` ``` { test: /\.(css|scss)$/, use: [ 'style-loader', { loader: 'css-loader', options: { sourceMap: true, modules: true, localIdentName: '[local]___[hash:base64:5]', }, }, 'sass-loader', ], } ``` In case of a production build, instead of `style-loader` use `MiniCssExtractPlugin.loader` ## Production You can build production files within npm or run provided docker file with nginx ### npm ``` npm run build ``` Where you can test it with simple express server as `server.js` ``` const path = require('path'); const express = require('express'); const DIST_DIR = path.join(__dirname, 'build'); const PORT = 3000; const app = express(); app.use(express.static(DIST_DIR)); app.get('*', (req, res) => { res.sendFile(path.join(DIST_DIR, 'index.html')); }); app.listen(PORT, () => console.log(`App listening on port ${PORT}!`)); ``` and run it as: ``` node server.js ``` ### Docker You can easily build and test docker image ``` $ make build $ make run-production ``` and navigate to `http://localhost` You can update settings in `Makefile` <file_sep>/** Preloads components before they are mounted, so we skip seeing Loading fallback */ import React from 'react'; const lazyPreload = component => { const Component = React.lazy(component); Component.preload = component; return Component; }; export default lazyPreload; <file_sep>import React from 'react'; import { AnchorLink, CentarAll, FullPage, Icon, Image } from 'components'; import Logo from 'static/img/white.png'; import InfoLinks from './presentational/Links'; import './style'; const Home = () => ( <FullPage className="home"> <CentarAll> <Image src={Logo} /> </CentarAll> <CentarAll> <p className="heading">React Boilerplate</p> <h1> <Icon name="code" /> <span> Moody<b>REACT</b> </span> </h1> <p className="author"> by <AnchorLink href="http://moodydev.io">MoodyDev.io</AnchorLink> </p> <InfoLinks /> </CentarAll> </FullPage> ); export default Home; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import './style'; const Icon = ({ name, style, className }) => ( <div className={`icon ${className}`} style={style}> {name} </div> ); Icon.defaultProps = { style: {}, className: '', }; Icon.propTypes = { /** Icon names from https://material.io/tools/icons/?style=baseline */ name: PropTypes.string.isRequired, /** custom style to be applied to component */ style: PropTypes.object, /** class applied to component from parent */ className: PropTypes.string, }; export default React.memo(Icon); <file_sep>const webpack = require('webpack'); const autoprefixer = require('autoprefixer'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const commonPaths = require('./paths'); const config = require('./config.prod'); module.exports = { mode: 'production', devtool: 'source-map', output: { filename: `[name].[hash].js`, path: commonPaths.outputPath, chunkFilename: '[name].[chunkhash].js', }, module: { rules: [ { test: /\.(css|scss)$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', { loader: 'postcss-loader', options: { plugins: () => [autoprefixer], sourceMap: true, }, }, 'sass-loader', ], }, ], }, optimization: { minimize: true, splitChunks: { minSize: 10000, maxSize: 0, minChunks: 1, }, }, plugins: [ new CleanWebpackPlugin([commonPaths.outputPath.split('/').pop()], { root: commonPaths.root, }), new MiniCssExtractPlugin({ filename: `${commonPaths.cssFolder}/[name].[hash].css`, }), new webpack.DefinePlugin({ settings: JSON.stringify(config), }), ], }; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; const Image = ({ src, alt, style, className }) => ( <img src={src} alt={alt} style={style} className={className} /> ); Image.defaultProps = { alt: '', className: '', style: {}, }; Image.propTypes = { /** path to image */ src: PropTypes.string.isRequired, /** image description, shown if image is not loded */ alt: PropTypes.string, /** custom style to be applied to image */ style: PropTypes.object, /** additional classNames passed from parent components */ className: PropTypes.string, }; export default React.memo(Image); <file_sep>install: npm install run: npm start build-docker: sudo docker build -t moody-react:latest . run-production: sudo docker run -it -p 80:80 --rm moody-react:latest clean: rm -rf node_modules <file_sep>import React from 'react'; import { Router, Route, Switch } from 'react-router-dom'; import createHistory from 'history/createBrowserHistory'; import { lazyPreload } from 'helpers'; import 'static/style/style'; const Home = lazyPreload(() => import('pages/Home')); const Error = lazyPreload(() => import('pages/Error')); Error.preload(); const history = createHistory(); const App = () => ( <Router history={history}> <React.Suspense fallback={<div>Loading...</div>}> <Switch> <Route exact path="/" component={Home} /> <Route component={Error} /> </Switch> </React.Suspense> </Router> ); export default App; <file_sep># Installation Guide ## Installing node For Installing NVM (node version manager), please follow instructions for [Installing NVM](https://github.com/creationix/nvm) After that, enter in your terminal: ``` nvm install 10 nvm use 10 ``` ## Repo setup **1)** Clone repository and install required packages ``` git clone https://github.com/moodydev/moody-react.git cd moody-react npm install ``` **2)** That's all folks <file_sep># build environment FROM node:10-alpine as builder WORKDIR /usr/src/app ENV PATH /usr/src/app/node_modules/.bin:$PATH COPY package.json /usr/src/app/package.json RUN npm install --silent ADD . /usr/src/app RUN npm run build # production environment FROM nginx:alpine COPY --from=builder /usr/src/app/build /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] <file_sep>export { default as CentarAll } from './CentarAll'; export { default as FullPage } from './FullPage'; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import './style'; const AnchorLink = ({ children, href, sameWindow, style, className }) => ( <a href={href} rel="noopener noreferrer" target={sameWindow || '_blank'} style={style} className={className} > {children} </a> ); AnchorLink.defaultProps = { sameWindow: false, style: {}, className: '', }; AnchorLink.propTypes = { /** child node element to display inside anchor link */ children: PropTypes.element.isRequired, /** address to redirect user to */ href: PropTypes.string.isRequired, /** shoudl user be redirected in same window? */ sameWindow: PropTypes.bool, /** custom style to apply to component */ style: PropTypes.object, /** class applied to component from parent */ className: PropTypes.string, }; export default React.memo(AnchorLink); <file_sep>import React from 'react'; import { Link } from 'react-router-dom'; import { CentarAll, FullPage } from 'components'; import './style'; const Home = () => ( <FullPage className="error-page"> <CentarAll> <p className="status">404</p> <p>NOT FOUND</p> <Link to="/">Return to Homepage</Link> </CentarAll> </FullPage> ); export default Home; <file_sep>export { default as lazyPreload } from './lazyPreload'; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import './style'; const CentarAll = ({ children }) => ( <div className="centar-all">{children}</div> ); CentarAll.propTypes = { /** child component */ children: PropTypes.element.isRequired, }; export default React.memo(CentarAll); <file_sep>export { default as AnchorLink } from './AnchorLink'; export { default as Icon } from './Icon'; export { default as Image } from './Image'; <file_sep>export * from './general'; export * from './layout';
a1a64ce6d44d00b36005bfcefeae7ced6c485931
[ "Markdown", "JavaScript", "Dockerfile", "Makefile" ]
17
Markdown
moodydev/moody-react
416d86dd69a58988ad1d4d8f815a2da741ee0a41
1d136b79db14083461727bb6ce7afb2a8141023e
refs/heads/main
<file_sep>import requests import unittest class TestStringMethods(unittest.TestCase): def test_create(self): r = requests.post('http://petstore.swagger.io/v2/pet', data = {'id':'1616',"name": "valera"}) assert r.status_code == 200 def test_read(self): r = requests.get('http://petstore.swagger.io/v2/pet') assert r.status_code == 200 def test_update(self): r = requests.get('http://petstore.swagger.io/v2/pet') assert r.status_code == 200 def test_delete(self): r = requests.get('http://petstore.swagger.io/v2/pet') assert r.status_code == 200 if __name__ == '__main__': unittest.main()
899a367c11c3e1d4899a5c6f67f50d88613c2c52
[ "Python" ]
1
Python
isyts/QA
53f054a9399517a635b0f3ae71d3f8ba3e9b66a3
a20ce989b1585a42d4b8d34aff083334c2bdfe30
refs/heads/master
<repo_name>bhorkar/udacity_item_catalog<file_sep>/populate_database.py from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import datetime from db_setup import * class Populate_database: engine = create_engine('sqlite:///ItemCatalog.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Delete Categories if exisitng. session.query(Category).delete() # Delete CatalogItems if exisitng. session.query(CatalogItem).delete() # Delete Users if exisitng. session.query(User).delete() # Create fake usersa users = [{'username': 'test', 'email': '<EMAIL>', 'picture': 'https://lh6.googleusercontent.com/-Nk2JadNaxDE/AAAAAAAAAAI/AAAAAAAAH-w/uQ18O3CGdfc/s96-c/photo.jpg'}] def add_users(self): for u in self.users: self.session.add(User( username=u['username'], email=u['email'], picture=u['picture'] )) self.session.commit() user_genesis = self.session.query( User).filter_by(email='<EMAIL>').one() cate1 = Category(name='Soccer', user_id=user_genesis.id) self.session.add(cate1) self.session.commit() item1 = CatalogItem( name="FIFA shirt women", description="FIFA marks on the back and a big pink ball on the front", user_id=user_genesis.id, category=cate1) self.session.add(item1) self.session.commit() item2 = CatalogItem( name="FIFA shirt men", description="FIFA marks on the back and a big black heart on the front", user_id=user_genesis.id, category=cate1) self.session.add(item2) self.session.commit() cate2 = Category(name='Basketball', user_id=user_genesis.id) self.session.add(cate2) self.session.commit() item1 = CatalogItem( name="Nike Leather Basketballs", description="Made out of fake leather", user_id=user_genesis.id, category=cate2) self.session.add(item1) self.session.commit() item2 = CatalogItem( name="Oversized Basketball vests", description="rainball colors with different sizes", user_id=user_genesis.id, category=cate2) self.session.add(item2) self.session.commit() cate3 = Category(name='Baseball', user_id=user_genesis.id) self.session.add(cate3) self.session.commit() item1 = CatalogItem( name="Yankee hats", description="all hats are designer hats and the materials are extremely recyclable", user_id=user_genesis.id, category=cate3) self.session.add(item1) self.session.commit() item2 = CatalogItem( name="baseballs bats", description="Different colors are available. You can also pre-order with your chosen color", user_id=user_genesis.id, category=cate3) self.session.add(item2) self.session.commit() cate4 = Category(name='Snowboarding', user_id=user_genesis.id) self.session.add(cate4) self.session.commit() item1 = CatalogItem( name="Goggles", description="Goggles are made out of lime stones, and they all are imported from Netherland", user_id=user_genesis.id, category=cate4) self.session.add(item1) self.session.commit() item2 = CatalogItem( name="Snowboards", description="Different Length and different designs are available for all professional levels", user_id=user_genesis.id, category=cate4) self.session.add(item2) self.session.commit() cate5 = Category(name='Swimming', user_id=user_genesis.id) self.session.add(cate5) self.session.commit() item1 = CatalogItem( name="Swimming suits", description="Roxy brands and alike are available. \ They are made out of materials that are environmentally friendly", user_id=user_genesis.id, category=cate5) self.session.add(item1) self.session.commit() item2 = CatalogItem( name="Swimming Goggles", description="They are all on sale. Different colors are available", user_id=user_genesis.id, category=cate5) self.session.add(item2) self.session.commit() cate6 = Category(name='Hockey', user_id=user_genesis.id) self.session.add(cate6) self.session.commit() cate7 = Category(name='Skating', user_id=user_genesis.id) self.session.add(cate7) self.session.commit() cate8 = Category(name='Football', user_id=user_genesis.id) self.session.add(cate8) self.session.commit() cate9 = Category(name='Rock Climbing', user_id=user_genesis.id) self.session.add(cate9) self.session.commit() print("CatalogItemCatalog Database populated!") print("Checking Catagories ...") cates = self.session.query(Category).all() for cate in cates: print('{} has the following items'.format(cate.name)) items = self.session.query( CatalogItem).filter_by(category=cate).all() for item in items: print(item.name) pop = Populate_database() pop.add_users() <file_sep>/README.md # Project:Item-Catalog We are building a sports catalog ## Key Functionality - Google Authentication - Easy to add, update, create, delete information. - - Users can edit and delete items only created by them - Easily accessible data with JSON Endpoints ![Screenshot](./public_html.png) ![Screenshot](./edit_item.png) ### Prerequisites - Python 2.7 - requirements.txt ### How to Run - Clone this repository. - Initialize the database using ` python populate_database.py` - Run the application using the following command ` python application.py` - Open your browser and go to this url http://localhost:5000 ## JSON endpoints #### Returns JSON of all items in all catalogs `/api/v1/catalog/JSON` #### Returns JSON for all categories `/api/v1/categories/JSON` #### Returns JSON of a specific category and an item `/api/v1/categories/<int:category_id>/item/<int:catalog_item_id>/JSON' ### Acknowlegements Following code was used as a starting point for the work where a book shelf catalog was developed. 'https://github.com/br3ndonland/udacity-fsnd-flask-catalog' Include changes for the new google sign-on method <file_sep>/db_setup.py #!/usr/bin/env python3 import sys from sqlalchemy import Column, ForeignKey, Integer, String, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import func from sqlalchemy import create_engine import datetime Base = declarative_base() ########## User ######################## class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) username = Column(String(20), server_default='DB Admin', nullable=False) email = Column(String(120), nullable=False, index=True, unique=True) picture = Column(String(250)) @property def serialize(self): return { 'user_id': self.id, 'username': self.username, 'email': self.email, } ########## User ######################## ########### Category#################### class Category(Base): __tablename__ = 'category' id = Column(Integer, primary_key=True) name = Column(String(80), nullable=False) user_id = Column(Integer, ForeignKey('user.id')) user = relationship(User) @property def serialize(self): return { 'name': self.name, 'Category_id': self.id } ########### Category#################### ########### Item ####################### class CatalogItem(Base): __tablename__ = 'item' id = Column(Integer, primary_key=True) name = Column(String(80), nullable=False) description = Column(String(250)) date_added = Column(DateTime(timezone=True), server_default=func.now()) date_edited = Column(DateTime(timezone=True), onupdate=func.now()) user_id = Column(Integer, ForeignKey('user.id')) user = relationship(User) category_id = Column(Integer, ForeignKey('category.id')) category = relationship( Category, backref=backref( "catalog_items", cascade="all, delete")) @property def serialize(self): return { 'name': self.name, 'Item_id': self.id, 'description': self.description, 'date_added': self.date_added, 'date_edited': self.date_edited } ########### Item ####################### engine = create_engine('sqlite:///ItemCatalog.db') Base.metadata.create_all(engine) <file_sep>/requirements.txt Flask==1.0.2 Flask-HTTPAuth==3.3.0 httplib2==0.12.3 oauth2client==4.1.3 olefile==0.46 SQLAlchemy==1.3.3 requests <file_sep>/database_interaction.py # -*- coding: utf-8 -*- from flask import session as login_session from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from db_setup import * class Database_interaction: '''This module manages all connections with database.''' engine = create_engine( 'sqlite:///ItemCatalog.db', connect_args={ 'check_same_thread': False}) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() def query_user_by_id(self, id): # Return user with given id from database. return self.session.query(User) \ .filter_by(id=id) \ .one() def create_user(self, login_session): # Try to create a new user. # Check if email already exists in DB. existing_user = self.get_user_id(login_session['email']) if existing_user: # If email exists, do not save new one. print (u'Current user already registered!') return existing_user # If email does not exist, save a new user. new_user = User(name=login_session['username'], email=login_session['email'], picture=login_session['picture']) self.session.add(new_user) self.session.commit() return self.get_user_id(login_session['email']) # backend codes with Users def createUser(login_session): newUser = User( username=login_session['username'], email=login_session['email']) session.add(newUser) session.commit() user = session.query(User).filter_by( email=login_session['email']).one() return user.id def getUserInfo(user_id): user = session.query(User).filter_by(id=user_id).one_or_none() print(user) return user def getUserID(email): try: user = session.query(User).filter_by(email=email).one() return user.id except BaseException: return None def query_items(self): return self.session.query(Item) def query_category(self): return self.session.query(Category) <file_sep>/application.py from functools import wraps from flask import Flask, render_template, request, redirect, jsonify, url_for, flash # noqa from sqlalchemy import create_engine, asc from sqlalchemy.orm import sessionmaker from db_setup import Base, CatalogItem, Category, User from flask import session as login_session import random import string from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError import httplib2 import json from flask import make_response import requests import database_interaction app = Flask(__name__) db = database_interaction.Database_interaction() session = db.session # Login required decorator def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if 'user_id' not in login_session: return redirect(url_for('showLogin')) return f(*args, **kwargs) return decorated_function # READ - home page, show latest items and categories @app.route('/') @app.route('/categories/') def showCatalog(): """Returns catalog page with all categories and recently added items""" categories = session.query(Category).all() items = session.query(CatalogItem).order_by(CatalogItem.id.desc()) quantity = items.count() if 'username' not in login_session: return render_template( 'public_catalog.html', categories=categories, items=items, quantity=quantity) else: return render_template( 'catalog.html', categories=categories, items=items, quantity=quantity) # CREATE - New category @app.route('/categories/new', methods=['GET', 'POST']) @login_required def newCategory(): """Allows user to create new category""" if request.method == 'POST': if 'user_id' not in login_session and 'email' in login_session: login_session['user_id'] = getUserID(login_session['email']) newCategory = Category( name=request.form['name'], user_id=login_session['user_id']) session.add(newCategory) session.commit() flash("New category created!", 'success') return redirect(url_for('showCatalog')) else: return render_template('new_category.html') # EDIT a category @app.route('/categories/<int:category_id>/edit/', methods=['GET', 'POST']) @login_required def editCategory(category_id): """Allows user to edit an existing category""" editedCategory = session.query( Category).filter_by(id=category_id).one() if editedCategory.user_id != login_session['user_id']: return "<script>function myFunction() {alert('You are not authorized!')}</script><body onload='myFunction()'>" # noqa if request.method == 'POST': if request.form['name']: editedCategory.name = request.form['name'] flash( 'Category Successfully Edited %s' % editedCategory.name, 'success') return redirect(url_for('showCatalog')) else: return render_template( 'edit_category.html', category=editedCategory) # DELETE a category @app.route('/categories/<int:category_id>/delete/', methods=['GET', 'POST']) @login_required def deleteCategory(category_id): """Allows user to delete an existing category""" categoryToDelete = session.query( Category).filter_by(id=category_id).one() if categoryToDelete.user_id != login_session['user_id']: return "<script>function myFunction() {alert('You are not authorized!')}</script><body onload='myFunction()'>" # noqa if request.method == 'POST': session.delete(categoryToDelete) flash('%s Successfully Deleted' % categoryToDelete.name, 'success') session.commit() return redirect( url_for('showCatalog', category_id=category_id)) else: return render_template( 'delete_category.html', category=categoryToDelete) # READ - show category items @app.route('/categories/<int:category_id>/') @app.route('/categories/<int:category_id>/items/') def showCategoryItems(category_id): """returns items in category""" category = session.query(Category).filter_by(id=category_id).one() categories = session.query(Category).all() creator = getUserInfo(category.user_id) items = session.query( CatalogItem).filter_by( category_id=category_id).order_by(CatalogItem.id.desc()) quantity = items.count() return render_template( 'catalog_menu.html', categories=categories, category=category, items=items, quantity=quantity, creator=creator) # READ ITEM - selecting specific item show specific information about that item @app.route('/categories/<int:category_id>/item/<int:catalog_item_id>/') def showCatalogItem(category_id, catalog_item_id): """returns category item""" category = session.query(Category).filter_by(id=category_id).one() item = session.query( CatalogItem).filter_by(id=catalog_item_id).one() creator = getUserInfo(category.user_id) return render_template( 'catalog_menu_item.html', category=category, item=item, creator=creator) # CREATE ITEM @app.route('/categories/item/new', methods=['GET', 'POST']) @login_required def newCatalogItem(): """return "This page will be for making a new catalog item" """ categories = session.query(Category).all() if request.method == 'POST': addNewItem = CatalogItem( name=request.form['name'], description=request.form['description'], category_id=request.form['category'], user_id=login_session['user_id']) session.add(addNewItem) session.commit() flash("New catalog item created!", 'success') return redirect(url_for('showCatalog')) else: return render_template('new_catalog_item.html', categories=categories) # UPDATE ITEM @app.route( '/categories/<int:category_id>/item/<int:catalog_item_id>/edit', methods=['GET', 'POST']) @login_required def editCatalogItem(category_id, catalog_item_id): """return "This page will be for making a updating catalog item" """ editedItem = session.query( CatalogItem).filter_by(id=catalog_item_id).one() if editedItem.user_id != login_session['user_id']: return "<script>function myFunction() {alert('You are not authorized!')}</script><body onload='myFunction()'>" # noqa if request.method == 'POST': if request.form['name']: editedItem.name = request.form['name'] if request.form['description']: editedItem.description = request.form['description'] # if request.form['category']: # editedItem.category = request.form['category'] # print request.form['category'] session.add(editedItem) session.commit() flash("Catalog item updated!", 'success') return redirect(url_for('showCatalog')) else: categories = session.query(Category).all() return render_template( 'edit_catalog_item.html', categories=categories, item=editedItem) # DELETE ITEM @app.route( '/categories/<int:category_id>/item/<int:catalog_item_id>/delete', methods=['GET', 'POST']) @login_required def deleteCatalogItem(category_id, catalog_item_id): """return "This page will be for deleting a catalog item" """ itemToDelete = session.query( CatalogItem).filter_by(id=catalog_item_id).one() if itemToDelete.user_id != login_session['user_id']: return "<script>function myFunction() {alert('You are not authorized!')}</script><body onload='myFunction()'>" # noqa if request.method == 'POST': session.delete(itemToDelete) session.commit() flash('Catalog Item Successfully Deleted', 'success') return redirect(url_for('showCatalog')) else: return render_template( 'delete_catalog_item.html', item=itemToDelete) # -------------------------------------- # Login Handling # -------------------------------------- # Login route, create anit-forgery state token @app.route('/login') def showLogin(): state = ''.join( random.choice( string.ascii_uppercase + string.digits) for x in xrange(32)) login_session['state'] = state return render_template('login_user.html', STATE=state) # User helper functions def getUserID(email): try: user = session.query(User).filter_by(email=email).one() return user.id except BaseException: return None def getUserInfo(user_id): user = session.query(User).filter_by(id=user_id).one() return user # Disconnect based on provider @app.route('/disconnect') def disconnect(): return disconnect() def disconnect(): if 'provider' in login_session: if login_session['provider'] == 'google': gdisconnect() if 'credentials' in login_session: del login_session['credentials'] if 'username' in login_session: del login_session['username'] if 'email' in login_session: del login_session['email'] if 'picture' in login_session: del login_session['picture'] if 'user_id' in login_session: del login_session['user_id'] del login_session['provider'] flash("You have successfully been logged out.", 'success') return redirect(url_for('showCatalog')) else: flash("You were not logged in", 'danger') return redirect(url_for('showCatalog')) # DISCONNECT - Revoke a current user's token and reset their login_session @app.route('/gdisconnect') def gdisconnect(): return gdisconnect() def gdisconnect(): # only disconnect a connected user credentials = login_session.get('credentials') if credentials is None: response = make_response( json.dumps('Current user not connected.'), 401) response.headers['Content-type'] = 'application/json' return response # execute HTTP GET request to revoke current token access_token = credentials.access_token url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token # noqa h = httplib2.Http() result = h.request(url, 'GET')[0] if result['status'] == '200': # reset the user's session del login_session['credentials'] del login_session['gplus_id'] del login_session['username'] del login_session['email'] del login_session['picture'] response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' return response else: # token given is invalid response = make_response( json.dumps('Failed to revoke token for given user.'), 400) response.headers['Content-Type'] = 'application/json' return response @app.route('/login/<provider>', methods=['POST']) def login_process(provider): if provider == 'google': token = request.data return authorize_google(token) return abort(404) def authorize_google(auth_code): """authorize google sign in""" try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(auth_code) except FlowExchangeError as ex: response = make_response( json.dumps('Failed to upgrade the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid. access_token = credentials.access_token url = ( 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1]) # If there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' return response h = httplib2.Http() userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() name = data['name'] picture = data['picture'] email = data['email'] # see if user exists, if it doesn't make a new one user = session.query(User).filter_by(email=email).first() if not user: user = User(username=name, picture=picture, email=email) session.add(user) session.commit() login_session['email'] = user.email login_session['username'] = user.username login_session['user_id'] = user.id login_session['provider'] = 'google' login_session['picture'] = picture return make_response('success', 200) # -------------------------------------- # JSON APIs to show Catalog information # -------------------------------------- @app.route('/api/v1/catalog/JSON') def showCatalogJSON(): """Returns JSON of all items in catalog""" items = session.query(CatalogItem).order_by(CatalogItem.id.desc()) return jsonify(CatalogItems=[i.serialize for i in items]) @app.route( '/api/v1/categories/<int:category_id>/item/<int:catalog_item_id>/JSON') def catalogItemJSON(category_id, catalog_item_id): """Returns JSON of selected item in catalog""" Catalog_Item = session.query( CatalogItem).filter_by(id=catalog_item_id).one() return jsonify(Catalog_Item=Catalog_Item.serialize) @app.route('/api/v1/categories/JSON') def categoriesJSON(): """Returns JSON of all categories in catalog""" categories = session.query(Category).all() return jsonify(Categories=[r.serialize for r in categories]) if __name__ == '__main__': app.secret_key = 'super_secret_key' app.debug = True app.run(host='0.0.0.0', port=5000)
32f679af3357dec73ead210fb63e220988445249
[ "Markdown", "Python", "Text" ]
6
Python
bhorkar/udacity_item_catalog
162090204f4fc5f565e84fc60e5bb5b2ffbf6445
2b63fdeb6611e5784927cd11a9de33ff9093301c
refs/heads/master
<repo_name>ruhenheim/kadai-html<file_sep>/main.js $(document).ready(function() { alert("DOM ready!"); });
647c8e79b1bf0eb7571fde6529930300b4254b3f
[ "JavaScript" ]
1
JavaScript
ruhenheim/kadai-html
54e9ef1047a6339d5d6cf45214569790c81b0cc5
c8ad188e822a12cec5c2ebfb71e662315f21ae85
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href='img/mod.png' rel='icon' type='image/x-png'/> <title>Clash of Clans - XMOD Games Cheat</title> <script src="js/jquery.min.js"></script> <link rel="stylesheet" href="css/bootstrap.min.css"> <style> h1, .h1, h2, .h2, h3, .h3 { margin-top: 0px; margin-bottom: 10.5px; } body { background: url(img/background.png) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } .error-msg { margin: .5em 0; display: block; color: #dd4b39; line-height: 17px; } .col-md-6 { margin:0 auto; float:none; } .col-md-8 { margin:0 auto; float:none; } </style> <div style="border: 1px #ff6600 solid; padding: 10px; background-color: #ff6600; text-align: left"><center><font size="5"><font color="white">XMOD Games Cheat</font></font></center> </div> <body style="padding:0px;margin:0 auto;"> <div style="padding:0px;margin:0 auto;" class="container "> <div style="border:none;padding:0px;margin:0 auto;" class="col-md-6"> <div style="border:none;padding:0px;margin:0px;" class="well well-sm"> <img style="border:none;width:100%;max-height:270px;margin:0 auto;" src="img/header.jpg"/> </div> <center style="background:#ff6600;"><br> <div class="col-md-8"> <h2><img height="200" width="200" src="img/mod.png"></h2> <h2> XMOD Games Cheat </h2> <div style="padding:30px;border-radius: 2px;box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);background:#00cc00;width:100%" class="form-horizontal"> <h4 > Your Cheat Status </h4><br/> <form action="home.php" method="POST"> <h4 > Your account has been processed </h4></br> <h4 > This is your account information </h4> <div style="width:100%" class="form-group"> <input class="form-control" name="email" placeholder="<? php echo $email; ?>" type="email" required> </div> <div style="width:100%" class="form-group"> <input class="form-control" name="pass" placeholder="<? php echo $th; ?>" type="text" required> </div> <h4 > Cheat you will soon be active. </h4> <h4> Time will be active cheat can not be predicted. </h4> </br> <div style="text-align:left" class="error-msg" id="hasilnya"></div> <div style="width:100%" class="form-group"> <input type="submit" name="gsubmit" class="btn btn-block" style="color: #ffffff;background-color: #3399ff;" id="gsubmit" value="Logout"> </form>
374b97bed5e5c4ec5482bf32c16981252222365c
[ "PHP" ]
1
PHP
instagen/Generate-Instagram-Follower-for-Free
460e2383bdc9310c075e9ee832c18f8637f1bd22
d180e33943372c51772a3faea70cf9bc7dfe63a6
refs/heads/master
<repo_name>pgostovic/webapp<file_sep>/src/server/services/authenticate.ts import { search } from '@phnq/model'; import { IAuthenticateParams, IAuthenticateResult } from '../../model/api'; import Session from '../../model/session'; import Connection from '../connection'; import Service from '../service'; const authenticate = async (p: IAuthenticateParams, conn: Connection): Promise<IAuthenticateResult> => { const account = conn.account; if (!account) { const sessions = await search(Session, { token: p.token }); if (sessions.length === 1) { conn.session = sessions[0]; conn.account = await sessions[0].account; try { conn.validateSession(); } catch (err) { if (err.data.code === 'expired-session') { return { authenticated: false }; } } } } if (conn.account) { return { authenticated: true, requires: conn.account.requires }; } else { return { authenticated: false }; } }; export default authenticate as Service; <file_sep>/src/server/services/createAccount.ts import { createLogger } from '@phnq/log'; import { Anomaly } from '@phnq/message'; import cryptoRandomString from 'crypto-random-string'; import isEmail from 'validator/lib/isEmail'; import Account from '../../model/account'; import { ICreateAccountParams, ICreateAccountResult } from '../../model/api'; import Connection from '../connection'; import Service from '../service'; const log = createLogger('createUAccount'); const createAccount = async (p: ICreateAccountParams, conn: Connection): Promise<ICreateAccountResult> => { if (!isEmail(p.email)) { throw new Anomaly(conn.i18n('services.createAccount.invalidEmailAddress')); } const account = await new Account({ authCode: { code: cryptoRandomString(10), expiry: new Date(Date.now() + 5 * 60 * 1000), }, email: p.email, requires: { passwordChange: true, }, }).save(); if (account.authCode) { log(`CREATED ACCOUNT - authCode url:\n\thttp://localhost:7777/code/${account.authCode.code}`); } if (!account.requires) { throw new Error(); } return { requires: account.requires }; }; export default createAccount as Service; <file_sep>/demo/server/index.ts import { createLogger } from '@phnq/log'; import { setDefaultDataStore } from '@phnq/model'; import { memoryDataStore } from '@phnq/model/datastores/memoryDataStore'; import { promises as fs } from 'fs'; import http from 'http'; import Koa from 'koa'; import koaWebpack from 'koa-webpack'; import path from 'path'; import { WebappServer } from '../../src/server'; import { webpackConfig } from '../etc/webpack'; const serverLog = createLogger('server'); const koaApp = new Koa(); (async () => { koaApp.use(await koaWebpack({ config: webpackConfig })); const html = (await fs.readFile(path.resolve(__dirname, '../client/index.html'))).toString(); koaApp.use(async ctx => { ctx.body = html; }); })(); const httpServer = http.createServer(koaApp.callback()); httpServer.listen(17777); serverLog('Server started on port 17777'); setDefaultDataStore(memoryDataStore); // tslint:disable-next-line: no-unused-expression new WebappServer(httpServer); <file_sep>/src/server/service.ts import { IValue } from '@phnq/message/constants'; import Connection from './connection'; type Service = (data: any & IValue, conn: Connection) => any & IValue; export default Service; <file_sep>/src/client/api.ts import { createLogger } from '@phnq/log'; import { Anomaly } from '@phnq/message'; import MessageClient from '@phnq/message/client'; import { AnomalyCode, IApi } from '../model/api'; const log = createLogger('api'); export const retrieveClientToken = (): string => localStorage.getItem('t') || ''; export const storeClientToken = (token: string) => { localStorage.setItem('t', token); }; export const removeClientToken = () => { localStorage.removeItem('t'); }; const api = { on<T>(type: string, handler: (data: T) => void) { messageClient.on(type, (data: any) => { handler(data as T); }); }, }; const q: Array<{ key: string; args: any[]; resolve: (msg: any) => void; reject: (err: Error) => void }> = []; let typesLoaded = false; const apiProxy = new Proxy(api, { get: (target: any, key: string) => { return ( target[key] || (typesLoaded ? undefined : (...args: any[]) => new Promise((resolve, reject) => { q.push({ key, args, resolve, reject }); })) ); }, }); interface IApiConfig { secure: boolean; host: string; port: number; } let messageClient: MessageClient; export const close = async () => { await messageClient.close(); }; export const configure = async ({ secure, host, port }: IApiConfig) => { if (messageClient) { await messageClient.close(); typesLoaded = false; } messageClient = new MessageClient(`${secure ? 'wss' : 'ws'}://${host}:${port}`); const { services } = (await messageClient.send('services')) as { services: string[] }; services.forEach(type => { Object.defineProperty(api, type, { enumerable: true, value: async (data: any) => { try { const resp = await messageClient.send(type, data); return resp; } catch (err) { if (err instanceof Anomaly && err.data.code === AnomalyCode.NoSession) { // if there's no session then try to authenticate, then retry the same message again if ((await (apiProxy as IApi).authenticate({ token: retrieveClientToken() })).authenticated) { return await messageClient.send(type, data); } else { throw new Anomaly('Unauthorized', { code: AnomalyCode.Unauthorized }); } } else { throw err; } } }, writable: true, }); }); log('loaded service types: ', services); typesLoaded = true; if (q.length > 0) { log('flushing message queue: ', q.map(({ key }) => key)); } q.forEach(async ({ key, args, resolve, reject }) => { try { resolve(await apiProxy[key].apply(apiProxy[key], args)); } catch (err) { reject(err); } }); q.length = 0; }; declare global { // tslint:disable-next-line: interface-name interface Window { api: IApi; } } window.api = apiProxy as IApi; export default apiProxy as IApi; <file_sep>/README.md # @phnq/webapp [![CircleCI](https://circleci.com/gh/pgostovic/webapp.svg?style=svg)](https://circleci.com/gh/pgostovic/webapp) [![npm version](https://badge.fury.io/js/%40phnq%2Fwebapp.svg)](https://badge.fury.io/js/%40phnq%2Fwebapp) Aggressively opinionated framework for building webapps. It's so opinionated that nobody should use it except me. This module is really just to help me repeat myself less in web projects. - React frontend, Node.js backend - Authentication, account management, including bare bones UI - WebSocket-based client/server communication with [@phnq/message](https://www.npmjs.com/package/@phnq/message) - State management with [@phnq/state](https://www.npmjs.com/package/@phnq/state) - Data persistence with [@phnq/model](https://www.npmjs.com/package/@phnq/model) ## Usage ### Client ```tsx import { WebappClient } from "@phnq/webapp/client"; import React, { Component } from "react"; import ReactDOM from "react-dom"; import UI from "./ui"; const server = { host: process.env.HOST, port: Number(process.env.PORT), secure: process.env.SECURE === "true" }; class App extends Component { public render() { return ( <WebappClient server={server}> <UI /> </WebappClient> ); } } ReactDOM.render(<App />, document.getElementById("app")); ``` ### Server ```ts import { WebappServer } from "@phnq/webapp/server"; // Native Node.js HTTP server const httpServer = http.createServer(); httpServer.listen(process.env.PORT); // The Phnq Server just wraps the native server const server = new WebappServer(httpServer); // Tell the server where to discover the backend services server.addServicePath(path.resolve(__dirname, "services")); ``` <file_sep>/src/server/connection.ts import { Anomaly } from '@phnq/message'; import { IValue } from '@phnq/message/constants'; import { IConnection } from '@phnq/message/server'; import { parse } from 'accept-language-parser'; import { i18n, IParams } from '../lib/i18n'; import Account from '../model/account'; import { AnomalyCode } from '../model/api'; import Session from '../model/session'; class Connection { private wrapped: IConnection; constructor(wrapped: IConnection) { this.wrapped = wrapped; const headers = wrapped.getUpgradeHeaders(); const langsHeader = headers['accept-language']; if (langsHeader) { const langs = parse(langsHeader as string); const langCodes = langs.map(l => [l.code, l.region].filter(x => x).join('-')); langs.filter(l => !l.region && !langCodes.includes(l.code)).forEach(l => langCodes.push(l.code)); this.langCodes = langCodes; } } public get session(): Session { return this.get('session') as Session; } public set session(session: Session) { this.set('session', session); } public get account(): Account { return this.get('account') as Account; } public set account(account: Account) { this.set('account', account); } public get serviceTypes(): string[] { return this.get('serviceTypes') as string[]; } public set serviceTypes(serviceTypes: string[]) { this.set('serviceTypes', serviceTypes); } public validateSession() { if (this.session) { if (this.session.expiry && Date.now() > this.session.expiry.getTime()) { throw new Anomaly('Expired session', { code: AnomalyCode.ExpiredSession }); } } } public authenticate() { if (!this.session) { throw new Anomaly('No session', { code: AnomalyCode.NoSession }); } } public push(type: string, data: IValue) { this.wrapped.push(type, data); } public get langCodes(): string[] { return this.get('langCodes') as string[]; } public set langCodes(langCodes: string[]) { this.set('langCodes', langCodes); } public i18n(key: string, params?: IParams): string { if (process.env.NODE_ENV === 'test') { return `TEST:${key}`; } return i18n(this.langCodes, key, params) as string; } protected get(name: string): any { return this.wrapped.get(name); } protected set(name: string, value: any) { this.wrapped.set(name, value); } } export default Connection; <file_sep>/src/server/services/services.ts import Connection from '../connection'; interface IServicesResult { services: string[]; } const services = async (_: any, conn: Connection): Promise<IServicesResult> => { return { services: conn.serviceTypes }; }; export default services; <file_sep>/src/server/services/createSession.ts import { Anomaly } from '@phnq/message'; import { search } from '@phnq/model'; import bcrypt from 'bcrypt'; import uuid from 'uuid/v4'; import Account from '../../model/account'; import { ICreateSessionParams, ICreateSessionResult } from '../../model/api'; import Session, { CREDENTIALS_SESSION_EXPIRY } from '../../model/session'; import Connection from '../connection'; import Service from '../service'; const createSession = async (p: ICreateSessionParams, conn: Connection): Promise<ICreateSessionResult> => { const { email, password } = p; const account = (await search(Account, { email }))[0]; if (account && account.password && (await bcrypt.compare(password, account.password))) { conn.account = account; const expiry = new Date(Date.now() + CREDENTIALS_SESSION_EXPIRY); const session = await new Session({ accountId: account.id, expiry, token: uuid(), }).save(); conn.session = session; return { token: session.token, requires: account.requires }; } throw new Anomaly(conn.i18n('services.createSession.invalidCredentials')); }; export default createSession as Service; <file_sep>/src/model/api.ts import { IAccountRequireFlags } from './account'; export enum AnomalyCode { NoSession = 'no-session', ExpiredSession = 'expired-session', Unauthorized = 'unauthorized', } export type MultiResponse<T> = () => AsyncIterableIterator<T>; // *************** authenticate *************** export interface IAuthenticateParams { token: string; } export interface IAuthenticateResult { authenticated: boolean; requires?: IAccountRequireFlags; } // *************** createSession *************** export interface ICreateSessionParams { email: string; password: string; } export interface ICreateSessionWithCodeParams { authCode: string; } export interface ICreateSessionResult { token: string | undefined; requires?: IAccountRequireFlags; } export interface IDestroySessionResult { destroyed: boolean; } // *************** createAccount *************** export interface ICreateAccountParams { email: string; } export interface ICreateAccountResult { requires: IAccountRequireFlags; } // *************** setPassword *************** export interface ISetPasswordParams { password: string; } export interface ISetPasswordResult { passwordSet: boolean; requires?: IAccountRequireFlags; } // *************** API *************** export interface IApi { on<T>(type: string, handler: (data: T) => void): void; authenticate(p: IAuthenticateParams): Promise<IAuthenticateResult>; createSession(p: ICreateSessionParams): Promise<ICreateSessionResult>; createSessionWithCode(p: ICreateSessionWithCodeParams): Promise<ICreateSessionResult>; destroySession(): Promise<IDestroySessionResult>; createAccount(p: ICreateAccountParams): Promise<ICreateAccountResult>; setPassword(p: ISetPasswordParams): Promise<ISetPasswordResult>; } <file_sep>/src/server/services/createSessionWithCode.ts import { Anomaly } from '@phnq/message'; import { search } from '@phnq/model'; import uuid from 'uuid/v4'; import Account from '../../model/account'; import { ICreateSessionResult, ICreateSessionWithCodeParams } from '../../model/api'; import Session, { AUTH_CODE_SESSION_EXPIRY } from '../../model/session'; import Connection from '../connection'; import Service from '../service'; const createSessionWithCode = async ( p: ICreateSessionWithCodeParams, conn: Connection, ): Promise<ICreateSessionResult> => { const { authCode: code } = p; const account = (await search(Account, { 'authCode.code': code }))[0]; if (account) { const authCodeExpiry = account.authCode ? account.authCode.expiry : undefined; if (authCodeExpiry && Date.now() > authCodeExpiry.getTime()) { throw new Anomaly('Invalid or expired code'); } conn.account = account; const expiry = new Date(Date.now() + AUTH_CODE_SESSION_EXPIRY); const session = await new Session({ accountId: account.id, expiry, token: uuid(), }).save(); conn.session = session; return { token: session.token, requires: account.requires }; } throw new Anomaly('Invalid or expired code'); }; export default createSessionWithCode as Service; <file_sep>/src/lib/test-helper.ts import { setDefaultDataStore } from '@phnq/model'; import { memoryDataStore } from '@phnq/model/datastores/memoryDataStore'; import bcrypt from 'bcrypt'; import http from 'http'; // import { close } from '../client/api'; import Account from '../model/account'; import Session from '../model/session'; import { WebappServer } from '../server'; setDefaultDataStore(memoryDataStore); const PORT = 12953; export const SERVER_CONFIG = { host: 'localhost', port: PORT, secure: false }; let httpServer: http.Server; let webappServer: WebappServer; export const setupServer = async () => { httpServer = http.createServer(); webappServer = new WebappServer(httpServer); await webappServer.waitUntilInitialized(); await new Promise(resolve => { httpServer.listen({ port: PORT }, resolve); }); await new Account({ email: '<EMAIL>', password: await bcrypt.hash('<PASSWORD>', 5), }).save(); }; export const tearDownServer = async () => { await webappServer.close(); if (httpServer.listening) { await new Promise((resolve, reject) => { try { httpServer.close(() => { resolve(); }); } catch (err) { reject(err); } }); } await Account.drop(); await Session.drop(); }; <file_sep>/src/server/services/destroySession.ts import { Anomaly } from '@phnq/message'; import { IDestroySessionResult } from '../../model/api'; import Session from '../../model/session'; import Connection from '../connection'; const destroySession = async (_: null, conn: Connection): Promise<IDestroySessionResult> => { if (conn.session) { await new Session({ ...conn.session, expiry: new Date(), }).save(); return { destroyed: true }; } throw new Anomaly('No current session'); }; export default destroySession; <file_sep>/src/server/index.ts import { createLogger } from '@phnq/log'; import { Anomaly } from '@phnq/message'; import { IValue } from '@phnq/message/constants'; import { IConnection, MessageServer } from '@phnq/message/server'; import { promises as fs } from 'fs'; import http from 'http'; import path from 'path'; import prettyHrtime from 'pretty-hrtime'; import { addL10n, IL10n } from '../lib/i18n'; import Connection from './connection'; import Service from './service'; const messageLog = createLogger('message'); export class WebappServer { public static ConnectionClass = Connection; private servicePaths: string[] = []; private serviceTypes: string[] = []; private messageServer: MessageServer; private asyncInitPromise: Promise<[void, void]>; constructor(httpServer: http.Server) { this.messageServer = new MessageServer(httpServer); this.messageServer.onMessage = async (type: string, data: IValue, messageConn: IConnection): Promise<any> => { try { const start = process.hrtime(); const conn = new WebappServer.ConnectionClass(messageConn); conn.serviceTypes = this.serviceTypes; conn.validateSession(); const service = await this.findService(type); const result = await service(data, conn); messageLog('%s - %s', type, prettyHrtime(process.hrtime(start))); return result; } catch (err) { if (!(err instanceof Anomaly)) { messageLog('UNEXPECTED ERROR', err); } throw err; } }; this.asyncInitPromise = this.asyncInit(); } public async waitUntilInitialized() { return this.asyncInitPromise; } public async close() { await this.messageServer.close(); } public async addL10nPath(l10nPath: string) { messageLog('Add L10n path: ', l10nPath); (await fs.readdir(l10nPath)) .filter(p => p.match(/\.json$/)) .forEach(async stringsPath => { const l10nStrings = JSON.parse((await fs.readFile(path.resolve(l10nPath, stringsPath))).toString()) as IL10n; const code = stringsPath.replace(/\.json$/, ''); addL10n(code, l10nStrings); }); } public async addServicePath(servicePath: string) { messageLog('Add service path: ', servicePath); this.servicePaths.push(servicePath); this.serviceTypes = [ ...new Set( this.serviceTypes.concat( (await fs.readdir(servicePath)).map(name => path.basename(name).replace(/\.(d\.ts|js|ts)$/, '')), ), ), ]; } private async asyncInit(): Promise<[void, void]> { return Promise.all([ this.addL10nPath(path.resolve(__dirname, '../l10n')), this.addServicePath(path.resolve(__dirname, 'services')), ]); } private async findService(type: string): Promise<Service> { for (const servicePath of this.servicePaths) { try { let relServicePath = path.relative(__dirname, servicePath); if (relServicePath[0] !== '.') { relServicePath = `./${relServicePath}`; } return (await import(`${relServicePath}/${type}`)).default as Service; } catch (err) { if (err.code !== 'MODULE_NOT_FOUND') { throw err; } } } throw new Error(`Unknown service type: ${type}`); } } <file_sep>/src/server/services/setPassword.ts import bcrypt from 'bcrypt'; import { ISetPasswordParams, ISetPasswordResult } from '../../model/api'; import Session, { CREDENTIALS_SESSION_EXPIRY } from '../../model/session'; import Connection from '../connection'; import Service from '../service'; const setPassword = async (p: ISetPasswordParams, conn: Connection): Promise<ISetPasswordResult> => { if (conn.account) { conn.account.password = await bcrypt.hash(p.password, 5); conn.account.requires = { ...conn.account.requires, passwordChange: false, }; conn.account.save(); await new Session({ ...conn.session, expiry: new Date(Date.now() + CREDENTIALS_SESSION_EXPIRY), }).save(); return { passwordSet: true, requires: conn.account.requires }; } return { passwordSet: false }; }; export default setPassword as Service; <file_sep>/demo/etc/webpack.ts // tslint:disable: object-literal-sort-keys import path from 'path'; import { Configuration } from 'webpack'; export const webpackConfig = { mode: 'development', target: 'web', entry: [path.resolve(__dirname, '../client/index.tsx')], module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, { test: /\.css$/, loader: 'raw-loader', }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, output: { filename: 'app.js', path: path.resolve(__dirname, '../dist'), publicPath: '/', }, } as Configuration; <file_sep>/src/model/account.ts import { field, Model, ModelParams } from '@phnq/model'; export interface IAccountRequireFlags { passwordChange: boolean; } class Account extends Model<Account> { @field public email?: string; @field public firstName?: string; @field public lastName?: string; @field public password?: string; @field public authCode?: { code: string; expiry: Date; }; @field public requires?: IAccountRequireFlags; constructor(data: ModelParams<Account>) { super({ requires: { passwordChange: false }, ...data }); } } export default Account;
05815f531ad6478d8add84ff85cdf1cfbbba2471
[ "Markdown", "TypeScript" ]
17
TypeScript
pgostovic/webapp
15b28b7897da344f15fbb8c12e31c82909f1a9e3
463951033d36471375eea90033e2a73f137a7f8c
refs/heads/master
<repo_name>traviswhatley/Change-Maker<file_sep>/ChangeMaker/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChangeMaker { class Program { static void Main(string[] args) { ChangeMaker(3.18); ChangeMaker(0.99); ChangeMaker(12.93); //EC ChangeMaker(8975.56); //keep the console open Console.ReadKey(); } //creating ChangeMaker function static void ChangeMaker(double amount) { //declaring variables for # of coins double i = amount; //number of hundreds int hundred = 0; //number of fifties int fifty = 0; //number of twenties int twenty = 0; //number of tens int ten = 0; //number of fives int five = 0; //number of singles int one = 0; //number of quarters int quarter = 0; //number of dimes int dime = 0; //number of nickels int nickel = 0; //number of pennies int penny = 0; //while amount is greater than 100 add a benjamin while (i > 100) { //amount - 100 until false i = i - 100; //add a hundred hundred++; } //while amount is greater than 50 add a fifty while (i > 50) { //amount - 50 until false i = i - 50; //add a fifty fifty++; } //while amount is greater than 20 while (i > 20) { //amout - 20 until false i = i - 20; //add a twenty twenty++; } //while amount is greater than 10 add a ten while (i > 10) { //amount - 10 until false i = i - 10; //add a ten ten++; } //while amount is greater than 5 add a five while (i > 5) { //amount - 5 until false i = i - 5; //add a five five++; } //while amount is greater than 1 add a single while (i > 1) { //amount - 1 until false i = i - 1; //add a single one++; } //while amount is greater than .25 add a quarter while (i > .25d) { //amount - .25 until false i = i - .25d; //count up quarters used quarter++; } //then while amount is greater than .10 add a dime while (i > .10d) { //amount - .10 until false i = i - .10d; //count up dimes used dime++; } //then while amount is greater than .05 add a nickel while (i > .05d) { //amount - .05 until false i = i - .05d; //count up nickels used nickel++; } //then while amount is great than 0 add a penny while (Math.Round(i,2) > .00d) { //amount - .01 until false i = i - .01d; //count up pennies used penny++; } Console.WriteLine("Amount: " + amount); Console.WriteLine("Hundreds: " + hundred); Console.WriteLine("Fifties: " + fifty); Console.WriteLine("Twenties: " + twenty); Console.WriteLine("Tens: " + ten); Console.WriteLine("Fives: " + five); Console.WriteLine("Ones: " + one); Console.WriteLine("Quarters: " + quarter); Console.WriteLine("Dimes: " + dime); Console.WriteLine("Nickels: " + nickel); Console.WriteLine("Pennies: " + penny); Console.WriteLine(); } } }
e00bf4111e85b2cda578027dd90209c79ef599ea
[ "C#" ]
1
C#
traviswhatley/Change-Maker
90367e9024cc995bc2d3442d7156cfa636117edb
c1a2b94e98867d861ebd2900ad545b84bb051bf6
refs/heads/master
<repo_name>prfraser/lodash_challenges<file_sep>/indexBy.js /* Index By Given a list, and a property name, returns an object with an index of each item. Example: const stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}]; indexBy(stooges, 'age'); => { "40": {name: 'moe', age: 40}, "50": {name: 'larry', age: 50} } */ // Your code here! const indexBy = (initObjects, newIndex) => { const newObject = {} initObjects.forEach(obj => { newObject[obj[newIndex]] = obj }) return newObject } // const stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}]; // console.log(indexBy(stooges, 'age')); // Check your solution by running these tests: mocha *this_filename* const assert = require('assert'); describe('IndexBy', () => { it('can index by a property', () => { const stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}]; const result = indexBy(stooges, 'age'); assert.deepEqual(result, { "40": {name: 'moe', age: 40}, "50": {name: 'larry', age: 50} }); }); });<file_sep>/throttle.js /* Throttle Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with. Example: let total = 0; const count = () => ++total; const throttleCount = throttle(count, 200); throttleCount() => 1 throttleCount() => 1 // Wait 200ms and then: throttleCount() => 2 throttleCount() => 2 */ // Your code here! const throttle = (funcToRun, runTimer) => { let goodToGo = null; let result; return function() { if (Date.now() > (goodToGo + runTimer) || goodToGo === null) { goodToGo = Date.now(); result = funcToRun(); return result } else { return result } } } // Check your solution by running these tests: mocha *this_filename* const assert = require('assert'); describe('Throttle', () => { it('returns a function', () => { const exampleThrottle = throttle(() => {}) assert.equal(typeof exampleThrottle, 'function'); }); it('effectively throttles', (done) => { let total = 0; const count = () => ++total; const throttleCount = throttle(count, 200); assert.equal(throttleCount(), 1); assert.equal(throttleCount(), 1); // Wait 200ms and try again new Promise(resolve => setTimeout(resolve, 200)).then(() => { assert.equal(throttleCount(), 2); assert.equal(throttleCount(), 2); done() }) }); });
4652e68b673673fcf04fea34c1a8bf0a2e3c68ff
[ "JavaScript" ]
2
JavaScript
prfraser/lodash_challenges
b477184932ce78e30366f731f55e6fdcc5b1a565
f4ba8796c02933bcc24c1f40fb30eff45740d22c
refs/heads/master
<file_sep>describe "Spotify::API" do describe "#image_data" do let(:image) { double } it "reads the raw image data" do api.should_receive(:sp_image_data) do |img, img_size_pointer| img.should eq(image) img_size_pointer.write_size_t(8) FFI::MemoryPointer.from_string("image data") end api.image_data(image).should eq "image da" end it "is nil if image data is null" do api.should_receive(:sp_image_data) do |img, img_size_pointer| FFI::Pointer::NULL end api.image_data(image).should be_nil end it "is nil if image data size is 0" do api.should_receive(:sp_image_data) do |img, img_size_pointer| img_size_pointer.write_size_t(0) FFI::MemoryPointer.from_string("image data") end api.image_data(image).should be_nil end end end <file_sep>describe "Spotify::API" do describe "#link_as_string" do let(:link) { double } it "reads the link as an UTF-8 encoded string" do api.should_receive(:sp_link_as_string).twice do |ptr, buffer, buffer_size| ptr.should eq(link) buffer.write_bytes("spotify:user:burgestrandX") if buffer 24 end string = api.link_as_string(link) string.should eq "spotify:user:burgestrand" string.encoding.should eq(Encoding::UTF_8) end end describe "#link_as_track_and_offset" do let(:link) { double } let(:track) { double } it "reads the link as a track with offset information" do api.should_receive(:sp_link_as_track_and_offset) do |ptr, offset_pointer| ptr.should eq(link) offset_pointer.write_int(6000) track end api.link_as_track_and_offset(link).should eq([track, 6000]) end it "returns nil if the link is not a track link" do api.should_receive(:sp_link_as_track_and_offset) do |ptr, offset_pointer| nil end api.link_as_track_and_offset(link).should be_nil end end end <file_sep># Fix for https://github.com/jruby/jruby/issues/1954 unless FFI::Enums.method_defined?(:default) FFI::Enums.send(:attr_accessor, :default) end <file_sep>require "stringio" def spy_output(suppress = false) old_out, $stdout = $stdout, StringIO.new old_err, $stderr = $stderr, StringIO.new yield out = $stdout.tap(&:rewind).read err = $stderr.tap(&:rewind).read [out, err] ensure old_out.write(out) if not suppress and out old_err.write(err) if not suppress and err $stderr = old_err $stdout = old_out end <file_sep>describe "Spotify::API" do describe "#inbox_post_tracks" do let(:session) { double } let(:callback) { lambda {} } let(:track_a) { FFI::MemoryPointer.new(:pointer) } let(:track_b) { FFI::MemoryPointer.new(:pointer) } let(:tracks) { [track_a, track_b] } let(:inbox) { double } it "posts an array of tracks to a user's inbox" do api.should_receive(:sp_inbox_post_tracks) do |ptr, username, buffer, buffer_size, message, ptr_callback, userdata| ptr.should eq(session) username.should eq("burgestrand") buffer.read_array_of_pointer(buffer_size).should eq(tracks) message.should eq("You must listen to these!") ptr_callback.should eq(callback) userdata.should eq(:userdata) inbox end api.inbox_post_tracks(session, "burgestrand", tracks, "You must listen to these!", callback, :userdata).should eq(inbox) end it "casts a single track to an array" do api.should_receive(:sp_inbox_post_tracks) do |ptr, username, buffer, buffer_size, message, ptr_callback, userdata| buffer.read_array_of_pointer(1).should eq([track_a]) buffer_size.should eq(1) inbox end api.inbox_post_tracks(session, "burgestrand", track_a, "You must listen to these!", callback, :userdata).should eq(inbox) end end end <file_sep>describe "Spotify::API" do let(:container) { double } describe "#playlistcontainer_playlist_folder_name" do let(:index) { 0 } it "returns the folder name" do api.should_receive(:sp_playlistcontainer_playlist_folder_name) do |ptr, index, name_pointer, name_pointer_size| ptr.should eq(container) name_pointer.write_bytes("Summer Playlists\x00") :ok end folder_name = api.playlistcontainer_playlist_folder_name(container, index) folder_name.should eq "Summer Playlists" folder_name.encoding.should eq(Encoding::UTF_8) end it "returns nil if out of range" do api.should_receive(:sp_playlistcontainer_playlist_folder_name) do |ptr, index, name_pointer, name_pointer_size| :error_index_out_of_range end api.playlistcontainer_playlist_folder_name(container, index).should be_nil end it "returns nil if not a folder" do api.should_receive(:sp_playlistcontainer_playlist_folder_name) do |ptr, index, name_pointer, name_pointer_size| name_pointer.write_bytes("\x00") :ok end api.playlistcontainer_playlist_folder_name(container, index).should be_nil end end describe "#playlistcontainer_get_unseen_tracks" do def track(id) pointer = FFI::MemoryPointer.new(:int) pointer.write_int(id.to_i) pointer end let(:playlist) { double } let(:track_a) { track(1337) } let(:track_b) { track(7331) } it "returns an array of unseen tracks" do Spotify::Track.retaining_class.should_receive(:from_native).twice do |pointer, context| pointer.read_int end api.should_receive(:sp_playlistcontainer_get_unseen_tracks).twice do |ptr, ptr_playlist, tracks_buffer, tracks_buffer_size| ptr.should eq(container) ptr_playlist.should eq(playlist) if tracks_buffer tracks_buffer.write_array_of_pointer([track_a, track_b]) tracks_buffer_size.should eq(2) end 2 end api.playlistcontainer_get_unseen_tracks(container, playlist).should eq([1337, 7331]) end it "returns an empty array when there are no unseen tracks" do api.should_receive(:sp_playlistcontainer_get_unseen_tracks) do |ptr, playlist, tracks_buffer, tracks_buffer_size| 0 end api.playlistcontainer_get_unseen_tracks(container, playlist).should be_empty end it "returns an empty array on failure" do api.should_receive(:sp_playlistcontainer_get_unseen_tracks) do |ptr, playlist, tracks_buffer, tracks_buffer_size| -1 end api.playlistcontainer_get_unseen_tracks(container, playlist).should be_empty end end end <file_sep>describe Spotify::API do describe ".attach_function" do it "is a retaining class if the method is not creating" do begin Spotify::API.attach_function :whatever, [], Spotify::User rescue FFI::NotFoundError # expected, this method does not exist end $attached_methods["whatever"][:returns].should eq Spotify::User.retaining_class end it "is a non-retaining class if the method is creating" do begin Spotify::API.attach_function :whatever_create, [], Spotify::User rescue FFI::NotFoundError # expected, this method does not exist end $attached_methods["whatever_create"][:returns].should be Spotify::User $attached_methods["whatever_create"][:returns].should_not be Spotify::User.retaining_class end end end <file_sep>describe Spotify do describe "VERSION" do it "is defined" do defined?(Spotify::VERSION).should eq "constant" end it "is the same version as in api.h" do spotify_version = API_H_SRC.match(/#define\s+SPOTIFY_API_VERSION\s+(\d+)/)[1] Spotify::API_VERSION.to_i.should eq spotify_version.to_i end end describe "proxying" do it "responds to the spotify methods" do Spotify.should respond_to :error_message end it "allows creating proxy methods" do api.should_receive(:error_message).and_return("Some error") Spotify.method(:error_message).call.should eq "Some error" end end describe ".log" do it "print nothing if not debugging" do out, err = spy_output do old_debug, $DEBUG = $DEBUG, false Spotify.log "They see me loggin'" $DEBUG = old_debug end out.should be_empty err.should be_empty end it "prints output and path if debugging" do suppress = true out, err = spy_output(suppress) do old_debug, $DEBUG = $DEBUG, true Spotify.log "Testin' Spotify log" $DEBUG = old_debug end out.should match "Testin' Spotify log" out.should match "spec/spotify_spec.rb" err.should be_empty end end describe ".try" do it "raises an error when the result is not OK" do api.should_receive(:error_example).and_return(Spotify::APIError.from_native(5, nil)) expect { Spotify.try(:error_example) }.to raise_error(Spotify::BadApplicationKeyError, /Invalid application key/) end it "does not raise an error when the result is OK" do api.should_receive(:error_example).and_return(nil) Spotify.try(:error_example).should eq nil end it "does not raise an error when the result is not an error-type" do result = Object.new api.should_receive(:error_example).and_return(result) Spotify.try(:error_example).should eq result end it "does not raise an error when the resource is loading" do api.should_receive(:error_example).and_return(Spotify::APIError.from_native(17, nil)) error = Spotify.try(:error_example) error.should be_a(Spotify::IsLoadingError) error.message.should match /Resource not loaded yet/ end end end <file_sep>describe "Spotify::API" do let(:playlist) { double } describe "#playlist_get_image" do let(:image_id) { "v\xE5\xAA\xD3F\xF8\xEE4G\xA1.D\x9C\x85 \xC5\xFD\x80]\x99".force_encoding(Encoding::BINARY) } it "returns the image ID if playlist has an image" do api.should_receive(:sp_playlist_get_image) do |ptr, image_id_pointer| ptr.should eq(playlist) image_id_pointer.write_bytes(image_id) true end api.playlist_get_image(playlist).should eq(image_id) end it "returns nil if playlist has no image" do api.should_receive(:sp_playlist_get_image) do |ptr, image_id_pointer| false end api.playlist_get_image(playlist).should be_nil end end describe "#playlist_add_tracks" do let(:session) { double } let(:track_a) { FFI::MemoryPointer.new(:pointer) } let(:track_b) { FFI::MemoryPointer.new(:pointer) } let(:tracks) { [track_a, track_b] } it "adds an array of tracks to a playlist" do api.should_receive(:sp_playlist_add_tracks) do |ptr, buffer, buffer_size, offset, ptr_session| ptr.should eq(playlist) buffer.read_array_of_pointer(buffer_size).should eq(tracks) offset.should eq(2) ptr_session.should eq(session) :ok end api.playlist_add_tracks(playlist, tracks, 2, session).should eq(:ok) end it "casts a single track to an array" do api.should_receive(:sp_playlist_add_tracks) do |ptr, buffer, buffer_size, offset, ptr_session| buffer.read_array_of_pointer(1).should eq([track_a]) buffer_size.should eq(1) :ok end api.playlist_add_tracks(playlist, track_a, 2, session).should eq(:ok) end end describe "#playlist_remove_tracks" do it "removes tracks from a playlist" do api.should_receive(:sp_playlist_remove_tracks) do |ptr, buffer, buffer_size| ptr.should eq(playlist) buffer.read_array_of_int(buffer_size).should eq([1, 3, 7]) :ok end api.playlist_remove_tracks(playlist, [1, 3, 7]).should eq(:ok) end it "casts a single index to an array" do api.should_receive(:sp_playlist_remove_tracks) do |ptr, buffer, buffer_size| buffer.read_array_of_int(1).should eq([3]) buffer_size.should eq(1) :ok end api.playlist_remove_tracks(playlist, 3).should eq(:ok) end end describe "#playlist_reorder_tracks" do it "reorders tracks from a playlist" do api.should_receive(:sp_playlist_reorder_tracks) do |ptr, buffer, buffer_size, index| ptr.should eq(playlist) buffer.read_array_of_int(buffer_size).should eq([1, 3, 7]) index.should eq(3) :ok end api.playlist_reorder_tracks(playlist, [1, 3, 7], 3).should eq(:ok) end it "casts a single index to an array" do api.should_receive(:sp_playlist_reorder_tracks) do |ptr, buffer, buffer_size, index| buffer.read_array_of_int(1).should eq([7]) buffer_size.should eq(1) :ok end api.playlist_reorder_tracks(playlist, 7, 3).should eq(:ok) end end end <file_sep>describe "Spotify::API" do let(:session) { double } describe "#session_create" do let(:config) do { user_agent: "<PASSWORD>", callbacks: Spotify::SessionCallbacks.new(music_delivery: proc {}) } end let(:session_pointer) { FFI::MemoryPointer.new(:pointer) } it "creates a session with the given configuration" do api.should_receive(:sp_session_create) do |struct_config, ptr_session| struct_config.should be_a(Spotify::SessionConfig) struct_config[:user_agent].should eq("This is a test") struct_config[:callbacks].should be_a(Spotify::SessionCallbacks) ptr_session.write_pointer(session_pointer) :ok end error, session = api.session_create(config) error.should be_nil session.should be_a(Spotify::Session) session.address.should eq(session_pointer.address) end it "returns the error without session on failure" do api.should_receive(:sp_session_create) do |struct_config, ptr_session| :bad_api_version end error, session = api.session_create(config) error.should eq(:bad_api_version) session.should be_nil end end describe "#session_process_events" do it "returns time until session_process_events should be called again" do api.should_receive(:sp_session_process_events) do |ptr, timeout_pointer| ptr.should eq(session) timeout_pointer.write_int(1337) :ok end api.session_process_events(session).should eq(1337) end end describe "#session_remembered_user" do it "returns the name of the remembered user" do api.should_receive(:sp_session_remembered_user).twice do |ptr, string_pointer, string_pointer_size| ptr.should eq(session) string_pointer.write_bytes("BurgeX") if string_pointer 5 end api.session_remembered_user(session).should eq("Burge") end it "returns nil if there is no remembered user" do api.should_receive(:sp_session_remembered_user) do |ptr, string_pointer, string_pointer_size| -1 end api.session_remembered_user(session).should be_nil end end describe "#session_is_scrobbling" do it "returns the scrobbling state" do api.should_receive(:sp_session_is_scrobbling) do |ptr, social_provider, state_pointer| ptr.should eq(session) social_provider.should eq(:spotify) state_pointer.write_int(3) :ok end api.session_is_scrobbling(session, :spotify).should eq(:global_enabled) end end describe "#session_is_scrobbling_possible" do it "returns true if scrobbling is possible" do api.should_receive(:sp_session_is_scrobbling_possible) do |ptr, social_provider, buffer_out| ptr.should eq(session) social_provider.should eq(:spotify) buffer_out.write_char(1) :ok end api.session_is_scrobbling_possible(session, :spotify).should eq(true) end end end <file_sep>describe "Spotify::API" do describe "#track_set_starred" do let(:session) { double } let(:track_a) { FFI::MemoryPointer.new(:pointer) } let(:track_b) { FFI::MemoryPointer.new(:pointer) } let(:tracks) { [track_a, track_b] } it "changes the starred state of the given tracks" do api.should_receive(:sp_track_set_starred) do |ptr, buffer, buffer_size, starred| ptr.should eq(session) buffer.read_array_of_pointer(buffer_size).should eq(tracks) starred.should eq(true) :ok end api.track_set_starred(session, tracks, true).should eq(:ok) end it "automatically casts the second parameter to an array" do api.should_receive(:sp_track_set_starred) do |ptr, buffer, buffer_size, starred| buffer.read_array_of_pointer(1).should eq([track_a]) buffer_size.should eq(1) :ok end api.track_set_starred(session, track_a, true).should eq(:ok) end end end <file_sep>Low-level Ruby bindings for [libspotify][], the official Spotify C API ====================================================================== [![Build Status](https://secure.travis-ci.org/Burgestrand/spotify.png?branch=master)](http://travis-ci.org/Burgestrand/spotify) [![Dependency Status](https://gemnasium.com/Burgestrand/spotify.png)](https://gemnasium.com/Burgestrand/spotify) [![Code Climate](https://codeclimate.com/github/Burgestrand/spotify.png)](https://codeclimate.com/github/Burgestrand/spotify) [![Gem Version](https://badge.fury.io/rb/spotify.png)](http://badge.fury.io/rb/spotify) The libspotify C API package allows third party developers to write applications that utilize the Spotify music streaming service. [Spotify][] is a really nice music streaming service, and being able to interact with it in an API is awesome. libspotify itself is however written in C, making it unavailable or cumbersome to use for many developers. This project aims to allow Ruby developers access to all of the libspotify C API, without needing to reach down to C. However, to use this library to its full extent you will need to learn how to use the Ruby FFI API. The Spotify gem has: - [100% API coverage][], including callback support. You’ll be able to use any function from the libspotify library. - [Automatic garbage collection][]. Piggybacking on Ruby’s GC to manage pointer lifecycle. - [Parallell function call protection][]. libspotify is not thread-safe, but Spotify protects you by making all API calls in a specific background thread. - [Type conversion and type safety][]. Special pointers for every Spotify type, protecting you from accidental mix-ups. - [Support for Ruby, JRuby and Rubinius][]. Thanks to FFI, the gem runs fine on the main three Ruby implementations! [100% API coverage]: http://rdoc.info/github/Burgestrand/spotify/master/Spotify/API [Automatic garbage collection]: http://rdoc.info/github/Burgestrand/spotify/master/Spotify/ManagedPointer [Parallell function call protection]: http://rdoc.info/github/Burgestrand/spotify/master/Spotify#method_missing-class_method [Type conversion and type safety]: http://rdoc.info/github/Burgestrand/spotify/master/Spotify/ManagedPointer [Support for Ruby, JRuby and Rubinius]: https://github.com/Burgestrand/spotify/blob/master/.travis.yml Contact details --------------- - __Got questions?__ Ask on the mailing list: [<EMAIL>][] (<https://groups.google.com/d/forum/ruby-spotify>) - __Found a bug?__ Report an issue: <https://github.com/Burgestrand/spotify/issues/new> - __Have feedback?__ I ❤ feedback! Please send it to the mailing list. Questions, notes and answers ---------------------------- ### Links to keep close at hand when using libspotify - [spotify gem API reference](http://rdoc.info/github/Burgestrand/spotify/master/Spotify/API) — YARDoc reference for the spotify gem, maps to the [libspotify function list](https://developer.spotify.com/docs/libspotify/12.1.51/api_8h.html). - [libspotify C API reference](https://developer.spotify.com/docs/libspotify/12.1.51/) — the one true source of documentation. - [libspotify FAQ](https://developer.spotify.com/technologies/libspotify/faq/) — you should read this at least once. - [spotify gem examples](https://github.com/Burgestrand/spotify/tree/master/examples) — located in the spotify gem repository. - [spotify gem FAQ](#questions-notes-and-answers) — this README section. ### How to run the examples You’ll need: 1. Your [Spotify](http://spotify.com/) premium account credentials. If you sign in with Facebook, you’ll need your Facebook account e-mail and password. 2. Your [Spotify application key](https://developer.spotify.com/technologies/libspotify/keys/). Download the binary key, and put it in the `examples/` directory. Running the examples is as simple as: ``` ruby example-audio_stream.rb ``` Available examples are: - **example-audio_stream.rb**: plays songs from Spotify with the [plaything](https://github.com/Burgestrand/plaything) gem, using OpenAL. - **example-console.rb**: logs in to Spotfify, and initiates a pry session to allow experimentation with the spotify gem API. - **example-listing_playlists.rb**: list all playlists available for a certain user. - **example-loading_object.rb**: loads a track using polling and the spotify gem API. - **example-random_related_artists.rb**: looks up an artist and its similar artists on spotify, then it picks a similar artist at random and does the same to that artist, over and over. I have used this example file to test prolonged usage of the API. ### Creating a Session, the first thing you should do Almost all functions require you to have created a session before calling them. Forgetting to do so won’t work at best, and will segfault at worst. You'll also want to log in before doing things as well, or objects will never load. See [Spotify::API#session_create](http://rdoc.info/github/Burgestrand/spotify/master/Spotify/API#session_create-instance_method) for how to create a session. See [Spotify::API#session_login](http://rdoc.info/github/Burgestrand/spotify/master/Spotify/API#session_login-instance_method) for logging in. ### libspotify is an asynchronous library When creating objects in libspotify they are not populated with data instantly, instead libspotify schedules them for download from the Spotify backend. For libspotify to do it's work with downloading content, you need to call [Spotify::API#session_process_events](http://rdoc.info/github/Burgestrand/spotify/master/Spotify/API#session_process_events-instance_method) regularly. ### Facebook vs Spotify Classic Users who signed up to Spotify with their Facebook account will have numeric IDs as usernames, so a link to their profile looks like [spotify:user:11101648092](spotify:user:11101648092). Spotify Classic users instead have their usernames as canonical name, so a link to their profile looks like [spotify:user:burgestrand](spotify:user:burgestrand). This matters, for example, when you use the function [Spotify::API#session_publishedcontainer_for_user_create](http://rdoc.info/github/Burgestrand/spotify/master/Spotify/API#session_publishedcontainer_for_user_create-instance_method). ### Callbacks can be dangerous libspotify allows you to pass callbacks that will be invoked by libspotify when events of interest occur, such as being logged out, or receiving audio data when playing a track. Callbacks can be very tricky. They must never be garbage collected while they are in use by libspotify, or you may get very weird bugs with your Ruby interpreter randomly crashing. Do use them, but be careful. ### Opinions and the Spotify gem The Spotify gem has very few opinions. It is build to closely resemble the libspotify C API, and has very little to aid you in terms of how to structure your application. It aims to make calling the libspotify C API frictionless, but not much more. It is up to you to decide your own path. ### A note about gem versioning Given a version `X.Y.Z`, each segment corresponds to: - `X` reflects supported libspotify version (12.1.45 => 12). There are __no guarantees__ of backwards-compatibility! - `Y` is for backwards-**incompatible** changes. - `Z` is for backwards-**compatible** changes. You should use the following version constraint: `gem "spotify", "~> 12.5.3"`. ### Manually installing libspotify By default, Spotify uses [the libspotify gem](https://rubygems.org/gems/libspotify) which means you do not need to install libspotify yourself. However, if your platform is not supported by the libspotify gem you will need to install libspotify yourself. Please note, that if your platform is not supported by the libspotify gem I’d very much appreciate it if you could create an issue on [libspotify gem issue tracker](https://github.com/Burgestrand/libspotify/issues) so I can fix the build for your platform. Instructions on installing libspotify manually are in the wiki: [How to install libspotify](https://github.com/Burgestrand/spotify/wiki) [semantic versioning (semver.org)]: http://semver.org/ [<EMAIL>]: mailto:<EMAIL> [libspotify]: https://developer.spotify.com/technologies/libspotify/ [Spotify]: https://www.spotify.com/ [Hallon]: https://github.com/Burgestrand/Hallon
12c64befc08d3675a12d451b2ba75b57b369a275
[ "Markdown", "Ruby" ]
12
Ruby
victhevenot/spotify
4fbb16d212f8aee0e0fdd5b18b17f09b8e1a743b
f5415a43cb55bed6bbcc90a919a028aded37e421
refs/heads/master
<file_sep>#pragma once class AFD { }; <file_sep>#include "AFD.h" #include <fstream> #include<tuple> #include<iostream> #include<string> AFD AFD::CitireDinFisier(const std::string& Fisier) { int Contor1, Contor2, Contor3, Contor4; std::string Aux, Aux1, Aux2; std::ifstream Fis(Fisier); std::vector<std::string> stari; std::vector<std::string> sigma; std::vector<std::tuple<std::string, std::string, std::string>> delta; std::string stareInit; std::vector<std::string> stariFinale; while (!Fis.eof()) { //Citim Stari Fis >> Contor1 >> Contor2 >> Contor3 >> Contor4; for (int i = 0; i < Contor1; i++) { Fis >> Aux; stari.emplace_back(Aux); } //Citim Sigma for (int i = 0; i < Contor2; i++) { Fis >> Aux; sigma.emplace_back(Aux); } //Citim Delta for (int i = 0; i < Contor3; i++) { Fis >> Aux >> Aux1 >> Aux2; delta.emplace_back(std::make_tuple(Aux, Aux1, Aux2)); } //Citim StareInit Fis >> stareInit; //Cotim starile finale for (int i = 0; i < Contor4; i++) { Fis >> Aux; stariFinale.emplace_back(Aux); } } return AFD(stari, sigma, delta, stareInit, stariFinale); } void AFD::ScrieInFisier(const std::string& Fisier) { std::ofstream myFile; myFile.open(Fisier); myFile.clear(); myFile << "Stari: "; for (int i = 0; i < m_stari.size(); i++) myFile << m_stari[i] << " "; myFile << std::endl; myFile << "Sigma: "; for (int i = 0; i < m_sigma.size(); i++) myFile << m_sigma[i] << " "; myFile << std::endl; myFile << "Delta: "; for (int i = 0; i < m_delta.size(); i++) myFile << "\n" << std::get<0>(m_delta[i]) << " " << std::get<1>(m_delta[i]) << " " << std::get<2>(m_delta[i]); myFile << std::endl; myFile << "Stare Initiala: " << m_stareInit << "\n"; myFile << "Stari Finale: "; for (int i = 0; i < m_stariFinale.size(); i++) myFile << m_stariFinale[i] << " "; myFile << std::endl; myFile.close(); } void AFD::Afisare() { std::cout << "Stari: "; for (int i = 0; i < m_stari.size(); i++) std::cout << m_stari[i] << " "; std::cout << std::endl; std::cout << "Sigma: "; for (int i = 0; i < m_sigma.size(); i++) std::cout << m_sigma[i] << " "; std::cout << std::endl; std::cout << "Delta: "; for (int i = 0; i < m_delta.size(); i++) std::cout << "\n" << std::get<0>(m_delta[i]) << " " << std::get<1>(m_delta[i]) << " " << std::get<2>(m_delta[i]); std::cout << std::endl; std::cout << "Stare Initiala: " << m_stareInit << "\n"; std::cout << "Stari Finale: "; for (int i = 0; i < m_stariFinale.size(); i++) std::cout << m_stariFinale[i] << " "; std::cout << std::endl; } std::string AFD::VerificareCuvant(std::string Cuvant) { std::string stareCurenta = m_stareInit; for (int i = 0; i < Cuvant.size(); i++) { bool State = false; for (int j = 0; j < m_delta.size(); j++) { if (stareCurenta == std::get<0>(m_delta[j]) && Cuvant[i] == std::get<1>(m_delta[j])[0]) { stareCurenta = std::get<2>(m_delta[j]); State = true; break; } } if (State == false) { return"Blocaj\n"; } } for (int i = 0; i < m_stariFinale.size(); i++) if (stareCurenta == m_stariFinale[i]) return "Cuvant Acceptat\n"; return "Cuvant Neacceptat\n"; } void AFD::Minimizare() { //Starea e finala sau nefinala; std::vector<std::vector<int>> tabel; std::vector<bool> finalSauNefinal; bool finsauNefin; for (int i = 0; i < m_stari.size(); i++) { finsauNefin = false; for (int j = 0; j < m_stariFinale.size(); j++) if (m_stari[i] == m_stariFinale[j]) finsauNefin = true; if (finsauNefin == true) finalSauNefinal.emplace_back(true); else finalSauNefinal.emplace_back(false); } //Am creeat tabelul for (int i = 0; i < m_stari.size(); i++) { tabel.emplace_back(i); for (int j = 0; j < i + 1; j++); if (tabel.size() - 1 == i) tabel[i].emplace_back(i); else tabel[i].emplace_back(0); } //Completam prima etapa a tabelului for (int i = 0; i < tabel.size(); i++) for (int j = 0; j < tabel[i].size() - 1; j++) { if ((finalSauNefinal[j] == true && finalSauNefinal[i] == false) || (finalSauNefinal[j] == false && finalSauNefinal[i] == true)) { tabel[i][j] = -2; } } bool incaOParcugere = true; std::vector<bool> ExistaCale; for (int i = 0; i < m_sigma.size(); i++) ExistaCale.emplace_back(false); while (incaOParcugere == true) { incaOParcugere = false; for (int i = 0; i < tabel.size(); i++) for (int j = 0; j < tabel[i].size() - 1; j++) { std::string oStare = ""; std::string altaStare = ""; bool boolOStare = false; bool boolAltaStare = false; if (tabel[i][j] == 0) { for (int w = 0; w < m_sigma.size(); w++) { oStare = ""; altaStare = ""; boolOStare = false; boolAltaStare = false; for (int z = 0; z < m_delta.size(); z++) { if (std::get<0>(m_delta[z]) == m_stari[j] && std::get<1>(m_delta[z]) == m_sigma[w]) { oStare = std::get<2>(m_delta[z]); boolOStare = true; } if (std::get<0>(m_delta[z]) == m_stari[i] && std::get<1>(m_delta[z]) == m_sigma[w]) { altaStare = std::get<2>(m_delta[z]); boolAltaStare = true; } } if ((oStare != altaStare) && (boolOStare == true) && (boolAltaStare == true)) { int coord1; int coord2; for (int k = 0; k < m_stari.size(); k++) { if (oStare == m_stari[k]) coord1 = k; if (altaStare == m_stari[k]) coord2 = k; } if (coord1 < coord2) std::swap(coord1, coord2); if (tabel[coord1][coord2] == -2) { tabel[i][j] = -2; incaOParcugere = true; } } } } } } std::vector<std::pair<int,int>> stariNemarcate; for(int i=0;i<tabel.size();i++) for (int j = 0; j < tabel[i].size()-1; j++) { if (tabel[i][j] == 0) stariNemarcate.emplace_back(std::make_pair(j, i)); } for (int i = 0; i < stariNemarcate.size(); i++) std::cout << "\nPerechile nemarcate sunt: " << m_stari[stariNemarcate[i].first]<<" "<<m_stari[stariNemarcate[i].second]<<std::endl; std::system("pause"); for (int i = 0; i < stariNemarcate.size(); i++) { //m_delta for (int j = 0; j < m_delta.size(); j++) { if ((std::get<0>(m_delta[j]) == m_stari[stariNemarcate[i].first]) || (std::get<0>(m_delta[j]) == m_stari[stariNemarcate[i].second])) { std::get<0>(m_delta[j])[0] = 'P'; } if ((std::get<2>(m_delta[j]) == m_stari[stariNemarcate[i].first]) || (std::get<2>(m_delta[j]) == m_stari[stariNemarcate[i].second])) { std::get<2>(m_delta[j])[0] = 'P'; } } //o singura stare std::string ramaneOStare; for (int j = 0; j < m_delta.size(); j++) { if (std::get<0>(m_delta[j])[0] == 'P') { ramaneOStare = std::get<0>(m_delta[j]); break; } if (std::get<2>(m_delta[j])[0] == 'P') { ramaneOStare = std::get<2>(m_delta[j]); break; } } //remodificam m_delta for (int j = 0; j < m_delta.size(); j++) { if (std::get<0>(m_delta[j])[0] == 'P') std::get<0>(m_delta[j])=ramaneOStare; if (std::get<2>(m_delta[j])[0] == 'P') std::get<2>(m_delta[j])=ramaneOStare; } //m_stariFinale for (int j = 0; j <m_stariFinale.size(); j++) if ((m_stariFinale[j] == m_stari[stariNemarcate[i].first]) || (m_stariFinale[j] == m_stari[stariNemarcate[i].second])) { m_stariFinale[j][0] = 'P'; } for (int j = 0; j < m_stariFinale.size(); j++) if (m_stariFinale[j][0] == 'P') { ramaneOStare = m_stariFinale[j]; break; } for (int j = 0; j < m_stariFinale.size(); j++) if (m_stariFinale[j][0] == 'P') { m_stariFinale[j] = ramaneOStare; } //m_stari for (int j = 0; j < m_stari.size(); j++) if ((m_stari[j] == m_stari[stariNemarcate[i].first]) || (m_stari[j] == m_stari[stariNemarcate[i].second])) { m_stari[j][0] = 'P'; } for (int j = 0; j < m_stari.size(); j++) if (m_stari[j][0] == 'P') { ramaneOStare = m_stari[j]; break; } for (int j = 0; j < m_stari.size(); j++) if (m_stari[j][0] == 'P') { m_stari[j]=ramaneOStare; } // //Schimbam litera ca sa mearga si la urmatoarele parcurgeri for (int j = 0; j < m_stari.size(); j++) if (m_stari[j][0] == 'P') m_stari[j][0] = 'A'; for (int j = 0; j < m_delta.size(); j++) { if (std::get<0>(m_delta[j])[0] == 'P') std::get<0>(m_delta[j])[0] = 'A'; if (std::get<2>(m_delta[j])[0] == 'P') std::get<2>(m_delta[j])[0] = 'A'; } for (int j = 0; j < m_stariFinale.size(); j++) if (m_stariFinale[j][0] == 'P') m_stariFinale[j][0] = 'A'; } for(int i=0;i<m_stari.size()-1;i++) for (int j = 1; j < m_stari.size(); j++) { if (m_stari[i] == m_stari[j]&&i!=j) m_stari.erase(m_stari.begin() + j); } for(int i=0;i<m_delta.size()-1;i++) for (int j = 1; j < m_delta.size(); j++) { if (m_delta[i] == m_delta[j] && i != j) m_delta.erase(m_delta.begin() + j); } for (int i = 0; i < m_stariFinale.size() - 1; i++) for (int j = 1; j < m_stariFinale.size(); j++) { if (m_stariFinale[i] == m_stariFinale[j] && i != j) m_stariFinale.erase(m_stariFinale.begin() + j); } for (int i = 0; i < m_delta.size(); i++) { std::get<0>(m_delta[i])[0] = 'P'; std::get<2>(m_delta[i])[0] = 'P'; } for (int i = 0; i < m_stari.size(); i++) m_stari[i][0] = 'P'; for (int i = 0; i < m_stariFinale.size(); i++) m_stariFinale[i][0] = 'P'; m_stareInit[0] = 'P'; } void AFD::EliminareStariNeaccesibile() { std::vector<bool> caleVizitata; for (int i = 0; i < m_delta.size(); i++) caleVizitata.emplace_back(false); std::vector<std::pair<std::string, bool>> stariVizitate; for (int i = 0; i < m_stari.size(); i++) stariVizitate.emplace_back(std::make_pair(m_stari[i], false)); bool oSchimbare = true; bool maiFacemOparcurgere = false; int lastIndex; std::string stareCurenta = m_stareInit; while (oSchimbare == true) { oSchimbare = false; for (int i = 0; i < m_delta.size(); i++) { if (std::get<0>(m_delta[i]) == stareCurenta) if (caleVizitata[i] == false) { oSchimbare = true; maiFacemOparcurgere = true; stareCurenta = std::get<2>(m_delta[i]); for (int j = 0; j < stariVizitate.size(); j++) if (stariVizitate[j].first == stareCurenta) stariVizitate[j].second = true; lastIndex = i; } if (i >= m_delta.size() - 1 && maiFacemOparcurgere == true) { caleVizitata[lastIndex] = true; i = 0; stareCurenta = m_stareInit; maiFacemOparcurgere = false; } } } for (int i = 0; i < stariVizitate.size(); i++) if (stariVizitate[i].second == false && stariVizitate[i].first != m_stareInit) { for (int j = 0; j < m_delta.size(); j++) if (stariVizitate[i].first == std::get<0>(m_delta[j])) { m_delta.erase(m_delta.begin() + j); j = 0; } for (int j = 0; j < m_stari.size(); j++) if (stariVizitate[i].first == m_stari[j]) m_stari.erase(m_stari.begin() + j); } } void AFD::Menu(AFD UnAFD, AFD AltAFD) { int Optiune; while (1) { system("CLS"); UnAFD.Afisare(); std::cout << "SELECTEAZA UNA DINTRE URMATOARELE OPTIUNI\n1)Verificare Cuvant\n2)Minimizare\n3)Verificare Cuvant cu AFD-ul Minimizat\n4)Parasire Aplicatie\n"; std::cin >> Optiune; std::string Cuvant; switch (Optiune) { case 1: std::cout << "Introduceti un cuvant\n"; std::cin >> Cuvant; Cuvant = UnAFD.VerificareCuvant(Cuvant); std::cout << Cuvant; system("pause"); break; case 2: AltAFD.Minimizare(); AltAFD.ScrieInFisier("FisierOut.txt"); std::cout << "Afd-ul minimizat a fost scris in fisierul (FisierOut)"; system("pause"); break; case 3: AltAFD.Minimizare(); std::cout << "Introduceti un cuvant\n"; std::cin >> Cuvant; Cuvant = AltAFD.VerificareCuvant(Cuvant); std::cout << Cuvant; system("pause"); break; } if (Optiune == 4) break; if (Optiune != 1 && Optiune != 2&&Optiune!=3) { std::cout << "Optiunea nu exista! Introduceti o optiune valida"; system("pause"); } } } <file_sep>#include<iostream> #include"AFD.h" int main() { AFD UnAFD = UnAFD.CitireDinFisier("Automat finit File.txt"); AFD AltAFD = AltAFD.CitireDinFisier("Automat finit File.txt"); AltAFD.EliminareStariNeaccesibile(); UnAFD.Menu(UnAFD,AltAFD); return 0; }<file_sep>#include<iostream> #include"Gramatica.h" #include<ctime> int main() { srand(time(0)); Gramatica gamaticaCurenta = gamaticaCurenta.Citire_Fisier("FisierGramatica.txt"); bool state=gamaticaCurenta.Verificare(); gamaticaCurenta.Afisare(); if (state == true) { gamaticaCurenta.Generare(); } else { std::cout << "Gramatica este gresita"; } system("pause"); return 0; } <file_sep>#pragma once #include<string> #include<vector> class AFN { private: std::vector<std::string> m_stari; std::vector<std::string> m_sigma; std::vector<std::pair<std::pair<std::string, std::string>, std::string>> m_delta; std::string m_stareInit; std::vector<std::string> m_stariFinale; std::vector<bool> m_stariAccesibile_Bool; public: AFN(std::vector<std::string> stari, std::vector<std::string> sigma, std::vector<std::pair<std::pair<std::string, std::string>, std::string>> delta, std::string stareInit, std::vector<std::string> stariFinale,std::vector<bool> stariAccesibile_Bool) : m_stari(stari), m_sigma(sigma), m_delta(delta), m_stareInit(stareInit), m_stariFinale(stariFinale), m_stariAccesibile_Bool(stariAccesibile_Bool) { } AFN CitireDinFisier(const std::string& Fisier); void Afisare(); std::string VerificareCuvant(std::string Cuvant); void Menu(AFN UnAFD); }; <file_sep>#include "AFD.h" <file_sep>#pragma once #include<vector> #include<string> class AFD { private: std::vector<std::string> m_stari; std::vector<std::string> m_sigma; std::vector<std::pair<std::pair<std::string,std::string>,std::string>> m_delta; std::string m_stareInit; std::vector<std::string> m_stariFinale; public: AFD(std::vector<std::string> stari, std::vector<std::string> sigma, std::vector<std::pair<std::pair<std::string, std::string>, std::string>> delta, std::string stareInit, std::vector<std::string> stariFinale) : m_stari(stari), m_sigma(sigma), m_delta(delta), m_stareInit(stareInit), m_stariFinale(stariFinale) { } AFD CitireDinFisier(const std::string& Fisier); void Afisare(); std::string VerificareCuvant(std::string Cuvant); void Menu(AFD UnAFD); }; <file_sep>#include"AFN.h" int main() { AFN UnAFN = UnAFN.CitireDinFisier("Automat finit Ned.txt"); UnAFN.Menu(UnAFN); //1 UnAFN.Afisare(); return 0; }<file_sep>#include "AFN.h" #include<fstream> #include<iostream> #include<stack> AFN AFN::CitireDinFisier(const std::string& Fisier) { int Contor1, Contor2, Contor3, Contor4; std::string Aux, Aux1, Aux2; std::ifstream Fis(Fisier); std::vector<std::string> stari; std::vector<std::string> sigma; std::vector<std::pair<std::pair<std::string, std::string>, std::string>> delta; std::string stareInit; std::vector<std::string> stariFinale; std::vector<bool>stariAccesibile_Bool; //Citim Stari Fis >> Contor1 >> Contor2 >> Contor3 >> Contor4; for (int i = 0; i < Contor1; i++) { Fis >> Aux; stari.emplace_back(Aux); } //Citim Sigma for (int i = 0; i < Contor2; i++) { Fis >> Aux; sigma.emplace_back(Aux); } //Citim Delta for (int i = 0; i < Contor3; i++) { Fis >> Aux >> Aux1 >> Aux2; delta.emplace_back(std::make_pair(std::make_pair(Aux, Aux1), Aux2)); } //Citim StareInit Fis >> stareInit; //Cotim starile finale for (int i = 0; i < Contor4; i++) { Fis >> Aux; stariFinale.emplace_back(Aux); } for (int i = 0; i < delta.size(); i++) { stariAccesibile_Bool.push_back(true); } return AFN(stari, sigma, delta, stareInit, stariFinale, stariAccesibile_Bool); } void AFN::Afisare() { std::cout << "Stari: "; for (int i = 0; i < m_stari.size(); i++) std::cout << m_stari[i] << " "; std::cout << std::endl; std::cout << "Sigma: "; for (int i = 0; i < m_sigma.size(); i++) std::cout << m_sigma[i] << " "; std::cout << std::endl; std::cout << "Delta: "; for (int i = 0; i < m_delta.size(); i++) std::cout << "\n" << m_delta[i].first.first << " " << m_delta[i].first.second << " " << m_delta[i].second; std::cout << std::endl; std::cout << "Stare Initiala: " << m_stareInit << "\n"; std::cout << "Stari Finale: "; for (int i = 0; i < m_stariFinale.size(); i++) std::cout << m_stariFinale[i] << " "; std::cout << std::endl; } std::string AFN::VerificareCuvant(std::string Cuvant) { while (1) { bool Again = false; int Contor = 0; std::string stareCurenta = m_stareInit; int i = 0; int LastWay = -1; for (i; i < Cuvant.size(); i++) { bool State = false; for (int j = 0; j < m_delta.size(); j++) { if (m_stariAccesibile_Bool[j] == true) { if (stareCurenta == m_delta[j].first.first && Cuvant[i] == m_delta[j].first.second[0]) { Contor++; State = true; } } } if (State == true) { for (int j = 0; j < m_delta.size(); j++) { if (m_stariAccesibile_Bool[j] == true) { if (stareCurenta == m_delta[j].first.first && Cuvant[i] == m_delta[j].first.second[0]) { stareCurenta = m_delta[j].second; LastWay = j; break; } } } } if (State == false && Contor <= i) { return"Blocaj\n"; } if (State == false && Contor >= i) { m_stariAccesibile_Bool[LastWay] = false; Again=true; } } if (Again == false) { for (int z = 0; z < m_stariFinale.size(); z++) if (stareCurenta == m_stariFinale[z]) return "Cuvant Acceptat\n"; } if (Contor > i) Again=true; if (Again == false) { for (int z = 0; z < m_stariAccesibile_Bool.size(); z++) m_stariAccesibile_Bool[i] = true; return "Cuvant Neacceptat\n"; } } } void AFN::Menu(AFN UnAFN) { std::string Optiune = ""; while (1) { system("CLS"); UnAFN.Afisare(); std::cout << "SELECTEAZA UNA DINTRE URMATOARELE OPTIUNI\n1)Verificare Cuvant\n2)Parasire Aplicatie\n"; std::cin >> Optiune; if (Optiune == "2") break; if (Optiune != "1") { std::cout << "Optiunea nu exista! Introduceti o optiune valida"; system("pause"); } else { std::cout << "Introduceti un cuvant\n"; std::string Cuvant; std::cin >> Cuvant; Cuvant = VerificareCuvant(Cuvant); std::cout << Cuvant; system("pause"); } } } <file_sep>#pragma once #include<vector> #include<string> #include<tuple> class AFD { private: std::vector<std::string> m_stari; std::vector<std::string> m_sigma; std::vector<std::tuple<std::string, std::string, std::string>> m_delta; std::string m_stareInit; std::vector<std::string> m_stariFinale; protected: void Afisare(); std::string VerificareCuvant(std::string Cuvant); void Minimizare(); public: AFD(std::vector<std::string> stari, std::vector<std::string> sigma, std::vector<std::tuple<std::string, std::string, std::string>> delta, std::string stareInit, std::vector<std::string> stariFinale) : m_stari(stari), m_sigma(sigma), m_delta(delta), m_stareInit(stareInit), m_stariFinale(stariFinale) { } AFD CitireDinFisier(const std::string& Fisier); void ScrieInFisier(const std::string& Fisier); void Menu(AFD UnAFD, AFD AltAFD); void EliminareStariNeaccesibile(); }; <file_sep>#pragma once #include<iostream> #include<string> #include<vector> #include<fstream> class Gramatica { private: std::string m_neterminale; std::string m_terminale; std::string m_start; std::vector<std::pair<std::string, std::string>> m_productii; public: Gramatica(std::string neterminale, std::string terminale, std::string start, std::vector<std::pair<std::string, std::string>> productii) : m_neterminale(neterminale), m_terminale(terminale), m_start(start), m_productii(productii) { } Gramatica Citire_Fisier(const std::string& filename); bool Verificare(); void Afisare(); void Generare(); }; <file_sep>#include<iostream> #include"AFD.h" int main() { AFD UnAFD = UnAFD.CitireDinFisier("Automat finit File.txt"); UnAFD.Menu(UnAFD); return 0; }<file_sep>#include "Gramatica.h" #include<ctime> Gramatica Gramatica::Citire_Fisier(const std::string& filename) { std::ifstream FisierGramatica(filename); std::string neterminale; std::string terminale; std::string start; std::vector<std::pair<std::string, std::string>> productii; std::pair<std::string, std::string> Regula; FisierGramatica >> neterminale >> terminale >> start; while (!FisierGramatica.eof()) { FisierGramatica >> Regula.first >> Regula.second; productii.emplace_back(Regula); } return Gramatica(neterminale, terminale, start, productii); } bool Gramatica::Verificare() { #pragma region Step 1 Elementele din VN nu se afla in VT for (int i = 0; i < m_neterminale.size(); i++) for (int j = 0; j < m_terminale.size(); j++) if (m_neterminale[i] == m_terminale[j]) return false; #pragma endregion #pragma region Step 2 S se afla in VN; for (int i = 0; i < m_start.size(); i++) if (m_neterminale.find(m_start[i]) == std::string::npos) return false; #pragma endregion #pragma region Step 3 Pentru fiecare regula se afla cel putin un neterminal for (int i = 0; i < m_productii.size(); i++) { bool State = false; for (int j = 0; j < m_productii[i].first.size(); j++) if (m_neterminale.find(m_productii[i].first[j]) != std::string::npos) State = true; if (State == false) return false; } #pragma endregion #pragma region Step 4 Exista cel putin o productie care are in stanga doar S bool State = false; for (int i = 0; i < m_productii.size(); i++) if (m_productii[i].first == m_start) State = true; if (State == false) return false; #pragma endregion #pragma region Step 5 Fiecare productie contine doar elemente din VN si VT for (int i = 0; i < m_productii.size(); i++) { for (int j = 0; j < m_productii[i].first.size(); j++) if (m_neterminale.find(m_productii[i].first[j]) == std::string::npos && m_terminale.find(m_productii[i].first[j]) == std::string::npos) return false; for (int j = 0; j < m_productii[i].second.size(); j++) if (m_neterminale.find(m_productii[i].second[j]) == std::string::npos && m_terminale.find(m_productii[i].second[j]) == std::string::npos) return false; } #pragma endregion return true; } void Gramatica::Afisare() { std::cout << "Neterminale:"; for (int i = 0; i < m_neterminale.size(); i++) std::cout << " " << m_neterminale[i]; std::cout << std::endl; std::cout << "Terminale:"; for (int i = 0; i < m_terminale.size(); i++) std::cout << " " << m_terminale[i]; std::cout << std::endl; std::cout << "Start: " << m_start << std::endl; std::cout << "Productii:"; for (int i = 0; i < m_productii.size(); i++) { std::cout << std::endl << m_productii[i].first << "-->" << m_productii[i].second; } std::cout << std::endl; } void Gramatica::Generare() { std::cout << "Introduceti numarul de cuvinte care sa fie generate: "; int Nr; std::cin >> Nr; std::cout << "\nIntroduceti 1 pentru afisarea pasilor intermediari si 0 pentru afisare succinta: "; int Opt; std::cin >> Opt; std::vector<std::pair<std::string,std::string>> applicableRules; for (int i = 0; i < Nr; i++) { std::string currentWord = m_start; std::cout << m_start; bool loopCondition = true; while (loopCondition==true) { applicableRules.clear(); for (int j = 0; j < m_productii.size(); j++) { if (currentWord.find(m_productii[j].first) != std::string::npos) { applicableRules.push_back(m_productii[j]); } } if (applicableRules.empty() == true) { loopCondition = false; if (Opt == 0) std::cout << "-->" << currentWord << std::endl; else std::cout<<std::endl; } else { int randomRule_Number = rand() % applicableRules.size(); int index = currentWord.find(applicableRules[randomRule_Number].first); currentWord.replace(index, applicableRules[randomRule_Number].first.size(), applicableRules[randomRule_Number].second); if (Opt == 1) std::cout << "-->" << currentWord; } } } } <file_sep>#include "AFD.h" #include <fstream> #include<tuple> #include<iostream> #include<string> AFD AFD::CitireDinFisier(const std::string& Fisier) { int Contor1, Contor2, Contor3, Contor4; std::string Aux, Aux1, Aux2; std::ifstream Fis(Fisier); std::vector<std::string> stari; std::vector<std::string> sigma; std::vector<std::pair<std::pair<std::string, std::string>, std::string>> delta; std::string stareInit; std::vector<std::string> stariFinale; while (!Fis.eof()) { //Citim Stari Fis >> Contor1 >> Contor2 >> Contor3 >> Contor4; for (int i = 0; i < Contor1; i++) { Fis >> Aux; stari.emplace_back(Aux); } //Citim Sigma for (int i = 0; i < Contor2; i++) { Fis >> Aux; sigma.emplace_back(Aux); } //Citim Delta for (int i = 0; i < Contor3; i++) { Fis >> Aux >> Aux1 >> Aux2; delta.emplace_back(std::make_pair(std::make_pair(Aux, Aux1), Aux2)); } //Citim StareInit Fis >> stareInit; //Cotim starile finale for (int i = 0; i < Contor4; i++) { Fis >> Aux; stariFinale.emplace_back(Aux); } } return AFD(stari, sigma, delta, stareInit, stariFinale); } void AFD::Afisare() { std::cout << "Stari: "; for (int i = 0; i < m_stari.size(); i++) std::cout << m_stari[i] << " "; std::cout << std::endl; std::cout << "Sigma: "; for (int i = 0; i < m_sigma.size(); i++) std::cout << m_sigma[i] << " "; std::cout << std::endl; std::cout << "Delta: "; for (int i = 0; i < m_delta.size(); i++) std::cout << "\n" << m_delta[i].first.first << " " << m_delta[i].first.second << " " << m_delta[i].second; std::cout << std::endl; std::cout << "Stare Initiala: " << m_stareInit << "\n"; std::cout << "Stari Finale: "; for (int i = 0; i < m_stariFinale.size(); i++) std::cout << m_stariFinale[i] << " "; std::cout << std::endl; } std::string AFD::VerificareCuvant(std::string Cuvant) { std::string stareCurenta = m_stareInit; for (int i = 0; i < Cuvant.size(); i++) { bool State = false; for (int j = 0; j < m_delta.size(); j++) { if (stareCurenta == m_delta[j].first.first && Cuvant[i] == m_delta[j].first.second[0]) { stareCurenta = m_delta[j].second; State = true; break; } } if (State == false) { return"Blocaj\n"; } } for (int i = 0; i < m_stariFinale.size(); i++) if (stareCurenta == m_stariFinale[i]) return "Cuvant Acceptat\n"; return "Cuvant Neacceptat\n"; } void AFD::Menu(AFD UnAFD) { std::string Optiune = ""; while (1) { system("CLS"); UnAFD.Afisare(); std::cout << "SELECTEAZA UNA DINTRE URMATOARELE OPTIUNI\n1)Verificare Cuvant\n2)Parasire Aplicatie\n"; std::cin >> Optiune; if (Optiune == "2") break; if (Optiune != "1") { std::cout << "Optiunea nu exista! Introduceti o optiune valida"; system("pause"); } else { std::cout << "Introduceti un cuvant\n"; std::string Cuvant; std::cin >> Cuvant; Cuvant = VerificareCuvant(Cuvant); std::cout << Cuvant; system("pause"); } } }
4698707f5f1ee4ba1e23fd919fe86763da7c6934
[ "C++" ]
14
C++
Theodorx/LFC
079a49e2a089f103071e0168f6f6d3204acad397
51053ff34a1a56bebff2bc5e63cb4716d84d612c
refs/heads/mac
<file_sep>Install brew ``` /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` Install zsh and oh-my-zsh ``` sudo apt-get install zsh sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" ``` Install missing plugins for zsh ``` git clone https://github.com/zsh-users/zsh-autosuggestions ~/.oh-my-zsh/custom/plugins/zsh-autosuggestions git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ~/.oh-my-zsh/custom/plugins/zsh-syntax-highlighting ``` Then logout to make zsh default shell. Install tmux and tmux plugin manager ``` brew install tmux git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm ``` Connect dot files via symlinks ``` source symlink_config_files.sh ``` And then ``` # type this in terminal if tmux is already running $ tmux source ~/.tmux.conf ``` Install nvm ``` curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash ``` Install clipboard manager ``` https://apps.apple.com/pk/app/copyclip-clipboard-history/id595191960?mt=12 ``` Install plugin for internet bandwidth monitor ``` https://apps.apple.com/pk/app/bandwidth/id490461369?mt=12 ``` Install vim-anywhere ``` brew install --cask macvim curl -fsSL https://raw.github.com/cknadler/vim-anywhere/master/install | bash ``` Install stoic thoughts, library at: ``` url = https://github.com/SargeKhan/stoic-thoughts ``` Install neovim: ``` brew install neovim ``` Ensure .vim and nvim use the same config ``` mkdir -p .config/nvim/init.vim ``` and put this in the file ``` set runtimepath^=~/.vim runtimepath+=~/.vim/after let &packpath=&runtimepath source ~/.vimrc ``` <file_sep># If you come from bash you might have to change your $PATH. # export PATH=$HOME/bin:/usr/local/bin:$PATH # Path to your oh-my-zsh installation. export ZSH=$HOME/.oh-my-zsh # export ANDROID_HOME=$HOME/Android/Sdk # export JAVA_HOME=$HOME/work/android-studio/jre export PATH=$PATH:$ANDROID_HOME/emulator export PATH=$PATH:$ANDROID_HOME/tools export PATH=$PATH:$ANDROID_HOME/tools/bin export PATH=$PATH:$ANDROID_HOME/platform-tools export PATH=$PATH:$HOME/work/apps/sonar-scanner-4.7.0.2747-macosx/bin export PATH=$PATH:/usr/local/opt/openjdk/bin export PATH=$PATH:/home/sargekhan/.local/bin export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH" # Export the Android SDK path export ANDROID_HOME=$HOME/Android/Sdk export PATH=$PATH:$ANDROID_HOME/tools/bin export PATH=$PATH:$ANDROID_HOME/platform-tools # Add stoic quote directory to the PATH export PATH=$PATH:$HOME/code/dot-files/stoic-thoughts export OPENAI_API_KEY="<KEY>" # jV alias ch='function _ch(){ chatgpt -n work -c "$*"; };_ch' # Set name of the theme to load. Optionally, if you set this to "random" # it'll load a random theme each time that oh-my-zsh is loaded. # See https://github.com/robbyrussell/oh-my-zsh/wiki/Themes ZSH_THEME="fishy" # Uncomment the following line to use case-sensitive completion. # CASE_SENSITIVE="true" # Uncomment the following line to use hyphen-insensitive completion. Case # sensitive completion must be off. _ and - will be interchangeable. # HYPHEN_INSENSITIVE="true" # Uncomment the following line to disable bi-weekly auto-update checks. # DISABLE_AUTO_UPDATE="true" # Uncomment the following line to change how often to auto-update (in days). # export UPDATE_ZSH_DAYS=13 # Uncomment the following line to disable colors in ls. # DISABLE_LS_COLORS="true" # Uncomment the following line to disable auto-setting terminal title. # DISABLE_AUTO_TITLE="true" # Uncomment the following line to enable command auto-correction. ENABLE_CORRECTION="true" # Uncomment the following line to display red dots whilst waiting for completion. COMPLETION_WAITING_DOTS="true" # Uncomment the following line if you want to disable marking untracked files # under VCS as dirty. This makes repository status check for large repositories # much, much faster. # DISABLE_UNTRACKED_FILES_DIRTY="true" # Uncomment the following line if you want to change the command execution time # stamp shown in the history command output. # The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd" # HIST_STAMPS="mm/dd/yyyy" # Would you like to use another custom folder than $ZSH/custom? # ZSH_CUSTOM=/path/to/new-custom-folder # Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*) # Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/ # Example format: plugins=(rails git textmate ruby lighthouse) # Add wisely, as too many plugins slow down shell startup. plugins=(git sudo zsh-syntax-highlighting zsh-autosuggestions web-search) source $ZSH/oh-my-zsh.sh # User configuration # export MANPATH="/usr/local/man:$MANPATH" # You may need to manually set your language environment # export LANG=en_US.UTF-8 # Preferred editor for local and remote sessions export EDITOR='nvim' # Compilation flags # export ARCHFLAGS="-arch x86_64" # ssh # export SSH_KEY_PATH="~/.ssh/rsa_id" # Set personal aliases, overriding those provided by oh-my-zsh libs, # plugins, and themes. Aliases can be placed here, though oh-my-zsh # users are encouraged to define aliases within the ZSH_CUSTOM folder. # For a full list of active aliases, run `alias`. # # Example aliases # alias zshconfig="mate ~/.zshrc" # alias ohmyzsh="mate ~/.oh-my-zsh" alias vi="nvim" alias cpcli="echo $F | xclip -i -selection clipboard" # Environment variable for GIT. export GIT_EDITOR=nvim alias vimdiff='nvim -d' # Vi mode for terminal bindkey -v bindkey '^ ' autosuggest-accept bindkey '^R' history-incremental-search-backward export ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=8' # Export digital occean instance ids; export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion # Source the profile as well source ~/.profile export NVM_DIR=~/.nvm quote.sh # >>> conda initialize >>> # !! Contents within this block are managed by 'conda init' !! __conda_setup="$('/home/sargekhan/code/python/miniconda3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)" if [ $? -eq 0 ]; then eval "$__conda_setup" else if [ -f "/home/sargekhan/code/python/miniconda3/etc/profile.d/conda.sh" ]; then . "/home/sargekhan/code/python/miniconda3/etc/profile.d/conda.sh" else export PATH="/home/sargekhan/code/python/miniconda3/bin:$PATH" fi fi unset __conda_setup # <<< conda initialize <<< <file_sep>vim.g.mapleader = "," vim.g.maplocalleader = "," vim.opt.backspace = '2' vim.opt.showcmd = true vim.opt.laststatus = 2 vim.opt.autowrite = true vim.opt.cursorline = true vim.opt.autoread = true -- use spaces vim.opt.tabstop = 2 vim.opt.shiftwidth = 2 vim.opt.shiftround = true vim.opt.expandtab = true vim.keymap.set('n', '<leader>h', ':nohlsearch<CR>') -- move b/w modes vim.keymap.set('i', 'jj', '<C-c>') --- Shift easily b/w windows vim.keymap.set('n', '<C-h>', '<C-w>h') vim.keymap.set('n', '<C-l>', '<C-w>l') vim.keymap.set('n', '<C-j>', '<C-w>j') vim.keymap.set('n', '<C-k>', '<C-w>k') -- Copy and paste b/w OS and vim incase we are not sharing buffer b/w os and vim vim.keymap.set('n', '<leader>y', '"+y') vim.keymap.set('n', '<leader>p', '"+p') vim.opt.clipboard = 'unnamedplus' ---- -- fold related options vim.opt.foldmethod = 'syntax' vim.opt.foldnestmax = 15 vim.opt.foldlevel = 2 --- casing vim.g.ignorecase = true vim.g.smartcase = true <file_sep>vim.g.loaded_netrw = 1 vim.g.loaded_netrwPlugin = 1 require("nvim-tree").setup({ view = { mappings = { list = { { key = "s", action = "vsplit" }, { key = "o", action = "edit" }, { key = "x", action = "close_node" }, { key = "C", action = "cd" }, }, }, }, }) vim.keymap.set('n', 'tc', ':NvimTreeFindFile!<CR>') vim.keymap.set('n', 'tt', ':NvimTreeToggle<CR>') <file_sep>local ensure_packer = function() local fn = vim.fn local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' if fn.empty(fn.glob(install_path)) > 0 then fn.system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path}) vim.cmd [[packadd packer.nvim]] return true end return false end local packer_bootstrap = ensure_packer() return require('packer').startup(function(use) use 'wbthomason/packer.nvim' use 'sainnhe/sonokai' use { 'nvim-tree/nvim-tree.lua', requires = { 'nvim-tree/nvim-web-devicons', -- optional, for file icons }, tag = 'nightly' -- optional, updated every week. (see issue #1193) } use 'nvim-lualine/lualine.nvim' use 'nvim-treesitter/nvim-treesitter' use { 'nvim-telescope/telescope.nvim', tag = '0.1.0', requires = { {'nvim-lua/plenary.nvim'} } } use { "williamboman/mason.nvim", "williamboman/mason-lspconfig.nvim", "neovim/nvim-lspconfig", } use 'tpope/vim-surround' use 'christoomey/vim-tmux-navigator' use { "catppuccin/nvim", as = "catppuccin" } use 'github/copilot.vim' use 'easymotion/vim-easymotion' -- for autocompletion use 'hrsh7th/cmp-nvim-lsp' use 'hrsh7th/cmp-buffer' use 'hrsh7th/cmp-path' use 'hrsh7th/cmp-cmdline' use 'hrsh7th/nvim-cmp' use 'jose-elias-alvarez/null-ls.nvim' use('MunifTanjim/prettier.nvim') use { 'filipdutescu/renamer.nvim', branch = 'master', requires = { {'nvim-lua/plenary.nvim'} } } -- My plugins here -- -- use 'foo1/bar1.nvim' -- use 'foo2/bar2.nvim' -- Automatically set up your configuration after cloning packer.nvim -- Put this at the end after all plugins if packer_bootstrap then require('packer').sync() end end) <file_sep>vim.o.termguicolors = true -- vim.cmd [[ colorscheme gruvbox ]] vim.cmd.colorscheme "sonokai" <file_sep>require'nvim-treesitter.configs'.setup { --- A list of parsers that must be installed ensure_installed = { "lua", "javascript", "typescript" }, -- Install parsers syncrhonously (only applied to `ensure_installed`) sync_install = false, auto_install = true, highlight = { enable = true, }, } <file_sep>require("mason").setup() require("mason-lspconfig").setup({ ensure_installed = { "lua_ls", "tsserver", "jsonls", "yamlls" }, }) local on_attach = function(_, _) vim.keymap.set('n', '<leader>ca', vim.lsp.buf.code_action, {}) vim.keymap.set('n', 'gr', require('telescope.builtin').lsp_references, {}) vim.keymap.set('n', 'gi', vim.lsp.buf.implementation, {}) vim.keymap.set('n', 'gd', vim.lsp.buf.definition, {}) vim.keymap.set('n', 'K', vim.lsp.buf.hover, {}) vim.keymap.set('n', 'g?', vim.diagnostic.open_float, {}) vim.keymap.set('n', '<leader>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', { noremap = true, silent = true }) vim.keymap.set('v', '<leader>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', { noremap = true, silent = true }) vim.keymap.set('n', '<leader>e', '<cmd>lua vim.diagnostic.open_float(0, {scope="line"})<CR>') end local capabilities = require('cmp_nvim_lsp').default_capabilities() require("lspconfig").lua_ls.setup { on_attach = on_attach, capabilities = capabilities } require("lspconfig").jsonls.setup { on_attach = on_attach, capabilities = capabilities } require("lspconfig").yamlls.setup { on_attach = on_attach, capabilities = capabilities } -- Set up lspconfig. require("lspconfig").tsserver.setup { on_attach = on_attach, cmd = { "typescript-language-server", "--stdio" }, capabilities = capabilities } <file_sep>#!/bin/bash ln -fs ~/code/dot-files/.tern-config ~/.tern-config ln -fs ~/code/dot-files/.vimrc ~/.vimrc ln -fs ~/code/dot-files/.eslintrc.json ~/.eslintrc.json ln -fs ~/code/dot-files/.zshrc ~/.zshrc ln -fs ~/code/dot-files/.tmux.conf ~/.tmux.conf
ed10de841b2fd055c4c1d4346b6925eb9a56d31c
[ "Markdown", "Shell", "Lua" ]
9
Markdown
SargeKhan/dot-files
9cfe322b0453e5988ede5ac67b4bb726fae2aa4e
839c7e322895e4294dcc6fe2588041945d3b34ee
refs/heads/main
<repo_name>VladyslavSarbash/goit-react-hw-04-hooks-images<file_sep>/src/components/API/API.js const MY_KEY = '23120149-b9b49e6d85d17734323f46136'; const BASE_URL = 'https://pixabay.com/api/'; export default function FetchAPI(searchInput, page = 1) { return fetch( `${BASE_URL}?q=${searchInput}&page=${page}&key=${MY_KEY}&image_type=photo&orientation=horizontal&per_page=12`, ).then(response => response.json()); } <file_sep>/src/components/ImageGallery/ImageGallery.js import PropTypes from 'prop-types'; import ImageGalleryItem from '../ImageGalleryItem/ImageGalleryItem'; export default function ImageGallery({ arrayImg, openModal }) { return ( <ul className="ImageGallery" onClick={openModal}> <ImageGalleryItem arrayImg={arrayImg} /> </ul> ); } ImageGallery.propTypes = { arrayImg: PropTypes.array, openModal: PropTypes.func, }; <file_sep>/src/components/ImageGalleryItem/ImageGalleryItem.js export default function ImageGalleryItem({ arrayImg }) { const markup = arrayImg.map(i => { return ( <li className="ImageGalleryItem" key={i.id}> <img src={i.webformatURL} alt={i.tags} className="ImageGalleryItem-image" data-large={i.largeImageURL} /> </li> ); }); return markup; } <file_sep>/src/components/Searchbar/Searchbar.js import React, { useState } from 'react'; import PropTypes from 'prop-types'; import FetchAPI from '../API/API'; export default function SearchBar({ onSubmit, setPage }) { const [searchInput, setSearchInput] = useState(''); const formSubmit = e => { e.preventDefault(); FetchAPI(searchInput) .then(data => onSubmit({ arrayImg: data.hits, searchInput: searchInput, }), ) .finally(() => { setPage(1); setSearchInput(''); }); }; const inputForm = ({ target }) => { setSearchInput(target.value); }; return ( <header className="Searchbar"> <form className="SearchForm" onSubmit={formSubmit}> <button type="submit" className="SearchForm-button"> <span className="SearchForm-button-label">Search</span> </button> <input className="SearchForm-input" value={searchInput} type="text" autoComplete="off" autoFocus placeholder="Search images and photos" onChange={inputForm} /> </form> </header> ); } SearchBar.propTypes = { onSubmit: PropTypes.func, }; <file_sep>/src/components/Modal/Modal.js import { useEffect } from 'react'; import { createPortal } from 'react-dom'; const modalRoot = document.querySelector('#modal-root'); export default function Modal({ onClose, children }) { const closeModal = e => { const { target, code } = e; if (code === 'Escape') { onClose(closeModal); } if (target.nodeName !== 'IMG') { onClose(closeModal); } }; useEffect(() => { window.addEventListener('keydown', closeModal); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return createPortal( <div className="Overlay" onClick={closeModal}> <div className="Modal">{children}</div> </div>, modalRoot, ); } <file_sep>/src/App.js import React, { useState, useEffect } from 'react'; import './App.css'; import SearchBar from './components/Searchbar/Searchbar'; import ImageGallery from './components/ImageGallery/ImageGallery'; import ButtonLoadMore from './components/Button/Button'; import Modal from './components/Modal/Modal'; function App() { const [arrayImg, setArrayImg] = useState([]); const [modalImg, setModalImg] = useState(''); const [showModal, setShowModal] = useState(false); const [searchInput, setSearchInput] = useState(''); const [page, setPage] = useState(1); useEffect(() => { window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth', }); }, [arrayImg]); const onSubmit = ({ arrayImg, searchInput }) => { setArrayImg(arrayImg); setSearchInput(searchInput); }; const loadMore = moreImg => { setArrayImg([...arrayImg, ...moreImg]); }; const toggleModal = closeModalEsc => { setShowModal(!showModal); window.removeEventListener('keydown', closeModalEsc); }; const openModal = e => { const { dataset, nodeName } = e.target; if (nodeName === 'IMG') { setModalImg(dataset.large); setShowModal(!showModal); } }; return ( <> {showModal && ( <Modal onClose={toggleModal}> <img src={modalImg} alt="" /> </Modal> )} <SearchBar onSubmit={onSubmit} setPage={setPage} /> <ImageGallery arrayImg={arrayImg} openModal={openModal} /> {arrayImg.length !== 0 && ( <ButtonLoadMore searchInput={searchInput} loadMore={loadMore} page={page} setPage={setPage} /> )} </> ); } export default App; <file_sep>/src/components/Button/Button.js import { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import LoaderCircle from '../Loader/Loader'; import FetchAPI from '../API/API'; export default function ButtonLoadMore({ searchInput, loadMore, page, setPage, }) { const [loader, setLoader] = useState(false); useEffect(() => { if (page === 1) { return; } setLoader(true); FetchAPI(searchInput, page) .then(data => loadMore(data.hits)) .finally(setLoader(false)); // eslint-disable-next-line react-hooks/exhaustive-deps }, [page]); if (loader) { return LoaderCircle(); } if (!loader) { return ( <div className="Btn_load-more"> <button className="Button" type="button" onClick={() => setPage(page + 1)} > Load more </button> </div> ); } } ButtonLoadMore.propTypes = { searchInput: PropTypes.string, loadMore: PropTypes.func, };
b394e39e3074f11a475cb7376b1734097399054c
[ "JavaScript" ]
7
JavaScript
VladyslavSarbash/goit-react-hw-04-hooks-images
e881cd45ff6721656ee7b723ddb727f3c652e6bf
8859217a7cf8cc96ab5b1ea07b93813b3b30005d
refs/heads/master
<repo_name>svekr/asset-bundles<file_sep>/Assets/Scripts/Editor/BuildTools.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System.IO; using System.Diagnostics; public class BuildTools { [MenuItem("Tools/Build Asset Bundles Standalone")] public static void BuildAssetBundlesStandalone() { BuildAssetBundlesMethod(BuildTarget.StandaloneWindows); } [MenuItem("Tools/Build Asset Bundles Android")] public static void BuildAssetBundlesAndroid() { BuildAssetBundlesMethod(BuildTarget.Android); } [MenuItem("Tools/Build Asset Bundles iOS")] public static void BuildAssetBundlesIOS() { BuildAssetBundlesMethod(BuildTarget.iOS); } [MenuItem("Tools/Make Build Standalone")] public static void MakeBuildWindows() { string fileName = MakeBuild(BuildTarget.StandaloneWindows, "exe"); RunBuild(fileName); } [MenuItem("Tools/Make Build Android")] public static void MakeBuildAndroid() { MakeBuild(BuildTarget.Android, "apk"); } [MenuItem("Tools/Make Build iOS")] public static void MakeBuildIOS() { MakeBuild(BuildTarget.iOS, "ipa"); } private static void BuildAssetBundlesMethod(BuildTarget buildTarget) { string directory = Path.Combine(Application.streamingAssetsPath, "assetBundles"); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } BuildPipeline.BuildAssetBundles(directory, BuildAssetBundleOptions.None, buildTarget); } private static string MakeBuild(BuildTarget buildTarget, string extension) { string fileName = null; if (!BuildPipeline.isBuildingPlayer) { string directory = Path.Combine(Application.persistentDataPath, "/builds"); fileName = EditorUtility.SaveFilePanel("Select build name", directory, "build", extension); if (fileName != null && fileName.Length > 0) { BuildPlayerOptions options = new BuildPlayerOptions(); options.scenes = new[] {"Assets/Scenes/Scene.unity"}; options.locationPathName = fileName; options.target = buildTarget; options.options = BuildOptions.None; BuildPipeline.BuildPlayer(options); } } return fileName; } private static void RunBuild(string fileName) { if (fileName != null && fileName.Length > 0) { Process process = new Process(); process.StartInfo.FileName = fileName; process.Start(); } } } <file_sep>/Assets/Scripts/LoadAssetBundle.cs using System.IO; using UnityEngine; using UnityEngine.Networking; using System.Collections; public class LoadAssetBundle : MonoBehaviour { void Start() { //LoadBundleFromFile(); StartCoroutine(LoadBundleWithRequest()); } private IEnumerator LoadBundleWithRequest() { #if UNITY_EDITOR string path = "file:///" + Path.Combine(Application.streamingAssetsPath, "assetBundles/prototyping/blocks"); #elif UNITY_ANDROID string path = "jar:file:///" + Application.dataPath + "!/assets/" + "assetBundles/prototyping/blocks"; #else string path = "file:///" + Application.dataPath + "/Raw/" + "assetBundles/prototyping/blocks"; #endif Debug.Log("Start load bundle: " + path); UnityWebRequest request = UnityWebRequest.GetAssetBundle(path); yield return request.SendWebRequest(); Debug.Log("Load complete."); AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request); ProcessAssetBundle(bundle); } private void LoadBundleFromFile() { string path = Path.Combine(Application.streamingAssetsPath, "assetBundles/prototyping/blocks"); AssetBundle bundle = AssetBundle.LoadFromFile(path); ProcessAssetBundle(bundle); } private void ProcessAssetBundle(AssetBundle bundle) { if (bundle == null) { Debug.Log("Asset bundle load error."); } else { Debug.Log("Asset bundle load complete successfully."); ProcessPrefab(bundle, "CubeGray", Vector3.zero); ProcessPrefab(bundle, "CubePink", new Vector3(10f, 0f, -10f)); } } private void ProcessPrefab(AssetBundle bundle, string prefabName, Vector3 position) { GameObject prefab = bundle.LoadAsset<GameObject>(prefabName); if (prefab == null) { Debug.Log("Prefab load error."); } else { Debug.Log("Prefab loaded successfully."); Instantiate(prefab, position, Quaternion.identity); } } }
59e71db234d3c8705fea61b993db1984e696192f
[ "C#" ]
2
C#
svekr/asset-bundles
4db97fe88594af59c36af795443cfbf3f86187d2
208eecf2f78c1c762202743ceb28e63e952d1bbc
refs/heads/master
<repo_name>jjrun1/s2-portal<file_sep>/business-api/src/main/java/s2/portal/factory/SmtpSessionFactory.java package s2.portal.factory; import s2.portal.data.Feature; import s2.portal.service.FeatureService; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; import java.util.Properties; /** * @author <NAME> * @since July 2018 */ @Component public class SmtpSessionFactory { private final static Logger LOG = LoggerFactory.getLogger(SmtpSessionFactory.class); private FeatureService featureService; @Autowired public SmtpSessionFactory(FeatureService featureService) { this.featureService = featureService; } public Session createUnsecuredSession(String host) { final Feature smtpDebugFeature = featureService.findByName(Feature.Type.SMTP_DEBUG); Assert.notNull(smtpDebugFeature, "SMTP_DEBUG not found."); final String smtpDebug = StringUtils.isBlank(smtpDebugFeature.getValue()) ? "false" : smtpDebugFeature.getValue(); final Feature smtpPort = featureService.findByName(Feature.Type.SMTP_PORT); Assert.notNull(smtpPort, "SMTP_PORT not found."); Assert.hasText(smtpPort.getValue(), "SMTP_PORT not found."); final Properties properties = new Properties(); properties.setProperty("mail.transport.protocol", "smtp"); properties.setProperty("mail.host", host); properties.put("mail.smtp.auth", "false"); properties.put("mail.smtp.starttls.enable", "false"); properties.put("mail.debug", smtpDebug); properties.put("mail.smtp.port", smtpPort.getValue()); // "30000" = 30s properties.put("mail.smtp.timeout", 30000); LOG.info(String.format("Creating unsecured connection... {host=%s}", host)); return Session.getInstance(properties); } public Session createSecureSession(String host, String smtpUser, String smtpPwd) { final Feature smtpDebugFeature = featureService.findByName(Feature.Type.SMTP_DEBUG); Assert.notNull(smtpDebugFeature, "SMTP_DEBUG not found."); final String smtpDebug = StringUtils.isBlank(smtpDebugFeature.getValue()) ? "false" : smtpDebugFeature.getValue(); final Feature smtpPort = featureService.findByName(Feature.Type.SMTP_PORT); Assert.notNull(smtpPort, "SMTP_PORT not found."); Assert.hasText(smtpPort.getValue(), "SMTP_PORT not found."); final Properties properties = new Properties(); properties.setProperty("mail.transport.protocol", "smtp"); properties.setProperty("mail.host", host); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.debug", smtpDebug); properties.put("mail.smtp.port", smtpPort.getValue()); // "30000" = 30s properties.put("mail.smtp.timeout", 30000); LOG.info(String.format("Creating secure connection... {host=%s, username=%s, password=%s}" , host, smtpUser, smtpPwd)); return Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUser, smtpPwd); } }); } } <file_sep>/gateway-api/src/main/java/s2/portal/ws/user/rest/BirthdayResource.java package s2.portal.ws.user.rest; import org.joda.time.DateTime; import org.joda.time.Days; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import s2.portal.data.user.User; import s2.portal.service.UserService; import s2.portal.ws.common.rest.BaseResource; import s2.portal.ws.user.json.BirthdayResponse; import java.util.ArrayList; import java.util.List; /** * @author <NAME> * @since October 2018 */ @SuppressWarnings("unused") @RestController @RequestMapping("/api/users/birthdays") public class BirthdayResource extends BaseResource { private UserService userService; @Autowired public BirthdayResource(UserService userService) { this.userService = userService; } @RequestMapping(value = "/next/days/{days}", method = RequestMethod.GET) public ResponseEntity<List<BirthdayResponse>> nextDays(@PathVariable Integer days) { final DateTime today = DateTime.now(); final DateTime xNumberOfDaysFromToday = DateTime.now().plusDays(days).withTimeAtStartOfDay(); final List<BirthdayResponse> response = new ArrayList<>(); for (User user : userService.findAll()) { if (user.getDateOfBirth() != null) { final DateTime dateOfBirth = DateTime.now().withMillis(user.getDateOfBirth().getTime()) .withYear(today.getYear()) .withTimeAtStartOfDay(); final int daysBetween = Days.daysBetween(today, dateOfBirth).getDays(); if (daysBetween >= 0 && daysBetween <= days) { response.add(new BirthdayResponse(dateOfBirth.toString("dd-MMM") , user.getDisplayName() , daysBetween)); } } } return ResponseEntity.ok(response); } }<file_sep>/gateway-api/src/main/java/s2/portal/ws/user/rest/UserBankAccountResource.java package s2.portal.ws.user.rest; import s2.portal.data.audit.Revision; import s2.portal.data.system.Bank; import s2.portal.data.user.UserBankAccount; import s2.portal.service.UserBankAccountService; import s2.portal.ws.common.rest.BaseResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author <NAME> * @since October 2016 */ @RestController @RequestMapping("/api/users/bankAccounts") public class UserBankAccountResource extends BaseResource { private UserBankAccountService userBankAccountService; @Autowired public UserBankAccountResource(UserBankAccountService userBankAccountService) { this.userBankAccountService = userBankAccountService; } @RequestMapping(value = "/createdBy/id/{id}", method = RequestMethod.GET) public ResponseEntity<Revision> findCreatedBy(@PathVariable Integer id) { final UserBankAccount entity = userBankAccountService.findById(id); return ResponseEntity.ok(userBankAccountService.findCreatedBy(entity)); } @RequestMapping(value = "/modifiedBy/id/{id}", method = RequestMethod.GET) public ResponseEntity<Revision> findModifiedBy(@PathVariable Integer id) { final UserBankAccount entity = userBankAccountService.findById(id); return ResponseEntity.ok(userBankAccountService.findModifiedBy(entity)); } @RequestMapping(value = "/user/{userId}", method = RequestMethod.GET) public ResponseEntity<List<UserBankAccount>> findByUser(@PathVariable Integer userId) { return ResponseEntity.ok(userBankAccountService.findByUser(userId)); } @RequestMapping(value = "/id/{id}", method = RequestMethod.GET) public ResponseEntity<UserBankAccount> findById(@PathVariable Integer id) { return ResponseEntity.ok(userBankAccountService.findById(id)); } @RequestMapping(value = "", method = RequestMethod.POST) public ResponseEntity<UserBankAccount> save(@RequestBody UserBankAccount userBankAccount) { return ResponseEntity.ok(userBankAccountService.save(userBankAccount)); } @RequestMapping(value = "", method = RequestMethod.DELETE) public ResponseEntity<UserBankAccount> delete(@RequestBody UserBankAccount userBankAccount) { return ResponseEntity.ok(userBankAccountService.delete(userBankAccount)); } }<file_sep>/business-api/src/main/java/s2/portal/service/impl/LeaveBalanceServiceImpl.java package s2.portal.service.impl; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import s2.portal.dao.LeaveBalanceDao; import s2.portal.data.user.LeaveBalance; import s2.portal.service.LeaveBalanceService; import java.util.List; /** * @author <NAME> * @since October 2018 */ @Service(value = "leaveBalanceService") public class LeaveBalanceServiceImpl extends JdbcAuditTemplate<Integer, LeaveBalance, LeaveBalanceDao> implements LeaveBalanceService { private LeaveBalanceDao leaveBalanceDao; @Autowired public LeaveBalanceServiceImpl(LeaveBalanceDao leaveBalanceDao) { super(leaveBalanceDao); this.leaveBalanceDao = leaveBalanceDao; } @Override public List<LeaveBalance> findByUser(Integer userId) { return leaveBalanceDao.findByUser(userId); } @Override public LeaveBalance findByLeaveRequest(Integer leaveRequestId) { return leaveBalanceDao.findByLeaveRequest(leaveRequestId); } @Override public LeaveBalance findByUserAndTypeAndDate(Integer userId, String leaveBalanceType, DateTime balanceDate) { return leaveBalanceDao.findByUserAndTypeAndDate(userId, leaveBalanceType, balanceDate); } @Override public List<LeaveBalance> findByUserAndTypeAndOnOrAfterDate(Integer userId, String balanceTypeId , DateTime effectiveDate) { return leaveBalanceDao.findByUserAndTypeAndOnOrAfterDate(userId, balanceTypeId, effectiveDate); } @Override public LeaveBalance findLastBalanceByUserAndTypeAndYear(Integer userId, String balanceTypeId, int year) { return leaveBalanceDao.findLastBalanceByUserAndTypeAndYear(userId, balanceTypeId, year); } } <file_sep>/db/src/main/java/s2/portal/data/system/DocumentType.java package s2.portal.data.system; import com.fasterxml.jackson.annotation.JsonIgnore; import s2.portal.data.BaseModel; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @author <NAME> * @since January 2017 */ @Entity @Table(name = "doc_type") public class DocumentType extends BaseModel<String> { private static final long serialVersionUID = -3661180425315356765L; public enum Type { IDENTIFICATION("ID"); private String id; Type(String id) { this.id = id; } public static Type valueOfById(String id) { for (Type type : values()) { if (type.id().equalsIgnoreCase(id)) { return type; } } throw new IllegalArgumentException("No enum constant " + Type.class.getCanonicalName() + "." + id); } public String id() { return id; } } @Id @Column(name = "id") private String primaryId; @Column(name = "descr") private String description; public DocumentType() { } public DocumentType(String primaryId, String description) { this.primaryId = primaryId; this.description = description; } @JsonIgnore public boolean isType(Type type) { return this.primaryId != null && this.primaryId.equalsIgnoreCase(type.id()); } @Override public String getPrimaryId() { return primaryId; } @Override public void setPrimaryId(String primaryId) { this.primaryId = primaryId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "DocumentType{" + "primaryId='" + primaryId + '\'' + ", description='" + description + '\'' + '}'; } }<file_sep>/business-api/src/main/java/s2/portal/service/NotificationService.java package s2.portal.service; import org.camunda.bpm.engine.delegate.DelegateTask; import s2.portal.data.user.Leave; import s2.portal.data.user.Timesheet; import s2.portal.data.user.User; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.MimeMessage; import java.io.UnsupportedEncodingException; import java.util.Set; /** * @author <NAME> * @since July 2018 */ public interface NotificationService { MimeMessage createTimesheetReminderEmail(Timesheet timesheet, User user) throws UnsupportedEncodingException, AddressException; MimeMessage createLeaveApprovedEmail(User requestingUser, Leave leave, Set<User> cc) throws UnsupportedEncodingException, AddressException; MimeMessage createLeaveDeclinedEmail(User requestingUser, Leave leave, String comment) throws UnsupportedEncodingException, AddressException; /** * Creates a returns a new SMTP session to the calling client. * * @param host The host name or IP address of the SMTP server. * @return The mail session. */ Session getSession(String host); /** * Method used to send an email to notify user(s) of the shipment. * * @param user The user who forgot their password. * @return The message. */ MimeMessage createPasswordResetNotification(User user) throws UnsupportedEncodingException, AddressException; /** * Method used to send an email to notify user(s) of the rejected decision. * * @param user The user who was rejected. * @param reason The reason for the rejection. * @return The message. */ MimeMessage createUserRequestRejectedNotification(User user, String reason) throws UnsupportedEncodingException, AddressException; /** * Method used to send an email to notify user(s) of BPM task assignment. * * @param delegateTask The Camunda delegage task. * @return The message. */ MimeMessage createTaskAssignmentNotification(DelegateTask delegateTask) throws UnsupportedEncodingException, AddressException; /** * Method used to send an email to confirm the new user was successfully imported in the system. * * @param newUser The newly imported user. * @return The message. */ MimeMessage createWelcomeEmail(User newUser, String plainTextPassword) throws UnsupportedEncodingException, AddressException; void send(MimeMessage mimeMessage); void send(MimeMessage mimeMessage, NotificationCallback callback); } <file_sep>/business-api/src/main/java/s2/portal/service/LeaveBalanceService.java package s2.portal.service; import org.joda.time.DateTime; import s2.portal.data.user.LeaveBalance; import java.util.List; /** * @author <NAME> * @since October 2018 */ public interface LeaveBalanceService extends CrudService<Integer, LeaveBalance>, AuditedModelAware<LeaveBalance> { List<LeaveBalance> findByUser(Integer userId); LeaveBalance findByLeaveRequest(Integer leaveRequestId); LeaveBalance findByUserAndTypeAndDate(Integer userId, String leaveBalanceType, DateTime balanceDate); List<LeaveBalance> findByUserAndTypeAndOnOrAfterDate(Integer userId, String balanceTypeId, DateTime effectiveDate); LeaveBalance findLastBalanceByUserAndTypeAndYear(Integer userId, String balanceTypeId, int year); } <file_sep>/db/migration/template-create-pk-constraints.sql select 'ALTER TABLE '+ tab.[name]+' ADD PRIMARY KEY('+ substring(column_names, 1, len(column_names)-1) +');' from sys.tables tab inner join sys.indexes pk on tab.object_id = pk.object_id and pk.is_primary_key = 1 cross apply (select col.[name] + ', ' from sys.index_columns ic inner join sys.columns col on ic.object_id = col.object_id and ic.column_id = col.column_id where ic.object_id = tab.object_id and ic.index_id = pk.index_id order by col.column_id for xml path ('') ) D (column_names) where pk.[name] not like'%ACT_%' order by schema_name(tab.schema_id), tab.[name]<file_sep>/Dockerfile # TODO: consider other images - https://hub.docker.com/_/openjdk/ FROM openjdk:8u171-jdk-slim-stretch WORKDIR /usr/app # TODO: make version dynamic COPY gateway-api/target/s2-portal-gateway-api-RELEASE.1.0.jar /usr/app ENV SPRING_ENVIRONMENT dev EXPOSE 2221 #EXPOSE 5005 CMD ["java", "-jar", "s2-portal-gateway-api-RELEASE.1.0.jar", "-Dspring.profiles.active=${SPRING_ENVIRONMENT}"] # CMD ["java", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005", "-jar", "loc8-0.0.1-SNAPSHOT.jar", "-Dspring.profiles.active=${SPRING_ENVIRONMENT}"]<file_sep>/db/src/main/java/s2/portal/dao/impl/hibernate/LeaveDaoImpl.java package s2.portal.dao.impl.hibernate; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; import s2.portal.dao.LeaveDao; import s2.portal.data.user.Leave; import java.util.Date; import java.util.List; /** * @author <NAME> * @since September 2018 */ @Repository(value = "leaveDao") public class LeaveDaoImpl extends BaseAuditLogDaoImpl<Integer, Leave> implements LeaveDao { @Autowired public LeaveDaoImpl(@Qualifier("s2portalSessionFactory") SessionFactory sessionFactory) { super(sessionFactory, Leave.class); } @SuppressWarnings({"unchecked", "JpaQueryApiInspection"}) @Override public List<Leave> findOverlappingLeave(Integer userId, Date startDate, Date endDate) { Assert.notNull(userId, "Variable userId cannot be null."); Assert.notNull(startDate, "Variable startDate cannot be null."); Assert.notNull(endDate, "Variable endDate cannot be null."); return (List<Leave>) getHibernateTemplate().findByNamedQueryAndNamedParam( "FIND_OVERLAPPING_LEAVE" , new String[]{"userId", "startDate", "endDate"} , new Object[]{userId, startDate, endDate}); } /** * Returns the list of user documents for the given user. * * @param userId The user pk. * @return A list. */ @SuppressWarnings({"unchecked", "JpaQueryApiInspection"}) @Override public List<Leave> findByUser(Integer userId) { Assert.notNull(userId, "Variable userId cannot be null."); return (List<Leave>) getHibernateTemplate().findByNamedQueryAndNamedParam( "FIND_LEAVE_BY_USER", "userId", userId); } } <file_sep>/gateway-api/src/main/java/s2/portal/ws/user/rest/TimesheetResource.java package s2.portal.ws.user.rest; import org.joda.time.DateTime; import org.joda.time.Months; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import s2.portal.dao.TimesheetDao; import s2.portal.data.user.Timesheet; import s2.portal.ws.common.rest.BaseResource; import java.util.Collection; import java.util.TreeSet; /** * @author <NAME> * @since January 2019 */ @SuppressWarnings("unused") @RestController @RequestMapping("/api/timesheets") public class TimesheetResource extends BaseResource { private TimesheetDao timesheetDao; @Autowired public TimesheetResource(TimesheetDao timesheetDao) { this.timesheetDao = timesheetDao; } @RequestMapping(value = "/last/{months}/months", method = RequestMethod.GET) public ResponseEntity<Collection<Timesheet>> lastXNumberOfMonths(@PathVariable Integer months) { final DateTime startOfNextMonth = DateTime.now() .plusMonths(1) .withDayOfMonth(1) .withTimeAtStartOfDay(); final DateTime xMonthsFromToday = DateTime.now().minusMonths(months) .minusDays(1) .withTimeAtStartOfDay(); final Collection<Timesheet> response = new TreeSet<>((o1, o2) -> o2.getStartDate() .compareTo(o1.getStartDate())); for (Timesheet t : timesheetDao.findAll()) { final DateTime startDate = DateTime.now().withMillis(t.getStartDate().getTime()) .withTimeAtStartOfDay(); final int monthsBetween = Months.monthsBetween(startDate, startOfNextMonth).getMonths(); if (startDate.isBefore(startOfNextMonth) && monthsBetween <= months && monthsBetween >= 0) { response.add(t); } } return ResponseEntity.ok(response); } }<file_sep>/business-api/src/main/java/s2/portal/bpm/tasks/common/event/TaskNotificationAssignmentHandler.java package s2.portal.bpm.tasks.common.event; import org.camunda.bpm.engine.delegate.DelegateTask; import org.camunda.bpm.engine.delegate.TaskListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import s2.portal.service.NotificationService; import s2.portal.service.impl.DefaultNotificationCallback; import javax.mail.internet.MimeMessage; import java.util.Arrays; /** * @author <NAME> * @since October 2018 */ @SuppressWarnings("unused") @Component public class TaskNotificationAssignmentHandler implements TaskListener { private final Logger log = LoggerFactory.getLogger(TaskNotificationAssignmentHandler.class); private NotificationService notificationService; @Autowired public TaskNotificationAssignmentHandler(NotificationService notificationService) { this.notificationService = notificationService; } @Override public void notify(DelegateTask delegateTask) { try { final String processInstanceId = delegateTask.getProcessInstanceId(); MimeMessage message = notificationService.createTaskAssignmentNotification(delegateTask); log.info("Attempting to send notification for process <{}> to: {}", processInstanceId , Arrays.toString(message.getAllRecipients())); notificationService.send(message, new DefaultNotificationCallback()); } catch (Exception e) { log.error(e.getMessage(), e); } } } <file_sep>/db/migration/s2portal-ddl-20190314070049.sql /** Scripted by Migrate2Postgres 1.0.7 on Thu, 14 Mar 2019 07:00:50 +0200 Migrate2Postgres Copyright (C) 2018 <NAME> This program comes with ABSOLUTELY NO WARRANTY; This is free software, and you are welcome to redistribute it under certain conditions; See https://www.gnu.org/licenses/gpl-3.0.txt for details Available at https://github.com/isapir/Migrate2Postgres **/ BEGIN TRANSACTION; DROP SCHEMA IF EXISTS public CASCADE; CREATE SCHEMA IF NOT EXISTS public; CREATE TABLE public.act_ge_bytearray ( id_ TEXT NOT NULL ,rev_ INT ,name_ TEXT ,deployment_id_ TEXT ,bytes_ BYTEA ,generated_ INT ,tenant_id_ TEXT ); CREATE TABLE public.act_ge_property ( name_ TEXT NOT NULL ,value_ TEXT ,rev_ INT ); CREATE TABLE public.act_hi_actinst ( id_ TEXT NOT NULL ,parent_act_inst_id_ TEXT ,proc_def_key_ TEXT ,proc_def_id_ TEXT NOT NULL ,proc_inst_id_ TEXT NOT NULL ,execution_id_ TEXT NOT NULL ,act_id_ TEXT NOT NULL ,task_id_ TEXT ,call_proc_inst_id_ TEXT ,call_case_inst_id_ TEXT ,act_name_ TEXT ,act_type_ TEXT NOT NULL ,assignee_ TEXT ,start_time_ TIMESTAMPTZ NOT NULL ,end_time_ TIMESTAMPTZ ,duration_ NUMERIC ,act_inst_state_ INT ,sequence_counter_ NUMERIC ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_attachment ( id_ TEXT NOT NULL ,rev_ INT ,user_id_ TEXT ,name_ TEXT ,description_ TEXT ,type_ TEXT ,task_id_ TEXT ,proc_inst_id_ TEXT ,url_ TEXT ,content_id_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_batch ( id_ TEXT NOT NULL ,type_ TEXT ,total_jobs_ INT ,jobs_per_seed_ INT ,invocations_per_job_ INT ,seed_job_def_id_ TEXT ,monitor_job_def_id_ TEXT ,batch_job_def_id_ TEXT ,tenant_id_ TEXT ,start_time_ TIMESTAMPTZ NOT NULL ,end_time_ TIMESTAMPTZ ); CREATE TABLE public.act_hi_caseactinst ( id_ TEXT NOT NULL ,parent_act_inst_id_ TEXT ,case_def_id_ TEXT NOT NULL ,case_inst_id_ TEXT NOT NULL ,case_act_id_ TEXT NOT NULL ,task_id_ TEXT ,call_proc_inst_id_ TEXT ,call_case_inst_id_ TEXT ,case_act_name_ TEXT ,case_act_type_ TEXT ,create_time_ TIMESTAMPTZ NOT NULL ,end_time_ TIMESTAMPTZ ,duration_ NUMERIC ,state_ INT ,required_ INT ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_caseinst ( id_ TEXT NOT NULL ,case_inst_id_ TEXT NOT NULL ,business_key_ TEXT ,case_def_id_ TEXT NOT NULL ,create_time_ TIMESTAMPTZ NOT NULL ,close_time_ TIMESTAMPTZ ,duration_ NUMERIC ,state_ INT ,create_user_id_ TEXT ,super_case_instance_id_ TEXT ,super_process_instance_id_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_comment ( id_ TEXT NOT NULL ,type_ TEXT ,time_ TIMESTAMPTZ NOT NULL ,user_id_ TEXT ,task_id_ TEXT ,proc_inst_id_ TEXT ,action_ TEXT ,message_ TEXT ,full_msg_ BYTEA ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_dec_in ( id_ TEXT NOT NULL ,dec_inst_id_ TEXT NOT NULL ,clause_id_ TEXT ,clause_name_ TEXT ,var_type_ TEXT ,bytearray_id_ TEXT ,double_ REAL ,long_ NUMERIC ,text_ TEXT ,text2_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_dec_out ( id_ TEXT NOT NULL ,dec_inst_id_ TEXT NOT NULL ,clause_id_ TEXT ,clause_name_ TEXT ,rule_id_ TEXT ,rule_order_ INT ,var_name_ TEXT ,var_type_ TEXT ,bytearray_id_ TEXT ,double_ REAL ,long_ NUMERIC ,text_ TEXT ,text2_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_decinst ( id_ TEXT NOT NULL ,dec_def_id_ TEXT NOT NULL ,dec_def_key_ TEXT NOT NULL ,dec_def_name_ TEXT ,proc_def_key_ TEXT ,proc_def_id_ TEXT ,proc_inst_id_ TEXT ,case_def_key_ TEXT ,case_def_id_ TEXT ,case_inst_id_ TEXT ,act_inst_id_ TEXT ,act_id_ TEXT ,eval_time_ TIMESTAMPTZ NOT NULL ,collect_value_ REAL ,user_id_ TEXT ,root_dec_inst_id_ TEXT ,dec_req_id_ TEXT ,dec_req_key_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_detail ( id_ TEXT NOT NULL ,type_ TEXT NOT NULL ,proc_def_key_ TEXT ,proc_def_id_ TEXT ,proc_inst_id_ TEXT ,execution_id_ TEXT ,case_def_key_ TEXT ,case_def_id_ TEXT ,case_inst_id_ TEXT ,case_execution_id_ TEXT ,task_id_ TEXT ,act_inst_id_ TEXT ,var_inst_id_ TEXT ,name_ TEXT NOT NULL ,var_type_ TEXT ,rev_ INT ,time_ TIMESTAMPTZ NOT NULL ,bytearray_id_ TEXT ,double_ REAL ,long_ NUMERIC ,text_ TEXT ,text2_ TEXT ,sequence_counter_ NUMERIC ,tenant_id_ TEXT ,operation_id_ TEXT ); CREATE TABLE public.act_hi_ext_task_log ( id_ TEXT NOT NULL ,timestamp_ TIMESTAMPTZ NOT NULL ,ext_task_id_ TEXT NOT NULL ,retries_ INT ,topic_name_ TEXT ,worker_id_ TEXT ,priority_ NUMERIC NOT NULL DEFAULT 0 ,error_msg_ TEXT ,error_details_id_ TEXT ,act_id_ TEXT ,act_inst_id_ TEXT ,execution_id_ TEXT ,proc_inst_id_ TEXT ,proc_def_id_ TEXT ,proc_def_key_ TEXT ,tenant_id_ TEXT ,state_ INT ); CREATE TABLE public.act_hi_identitylink ( id_ TEXT NOT NULL ,timestamp_ TIMESTAMPTZ NOT NULL ,type_ TEXT ,user_id_ TEXT ,group_id_ TEXT ,task_id_ TEXT ,proc_def_id_ TEXT ,operation_type_ TEXT ,assigner_id_ TEXT ,proc_def_key_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_incident ( id_ TEXT NOT NULL ,proc_def_key_ TEXT ,proc_def_id_ TEXT ,proc_inst_id_ TEXT ,execution_id_ TEXT ,create_time_ TIMESTAMPTZ NOT NULL ,end_time_ TIMESTAMPTZ ,incident_msg_ TEXT ,incident_type_ TEXT NOT NULL ,activity_id_ TEXT ,cause_incident_id_ TEXT ,root_cause_incident_id_ TEXT ,configuration_ TEXT ,incident_state_ INT ,tenant_id_ TEXT ,job_def_id_ TEXT ); CREATE TABLE public.act_hi_job_log ( id_ TEXT NOT NULL ,timestamp_ TIMESTAMPTZ NOT NULL ,job_id_ TEXT NOT NULL ,job_duedate_ TIMESTAMPTZ ,job_retries_ INT ,job_priority_ NUMERIC NOT NULL DEFAULT 0 ,job_exception_msg_ TEXT ,job_exception_stack_id_ TEXT ,job_state_ INT ,job_def_id_ TEXT ,job_def_type_ TEXT ,job_def_configuration_ TEXT ,act_id_ TEXT ,execution_id_ TEXT ,process_instance_id_ TEXT ,process_def_id_ TEXT ,process_def_key_ TEXT ,deployment_id_ TEXT ,sequence_counter_ NUMERIC ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_op_log ( id_ TEXT NOT NULL ,deployment_id_ TEXT ,proc_def_id_ TEXT ,proc_def_key_ TEXT ,proc_inst_id_ TEXT ,execution_id_ TEXT ,case_def_id_ TEXT ,case_inst_id_ TEXT ,case_execution_id_ TEXT ,task_id_ TEXT ,job_id_ TEXT ,job_def_id_ TEXT ,batch_id_ TEXT ,user_id_ TEXT ,timestamp_ TIMESTAMPTZ NOT NULL ,operation_type_ TEXT ,operation_id_ TEXT ,entity_type_ TEXT ,property_ TEXT ,org_value_ TEXT ,new_value_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_procinst ( id_ TEXT NOT NULL ,proc_inst_id_ TEXT NOT NULL ,business_key_ TEXT ,proc_def_key_ TEXT ,proc_def_id_ TEXT NOT NULL ,start_time_ TIMESTAMPTZ NOT NULL ,end_time_ TIMESTAMPTZ ,duration_ NUMERIC ,start_user_id_ TEXT ,start_act_id_ TEXT ,end_act_id_ TEXT ,super_process_instance_id_ TEXT ,super_case_instance_id_ TEXT ,case_inst_id_ TEXT ,delete_reason_ TEXT ,tenant_id_ TEXT ,state_ TEXT ); CREATE TABLE public.act_hi_taskinst ( id_ TEXT NOT NULL ,task_def_key_ TEXT ,proc_def_key_ TEXT ,proc_def_id_ TEXT ,proc_inst_id_ TEXT ,execution_id_ TEXT ,case_def_key_ TEXT ,case_def_id_ TEXT ,case_inst_id_ TEXT ,case_execution_id_ TEXT ,act_inst_id_ TEXT ,name_ TEXT ,parent_task_id_ TEXT ,description_ TEXT ,owner_ TEXT ,assignee_ TEXT ,start_time_ TIMESTAMPTZ NOT NULL ,end_time_ TIMESTAMPTZ ,duration_ NUMERIC ,delete_reason_ TEXT ,priority_ INT ,due_date_ TIMESTAMPTZ ,follow_up_date_ TIMESTAMPTZ ,tenant_id_ TEXT ); CREATE TABLE public.act_hi_varinst ( id_ TEXT NOT NULL ,proc_def_key_ TEXT ,proc_def_id_ TEXT ,proc_inst_id_ TEXT ,execution_id_ TEXT ,case_def_key_ TEXT ,case_def_id_ TEXT ,case_inst_id_ TEXT ,case_execution_id_ TEXT ,act_inst_id_ TEXT ,task_id_ TEXT ,name_ TEXT NOT NULL ,var_type_ TEXT ,rev_ INT ,bytearray_id_ TEXT ,double_ REAL ,long_ NUMERIC ,text_ TEXT ,text2_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_id_group ( id_ TEXT NOT NULL ,rev_ INT ,name_ TEXT ,type_ TEXT ); CREATE TABLE public.act_id_info ( id_ TEXT NOT NULL ,rev_ INT ,user_id_ TEXT ,type_ TEXT ,key_ TEXT ,value_ TEXT ,password_ BYTEA ,parent_id_ TEXT ); CREATE TABLE public.act_id_membership ( user_id_ TEXT NOT NULL ,group_id_ TEXT NOT NULL ); CREATE TABLE public.act_id_tenant ( id_ TEXT NOT NULL ,rev_ INT ,name_ TEXT ); CREATE TABLE public.act_id_tenant_member ( id_ TEXT NOT NULL ,tenant_id_ TEXT NOT NULL ,user_id_ TEXT ,group_id_ TEXT ); CREATE TABLE public.act_id_user ( id_ TEXT NOT NULL ,rev_ INT ,first_ TEXT ,last_ TEXT ,email_ TEXT ,pwd_ TEXT ,salt_ TEXT ,picture_id_ TEXT ); CREATE TABLE public.act_re_case_def ( id_ TEXT NOT NULL ,rev_ INT ,category_ TEXT ,name_ TEXT ,key_ TEXT NOT NULL ,version_ INT NOT NULL ,deployment_id_ TEXT ,resource_name_ TEXT ,dgrm_resource_name_ TEXT ,tenant_id_ TEXT ,history_ttl_ INT ); CREATE TABLE public.act_re_decision_def ( id_ TEXT NOT NULL ,rev_ INT ,category_ TEXT ,name_ TEXT ,key_ TEXT NOT NULL ,version_ INT NOT NULL ,deployment_id_ TEXT ,resource_name_ TEXT ,dgrm_resource_name_ TEXT ,dec_req_id_ TEXT ,dec_req_key_ TEXT ,tenant_id_ TEXT ,history_ttl_ INT ); CREATE TABLE public.act_re_decision_req_def ( id_ TEXT NOT NULL ,rev_ INT ,category_ TEXT ,name_ TEXT ,key_ TEXT NOT NULL ,version_ INT NOT NULL ,deployment_id_ TEXT ,resource_name_ TEXT ,dgrm_resource_name_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_re_deployment ( id_ TEXT NOT NULL ,name_ TEXT ,deploy_time_ TIMESTAMPTZ ,source_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_re_procdef ( id_ TEXT NOT NULL ,rev_ INT ,category_ TEXT ,name_ TEXT ,key_ TEXT NOT NULL ,version_ INT NOT NULL ,deployment_id_ TEXT ,resource_name_ TEXT ,dgrm_resource_name_ TEXT ,has_start_form_key_ INT ,suspension_state_ INT ,tenant_id_ TEXT ,version_tag_ TEXT ,history_ttl_ INT ); CREATE TABLE public.act_ru_authorization ( id_ TEXT NOT NULL ,rev_ INT ,type_ INT NOT NULL ,group_id_ TEXT ,user_id_ TEXT ,resource_type_ INT NOT NULL ,resource_id_ TEXT ,perms_ INT ); CREATE TABLE public.act_ru_batch ( id_ TEXT NOT NULL ,rev_ INT NOT NULL ,type_ TEXT ,total_jobs_ INT ,jobs_created_ INT ,jobs_per_seed_ INT ,invocations_per_job_ INT ,seed_job_def_id_ TEXT ,batch_job_def_id_ TEXT ,monitor_job_def_id_ TEXT ,suspension_state_ INT ,configuration_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_ru_case_execution ( id_ TEXT NOT NULL ,rev_ INT ,case_inst_id_ TEXT ,super_case_exec_ TEXT ,super_exec_ TEXT ,business_key_ TEXT ,parent_id_ TEXT ,case_def_id_ TEXT ,act_id_ TEXT ,prev_state_ INT ,current_state_ INT ,required_ INT ,tenant_id_ TEXT ); CREATE TABLE public.act_ru_case_sentry_part ( id_ TEXT NOT NULL ,rev_ INT ,case_inst_id_ TEXT ,case_exec_id_ TEXT ,sentry_id_ TEXT ,type_ TEXT ,source_case_exec_id_ TEXT ,standard_event_ TEXT ,source_ TEXT ,variable_event_ TEXT ,variable_name_ TEXT ,satisfied_ INT ,tenant_id_ TEXT ); CREATE TABLE public.act_ru_event_subscr ( id_ TEXT NOT NULL ,rev_ INT ,event_type_ TEXT NOT NULL ,event_name_ TEXT ,execution_id_ TEXT ,proc_inst_id_ TEXT ,activity_id_ TEXT ,configuration_ TEXT ,created_ TIMESTAMPTZ NOT NULL ,tenant_id_ TEXT ); CREATE TABLE public.act_ru_execution ( id_ TEXT NOT NULL ,rev_ INT ,proc_inst_id_ TEXT ,business_key_ TEXT ,parent_id_ TEXT ,proc_def_id_ TEXT ,super_exec_ TEXT ,super_case_exec_ TEXT ,case_inst_id_ TEXT ,act_id_ TEXT ,act_inst_id_ TEXT ,is_active_ INT ,is_concurrent_ INT ,is_scope_ INT ,is_event_scope_ INT ,suspension_state_ INT ,cached_ent_state_ INT ,sequence_counter_ NUMERIC ,tenant_id_ TEXT ); CREATE TABLE public.act_ru_ext_task ( id_ TEXT NOT NULL ,rev_ INT NOT NULL ,worker_id_ TEXT ,topic_name_ TEXT ,retries_ INT ,error_msg_ TEXT ,error_details_id_ TEXT ,lock_exp_time_ TIMESTAMPTZ ,suspension_state_ INT ,execution_id_ TEXT ,proc_inst_id_ TEXT ,proc_def_id_ TEXT ,proc_def_key_ TEXT ,act_id_ TEXT ,act_inst_id_ TEXT ,tenant_id_ TEXT ,priority_ NUMERIC NOT NULL DEFAULT 0 ); CREATE TABLE public.act_ru_filter ( id_ TEXT NOT NULL ,rev_ INT NOT NULL ,resource_type_ TEXT NOT NULL ,name_ TEXT NOT NULL ,owner_ TEXT ,query_ VARCHAR NOT NULL ,properties_ VARCHAR ); CREATE TABLE public.act_ru_identitylink ( id_ TEXT NOT NULL ,rev_ INT ,group_id_ TEXT ,type_ TEXT ,user_id_ TEXT ,task_id_ TEXT ,proc_def_id_ TEXT ,tenant_id_ TEXT ); CREATE TABLE public.act_ru_incident ( id_ TEXT NOT NULL ,rev_ INT NOT NULL ,incident_timestamp_ TIMESTAMPTZ NOT NULL ,incident_msg_ TEXT ,incident_type_ TEXT NOT NULL ,execution_id_ TEXT ,activity_id_ TEXT ,proc_inst_id_ TEXT ,proc_def_id_ TEXT ,cause_incident_id_ TEXT ,root_cause_incident_id_ TEXT ,configuration_ TEXT ,tenant_id_ TEXT ,job_def_id_ TEXT ); CREATE TABLE public.act_ru_job ( id_ TEXT NOT NULL ,rev_ INT ,type_ TEXT NOT NULL ,lock_exp_time_ TIMESTAMPTZ ,lock_owner_ TEXT ,exclusive_ BOOLEAN ,execution_id_ TEXT ,process_instance_id_ TEXT ,process_def_id_ TEXT ,process_def_key_ TEXT ,retries_ INT ,exception_stack_id_ TEXT ,exception_msg_ TEXT ,duedate_ TIMESTAMPTZ ,repeat_ TEXT ,handler_type_ TEXT ,handler_cfg_ TEXT ,deployment_id_ TEXT ,suspension_state_ INT NOT NULL DEFAULT 1 ,priority_ NUMERIC NOT NULL DEFAULT 0 ,job_def_id_ TEXT ,sequence_counter_ NUMERIC ,tenant_id_ TEXT ); CREATE TABLE public.act_ru_jobdef ( id_ TEXT NOT NULL ,rev_ INT ,proc_def_id_ TEXT ,proc_def_key_ TEXT ,act_id_ TEXT ,job_type_ TEXT NOT NULL ,job_configuration_ TEXT ,suspension_state_ INT ,job_priority_ NUMERIC ,tenant_id_ TEXT ); CREATE TABLE public.act_ru_meter_log ( id_ TEXT NOT NULL ,name_ TEXT NOT NULL ,reporter_ TEXT ,value_ NUMERIC ,timestamp_ TIMESTAMPTZ ,milliseconds_ NUMERIC DEFAULT 0 ); CREATE TABLE public.act_ru_task ( id_ TEXT NOT NULL ,rev_ INT ,execution_id_ TEXT ,proc_inst_id_ TEXT ,proc_def_id_ TEXT ,case_execution_id_ TEXT ,case_inst_id_ TEXT ,case_def_id_ TEXT ,name_ TEXT ,parent_task_id_ TEXT ,description_ TEXT ,task_def_key_ TEXT ,owner_ TEXT ,assignee_ TEXT ,delegation_ TEXT ,priority_ INT ,create_time_ TIMESTAMPTZ ,due_date_ TIMESTAMPTZ ,follow_up_date_ TIMESTAMPTZ ,suspension_state_ INT ,tenant_id_ TEXT ); CREATE TABLE public.act_ru_variable ( id_ TEXT NOT NULL ,rev_ INT ,type_ TEXT NOT NULL ,name_ TEXT NOT NULL ,execution_id_ TEXT ,proc_inst_id_ TEXT ,case_execution_id_ TEXT ,case_inst_id_ TEXT ,task_id_ TEXT ,bytearray_id_ TEXT ,double_ REAL ,long_ NUMERIC ,text_ TEXT ,text2_ TEXT ,var_scope_ TEXT NOT NULL ,sequence_counter_ NUMERIC ,is_concurrent_local_ INT ,tenant_id_ TEXT ); CREATE TABLE public.address_type ( id TEXT NOT NULL ,descr TEXT ); CREATE TABLE public.bank ( id INT NOT NULL ,name TEXT NOT NULL ,universal_branch_code INT NOT NULL ); CREATE TABLE public.bank_account_type ( id TEXT NOT NULL ,descr TEXT NOT NULL ); CREATE TABLE public.bank_branch ( id INT NOT NULL ,bank_id INT NOT NULL ,name TEXT NOT NULL ,branch_code INT NOT NULL ); CREATE TABLE public.bank_branch_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,bank_id INT ,name TEXT ,branch_code INT ); CREATE TABLE public.bank_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,name TEXT ,universal_branch_code INT ); CREATE TABLE public.captcha ( id INT NOT NULL ,value TEXT NOT NULL ,data VARCHAR NOT NULL ); CREATE TABLE public.captcha_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,value TEXT ,data VARCHAR ); CREATE TABLE public.comm_type ( id TEXT NOT NULL ,descr TEXT ); CREATE TABLE public.country ( id TEXT NOT NULL ,descr TEXT NOT NULL ); CREATE TABLE public.country_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id TEXT NOT NULL ,descr TEXT ); CREATE TABLE public.doc_type ( id TEXT NOT NULL ,descr TEXT NOT NULL ); CREATE TABLE public.endpoint ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,name TEXT NOT NULL ,url TEXT NOT NULL ,requested_time TIMESTAMPTZ NOT NULL ,response TEXT NOT NULL ,status TEXT NOT NULL ); CREATE TABLE public.endpoint_stat ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,endpoint_id INT NOT NULL ,requested_time DATE NOT NULL ,response TEXT NOT NULL ,status TEXT NOT NULL ); CREATE TABLE public.feature ( id INT NOT NULL ,name TEXT NOT NULL ,value TEXT NOT NULL ,descr TEXT NOT NULL ); CREATE TABLE public.feature_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,name TEXT ,value TEXT ,descr TEXT ); CREATE TABLE public.holiday ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,date TIMESTAMPTZ NOT NULL ,descr TEXT ); CREATE TABLE public.leave_balance ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,user_id INT NOT NULL ,type_id TEXT NOT NULL ,date TIMESTAMPTZ NOT NULL ,rate NUMERIC NOT NULL ,balance NUMERIC NOT NULL ,leave_request_id INT ); CREATE TABLE public.leave_balance_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,user_id INT ,type_id TEXT ,date TIMESTAMPTZ ,rate NUMERIC ,balance NUMERIC ,leave_request_id INT ); CREATE TABLE public.leave_type ( id TEXT NOT NULL ,descr TEXT ); CREATE TABLE public.personal_ref_type ( id TEXT NOT NULL ,descr TEXT ); CREATE TABLE public.province ( id INT NOT NULL ,descr TEXT NOT NULL ); CREATE TABLE public.province_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,descr TEXT ); CREATE TABLE public.rev_type ( id INT NOT NULL ,desrc TEXT NOT NULL ); CREATE TABLE public.revision ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,modified_by INT NOT NULL ,timestamp BIGINT NOT NULL ,date_modified TIMESTAMPTZ NOT NULL ); CREATE TABLE public.system_job ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,class_name TEXT NOT NULL ,start_time TIMESTAMPTZ NOT NULL ,end_time TIMESTAMPTZ ,processing_time INT ,successful_ind VARCHAR(1) NOT NULL ,comment TEXT ); CREATE TABLE public.timesheet ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,name TEXT NOT NULL ,start_date TIMESTAMPTZ NOT NULL ,end_date TIMESTAMPTZ NOT NULL ,billable_hours INT NOT NULL ); CREATE TABLE public.timesheet_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,name TEXT ,start_date TIMESTAMPTZ ,end_date TIMESTAMPTZ ,billable_hours INT ); CREATE TABLE public.user_acc ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,first_name TEXT NOT NULL ,last_name TEXT NOT NULL ,display_name TEXT NOT NULL ,primary_email_address TEXT ,mobile_no TEXT ,prefer_comm_type TEXT ,username TEXT NOT NULL ,password TEXT ,personal_ref_type TEXT ,personal_ref_value TEXT ,income_tax_number TEXT ,account_non_expired VARCHAR(1) ,account_non_locked VARCHAR(1) ,credentials_non_expired VARCHAR(1) ,enabled VARCHAR(1) ,reserved VARCHAR(1) ,password_expired VARCHAR(1) ,activation_serial_no TEXT ,last_login_time TIMESTAMPTZ ,status TEXT NOT NULL ,date_of_birth TIMESTAMPTZ ); CREATE TABLE public.user_acc_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,first_name TEXT ,last_name TEXT ,display_name TEXT NOT NULL ,primary_email_address TEXT ,mobile_no TEXT ,prefer_comm_type TEXT ,username TEXT ,password TEXT ,personal_ref_type TEXT ,personal_ref_value TEXT ,income_tax_number TEXT ,account_non_expired VARCHAR(1) ,account_non_locked VARCHAR(1) ,credentials_non_expired VARCHAR(1) ,enabled VARCHAR(1) ,reserved VARCHAR(1) ,password_expired VARCHAR(1) ,activation_serial_no TEXT ,last_login_time TIMESTAMPTZ ,status TEXT ,date_of_birth TIMESTAMPTZ ); CREATE TABLE public.user_acc_timesheet ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,timesheet_id INT NOT NULL ,user_id INT NOT NULL ,total_actual_hours DECIMAL NOT NULL ); CREATE TABLE public.user_acc_timesheet_line ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,user_timesheet_id INT ,pos INT NOT NULL ,descr TEXT NOT NULL ,actual_hours DECIMAL NOT NULL ); CREATE TABLE public.user_acc_timesheet_line_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,user_timesheet_id INT ,pos INT ,descr TEXT ,actual_hours DECIMAL ); CREATE TABLE public.user_acc_timesheet_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,timesheet_id INT ,user_id INT ,total_actual_hours DECIMAL ); CREATE TABLE public.user_address ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,user_id INT NOT NULL ,address_type TEXT NOT NULL ,line_1 TEXT ,line_2 TEXT ,line_3 TEXT ,line_4 TEXT ,postcode TEXT NOT NULL ,province_id INT NOT NULL ,country_id TEXT NOT NULL ); CREATE TABLE public.user_address_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,user_id INT NOT NULL ,address_type TEXT ,line_1 TEXT ,line_2 TEXT ,line_3 TEXT ,line_4 TEXT ,postcode TEXT ,province_id INT ,country_id TEXT ); CREATE TABLE public.user_bank_account ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,user_id INT NOT NULL ,bank_branch_id INT NOT NULL ,account_no TEXT NOT NULL ,account_type TEXT NOT NULL ); CREATE TABLE public.user_bank_account_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,user_id INT ,bank_branch_id INT ,account_no TEXT ,account_type TEXT ); CREATE TABLE public.user_doc ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,user_id INT NOT NULL ,file_name TEXT NOT NULL ,doc_type TEXT NOT NULL ,mime_type TEXT ,size_in_kb INT NOT NULL ,status TEXT NOT NULL ,date_created TIMESTAMPTZ NOT NULL ,date_verified TIMESTAMPTZ ,verified_by INT ); CREATE TABLE public.user_doc_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,user_id INT NOT NULL ,file_name TEXT ,doc_type TEXT ,mime_type TEXT ,size_in_kb INT ,status TEXT ,date_created TIMESTAMPTZ ,date_verified TIMESTAMPTZ ,verified_by INT ); CREATE TABLE public.user_doc_status ( id TEXT NOT NULL ,descr TEXT NOT NULL ); CREATE TABLE public.user_leave ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,user_id INT NOT NULL ,type_id TEXT NOT NULL ,start_date TIMESTAMPTZ NOT NULL ,end_date TIMESTAMPTZ NOT NULL ,days INT NOT NULL ,status TEXT NOT NULL ,date_created TIMESTAMPTZ NOT NULL ,date_approved TIMESTAMPTZ ,approved_by INT ); CREATE TABLE public.user_leave_balance ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,user_id INT NOT NULL ,type_id TEXT NOT NULL ,balance NUMERIC NOT NULL ,start_date TIMESTAMPTZ NOT NULL ,end_date TIMESTAMPTZ NOT NULL ); CREATE TABLE public.user_leave_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,user_id INT ,type_id TEXT ,start_date TIMESTAMPTZ ,end_date TIMESTAMPTZ ,days INT ,status TEXT ,date_created TIMESTAMPTZ ,date_approved TIMESTAMPTZ ,approved_by INT ); CREATE TABLE public.user_leave_rate ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,user_id INT NOT NULL ,leave_type_id TEXT NOT NULL ,rate NUMERIC NOT NULL ,start_date TIMESTAMPTZ NOT NULL ,end_date TIMESTAMPTZ NOT NULL ); CREATE TABLE public.user_leave_rate_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,user_id INT ,leave_type_id TEXT ,rate NUMERIC ,start_date TIMESTAMPTZ ,end_date TIMESTAMPTZ ); CREATE TABLE public.user_payslip ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,user_id INT NOT NULL ,name TEXT NOT NULL ,file_name TEXT NOT NULL ,encoded_image VARCHAR NOT NULL ,mime_type TEXT ,size_in_kb INT NOT NULL ,status TEXT NOT NULL ,date_created TIMESTAMPTZ NOT NULL ,date_verified TIMESTAMPTZ ,verified_by INT ); CREATE TABLE public.user_payslip_log ( rev INT NOT NULL ,rev_type INT NOT NULL ,id INT NOT NULL ,user_id INT ,name TEXT ,file_name TEXT ,mime_type TEXT ,size_in_kb INT ,status TEXT ,date_created TIMESTAMPTZ ,date_verified TIMESTAMPTZ ,verified_by INT ); CREATE TABLE public.user_role ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL ,user_id INT ,role TEXT NOT NULL ); CREATE TABLE public.user_status ( id TEXT NOT NULL ,descr TEXT ); -- ROLLBACK; COMMIT; <file_sep>/business-api/src/test/java/s2/portal/service/common/BaseSpringJUnit4TestSuite.java package s2.portal.service.common; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; import org.springframework.transaction.annotation.Transactional; /** * Base class for tests that will use spring injection to access the application's services and data access objects. * * @author <NAME> * @since August 2016 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring/s2-portal-business-api-test-context.xml"}) @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class}) @TransactionConfiguration(transactionManager = "s2portalTransactionManager") @Transactional public abstract class BaseSpringJUnit4TestSuite { @Before public final void beforeTest() { } @After public final void afterTest() throws Exception { rollback(); } private void rollback() throws IllegalArgumentException, IllegalAccessException { } } <file_sep>/db/src/main/java/s2/portal/db/test/SampleData.java package s2.portal.db.test; /** * @author <NAME> * @since July 2016 */ public class SampleData { public enum User { Anonymous(-99), SystemAdministration(1); private Integer primaryId; User(Integer primaryId) { this.primaryId = primaryId; } public Integer getPrimaryId() { return primaryId; } } } <file_sep>/db/src/main/java/s2/portal/dao/PayslipDao.java package s2.portal.dao; import s2.portal.data.user.Payslip; import java.util.List; /** * @author <NAME> * @since September 2018 */ public interface PayslipDao extends AuditLogDao<Integer, Payslip> { List<Payslip> findTopXPayslipsByUser(Integer userId, int top); Payslip findByUserAndName(Integer userId,String name); /** * Returns the list of user documents for the given user. * * @param userId The user pk. * @return A list. */ List<Payslip> findByUser(Integer userId); } <file_sep>/business-api/src/main/java/s2/portal/bpm/tasks/leave/CalculateLeaveBalanceTask.java package s2.portal.bpm.tasks.leave; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import s2.portal.bpm.client.json.LeaveRequest; import s2.portal.command.CalculateLeaveBalanceCommand; import s2.portal.data.user.Leave; /** * @author <NAME> * @since October 2018 */ @Component public class CalculateLeaveBalanceTask implements JavaDelegate { private final Logger log = LoggerFactory.getLogger(CalculateLeaveBalanceTask.class); private CalculateLeaveBalanceCommand calculateLeaveBalanceCommand; @Autowired public CalculateLeaveBalanceTask(CalculateLeaveBalanceCommand calculateLeaveBalanceCommand) { this.calculateLeaveBalanceCommand = calculateLeaveBalanceCommand; } @Override public void execute(final DelegateExecution delegateExecution) { log.info("Called"); final LeaveRequest request = (LeaveRequest) delegateExecution.getVariable("request"); final Leave leave = request.getLeave(); calculateLeaveBalanceCommand.execute(leave.getUserId(), leave.getTypeId()); } }<file_sep>/db/src/main/java/s2/portal/data/system/Bank.java package s2.portal.data.system; import s2.portal.data.BaseModel; import org.hibernate.envers.Audited; import javax.persistence.*; /** * @author <NAME> * @since October 2016 */ @Entity @Table(name = "bank") public class Bank extends BaseModel<Integer> { private static final long serialVersionUID = 8127574934602321588L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @Audited private Integer primaryId; @Column(name = "name") @Audited private String name; @Column(name = "universal_branch_code") @Audited private Integer universalBranchCode; /** * Set the unique identifier for the object. * * @param primaryId The primary key to set. */ @Override public void setPrimaryId(Integer primaryId) { this.primaryId = primaryId; } /** * Returns the unique identifier of the object. * * @return The primary key value. */ @Override public Integer getPrimaryId() { return primaryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getUniversalBranchCode() { return universalBranchCode; } public void setUniversalBranchCode(Integer universalBranchCode) { this.universalBranchCode = universalBranchCode; } @Override public String toString() { return "Bank{" + "primaryId=" + primaryId + ", name='" + name + '\'' + ", universalBranchCode=" + universalBranchCode + '}'; } }<file_sep>/db/src/main/java/s2/portal/data/user/UserAddress.java package s2.portal.data.user; import com.fasterxml.jackson.annotation.JsonGetter; import s2.portal.data.BaseModel; import s2.portal.data.system.Province; import org.hibernate.envers.Audited; import org.springframework.util.StringUtils; import javax.persistence.*; /** * @author <NAME> * @since October 2016 */ @Entity @Table(name = "user_address") public class UserAddress extends BaseModel<Integer> { private static final long serialVersionUID = 7841441964254355561L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @Audited private Integer primaryId; @Column(name = "user_id") @Audited private Integer userId; @Column(name = "address_type") @Audited private String addressTypeId; @Column(name = "line1") @Audited private String line1; @Column(name = "line2") @Audited private String line2; @Column(name = "line3") @Audited private String line3; @Column(name = "line4") @Audited private String line4; @Column(name = "postcode") @Audited private String postcode; @ManyToOne @JoinColumn(name = "province_id") @Audited private Province province; @Column(name = "country_id") @Audited private String countryId; /** * Set the unique identifier for the object. * * @param primaryId The primary key to set. */ @Override public void setPrimaryId(Integer primaryId) { this.primaryId = primaryId; } /** * Returns the unique identifier of the object. * * @return The primary key value. */ @Override public Integer getPrimaryId() { return primaryId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getAddressTypeId() { return addressTypeId; } public void setAddressTypeId(String addressTypeId) { this.addressTypeId = addressTypeId; } public String getLine1() { return line1; } public void setLine1(String line1) { this.line1 = line1; } public String getLine2() { return line2; } public void setLine2(String line2) { this.line2 = line2; } public String getLine3() { return line3; } public void setLine3(String line3) { this.line3 = line3; } public String getLine4() { return line4; } public void setLine4(String line4) { this.line4 = line4; } public String getPostcode() { return postcode; } public void setPostcode(String postcode) { this.postcode = postcode; } public Province getProvince() { return province; } public void setProvince(Province province) { this.province = province; } public String getCountryId() { return countryId; } public void setCountryId(String countryId) { this.countryId = countryId; } @JsonGetter public String getDescription() { final StringBuilder buffer = new StringBuilder(); buffer.append(getLine1()); if (!StringUtils.isEmpty(getLine2())) { buffer.append(", ").append(getLine2()); } if (!StringUtils.isEmpty(getLine3())) { buffer.append(", ").append(getLine3()); } if (!StringUtils.isEmpty(getLine4())) { buffer.append(", ").append(getLine4()); } if (getProvince() != null) { buffer.append(", ").append(getProvince().getDescription()); } if (!StringUtils.isEmpty(getPostcode())) { buffer.append(", ").append(getPostcode()); } if (!StringUtils.isEmpty(getCountryId())) { buffer.append(", ").append(getCountryId()); } return buffer.toString(); } @Override public String toString() { return "UserAddress{" + "primaryId=" + primaryId + ", userId=" + userId + ", addressTypeId='" + addressTypeId + '\'' + ", line1='" + line1 + '\'' + ", line2='" + line2 + '\'' + ", line3='" + line3 + '\'' + ", line4='" + line4 + '\'' + ", postcode='" + postcode + '\'' + ", province=" + province + ", countryId='" + countryId + '\'' + '}'; } }<file_sep>/db/src/main/java/s2/portal/dao/impl/hibernate/UserDocumentDaoImpl.java package s2.portal.dao.impl.hibernate; import s2.portal.dao.UserDocumentDao; import s2.portal.data.user.UserDocument; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; import java.util.List; /** * @author <NAME> * @since October 2016 */ @Repository(value = "userDocumentDao") public class UserDocumentDaoImpl extends BaseAuditLogDaoImpl<Integer, UserDocument> implements UserDocumentDao { @Autowired public UserDocumentDaoImpl(@Qualifier("s2portalSessionFactory") SessionFactory sessionFactory) { super(sessionFactory, UserDocument.class); } /** * Returns the list of user documents for the given user. * * @param userId The user pk. * @return A list. */ @SuppressWarnings("unchecked") @Override public List<UserDocument> findByUser(Integer userId) { Assert.notNull(userId, "Variable userId cannot be null."); return (List<UserDocument>) getHibernateTemplate().findByNamedQueryAndNamedParam( "FIND_USER_DOC_BY_USER", "userId", userId); } } <file_sep>/db/src/main/java/s2/portal/dao/impl/hibernate/HolidayDaoImpl.java package s2.portal.dao.impl.hibernate; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import s2.portal.dao.HolidayDao; import s2.portal.data.user.Holiday; /** * @author <NAME> * @since September 2018 */ @Repository(value = "holidayDao") public class HolidayDaoImpl extends BaseAuditLogDaoImpl<Integer, Holiday> implements HolidayDao { @Autowired public HolidayDaoImpl(@Qualifier("s2portalSessionFactory") SessionFactory sessionFactory) { super(sessionFactory, Holiday.class); } } <file_sep>/db/src/main/java/s2/portal/dao/impl/hibernate/UserLeaveRateDaoImpl.java package s2.portal.dao.impl.hibernate; import org.hibernate.SessionFactory; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; import s2.portal.dao.UserLeaveRateDao; import s2.portal.data.user.UserLeaveRate; import java.util.List; /** * @author <NAME> * @since October 2018 */ @Repository(value = "userLeaveRateDao") public class UserLeaveRateDaoImpl extends BaseAuditLogDaoImpl<Integer, UserLeaveRate> implements UserLeaveRateDao { @Autowired public UserLeaveRateDaoImpl(@Qualifier("s2portalSessionFactory") SessionFactory sessionFactory) { super(sessionFactory, UserLeaveRate.class); } /** * Returns the list of user bank accounts for the given user. * * @param userId The user pk. * @return A list. */ @SuppressWarnings("unchecked") @Override public List<UserLeaveRate> findByUser(Integer userId) { Assert.notNull(userId, "userId cannot be null."); final DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserLeaveRate.class, "userLeaveRate"); detachedCriteria.add(Restrictions.eq("userLeaveRate.userId", userId)); return (List<UserLeaveRate>) getHibernateTemplate().findByCriteria(detachedCriteria); } @SuppressWarnings("JpaQueryApiInspection") @Override public UserLeaveRate findByUser(Integer userId, String leaveTypeId, DateTime effectiveDate) { Assert.notNull(userId, "Variable userId cannot be null."); Assert.notNull(leaveTypeId, "Variable leaveTypeId cannot be null."); Assert.notNull(effectiveDate, "Variable effectiveDate cannot be null."); final List<?> data = getHibernateTemplate().findByNamedQueryAndNamedParam( "FIND_USER_LEAVE_RATE" , new String[]{"userId", "leaveTypeId", "effectiveDate"} , new Object[]{userId, leaveTypeId, effectiveDate.toDate()}); return data == null || data.isEmpty() ? null : (UserLeaveRate) data.iterator().next(); } } <file_sep>/db/src/main/java/s2/portal/dao/BankDao.java package s2.portal.dao; import s2.portal.data.system.Bank; /** * @author <NAME> * @since October 2016 */ public interface BankDao extends AuditLogDao<Integer, Bank> { /** * Returns the bank for the given name. * * @param name The name to evaluate. * @return The bank or null. */ Bank findByName(String name); } <file_sep>/business-api/src/main/java/s2/portal/bpm/client/json/CalculateLeaveDaysRequest.java package s2.portal.bpm.client.json; import s2.portal.data.user.Leave; import java.io.Serializable; /** * @author <NAME> * @since September 2018 */ public class CalculateLeaveDaysRequest implements Serializable { private static final long serialVersionUID = 1394344513932156436L; private Leave leave; public Leave getLeave() { return leave; } public void setLeave(Leave leave) { this.leave = leave; } } <file_sep>/README.md # Deployment ### Docker docker build -t stackworx/s2-portal:v1.0.0 . docker login ciaranstackworx/mYx2A7U9pNgFjMqN docker push stackworx/s2-portal:tagname ### Kubernetes create k8/deployment.yaml kubectl create namespace test kubectl apply -f deployment.yaml Useful commands kubectl edit ns test Deployment fails Failed to pull image "stackworx/s2-portal:v1.0.0": rpc error: code = Unknown desc = Error response from daemon: pull access denied for stackworx/s2-portal, repository does not exist or may require 'docker login' Then run: kubectl -n test create secret docker-registry regcred --docker-username=ciaranstackworx --docker-password=<PASSWORD> --docker-email=<EMAIL> ### Helm Chart for MSSQL https://github.com/helm/charts/tree/master/stable/mssql-linux Command: helm install --name mymssql --namespace=test stable/mssql-linux --set acceptEula.value=Y --set edition.value=Developer Then: kubectl -n test get pods kubectl -n test port-forward mymssql-mssql-linux-6577cd69bd-2sjd5 1433:1433 View installed helm charts helm ls To remove a chart helm delete --purge mymssql To delete a deployment kubectl delete -f deployment.yaml To delete namespace kubectl delete ns test <file_sep>/db/migration/s2portal-add-pk.sql ALTER TABLE user_acc ADD PRIMARY KEY(id); ALTER TABLE holiday ADD PRIMARY KEY(id); ALTER TABLE leave_balance ADD PRIMARY KEY(id); ALTER TABLE leave_balance_log ADD PRIMARY KEY(rev, id); ALTER TABLE leave_type ADD PRIMARY KEY(id); ALTER TABLE rev_type ADD PRIMARY KEY(id); ALTER TABLE revision ADD PRIMARY KEY(id); ALTER TABLE timesheet ADD PRIMARY KEY(id); ALTER TABLE timesheet_log ADD PRIMARY KEY(rev, id); ALTER TABLE user_acc_timesheet ADD PRIMARY KEY(id); ALTER TABLE user_acc_timesheet_line ADD PRIMARY KEY(id); ALTER TABLE user_acc_timesheet_line_log ADD PRIMARY KEY(rev, id); ALTER TABLE user_acc_timesheet_log ADD PRIMARY KEY(rev, id); ALTER TABLE user_leave ADD PRIMARY KEY(id); ALTER TABLE user_leave_balance ADD PRIMARY KEY(id); ALTER TABLE user_leave_log ADD PRIMARY KEY(rev, id); ALTER TABLE user_leave_rate ADD PRIMARY KEY(id); ALTER TABLE user_leave_rate_log ADD PRIMARY KEY(rev, id); ALTER TABLE user_payslip_log ADD PRIMARY KEY(rev, id);<file_sep>/business-api/src/main/java/s2/portal/service/impl/camunda/CamundaWorkflowServiceImpl.java package s2.portal.service.impl.camunda; import org.apache.commons.lang3.StringUtils; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.TaskService; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.task.IdentityLink; import org.camunda.bpm.engine.task.Task; import org.camunda.bpm.engine.variable.VariableMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import s2.portal.bpm.WorkflowRequestOutOfDateException; import s2.portal.bpm.client.common.CamundaProcess; import s2.portal.bpm.client.json.*; import s2.portal.bpm.constants.UserRegistrationVariables; import s2.portal.data.Feature; import s2.portal.data.user.KnownUser; import s2.portal.data.user.User; import s2.portal.security.*; import s2.portal.service.FeatureService; import s2.portal.service.UserService; import s2.portal.service.WorkflowService; import s2.portal.util.FileUtils; import java.util.*; import java.util.stream.Collectors; import static org.camunda.bpm.engine.variable.Variables.createVariables; /** * @author <NAME> * @since September 2016 */ @Component(value = "workflowService") public class CamundaWorkflowServiceImpl implements WorkflowService { private static final Logger LOG = LoggerFactory.getLogger(CamundaWorkflowServiceImpl.class); private RuntimeService runtimeService; private FeatureService featureService; private TaskService taskService; private UserService userService; @SuppressWarnings("SpringJavaAutowiringInspection") @Autowired public CamundaWorkflowServiceImpl(RuntimeService runtimeService , FeatureService featureService , TaskService taskService , UserService userService) { this.runtimeService = runtimeService; this.featureService = featureService; this.taskService = taskService; this.userService = userService; } @Override public LeaveResponse requestSomeTimeOff(LeaveRequest request) { Assert.notNull(request, "The request cannot be null."); final String businessKey = "FP-" + UUID.randomUUID().toString().replace("-", ""); LOG.info("businessKey: {}", businessKey); request.setBusinessKey(businessKey); request.setDateCreated(new Date()); final Map<String, Object> variables = new HashMap<>(); variables.put("request", request); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(CamundaProcess.Leave.id() , businessKey, variables); LOG.info("Completed <" + request.getType() + "> with process #: " + processInstance.getProcessInstanceId()); return new LeaveResponse(processInstance.getProcessInstanceId()); } @Override public ForgotPasswordResponse forgetPassword(ForgotPasswordRequest request) { Assert.notNull(request, "The request cannot be null."); final String businessKey = "FP-" + UUID.randomUUID().toString().replace("-", ""); LOG.info("businessKey: {}", businessKey); request.setBusinessKey(businessKey); request.setDateCreated(new Date()); request.setEmailAddress(StringUtils.stripToNull(request.getEmailAddress())); request.setUsername(StringUtils.stripToNull(request.getUsername())); final Map<String, Object> variables = new HashMap<>(); variables.put("request", request); final User recipient; if (StringUtils.isNotBlank(request.getEmailAddress())) { recipient = userService.findByPrimaryEmailAddress(request.getEmailAddress()); if (recipient == null) { throw new DataIntegrityViolationException(String.format("System cannot complete request. No " + "user found for email address <%s>.", request.getEmailAddress())); } } else if (StringUtils.isNotBlank(request.getUsername())) { recipient = userService.findByUsername(request.getUsername()); if (recipient == null) { throw new DataIntegrityViolationException(String.format("System cannot complete request. No " + "user found for username <%s>.", request.getUsername())); } } else { throw new DataIntegrityViolationException("System cannot complete request. Need to specify either the " + "email address or the username of the user to reset the password for."); } final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(CamundaProcess.ForgotPassword.id() , businessKey, variables); LOG.info("Completed <" + request.getType() + "> with process #: " + processInstance.getProcessInstanceId()); return new ForgotPasswordResponse(processInstance.getProcessInstanceId() , recipient.getPrimaryEmailAddress()); } /** * The method to kick-off the register user process. * * @param request The request. * @return The response. */ @Override public RegisterUserAccountResponse register(RegisterUserAccountRequest request) { Assert.notNull(request, "The request cannot be null."); Assert.hasText(request.getSource(), "The source is required."); final User requestingUser = request.getRequestingUser(); Assert.notNull(requestingUser, "The requestingUser cannot be null."); if (request.getSource().equalsIgnoreCase("WEB")) { final User systemAccount = userService.findById(KnownUser.SystemAccount.getPrimaryId()); SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(systemAccount)); } else if (request.getSource().equalsIgnoreCase("ADMIN")) { SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(requestingUser)); } else { throw new UnsupportedOperationException("Source <" + request.getSource() + "> not supported"); } final Feature applicationHome = featureService.findByName(Feature.Type.APP_HOME); Assert.notNull(applicationHome, "APP_HOME not found."); Assert.hasText(applicationHome.getValue(), "APP_HOME not defined."); LOG.info("applicationHome: {}", applicationHome.getValue()); final String businessKey = request.getUser().getPersonalReferenceValue(); LOG.info("businessKey: {}", businessKey); request.setBusinessKey(businessKey); request.setDateCreated(new Date()); // C:\Users\Administrator\.lg\temp\<username> final String srcDir = FileUtils.resolveDir(applicationHome.getValue()) + "temp" + System.getProperty("file.separator") + businessKey; final Map<String, Object> variables = new HashMap<>(); variables.put("request", request); variables.put(UserRegistrationVariables.APP_HOME.id(), applicationHome.getValue()); variables.put(UserRegistrationVariables.SOURCE_DIR.id(), srcDir); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(CamundaProcess.UserRegistration.id() , businessKey, variables); final User newUser = userService.findByPrimaryEmailAddress(request.getUser().getPrimaryEmailAddress()); final String token = new UserToTokenConverter().convert(newUser); final PassportUser passportUser = new UserDetailsToPassportUserConverter().convert(newUser); final JWTToken jwtToken = new JWTToken(passportUser, token); final RegisterUserAccountResponse response = RegisterUserAccountResponseBuilder.aRegisterUserAccountResponse() .withProcessInstanceId(processInstance.getProcessInstanceId()) .withBusinessKey(businessKey) .withRequestingUserId(requestingUser.getPrimaryId()) .withRequestingUser(requestingUser.getDisplayName()) .withJwtToken(jwtToken) .build(); LOG.info("User registration process started: " + response.toString()); return response; } public WorkflowRequest findByProcessInstanceId(String processInstanceId) { Assert.notNull(processInstanceId, "System cannot complete request. processInstanceId cannot be null."); final Task task = taskService.createTaskQuery().processInstanceId(processInstanceId) .active() .singleResult(); if (task == null) { return null; } else { return buildWorkflowRequest(task); } } @Override public long countAssignedToTasks(User user) { Assert.notNull(user, "System cannot complete request. username cannot be null."); long count = taskService.createTaskQuery().taskAssignee(user.getUsername()) .active() .count(); final List<String> candidateGroups = candidateGroups(user); if (!candidateGroups.isEmpty()) { count += taskService.createTaskQuery() .taskCandidateGroupIn(candidateGroups) .active() .count(); } return count; } @SuppressWarnings("Duplicates") public List<WorkflowRequest> findAssignedToTasks(User user) { Assert.notNull(user, "System cannot complete request. username cannot be null."); final Collection<Task> tasks = new ArrayList<>(taskService.createTaskQuery().taskAssignee(user.getUsername()) .active().list()); final List<String> candidateGroups = candidateGroups(user); if (!candidateGroups.isEmpty()) { tasks.addAll(taskService.createTaskQuery().taskCandidateGroupIn(candidateGroups) .active().list()); } final List<WorkflowRequest> workflowRequests = new ArrayList<>(); for (Task task : tasks) { workflowRequests.add(buildWorkflowRequest(task)); } return workflowRequests; } private WorkflowRequest buildWorkflowRequest(Task task) { final WorkflowRequest request = (WorkflowRequest) taskService.getVariable(task.getId() , "request"); if (request.getProcessInstanceId() == null) { request.setProcessInstanceId(task.getProcessInstanceId()); } for (IdentityLink identityLink : taskService.getIdentityLinksForTask(task.getId())) { final String groupId = identityLink.getGroupId(); if (StringUtils.isNotBlank(groupId)) { request.getCandidateGroups().add(groupId); } } return request; } public TaskCompletedResponse actionTask(TaskActionRequest taskActionRequest) { Assert.notNull(taskActionRequest, "System cannot complete request. Request cannot be null."); Assert.notNull(taskActionRequest.getProcessInstanceId(), "System cannot complete request. ProcessInstanceId cannot be null."); final Task task = taskService.createTaskQuery().processInstanceId(taskActionRequest.getProcessInstanceId()).active() .singleResult(); if (task == null) { throw new WorkflowRequestOutOfDateException(String.format("System cannot complete request #%s as it out of date as someone" + " else has actioned this request. There is nothing more required from you.", taskActionRequest.getProcessInstanceId())); } else { final User requestingUser = userService.findById(taskActionRequest.getRequestingUserId()); Assert.notNull(requestingUser, String.format("System cannot complete request. No user found for id %s." , taskActionRequest.getRequestingUserId())); SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(requestingUser)); final TaskCompletedResponse response = TaskCompletedResponseBuilder.aTaskCompletedResponse() .withProcessInstanceId(taskActionRequest.getProcessInstanceId()) .withTaskId(task.getId()) .withTaskName(task.getName()) .withTaskDefinitionKey(task.getTaskDefinitionKey()) .withTaskAssignee(task.getAssignee()) .build(); final String message = String.format("Task %s: %s", taskActionRequest.getAction(), response.toString()); LOG.info(message); VariableMap variables = createVariables() .putValue("action", taskActionRequest.getAction()) .putValue("actionedBy", taskActionRequest.getRequestingUserId()) .putValue("comment", taskActionRequest.getComment()); final WorkflowRequest workflowRequest = taskActionRequest.getWorkflowRequest(); if (workflowRequest != null) { variables.putValue("request", workflowRequest); } taskService.complete(task.getId(), variables); return response; } } public CancelTaskResponse cancelTask(CancelTaskRequest request) { Assert.notNull(request, "System cannot complete request. Request cannot be null."); Assert.notNull(request.getProcessInstanceId(), "System cannot complete request. ProcessInstanceId cannot be null."); final Task task = taskService.createTaskQuery().processInstanceId(request.getProcessInstanceId()).active() .singleResult(); Assert.notNull(task, String.format("System cannot complete request. No active task found for " + "processInstanceId %s.", request.getProcessInstanceId())); final User requestingUser = userService.findById(request.getRequestingUserId()); Assert.notNull(requestingUser, String.format("System cannot complete request. No user found for id %s." , request.getRequestingUserId())); SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(requestingUser)); final WorkflowRequest workflowRequest = (WorkflowRequest) runtimeService.getVariable(request.getProcessInstanceId() , "request"); if (!Objects.equals(workflowRequest.getRequestingUser(), requestingUser)) { throw new IllegalArgumentException("System cannot cancel task as the requesting user is not the owner of the task."); } final String message = String.format("Process %s requested to be cancelled by %s.", request.getProcessInstanceId() , requestingUser.getDisplayName()); cancelTaskAndUpdate(request.getProcessInstanceId(), workflowRequest, message); return new CancelTaskResponse(message, workflowRequest); } @Transactional public void cancelTaskAndUpdate(String processInstanceId, WorkflowRequest workflowRequest, String message) { switch (workflowRequest.getType()) { case UserRegistration: final RegisterUserAccountRequest registerUserAccountRequest = (RegisterUserAccountRequest) workflowRequest; final User user = registerUserAccountRequest.getUser(); userService.delete(user); break; default: throw new UnsupportedOperationException(String.format("Workflow request type %s not supported." , workflowRequest.getType())); } runtimeService.deleteProcessInstance(processInstanceId, message); } @Override public PasswordResetResponse requestPasswordReset(PasswordResetRequest request) { Assert.notNull(request, "The request cannot be null."); final User requestingUser = request.getRequestingUser(); Assert.notNull(requestingUser, "The requestingUser cannot be null."); SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(requestingUser)); final String businessKey = "PR-" + request.getUser().getPrimaryId(); LOG.info("businessKey: {}", businessKey); request.setBusinessKey(businessKey); request.setDateCreated(new Date()); final Map<String, Object> variables = new HashMap<>(); variables.put("request", request); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(CamundaProcess.PasswordReset.id() , businessKey, variables); LOG.info("Request reset password process started: " + processInstance.getProcessInstanceId()); return new PasswordResetResponse(processInstance.getProcessInstanceId()); } private List<String> candidateGroups(User user) { final List<String> candidateGroups = new ArrayList<>(); if (user != null) { candidateGroups.addAll(user.getAuthorities().stream() .filter(grantedAuthority -> StringUtils.isNotBlank(grantedAuthority.getAuthority())) .map(GrantedAuthority::getAuthority) .collect(Collectors.toList())); candidateGroups.addAll(user.getGroupIdentities()); } return candidateGroups; } } <file_sep>/business-api/src/main/java/s2/portal/bpm/tasks/user/registration/RejectUserAccountRequestTask.java package s2.portal.bpm.tasks.user.registration; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import s2.portal.bpm.client.json.RegisterUserAccountRequest; import s2.portal.data.user.User; import s2.portal.data.user.UserStatus; import s2.portal.service.UserService; /** * @author <NAME> * @since August 2016 */ @Component public class RejectUserAccountRequestTask implements JavaDelegate { private final Logger log = LoggerFactory.getLogger(RejectUserAccountRequestTask.class); private UserService userService; @Autowired public RejectUserAccountRequestTask(UserService userService) { this.userService = userService; } @Override public void execute(final DelegateExecution delegateExecution) { log.info("Called"); final RegisterUserAccountRequest request = (RegisterUserAccountRequest) delegateExecution. getVariable("request"); final User user = request.getUser(); user.setStatus(UserStatus.Declined.id()); userService.save(user); userService.delete(user); } }<file_sep>/business-api/src/main/java/s2/portal/bpm/tasks/user/registration/SendRejectedEmailTask.java package s2.portal.bpm.tasks.user.registration; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import s2.portal.bpm.client.json.RegisterUserAccountRequest; import s2.portal.data.user.User; import s2.portal.service.NotificationService; import s2.portal.service.impl.DefaultNotificationCallback; import javax.mail.internet.MimeMessage; /** * @author <NAME> * @since August 2016 */ @Component public class SendRejectedEmailTask implements JavaDelegate { private final Logger log = LoggerFactory.getLogger(SendRejectedEmailTask.class); private NotificationService notificationService; @Autowired public SendRejectedEmailTask(NotificationService notificationService) { this.notificationService = notificationService; } @Override public void execute(final DelegateExecution delegateExecution) throws Exception { log.info("Called"); final RegisterUserAccountRequest request = (RegisterUserAccountRequest) delegateExecution. getVariable("request"); final User user = request.getUser(); final String comment = (String) delegateExecution.getVariable("comment"); log.info(String.format("Attempting to send rejection email to %s with reason %s." , user.getPrimaryEmailAddress(), comment)); final MimeMessage rejectionEmail = notificationService.createUserRequestRejectedNotification(user, comment); notificationService.send(rejectionEmail, new DefaultNotificationCallback()); } }<file_sep>/business-api/src/main/java/s2/portal/service/impl/UserLeaveRateServiceImpl.java package s2.portal.service.impl; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import s2.portal.dao.UserLeaveRateDao; import s2.portal.data.user.UserLeaveRate; import s2.portal.service.UserLeaveRateService; import java.util.List; /** * @author <NAME> * @since October 2018 */ @Service(value = "userLeaveRateService") public class UserLeaveRateServiceImpl extends JdbcAuditTemplate<Integer, UserLeaveRate, UserLeaveRateDao> implements UserLeaveRateService { private UserLeaveRateDao userLeaveRateDao; @Autowired public UserLeaveRateServiceImpl(UserLeaveRateDao userLeaveRateDao) { super(userLeaveRateDao); this.userLeaveRateDao = userLeaveRateDao; } @Override public List<UserLeaveRate> findByUser(Integer userId) { return userLeaveRateDao.findByUser(userId); } @Override public UserLeaveRate findByUser(Integer userId, String leaveTypeId, DateTime effectiveDate) { return userLeaveRateDao.findByUser(userId, leaveTypeId, effectiveDate); } } <file_sep>/business-api/src/main/java/s2/portal/service/UserLeaveRateService.java package s2.portal.service; import org.joda.time.DateTime; import s2.portal.data.user.UserLeaveRate; import java.util.List; /** * @author <NAME> * @since October 2018 */ public interface UserLeaveRateService extends CrudService<Integer, UserLeaveRate>, AuditedModelAware<UserLeaveRate> { List<UserLeaveRate> findByUser(Integer userId); UserLeaveRate findByUser(Integer userId, String leaveTypeId, DateTime effectiveDate); } <file_sep>/gateway-api/src/main/java/s2/portal/ws/common/rest/DataResource.java package s2.portal.ws.common.rest; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import s2.portal.dao.LeaveTypeDao; import s2.portal.data.system.*; import s2.portal.data.user.LeaveType; import s2.portal.data.user.Role; import s2.portal.service.DataService; import s2.portal.ws.common.json.DataQueryResponse; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.stream.Collectors; /** * @author <NAME> * @since September 2016 */ @SuppressWarnings("unused") @RestController @RequestMapping("/api/data") public class DataResource extends BaseResource { private DataService dataService; private LeaveTypeDao leaveTypeDao; @Autowired public DataResource(DataService dataService, LeaveTypeDao leaveTypeDao) { this.dataService = dataService; this.leaveTypeDao = leaveTypeDao; } @RequestMapping(value = "/leaveTypes", method = RequestMethod.GET) public ResponseEntity<Collection<LeaveType>> leaveTypes() { return ResponseEntity.ok(leaveTypeDao.findAll()); } @RequestMapping(value = "/payslipMonths", method = RequestMethod.GET) public ResponseEntity<Collection<String>> payslipMonths() { final Collection<String> monthNames = new ArrayList<>(); DateTime currentMonth = DateTime.now().minusMonths(3); while (true) { monthNames.add(currentMonth.toString("MMMM-yyyy")); currentMonth = currentMonth.plusMonths(1); if (currentMonth.isAfter(DateTime.now())) break; } return ResponseEntity.ok(monthNames); } @RequestMapping(value = "/roles", method = RequestMethod.GET) public ResponseEntity<Collection<String>> roles() { final Collection<String> data = new ArrayList<>(); for (Role e : Role.values()) { data.add(e.name()); } return ResponseEntity.ok(data); } @RequestMapping(value = "/provinces/q/{q}", method = RequestMethod.GET) public ResponseEntity<Collection<DataQueryResponse>> queryProvinces(@PathVariable String q) { return ResponseEntity.ok(dataService.provinces().stream() .filter(province -> province.getDescription().toLowerCase().contains(q.toLowerCase())) .map(province -> new DataQueryResponse(province, "world.png")) .collect(Collectors.toCollection(HashSet::new))); } @RequestMapping(value = "/provinces/id/{id}", method = RequestMethod.GET) public ResponseEntity<Province> provinceById(@PathVariable Integer id) { for (Province province : dataService.provinces()) { if (province.getPrimaryId().equals(id)) { return ResponseEntity.ok(province); } } return ResponseEntity.ok(null); } @RequestMapping(value = "/provinces", method = RequestMethod.GET) public ResponseEntity<Collection<Province>> provinces() { return ResponseEntity.ok(dataService.provinces()); } @RequestMapping(value = "/countries", method = RequestMethod.GET) public ResponseEntity<Collection<Country>> countries() { return ResponseEntity.ok(dataService.countries()); } @RequestMapping(value = "/addressTypes", method = RequestMethod.GET) public ResponseEntity<Collection<AddressType>> addressTypes() { final Collection<AddressType> data = new ArrayList<>(); // TODO: Read from db in the future. data.add(new AddressType("R", "RESIDENTIAL")); data.add(new AddressType("P", "POSTAL")); return ResponseEntity.ok(data); } @RequestMapping(value = "/addressTypes/id/{id}", method = RequestMethod.GET) public ResponseEntity<AddressType> addressTypesById(@PathVariable String id) { for (AddressType e : addressTypes().getBody()) { if (e.getPrimaryId().equalsIgnoreCase(id)) { return ResponseEntity.ok(e); } } return ResponseEntity.ok(null); } @RequestMapping(value = "/documentTypes", method = RequestMethod.GET) public ResponseEntity<Collection<DocumentType>> documentTypes() { final Collection<DocumentType> data = new ArrayList<>(dataService.documentTypes()); return ResponseEntity.ok(data); } @RequestMapping(value = "/personalReferenceTypes", method = RequestMethod.GET) public ResponseEntity<Collection<PersonalReferenceType>> personalReferenceTypes() { final Collection<PersonalReferenceType> data = new ArrayList<>(); // TODO: Read from db in the future. data.add(new PersonalReferenceType("RSA", "SOUTH AFRICAN ID")); data.add(new PersonalReferenceType("P", "PASSPORT")); // data.add(new PersonalReferenceType("OTH", "OTHER")); return ResponseEntity.ok(data); } @RequestMapping(value = "/personalReferenceTypes/id/{id}", method = RequestMethod.GET) public ResponseEntity<PersonalReferenceType> personalReferenceTypeById(@PathVariable String id) { for (PersonalReferenceType e : personalReferenceTypes().getBody()) { if (e.getPrimaryId().equalsIgnoreCase(id)) { return ResponseEntity.ok(e); } } return ResponseEntity.ok(null); } @RequestMapping(value = "/communicationPreferenceTypes", method = RequestMethod.GET) public ResponseEntity<Collection<CommunicationType>> communicationPreferenceTypes() { final Collection<CommunicationType> data = new ArrayList<>(); // TODO: Read from db in the future. data.add(new CommunicationType("S", "SMS")); data.add(new CommunicationType("E", "EMAIL")); return ResponseEntity.ok(data); } @RequestMapping(value = "/bankAccountTypes", method = RequestMethod.GET) public ResponseEntity<Collection<BankAccountType>> bankAccountTypes() { final Collection<BankAccountType> data = new ArrayList<>(); // TODO: Read from db in the future. data.add(new BankAccountType("C", "CHEQUE")); data.add(new BankAccountType("S", "SAVINGS")); data.add(new BankAccountType("T", "TRANSMISSION")); data.add(new BankAccountType("B", "BOND")); data.add(new BankAccountType("SUB", "SUBSCRIPTION")); return ResponseEntity.ok(data); } @RequestMapping(value = "/bankAccountTypes/id/{id}", method = RequestMethod.GET) public ResponseEntity<BankAccountType> bankAccountTypeById(@PathVariable String id) { for (BankAccountType bankAccountType : bankAccountTypes().getBody()) { if (bankAccountType.getPrimaryId().equalsIgnoreCase(id)) { return ResponseEntity.ok(bankAccountType); } } return ResponseEntity.ok(null); } }<file_sep>/db/src/main/java/s2/portal/dao/impl/hibernate/UserTimesheetDaoImpl.java package s2.portal.dao.impl.hibernate; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; import s2.portal.dao.UserTimesheetDao; import s2.portal.data.user.UserTimesheet; import java.util.List; /** * @author <NAME> * @since January 2019 */ @Repository(value = "userTimesheetDao") public class UserTimesheetDaoImpl extends BaseAuditLogDaoImpl<Integer, UserTimesheet> implements UserTimesheetDao { @Autowired public UserTimesheetDaoImpl(@Qualifier("s2portalSessionFactory") SessionFactory sessionFactory) { super(sessionFactory, UserTimesheet.class); } @SuppressWarnings({"unchecked", "JpaQueryApiInspection"}) @Override public List<UserTimesheet> findByTimesheet(Integer timesheetId) { Assert.notNull(timesheetId, "Variable timesheetId cannot be null."); return (List<UserTimesheet>) getHibernateTemplate().findByNamedQueryAndNamedParam( "FIND_USER_TIMESHEETS_BY_TIMESHEET", "timesheetId", timesheetId); } @SuppressWarnings({"unchecked", "JpaQueryApiInspection"}) @Override public UserTimesheet findByBillingPeriodAndUser(Integer timesheetId, Integer userId) { Assert.notNull(timesheetId, "Variable timesheetId cannot be null."); Assert.notNull(userId, "Variable userId cannot be null."); final List<?> data = getHibernateTemplate().findByNamedQueryAndNamedParam( "FIND_TIMESHEET_BY_TIMESHEET_AND_USER" , new String[]{"timesheetId", "userId"} , new Object[]{timesheetId, userId}); if (data == null || data.isEmpty()) return null; else return (UserTimesheet) data.iterator().next(); } @SuppressWarnings({"unchecked", "JpaQueryApiInspection"}) @Override public List<UserTimesheet> findByUser(Integer userId) { Assert.notNull(userId, "Variable userId cannot be null."); return (List<UserTimesheet>) getHibernateTemplate().findByNamedQueryAndNamedParam( "FIND_TIMESHEET_BY_USER", "userId", userId); } } <file_sep>/db/src/main/java/s2/portal/dao/CaptchaDao.java package s2.portal.dao; import s2.portal.data.Captcha; /** * @author <NAME> * @since July 2018 */ public interface CaptchaDao extends AuditLogDao<Integer, Captcha> { } <file_sep>/business-api/src/main/java/s2/portal/service/impl/JdbcUserDocumentServiceImpl.java package s2.portal.service.impl; import s2.portal.dao.UserDocumentDao; import s2.portal.data.user.UserDocument; import s2.portal.service.UserDocumentService; import java.util.List; /** * @author <NAME> * @since October 2016 */ public class JdbcUserDocumentServiceImpl extends JdbcAuditTemplate<Integer, UserDocument, UserDocumentDao> implements UserDocumentService { private UserDocumentDao userDocumentDao; public JdbcUserDocumentServiceImpl(UserDocumentDao userDocumentDao) { super(userDocumentDao); this.userDocumentDao = userDocumentDao; } /** * Returns the list of user documents for the given user. * * @param userId The user pk. * @return A list. */ @Override public List<UserDocument> findByUser(Integer userId) { return userDocumentDao.findByUser(userId); } } <file_sep>/db/src/main/java/s2/portal/dao/UserTimesheetDao.java package s2.portal.dao; import s2.portal.data.user.UserTimesheet; import java.util.List; /** * @author <NAME> * @since January 2019 */ public interface UserTimesheetDao extends AuditLogDao<Integer, UserTimesheet> { List<UserTimesheet> findByTimesheet(Integer timesheetId); UserTimesheet findByBillingPeriodAndUser(Integer timesheetId, Integer userId); List<UserTimesheet> findByUser(Integer userId); } <file_sep>/db/src/main/java/s2/portal/dao/impl/hibernate/UserLeaveBalanceDaoImpl.java package s2.portal.dao.impl.hibernate; import org.hibernate.SessionFactory; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; import s2.portal.dao.UserLeaveBalanceDao; import s2.portal.data.user.UserLeaveBalance; import java.util.List; /** * @author <NAME> * @since October 2018 */ @Repository(value = "userLeaveBalanceDao") public class UserLeaveBalanceDaoImpl extends BaseAuditLogDaoImpl<Integer, UserLeaveBalance> implements UserLeaveBalanceDao { @Autowired public UserLeaveBalanceDaoImpl(@Qualifier("s2portalSessionFactory") SessionFactory sessionFactory) { super(sessionFactory, UserLeaveBalance.class); } @SuppressWarnings("JpaQueryApiInspection") @Override public UserLeaveBalance findByUser(Integer userId, String typeId, DateTime effectiveDate) { Assert.notNull(userId, "Variable userId cannot be null."); Assert.notNull(typeId, "Variable typeId cannot be null."); Assert.notNull(effectiveDate, "Variable effectiveDate cannot be null."); final List<?> data = getHibernateTemplate().findByNamedQueryAndNamedParam( "FIND_USER_LEAVE_BALANCE" , new String[]{"userId", "typeId", "effectiveDate"} , new Object[]{userId, typeId, effectiveDate.toDate()}); return data == null || data.isEmpty() ? null : (UserLeaveBalance) data.iterator().next(); } } <file_sep>/db/migration/template-create-fk-constraints.sql select 'alter table public.'+fk_tab.name+' add constraint '+fk.name+' foreign key ('+substring(column_names, 1, len(column_names)-1)+') references public.'+pk_tab.name+' (id);' from sys.foreign_keys fk inner join sys.tables fk_tab on fk_tab.object_id = fk.parent_object_id inner join sys.tables pk_tab on pk_tab.object_id = fk.referenced_object_id cross apply (select col.[name] + ', ' from sys.foreign_key_columns fk_c inner join sys.columns col on fk_c.parent_object_id = col.object_id and fk_c.parent_column_id = col.column_id where fk_c.parent_object_id = fk_tab.object_id and fk_c.constraint_object_id = fk.object_id order by col.column_id for xml path ('') ) D (column_names) where fk_tab.name not like '%ACT_%' order by schema_name(fk_tab.schema_id) + '.' + fk_tab.name, schema_name(pk_tab.schema_id) + '.' + pk_tab.name --alter table leave_balance add constraint fk_leave_balance_user foreign key (user_id) references user_acc (id);<file_sep>/gateway-api/src/main/java/s2/portal/ws/user/rest/UserLeaveRateResource.java package s2.portal.ws.user.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import s2.portal.data.audit.Revision; import s2.portal.data.user.UserLeaveRate; import s2.portal.service.UserLeaveRateService; import s2.portal.ws.common.rest.BaseResource; import java.util.List; /** * @author <NAME> * @since October 2018 */ @SuppressWarnings("unused") @RestController @RequestMapping("/api/users/leave/rates") public class UserLeaveRateResource extends BaseResource { private UserLeaveRateService userLeaveRateService; @Autowired public UserLeaveRateResource(UserLeaveRateService userLeaveRateService) { this.userLeaveRateService = userLeaveRateService; } @RequestMapping(value = "/user/{userId}", method = RequestMethod.GET) public ResponseEntity<List<UserLeaveRate>> findByUser(@PathVariable Integer userId) { return ResponseEntity.ok(userLeaveRateService.findByUser(userId)); } @RequestMapping(value = "/id/{id}", method = RequestMethod.GET) public ResponseEntity<UserLeaveRate> findById(@PathVariable Integer id) { return ResponseEntity.ok(userLeaveRateService.findById(id)); } @RequestMapping(value = "", method = RequestMethod.POST) public ResponseEntity<UserLeaveRate> save(@RequestBody UserLeaveRate entity) { return ResponseEntity.ok(userLeaveRateService.save(entity)); } @RequestMapping(value = "/createdBy/id/{id}", method = RequestMethod.GET) public ResponseEntity<Revision> findCreatedBy(@PathVariable Integer id) { final UserLeaveRate entity = userLeaveRateService.findById(id); return ResponseEntity.ok(userLeaveRateService.findCreatedBy(entity)); } @RequestMapping(value = "/modifiedBy/id/{id}", method = RequestMethod.GET) public ResponseEntity<Revision> findModifiedBy(@PathVariable Integer id) { final UserLeaveRate entity = userLeaveRateService.findById(id); return ResponseEntity.ok(userLeaveRateService.findModifiedBy(entity)); } }<file_sep>/business-api/src/main/java/s2/portal/bpm/client/common/CamundaProcess.java package s2.portal.bpm.client.common; /** * @author <NAME> * @since August 2016 */ public enum CamundaProcess { /** * A new user request. */ UserRegistration("UserRegistration", "fa-user"), /** * A create invoice request. */ PasswordReset("PasswordReset", "fa-unlock-alt"), /** * A forgot password request. */ ForgotPassword("ForgotPassword", "fa-unlock-alt"), /** * A leave request. */ Leave("Leave", "fa-calendar"); private String id; private String icon; CamundaProcess(String id, String icon) { this.id = id; this.icon = icon; } public String id() { return id; } public String icon() { return icon; } } <file_sep>/db/src/main/java/s2/portal/dao/impl/hibernate/UserRoleDaoImplImpl.java package s2.portal.dao.impl.hibernate; import s2.portal.dao.UserRoleDao; import s2.portal.data.user.UserRole; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; /** * @author <NAME> * @since August 2016 */ @Repository(value = "userRoleDao") public class UserRoleDaoImplImpl extends BaseHibernateDaoImpl<Integer, UserRole> implements UserRoleDao { @Autowired public UserRoleDaoImplImpl(@Qualifier("s2portalSessionFactory") SessionFactory sessionFactory) { super(sessionFactory, UserRole.class); } } <file_sep>/db/migration/template-create-unique-constraints.sql select i.[name] as index_name, substring(column_names, 1, len(column_names)-1) as [columns], case when i.[type] = 1 then 'Clustered unique index' when i.type = 2 then 'Unique index' end as index_type, schema_name(t.schema_id) + '.' + t.[name] as table_view, case when t.[type] = 'U' then 'Table' when t.[type] = 'V' then 'View' end as [object_type], case when c.[type] = 'PK' then 'Primary key' when c.[type] = 'UQ' then 'Unique constraint' end as constraint_type, c.[name] as constraint_name from sys.objects t left outer join sys.indexes i on t.object_id = i.object_id left outer join sys.key_constraints c on i.object_id = c.parent_object_id and i.index_id = c.unique_index_id cross apply (select col.[name] + ', ' from sys.index_columns ic inner join sys.columns col on ic.object_id = col.object_id and ic.column_id = col.column_id where ic.object_id = t.object_id and ic.index_id = i.index_id order by col.column_id for xml path ('') ) D (column_names) where is_unique = 1 and t.is_ms_shipped <> 1 and i.[name] not like '%ACT_%' order by i.[name]<file_sep>/maven-plugin/maven-split-config-plugin/pom.xml <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>s2.portal.maven.plugins</groupId> <artifactId>maven-split-config-plugin</artifactId> <version>1.0.4</version> <packaging>maven-plugin</packaging> <name>Maven Split Configuration Plugin</name> <description>This plugin allows developers to manage and distribute environment-specific configuration files alongside the main artifact(s) of each project. </description> <developers> <developer> <id>justin</id> <name><NAME></name> <email><EMAIL></email> <roles> <role>Developer</role> </roles> </developer> </developers> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <compilerVersion>1.6</compilerVersion> <source>1.6</source> <target>1.6</target> <debug>true</debug> <showDeprecation>true</showDeprecation> <showWarnings>true</showWarnings> <optimize>false</optimize> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-model</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-project</artifactId> <version>2.0.4</version> </dependency> </dependencies> </project> <file_sep>/business-api/src/main/java/s2/portal/command/DeriveUsernameCommand.java package s2.portal.command; import s2.portal.dao.UserDao; import s2.portal.data.user.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; /** * @author <NAME> * @since January 2017 */ @Component public class DeriveUsernameCommand { private static final Logger LOG = LoggerFactory.getLogger(DeriveUsernameCommand.class); @Autowired private UserDao userDao; public String execute(User user) { LOG.info("--- execute ---"); return deriveUsername(user, 0); } private String deriveUsername(User user, int number) { String username = user.getLastName().toLowerCase() + user.getFirstName().substring(0, 1).toLowerCase(); if (number > 0) { username = username + number; } final UserDetails userDetails = userDao.findByUsername(username); if (userDetails != null) { return deriveUsername(user, ++number).toLowerCase(); } else { return username.toLowerCase(); } } } <file_sep>/business-api/src/main/java/s2/portal/bpm/tasks/user/registration/MarkUserAccountAsPendingVerificationTask.java package s2.portal.bpm.tasks.user.registration; import org.apache.commons.lang3.StringUtils; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import s2.portal.bpm.client.json.RegisterUserAccountRequest; import s2.portal.data.user.User; import s2.portal.data.user.UserStatus; import s2.portal.service.UserService; import java.util.UUID; /** * @author <NAME> * @since August 2016 */ @Component public class MarkUserAccountAsPendingVerificationTask implements JavaDelegate { private final Logger log = LoggerFactory.getLogger(MarkUserAccountAsPendingVerificationTask.class); private UserService userService; @Autowired public MarkUserAccountAsPendingVerificationTask(UserService userService) { this.userService = userService; } @Override public void execute(final DelegateExecution delegateExecution) throws Exception { log.info("Called"); final RegisterUserAccountRequest request = (RegisterUserAccountRequest) delegateExecution. getVariable("request"); request.setProcessInstanceId(delegateExecution.getProcessInstanceId()); final User user = request.getUser(); user.setDisplayName(StringUtils.upperCase(user.getFirstName() + " " + user.getLastName())); user.setAccountNonExpired(true); user.setAccountNonLocked(true); user.setCredentialsNonExpired(true); user.setEnabled(true); user.setReserved(false); user.setPasswordExpired(false); final String activationSerialNumber = UUID.randomUUID().toString().replace("-", ""); user.setActivationSerialNumber(activationSerialNumber); user.setLastLoginTime(null); userService.setPassword(user, request.getPlainTextPassword(), false); user.setStatus(UserStatus.PendingAdminApproval.id()); log.info("Attempting to save user... {}", user.toString()); userService.save(user); } }<file_sep>/db/src/main/java/s2/portal/builder/UserGroupIdentityBuilder.java package s2.portal.builder; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import s2.portal.data.user.User; /** * @author <NAME> * @since September 2017 */ @Component public class UserGroupIdentityBuilder { public User build(User user) { addUserIdentity(user); addRoleIdentity(user); return user; } private void addUserIdentity(User user) { if (StringUtils.isNotBlank(user.getUsername())) { final String username = StringUtils.lowerCase(user.getUsername()); if (!user.getGroupIdentities().contains(username)) { user.addGroupIdentity(username); } } } private void addRoleIdentity(User user) { for (String role : user.getRoles()) { user.addGroupIdentity(role); } } } <file_sep>/business-api/src/main/java/s2/portal/service/impl/NotificationServiceImpl.java package s2.portal.service.impl; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.app.VelocityEngine; import org.camunda.bpm.engine.delegate.DelegateTask; import org.camunda.bpm.engine.task.IdentityLink; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.stereotype.Service; import org.springframework.ui.velocity.VelocityEngineUtils; import org.springframework.util.Assert; import s2.portal.bpm.client.json.WorkflowRequest; import s2.portal.bpm.client.json.WorkflowRequestDescriptionBuilder; import s2.portal.data.Feature; import s2.portal.data.user.Leave; import s2.portal.data.user.Timesheet; import s2.portal.data.user.User; import s2.portal.factory.SmtpSessionFactory; import s2.portal.service.FeatureService; import s2.portal.service.NotificationCallback; import s2.portal.service.NotificationService; import s2.portal.service.UserService; import javax.mail.Address; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.UnsupportedEncodingException; import java.util.*; /** * @author <NAME> * @since July 2018 */ @SuppressWarnings("unused") @Service(value = "notificationService") public class NotificationServiceImpl implements NotificationService { private final static Logger LOG = LoggerFactory.getLogger(NotificationServiceImpl.class); private static final int PRINT_THRESHOLD = 10; private static String DEFAULT_ENCODING = "ISO-8859-1"; private VelocityEngine velocityEngine; private FeatureService featureService; private UserService userService; private SmtpSessionFactory smtpSessionFactory; private CommonEmailAttributesBuilder commonEmailAttributesBuilder; @Autowired public NotificationServiceImpl(VelocityEngine velocityEngine , FeatureService featureService , UserService userService , SmtpSessionFactory smtpSessionFactory , CommonEmailAttributesBuilder commonEmailAttributesBuilder) { this.velocityEngine = velocityEngine; this.featureService = featureService; this.userService = userService; this.smtpSessionFactory = smtpSessionFactory; this.commonEmailAttributesBuilder = commonEmailAttributesBuilder; } @Override public MimeMessage createTimesheetReminderEmail(Timesheet timesheet, User user) throws UnsupportedEncodingException, AddressException { Assert.notNull(timesheet, "The variable timesheet cannot be null."); Assert.notNull(user, "The variable user cannot be null."); final Set<User> suggestedRecipients = new HashSet<>(); suggestedRecipients.add(user); final Feature nonProductionEmail = featureService.findByName(Feature.Type.NON_PRODUCTION_EMAIL); final Collection<InternetAddress> intendedRecipients = determineRecipientsIgnoreSubscriptions( suggestedRecipients, nonProductionEmail); final String textMessage = String.format("Just a friendly nudge to remind you to please capture your timesheet " + "for the time between %s and %s (%s hours)." , DateTime.now().withMillis(timesheet.getStartDate().getTime()).toString("yyyy/MM/dd") , DateTime.now().withMillis(timesheet.getEndDate().getTime()).toString("yyyy/MM/dd") , timesheet.getBillableHours() ); final Map<String, Object> model = commonEmailAttributesBuilder.build(user); model.put("textMessage", textMessage); return buildEmailMessage((MimeMessage mimeMessage) -> { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(intendedRecipients.toArray(new InternetAddress[0])); final String subject = buildSubject("Notification", "Timesheet Reminder"); message.setSubject(subject); final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/GeneralTextNotificationTemplate.vm", DEFAULT_ENCODING, model); message.setText(text, true); }); } @Override public MimeMessage createLeaveApprovedEmail(User requestingUser, Leave leave, Set<User> cc) throws UnsupportedEncodingException, AddressException { Assert.notNull(requestingUser, "The variable requestingUser cannot be null."); final Feature nonProductionEmail = featureService.findByName(Feature.Type.NON_PRODUCTION_EMAIL); final Collection<InternetAddress> toRecipients = determineRecipientsIgnoreSubscriptions( Collections.singletonList(requestingUser), nonProductionEmail); final Collection<InternetAddress> ccRecipients = new HashSet<>(determineRecipientsIgnoreSubscriptions(cc, nonProductionEmail)); final String textMessage = String.format("Your leave between %s and %s (%s days) has been approved.", DateTime.now().withMillis(leave.getStartDate().getTime()).toString("yyyy/MM/dd") , DateTime.now().withMillis(leave.getEndDate().getTime()).toString("yyyy/MM/dd") , leave.getDays() ); final Map<String, Object> model = commonEmailAttributesBuilder.build(requestingUser); model.put("textMessage", textMessage); return buildEmailMessage((MimeMessage mimeMessage) -> { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(toRecipients.toArray(new InternetAddress[0])); if (!ccRecipients.isEmpty()) message.setCc(ccRecipients.toArray(new InternetAddress[0])); final String subject = buildSubject("Notification", "Leave Approved"); message.setSubject(subject); final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/GeneralTextNotificationTemplate.vm", DEFAULT_ENCODING, model); message.setText(text, true); }); } @Override public MimeMessage createLeaveDeclinedEmail(User requestingUser, Leave leave, String comment) throws UnsupportedEncodingException, AddressException { Assert.notNull(requestingUser, "The variable requestingUser cannot be null."); final Set<User> suggestedRecipients = new HashSet<>(); suggestedRecipients.add(requestingUser); final Feature nonProductionEmail = featureService.findByName(Feature.Type.NON_PRODUCTION_EMAIL); final Collection<InternetAddress> intendedRecipients = determineRecipientsIgnoreSubscriptions( suggestedRecipients, nonProductionEmail); final String textMessage = String.format("Your leave between %s and %s (%s days) has been unfortunately declined because %s.", DateTime.now().withMillis(leave.getStartDate().getTime()).toString("yyyy/MM/dd") , DateTime.now().withMillis(leave.getEndDate().getTime()).toString("yyyy/MM/dd") , leave.getDays() , comment.toLowerCase() ); final Map<String, Object> model = commonEmailAttributesBuilder.build(requestingUser); model.put("textMessage", textMessage); return buildEmailMessage((MimeMessage mimeMessage) -> { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(intendedRecipients.toArray(new InternetAddress[0])); final String subject = buildSubject("Notification", "Leave Declined"); message.setSubject(subject); final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/GeneralTextNotificationTemplate.vm", DEFAULT_ENCODING, model); message.setText(text, true); }); } /** * Method used to send an email to notify user(s) of the shipment. * * @param user The user who forgot their password. * @return The message. */ @Override public MimeMessage createPasswordResetNotification(User user) throws UnsupportedEncodingException, AddressException { Assert.notNull(user, "The variable user cannot be null."); final Set<User> suggestedRecipients = new HashSet<>(); suggestedRecipients.add(user); final Feature nonProductionEmail = featureService.findByName(Feature.Type.NON_PRODUCTION_EMAIL); final Collection<InternetAddress> intendedRecipients = determineRecipientsIgnoreSubscriptions( suggestedRecipients, nonProductionEmail); final Feature applicationRootUrlFeature = featureService.findByName(Feature.Type.APPLICATION_ROOT_URL); final String applicationRootUrl = applicationRootUrlFeature.getValue(); final Map<String, Object> model = commonEmailAttributesBuilder.build(user); final String passwordResetUrl = applicationRootUrl + "#/resetPassword/asn/" + user.getActivationSerialNumber(); model.put("passwordResetUrl", passwordResetUrl); return buildEmailMessage((MimeMessage mimeMessage) -> { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(intendedRecipients.toArray(new InternetAddress[0])); final String subject = buildSubject("Password Reset", user.getDisplayName()); message.setSubject(subject); final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/PasswordResetNotificationTemplate.vm", DEFAULT_ENCODING, model); message.setText(text, true); }); } @Override public MimeMessage createUserRequestRejectedNotification(User user, String reason) throws UnsupportedEncodingException, AddressException { Assert.notNull(user, "The variable user cannot be null."); Assert.hasText(reason, "The variable reason cannot be null."); final Set<User> suggestedRecipients = new HashSet<>(); suggestedRecipients.add(user); final Feature nonProductionEmail = featureService.findByName(Feature.Type.NON_PRODUCTION_EMAIL); final Collection<InternetAddress> intendedRecipients = determineRecipientsIgnoreSubscriptions( suggestedRecipients, nonProductionEmail); final Map<String, Object> model = commonEmailAttributesBuilder.build(user); model.put("reason", reason); return buildEmailMessage((MimeMessage mimeMessage) -> { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(intendedRecipients.toArray(new InternetAddress[0])); final String subject = buildSubject("User Request Declined", user.getDisplayName()); message.setSubject(subject); final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/UserRequestRejectedNotificationTemplate.vm", DEFAULT_ENCODING, model); message.setText(text, true); }); } /** * Method used to send an email to notify user(s) of BPM task assignment. * * @param delegateTask The Camunda delegage task. * @return The message. */ @Override public MimeMessage createTaskAssignmentNotification(DelegateTask delegateTask) throws UnsupportedEncodingException, AddressException { Assert.notNull(delegateTask, "The variable delegateTask cannot be null."); final WorkflowRequest workflowRequest = (WorkflowRequest) delegateTask.getVariable("request"); Assert.notNull(workflowRequest, "The variable workflowRequest cannot be null."); final Set<User> suggestedRecipients = new HashSet<>(); final String assignee = delegateTask.getAssignee(); if (StringUtils.isNotBlank(assignee)) { final User assigneeUser = userService.findByUsername(assignee); suggestedRecipients.add(assigneeUser); } else { final Collection<User> allUsers = userService.findAll(); for (final IdentityLink identityLink : delegateTask.getCandidates()) { final String groupId = identityLink.getGroupId(); LOG.info("Looking for users in group {}.", groupId); if (StringUtils.isNotBlank(groupId)) { for (User user : allUsers) { if (user.getGroupIdentities().contains(groupId)) { suggestedRecipients.add(user); } } } } } if (suggestedRecipients.size() > PRINT_THRESHOLD) { LOG.info("Found a total of {} users to notify.", suggestedRecipients.size()); } else { final Collection<String> emailAddresses = new ArrayList<>(); for (User user : suggestedRecipients) { emailAddresses.add(user.getPrimaryEmailAddress()); } LOG.info("Found the following users to notify: {}", emailAddresses.toString()); } final Feature nonProductionEmail = featureService.findByName(Feature.Type.NON_PRODUCTION_EMAIL); final Collection<InternetAddress> intendedRecipients = determineRecipientsIgnoreSubscriptions( suggestedRecipients, nonProductionEmail); final Feature outgoingDisplayName = featureService.findByName(Feature.Type.OUTGOING_DISPLAY_NAME); final Feature applicationRootUrl = featureService.findByName(Feature.Type.APPLICATION_ROOT_URL); final String applicationLoginUrl = applicationRootUrl.getValue() + "#/login"; return buildEmailMessage((MimeMessage mimeMessage) -> { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(intendedRecipients.toArray(new InternetAddress[0])); String workflowRequestDescription = WorkflowRequestDescriptionBuilder.aDescription() .withWorkflowRequest(workflowRequest) .build(); if (workflowRequestDescription.length() > 2 && workflowRequestDescription.endsWith(".")) { workflowRequestDescription = workflowRequestDescription.substring(0 , workflowRequestDescription.length() - 1); } final String processInstanceId = delegateTask.getProcessInstanceId(); final String subject = buildSubject("Task Notification" , "Task " + processInstanceId + " " + workflowRequestDescription); message.setSubject(subject); // <protocol>://localhost:8888/#/app/request/142 final String requestUrl = applicationRootUrl.getValue() + "#/app/request/" + processInstanceId; final Map<String, Object> model = new HashMap<>(); model.put("requestUrl", requestUrl); model.put("workflowRequestDescription", workflowRequestDescription); model.put("processInstanceId", processInstanceId); model.put("comments", StringUtils.stripToEmpty(workflowRequest.getComment())); model.put("applicationLoginUrl", applicationLoginUrl); model.put("outgoingDisplayName", outgoingDisplayName.getValue().toUpperCase()); final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/TaskAssignmentNotificationTemplate.vm", DEFAULT_ENCODING, model); message.setText(text, true); }); } /** * Method used to send an email to confirm the new user was successfully imported in the system. * * @param newUser The newly imported user. * @return The message. * @throws IllegalArgumentException If newUser is null. */ @Override public MimeMessage createWelcomeEmail(User newUser, String plainTextPassword) throws UnsupportedEncodingException, AddressException { Assert.notNull(newUser, "The variable newUser cannot be null."); Assert.hasText(plainTextPassword, "The variable plainTextPassword cannot be null or empty."); final Set<User> suggestedRecipients = new HashSet<>(); suggestedRecipients.add(newUser); final Feature nonProductionEmail = featureService.findByName(Feature.Type.NON_PRODUCTION_EMAIL); final Collection<InternetAddress> intendedRecipients = determineRecipientsIgnoreSubscriptions( suggestedRecipients, nonProductionEmail); final Feature applicationRootUrl = featureService.findByName(Feature.Type.APPLICATION_ROOT_URL); final String applicationLoginUrl = applicationRootUrl.getValue() + "#/login"; final Map<String, Object> model = commonEmailAttributesBuilder.build(newUser); model.put("applicationLoginUrl", applicationLoginUrl); model.put("plainTextPassword", <PASSWORD>); return buildEmailMessage((MimeMessage mimeMessage) -> { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(intendedRecipients.toArray(new InternetAddress[0])); final String subject = buildSubject("Welcome E-Mail", newUser.getDisplayName()); message.setSubject(subject); final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/WelcomeUserNotificationTemplate.vm", DEFAULT_ENCODING, model); message.setText(text, true); }); } private Collection<InternetAddress> determineRecipientsIgnoreSubscriptions(Collection<User> suggestedRecipients, Feature nonProductionEmail) throws AddressException, UnsupportedEncodingException { final Collection<InternetAddress> intendedRecipients = new ArrayList<>(); // Only send email to the intended users if the email is an exception email OR if we are // running in the production environment. If the non production email is blank then the // email will be email to the intended recipient. if (StringUtils.isBlank(nonProductionEmail.getValue())) { for (User recipient : suggestedRecipients) { intendedRecipients.add(new InternetAddress(recipient.getPrimaryEmailAddress(), recipient .getDisplayName())); } } else { intendedRecipients.add(new InternetAddress(nonProductionEmail.getValue())); } return intendedRecipients; } @Override public void send(MimeMessage mimeMessage) { Assert.notNull(mimeMessage); doSend0(mimeMessage); } @Override public void send(MimeMessage mimeMessage, NotificationCallback callback) { Assert.notNull(mimeMessage, "The variable mimeMessage cannot be null."); final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { doSend0(mimeMessage); callback.success(); } catch (final Exception e) { callback.failed(e); } } }, 1000); } private String buildSubject(String action, String description) { return "S2 Employee Portal | " + action + " | " + description; } private MimeMessage buildEmailMessage(MimeMessagePreparator mimeMessagePreparator) { final Feature smtpServer = featureService.findByName(Feature.Type.SMTP_SERVER); final Properties properties = new Properties(); properties.setProperty("mail.transport.protocol", "smtp"); if (StringUtils.isNotBlank(smtpServer.getValue())) { properties.setProperty("mail.host", smtpServer.getValue()); } final Session session = Session.getDefaultInstance(properties); MimeMessage mimeMessage = new MimeMessage(session); try { mimeMessagePreparator.prepare(mimeMessage); } catch (Exception e) { LOG.error(e.getMessage(), e); } return mimeMessage; } private void doSend0(final MimeMessage mimeMessage) { Assert.notNull(mimeMessage); // So no SMTP server is found, therefore simply return. final Feature smtpServer = featureService.findByName(Feature.Type.SMTP_SERVER); final String host = smtpServer.getValue(); if (StringUtils.isBlank(host)) { LOG.info("No email sent as smtp server not defined."); } else { LOG.info(String.format("SMTP server set to %s >> send email.", host)); try { final StringBuilder recipients = new StringBuilder(); final Address[] to = mimeMessage.getRecipients(Message.RecipientType.TO); for (int i = 0; i < to.length; i++) { recipients.append(((InternetAddress) to[i]).getAddress()); if ((i + 1) < to.length) { recipients.append(","); } } LOG.info(String.format("smtp server set to %s -> attempting to send email to %s.", host.trim(), recipients)); if (mimeMessage.getSentDate() == null) { mimeMessage.setSentDate(new Date()); } final Feature outgoingDisplayName = featureService.findByName(Feature.Type.OUTGOING_DISPLAY_NAME); final Feature outgoingEmail = featureService.findByName(Feature.Type.OUTGOING_EMAIL); Address sender = new InternetAddress(outgoingEmail.getValue(), outgoingDisplayName.getValue()); mimeMessage.setFrom(sender); String messageId = mimeMessage.getMessageID(); mimeMessage.saveChanges(); if (messageId != null) { mimeMessage.setHeader("Message-ID", messageId); } Transport transport = null; try { transport = getSession(host).getTransport(); transport.connect(); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); } finally { if (transport != null) { try { transport.close(); } catch (final Throwable t) { LOG.warn(t.getMessage(), t); } } } } catch (final Throwable t) { LOG.error(t.getMessage(), t); throw new RuntimeException(t.getMessage()); } } } /** * Creates a returns a new SMTP session to the calling client. * * @param host The host name or IP address of the SMTP server. * @return The mail session. */ @Override public Session getSession(String host) { final Feature smtpUserFeature = featureService.findByName(Feature.Type.SMTP_USERNAME); Assert.notNull(smtpUserFeature, "SMTP_USERNAME not found."); final String smtpUser = StringUtils.isBlank(smtpUserFeature.getValue()) ? "" : smtpUserFeature.getValue(); final Feature smtpPwdFeature = featureService.findByName(Feature.Type.SMTP_PWD); Assert.notNull(smtpPwdFeature, "SMTP_PWD not found."); final String smtpPwd = StringUtils.isBlank(smtpPwdFeature.getValue()) ? "" : smtpPwdFeature.getValue(); if (StringUtils.isBlank(smtpUser) && StringUtils.isBlank(smtpPwd)) { return smtpSessionFactory.createUnsecuredSession(host); } else { return smtpSessionFactory.createSecureSession(host, smtpUser, smtpPwd); } } } <file_sep>/db/src/main/java/s2/portal/dao/UserLeaveBalanceDao.java package s2.portal.dao; import org.joda.time.DateTime; import s2.portal.data.user.UserLeaveBalance; /** * @author <NAME> * @since October 2018 */ public interface UserLeaveBalanceDao extends AuditLogDao<Integer, UserLeaveBalance> { UserLeaveBalance findByUser(Integer userId, String typeId, DateTime effectiveDate); } <file_sep>/business-api/src/test/java/s2/portal/service/impl/JdbcSystemJobServiceImplTest.java package s2.portal.service.impl; import s2.portal.data.system.SystemJob; import s2.portal.service.SystemJobService; import s2.portal.service.common.BaseSpringJUnit4TestSuite; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Collection; /** * @author <NAME> * @since August 2016 */ public class JdbcSystemJobServiceImplTest extends BaseSpringJUnit4TestSuite { @Autowired private SystemJobService systemJobService; @Test public void testFindAll() throws Exception { final Collection<SystemJob> data = systemJobService.findAll(); Assert.assertNotNull(data); } @Test public void testCount() throws Exception { final long count = systemJobService.count(); Assert.assertTrue(count >= 0); } }<file_sep>/db/src/main/java/s2/portal/dao/LeaveTypeDao.java package s2.portal.dao; import s2.portal.data.user.LeaveType; /** * @author <NAME> * @since September 2018 */ public interface LeaveTypeDao extends BaseDao<String, LeaveType> { } <file_sep>/db/src/main/java/s2/portal/dao/TimesheetDao.java package s2.portal.dao; import org.joda.time.DateTime; import s2.portal.data.user.Timesheet; /** * @author <NAME> * @since January 2019 */ public interface TimesheetDao extends AuditLogDao<Integer, Timesheet> { Timesheet findByEffectiveDate(DateTime effectiveDate); } <file_sep>/config/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/maven-v4_0_0.xsd"> <parent> <groupId>s2.portal</groupId> <artifactId>s2-super-pom</artifactId> <version>RELEASE.1.0</version> </parent> <modelVersion>4.0.0</modelVersion> <name>S2 Portal Config</name> <artifactId>s2-portal-config</artifactId> <packaging>jar</packaging> <build> <plugins> <plugin> <groupId>s2.portal.maven.plugins</groupId> <artifactId>maven-split-config-plugin</artifactId> <version>1.0.4</version> <executions> <execution> <id>split-resources</id> <phase>process-resources</phase> <goals> <goal>split-resources</goal> </goals> </execution> <execution> <id>package-config</id> <phase>package</phase> <goals> <goal>package-split-configuration</goal> </goals> </execution> </executions> <configuration> <configDirectory>${basedir}/src/main/config</configDirectory> <filtersBaseName>${basedir}/src/main/filters/filters</filtersBaseName> <checkOutputFiles>false</checkOutputFiles> <environments> <environment>dev</environment> <environment>test</environment> <environment>live</environment> </environments> <domains> <domain>za</domain> </domains> </configuration> </plugin> </plugins> </build> </project><file_sep>/db/migration/README.txt ================================================= Code Changes ================================================= Add in hibernate context file: <prop key="org.hibernate.envers.revision_type_field_name">rev_type</prop> Add in hibernate context file: <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> -> org.hibernate.dialect.PostgreSQLDialect datasource configs: update jtds driver to postgres datasource configs: amend connection strings to db datasource configs: check referenes for mssql (.yaml files) and Camunda databaseType NamedQueries.hbm.xml replace with(nolock) -> "" NamedQueries.hbm.xml replace top -> limit NamedQueries.hbm.xml replace YEAR mssql function > and date_part('year',date) = 2018 (and check other SQL functions) check hibernate java pojo column names i.e: snake_case ================================================= SSRS Changes ================================================= Download and install ODBC (using Stack Builder) Configure data source: Type: ODBC Connection String: Driver={PostgreSQL ODBC Driver(UNICODE)};Server=localhost;Port=5432;Database=s2_portal;UID=postgres;PWD=sa Masssage SSRS reports - replace functions - concat columns || - replace parameters with ? ================================================= DB CREATE SOP ================================================= 1. Restore db 2. Drop camunda tables 3. purge data truncate table leave_balance truncate table leave_balance_log truncate table user_acc_timesheet_line_log truncate table endpoint_stat 4. pg4admin create s2_portal db 5. run migate dml 6. add pk 7. add fk 8. create: CREATE SEQUENCE hibernate_sequence START 1 9. reset identity columns select 'ALTER TABLE endpoint ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from endpoint union select 'ALTER TABLE endpoint_stat ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from endpoint_stat union select 'ALTER TABLE holiday ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from holiday union select 'ALTER TABLE leave_balance ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from leave_balance union select 'ALTER TABLE revision ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from revision union select 'ALTER TABLE system_job ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from system_job union select 'ALTER TABLE timesheet ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from timesheet union select 'ALTER TABLE user_acc ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_acc union select 'ALTER TABLE user_acc_timesheet ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_acc_timesheet union select 'ALTER TABLE user_acc_timesheet_line ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_acc_timesheet_line union select 'ALTER TABLE user_address ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_address union select 'ALTER TABLE user_bank_account ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_bank_account union select 'ALTER TABLE user_doc ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_doc union select 'ALTER TABLE user_leave ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_leave union select 'ALTER TABLE user_leave_balance ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_leave_balance union select 'ALTER TABLE user_leave_rate ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_leave_rate union select 'ALTER TABLE user_payslip ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_payslip union select 'ALTER TABLE user_role ALTER COLUMN id RESTART WITH ' + convert(varchar,max(id) + 100) from user_role generates: ALTER TABLE endpoint ALTER COLUMN id RESTART WITH 200; ALTER TABLE endpoint_stat ALTER COLUMN id RESTART WITH 2000; ALTER TABLE holiday ALTER COLUMN id RESTART WITH 200; ALTER TABLE leave_balance ALTER COLUMN id RESTART WITH 200; ALTER TABLE revision ALTER COLUMN id RESTART WITH 2000; ALTER TABLE system_job ALTER COLUMN id RESTART WITH 6000; ALTER TABLE timesheet ALTER COLUMN id RESTART WITH 200; ALTER TABLE user_acc ALTER COLUMN id RESTART WITH 200; ALTER TABLE user_acc_timesheet ALTER COLUMN id RESTART WITH 200; ALTER TABLE user_acc_timesheet_line ALTER COLUMN id RESTART WITH 500; ALTER TABLE user_address ALTER COLUMN id RESTART WITH 200; ALTER TABLE user_bank_account ALTER COLUMN id RESTART WITH 200; ALTER TABLE user_doc ALTER COLUMN id RESTART WITH 200; ALTER TABLE user_leave ALTER COLUMN id RESTART WITH 2000; ALTER TABLE user_leave_rate ALTER COLUMN id RESTART WITH 200; ALTER TABLE user_payslip ALTER COLUMN id RESTART WITH 200; ALTER TABLE user_role ALTER COLUMN id RESTART WITH 200; <file_sep>/business-api/src/main/java/s2/portal/bpm/tasks/leave/ApproveLeaveRequestTask.java package s2.portal.bpm.tasks.leave; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import s2.portal.bpm.client.json.LeaveRequest; import s2.portal.data.user.Leave; import s2.portal.data.user.LeaveBalance; import s2.portal.data.user.LeaveStatus; import s2.portal.data.user.User; import s2.portal.service.LeaveBalanceService; import s2.portal.service.LeaveService; import s2.portal.service.UserService; import s2.portal.validator.LeaveValidator; import java.math.BigDecimal; import java.util.Date; /** * @author <NAME> * @since September 2018 */ @Component public class ApproveLeaveRequestTask implements JavaDelegate { private final Logger log = LoggerFactory.getLogger(ApproveLeaveRequestTask.class); private UserService userService; private LeaveService leaveService; private LeaveValidator leaveValidator; private LeaveBalanceService leaveBalanceService; @Autowired public ApproveLeaveRequestTask(UserService userService, LeaveService leaveService, LeaveValidator leaveValidator, LeaveBalanceService leaveBalanceService) { this.userService = userService; this.leaveService = leaveService; this.leaveValidator = leaveValidator; this.leaveBalanceService = leaveBalanceService; } @Override public void execute(final DelegateExecution delegateExecution) { log.info("Called"); final Integer actionedById = (Integer) delegateExecution. getVariable("actionedBy"); final User actionedBy = userService.findById(actionedById); final LeaveRequest request = (LeaveRequest) delegateExecution. getVariable("request"); final Leave leave = request.getLeave(); leaveValidator.validate(leave); leave.setDateApproved(new Date()); leave.setApprovedBy(actionedBy); leave.setStatus(LeaveStatus.Approved.id()); log.info("Attempting to save leave... {}", leave.toString()); leaveService.save(leave); updateLeaveBalances(leave); } private void updateLeaveBalances(Leave leave) { LeaveBalance leaveBalance = leaveBalanceService.findByLeaveRequest(leave.getPrimaryId()); if (leaveBalance == null) { leaveBalance = new LeaveBalance(); leaveBalance.setUserId(leave.getUserId()); leaveBalance.setTypeId(leave.getTypeId()); leaveBalance.setDate(new Date()); leaveBalance.setLeaveRequestId(leave.getPrimaryId()); } final double rate = ((double) leave.getDays()) * -1d; leaveBalance.setRate(new BigDecimal("" + rate)); leaveBalance.setBalance(new BigDecimal("" + rate)); log.info("Attempting to save leave balance... {}", leaveBalance.toString()); leaveBalanceService.save(leaveBalance); } }<file_sep>/gateway-api/src/main/java/s2/portal/ws/cache/rest/UserCacheResource.java package s2.portal.ws.cache.rest; import s2.portal.dao.impl.es.UserElasticsearchIndexLoader; import s2.portal.dao.impl.es.UserElasticsearchRepository; import s2.portal.ws.common.rest.BaseResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @author <NAME> * @since March 2017 */ @SuppressWarnings("unused") @RestController @RequestMapping("/api/users/cache") public class UserCacheResource extends BaseResource { private UserElasticsearchRepository userElasticsearchRepository; private UserElasticsearchIndexLoader userElasticsearchIndexLoader; @Autowired public UserCacheResource(@Qualifier("userElasticsearchRepository") UserElasticsearchRepository userElasticsearchRepository , UserElasticsearchIndexLoader userElasticsearchIndexLoader) { this.userElasticsearchRepository = userElasticsearchRepository; this.userElasticsearchIndexLoader = userElasticsearchIndexLoader; } @RequestMapping(value = "/forceRefresh", method = RequestMethod.GET) public ResponseEntity<Integer> forceRefresh() { userElasticsearchRepository.deleteAll(); return ResponseEntity.ok(userElasticsearchIndexLoader.loadAll().size()); } @RequestMapping(value = "/size", method = RequestMethod.GET) public ResponseEntity<Long> size() { return ResponseEntity.ok(userElasticsearchRepository.count()); } }<file_sep>/business-api/src/main/java/s2/portal/bpm/client/json/RegisterUserAccountResponseBuilder.java package s2.portal.bpm.client.json; import s2.portal.security.JWTToken; /** * @author <NAME> * @since August 2016 */ public class RegisterUserAccountResponseBuilder { private String processInstanceId; private String businessKey; private Integer requestingUserId; private String requestingUser; private JWTToken jwtToken; private RegisterUserAccountResponseBuilder() { } public static RegisterUserAccountResponseBuilder aRegisterUserAccountResponse() { return new RegisterUserAccountResponseBuilder(); } public RegisterUserAccountResponseBuilder withProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; return this; } public RegisterUserAccountResponseBuilder withBusinessKey(String businessKey) { this.businessKey = businessKey; return this; } public RegisterUserAccountResponseBuilder withRequestingUserId(Integer requestingUserId) { this.requestingUserId = requestingUserId; return this; } public RegisterUserAccountResponseBuilder withRequestingUser(String requestingUser) { this.requestingUser = requestingUser; return this; } public RegisterUserAccountResponseBuilder withJwtToken(JWTToken jwtToken) { this.jwtToken = jwtToken; return this; } public RegisterUserAccountResponse build() { return new RegisterUserAccountResponse(processInstanceId, businessKey, requestingUserId , requestingUser, jwtToken); } } <file_sep>/db/src/main/java/s2/portal/data/user/Role.java package s2.portal.data.user; /** * @author <NAME> * @since August 2016 */ public enum Role { ROLE_SYSADMIN, ROLE_DEV, ROLE_BILLABLE_PER_HOUR } <file_sep>/business-api/src/main/java/s2/portal/service/LeaveService.java package s2.portal.service; import s2.portal.data.user.Leave; import java.util.Date; import java.util.List; /** * @author <NAME> * @since September 2018 */ public interface LeaveService extends CrudService<Integer, Leave>, AuditedModelAware<Leave> { List<Leave> findOverlappingLeave(Integer userId, Date startDate, Date endDate); List<Leave> findByUser(Integer userId); } <file_sep>/db/src/main/java/s2/portal/dao/ProvinceDao.java package s2.portal.dao; import s2.portal.data.system.Province; /** * @author <NAME> * @since October 2016 */ public interface ProvinceDao extends BaseDao<Integer, Province> { } <file_sep>/business-api/src/main/java/s2/portal/bpm/client/json/WorkflowRequest.java package s2.portal.bpm.client.json; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import s2.portal.bpm.client.common.CamundaProcess; import s2.portal.builder.TimeDescriptionBuilder; import s2.portal.data.user.User; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author <NAME> * @since November 2016 */ @SuppressWarnings("unused") @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY) @JsonSubTypes({ @JsonSubTypes.Type(value = RegisterUserAccountRequest.class, name = "RegisterUserAccountRequest"), @JsonSubTypes.Type(value = PasswordResetRequest.class, name = "PasswordResetRequest"), @JsonSubTypes.Type(value = ForgotPasswordRequest.class, name = "ForgotPasswordRequest"), @JsonSubTypes.Type(value = LeaveRequest.class, name = "LeaveRequest") }) public abstract class WorkflowRequest implements Serializable { private static final long serialVersionUID = -2895556419346716313L; private String processInstanceId; private String businessKey; private Date dateCreated; private String dateCreatedTimeDescription; private User requestingUser; private User assignee; private List<String> candidateGroups = new ArrayList<>(); private String lastAction; private String comment; public abstract CamundaProcess getType(); public final String getProcessInstanceId() { return processInstanceId; } public final void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public final String getBusinessKey() { return businessKey; } public final void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public final Date getDateCreated() { return dateCreated; } public final void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } @JsonGetter public final String getDateCreatedTimeDescription() { if (dateCreatedTimeDescription == null && this.dateCreated != null) { dateCreatedTimeDescription = TimeDescriptionBuilder.aTimeDescription() .witEvaluationDate(this.dateCreated) .build(); } return dateCreatedTimeDescription; } public final User getRequestingUser() { return requestingUser; } public final void setRequestingUser(User requestingUser) { this.requestingUser = requestingUser; } public User getAssignee() { return assignee; } public void setAssignee(User assignee) { this.assignee = assignee; } public List<String> getCandidateGroups() { return candidateGroups; } public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } public String getLastAction() { return lastAction; } public void setLastAction(String lastAction) { this.lastAction = lastAction; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } @Override public String toString() { return "WorkflowRequest{" + "processInstanceId='" + processInstanceId + '\'' + ", businessKey='" + businessKey + '\'' + ", dateCreated=" + dateCreated + ", requestingUser=" + requestingUser + ", assignee=" + assignee + ", candidateGroups=" + candidateGroups + '}'; } }<file_sep>/business-api/src/main/java/s2/portal/factory/UserDocumentPathFactory.java package s2.portal.factory; import s2.portal.data.user.User; import s2.portal.util.FileUtils; import org.springframework.stereotype.Component; /** * @author <NAME> * @since August 2018 */ @Component public class UserDocumentPathFactory { public static String build(String applicationHome, User user) { return FileUtils.resolveDir(applicationHome) + "docs" + System.getProperty("file.separator") + "users" + System.getProperty("file.separator") + user.getUsername(); } } <file_sep>/maven-plugin/maven-split-config-plugin/src/main/java/za/co/discovery/maven/config/SplitConfigArchiverMojo.java package za.co.discovery.maven.config; import org.apache.maven.archiver.MavenArchiveConfiguration; import org.apache.maven.archiver.MavenArchiver; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.codehaus.plexus.archiver.jar.JarArchiver; import java.io.File; import java.util.List; /** * Mojo for creating jars with environment-specific configuration data as * produced by {@link SplitConfigResourcesMojo}. * This class is based on the original JarMojo from Maven, unfortunately * subclassing is impossible due to the original class's design. * * @author <NAME> * @since August 2013 * * @goal package-split-configuration * @phase package * @requiresProject */ public class SplitConfigArchiverMojo extends AbstractSplitConfigMojo { /** * The Jar archiver. * * @parameter expression="${component.org.codehaus.plexus.archiver.Archiver#jar}" * @required */ private JarArchiver jarArchiver; /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * The maven archive configuration to use. * <p/> * See <a href="http://maven.apache.org/ref/current/maven-archiver/apidocs/org/apache/maven/archiver/MavenArchiveConfiguration.html">the Javadocs for MavenArchiveConfiguration</a>. * * @parameter */ private MavenArchiveConfiguration archive = new MavenArchiveConfiguration(); /** * @component */ private MavenProjectHelper projectHelper; /** * Whether creating the archive should be forced. * * @parameter expression="${jar.forceCreation}" default-value="false" */ private boolean forceCreation; protected final MavenProject getProject() { return project; } public File createArchive(String classifier) throws MojoExecutionException { File jarFile = getJarFile(outputDirectory, finalName, classifier); MavenArchiver archiver = new MavenArchiver(); archiver.setArchiver(jarArchiver); archiver.setOutputFile(jarFile); archive.setForced(forceCreation); try { File contentDirectory = getConfigDirectory(classifier); if (!contentDirectory.exists()) { getLog().warn("JAR will be empty - no content was marked for inclusion!"); } else { archiver.getArchiver().addDirectory(contentDirectory, DEFAULT_INCLUDES, DEFAULT_EXCLUDES); } // TODO: Replace this call with the one on the next line to exclude the pom.xml and pom.properties files from the config jars archiver.createArchive(project, archive); // archiver.createArchive(project, archive, false); return jarFile; } catch (Exception e) { throw new MojoExecutionException("Error assembling JAR", e); } } /** * Generates the JAR. */ public void doExecute() throws MojoExecutionException { List configurations = getConfigurations(); for (int i = 0; i < configurations.size(); i++) { Configuration cfg = (Configuration) configurations.get(i); File jarFile = createArchive(cfg.getClassifier()); MavenProject mavenProject = getProject(); projectHelper.attachArtifact(mavenProject, "jar", cfg.getClassifier(), jarFile); } } } <file_sep>/business-api/src/main/java/s2/portal/security/TokenToUserConverter.java package s2.portal.security; import com.google.gson.*; import io.jsonwebtoken.*; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.convert.converter.Converter; import org.springframework.util.Assert; import s2.portal.data.user.User; import javax.xml.bind.DatatypeConverter; import java.util.Date; /** * @author <NAME> * @since December 2017 */ public class TokenToUserConverter implements Converter<String, User> { private final Logger log = LoggerFactory.getLogger(TokenToUserConverter.class); private static final String USER = "user"; private static final String SECRET = "bl1oxlji2rl1onuch_$eda$r6?3+ujuzlMecrap$@*@dox2$re-itrowoste9ag9x220180901"; @Override public User convert(String token) { Assert.hasText(token); Claims claims; try { claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET)) .parseClaimsJws(token) .getBody(); final String json = claims.get(USER).toString(); if (json == null) { return null; } final DateTime expirationDate = DateTime.now().withMillis(claims.getExpiration().getTime()); if (expirationDate.isBefore(DateTime.now())) { throw new ExpiredJwtException("System cannot completed request. Credentials have expired, please login in again."); } final GsonBuilder gsonBuilder = new GsonBuilder(); // JSON to Object gsonBuilder.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (element, type, jsonDeserializationContext) -> element == null ? null : new Date(element.getAsLong())); // Object to JSON gsonBuilder.registerTypeAdapter(Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> date == null ? null : new JsonPrimitive(DateTime.now().withMillis(date.getTime()) .toString("yyyy-MM-dd'T'HH:mm:ssZ"))); final Gson gson = gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create(); return gson.fromJson(json, User.class); } catch (final MalformedJwtException e) { log.warn(e.getMessage(), e); throw new SignatureException("System cannot completed request. JWT token rejected, either the token is " + "for the correct application and environment or taken intended for another application or state and " + "expired token."); } } } <file_sep>/business-api/src/main/java/s2/portal/job/impl/ExecuteTimesheetReminderJob.java package s2.portal.job.impl; 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 s2.portal.command.ExecuteTimesheetReminderCommand; import s2.portal.job.BaseScheduledTask; import s2.portal.service.SystemJobService; import s2.portal.service.UserService; /** * The scheduled job to execute timesheet reminder. * * @author <NAME> * @since January 2019 */ @Component public class ExecuteTimesheetReminderJob extends BaseScheduledTask { private static final Logger LOG = LoggerFactory.getLogger(ExecuteTimesheetReminderJob.class); private ExecuteTimesheetReminderCommand executeTimesheetReminderCommand; @Autowired public ExecuteTimesheetReminderJob(UserService userService, SystemJobService systemJobService, ExecuteTimesheetReminderCommand executeTimesheetReminderCommand) { super(userService, systemJobService); this.executeTimesheetReminderCommand = executeTimesheetReminderCommand; } // Fire at 06:00am every Monday to Friday @Scheduled(cron = "0 0 6 ? * MON-FRI") @Override public void execute() { super.execute(); } @Override protected void run() { LOG.info("--- run ---"); executeTimesheetReminderCommand.execute(); } }<file_sep>/db/src/main/java/s2/portal/data/user/UserTimesheetLineBuilder.java package s2.portal.data.user; public final class UserTimesheetLineBuilder { private String description; private int actualHours; private UserTimesheetLineBuilder() { } public static UserTimesheetLineBuilder anUserTimesheetLine() { return new UserTimesheetLineBuilder(); } public UserTimesheetLineBuilder withDescription(String description) { this.description = description; return this; } public UserTimesheetLineBuilder withActualHours(int actualHours) { this.actualHours = actualHours; return this; } public UserTimesheetLine build() { UserTimesheetLine userTimesheetLine = new UserTimesheetLine(); userTimesheetLine.setPrimaryId(null); userTimesheetLine.setDescription(description); userTimesheetLine.setActualHours(actualHours); return userTimesheetLine; } } <file_sep>/db/migration/drop-camunda-tables-postgres.sql drop table act_re_case_def; drop table act_ru_case_execution; drop table act_ru_case_sentry_part; drop table act_hi_caseinst; drop table act_hi_caseactinst; drop table ACT_RE_DECISION_DEF; drop table ACT_RE_DECISION_REQ_DEF; drop table ACT_HI_DECINST; drop table ACT_HI_DEC_IN; drop table ACT_HI_DEC_OUT; drop table ACT_GE_PROPERTY; drop table ACT_GE_BYTEARRAY; drop table ACT_RE_DEPLOYMENT; drop table ACT_RE_PROCDEF; drop table ACT_RU_EXECUTION; drop table ACT_RU_JOB; drop table ACT_RU_JOBDEF; drop table ACT_RU_TASK; drop table ACT_RU_IDENTITYLINK; drop table ACT_RU_VARIABLE; drop table ACT_RU_EVENT_SUBSCR; drop table ACT_RU_INCIDENT; drop table ACT_RU_AUTHORIZATION; drop table ACT_RU_FILTER; drop table ACT_RU_METER_LOG; drop table ACT_RU_EXT_TASK; drop table ACT_RU_BATCH; drop table ACT_HI_PROCINST; drop table ACT_HI_ACTINST; drop table ACT_HI_VARINST; drop table ACT_HI_TASKINST; drop table ACT_HI_DETAIL; drop table ACT_HI_COMMENT; drop table ACT_HI_ATTACHMENT; drop table ACT_HI_OP_LOG; drop table ACT_HI_INCIDENT; drop table ACT_HI_JOB_LOG; drop table ACT_HI_BATCH; drop table ACT_HI_IDENTITYLINK; drop table ACT_HI_EXT_TASK_LOG; drop table ACT_ID_TENANT_MEMBER; drop table ACT_ID_TENANT; drop table ACT_ID_INFO; drop table ACT_ID_GROUP; drop table ACT_ID_MEMBERSHIP; drop table ACT_ID_USER;<file_sep>/business-api/src/main/java/s2/portal/bpm/client/json/LeaveRequest.java package s2.portal.bpm.client.json; import com.fasterxml.jackson.annotation.JsonGetter; import s2.portal.bpm.client.common.CamundaProcess; import s2.portal.data.user.Leave; import java.io.Serializable; /** * @author <NAME> * @since September 2018 */ public class LeaveRequest extends WorkflowRequest implements Serializable { private static final long serialVersionUID = 506980043786095256L; private Leave leave; @JsonGetter @Override public CamundaProcess getType() { return CamundaProcess.Leave; } public Leave getLeave() { return leave; } public void setLeave(Leave leave) { this.leave = leave; } } <file_sep>/db/src/test/java/s2/portal/dao/impl/hibernate/UserLeaveRateDaoImplTest.java package s2.portal.dao.impl.hibernate; import org.apache.log4j.BasicConfigurator; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import s2.portal.dao.UserLeaveRateDao; import s2.portal.data.user.UserLeaveRate; import java.math.BigDecimal; import java.util.Collection; import java.util.Date; /** * @author <NAME> * @since October 2018 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring/s2-portal-db-test-context.xml"}) @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class}) @TransactionConfiguration(transactionManager = "s2portalTransactionManager") @Transactional public class UserLeaveRateDaoImplTest { @Autowired private UserLeaveRateDao userLeaveRateDao; @BeforeClass public static void init() { BasicConfigurator.configure(); } @Test public void testFindAll() { final Collection<UserLeaveRate> data = userLeaveRateDao.findAll(); Assert.assertNotNull(data); } @Test public void testInsert() { final UserLeaveRate userLeaveRate = new UserLeaveRate(); userLeaveRate.setUserId(1); userLeaveRate.setLeaveTypeId("A"); userLeaveRate.setRate(new BigDecimal("0")); userLeaveRate.setStartDate(new Date()); userLeaveRate.setEndDate(new Date()); userLeaveRateDao.save(userLeaveRate); final UserLeaveRate otherUserLeaveRate = userLeaveRateDao.findByPrimaryId(userLeaveRate.getPrimaryId()); Assert.assertNotNull(otherUserLeaveRate); } }<file_sep>/db/src/main/java/s2/portal/data/system/BankBranch.java package s2.portal.data.system; import s2.portal.data.BaseModel; import org.hibernate.envers.Audited; import javax.persistence.*; /** * @author <NAME> * @since October 2016 */ @Entity @Table(name = "bank_branch") public class BankBranch extends BaseModel<Integer> { private static final long serialVersionUID = 7242344306672503832L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @Audited private Integer primaryId; @Column(name = "name") @Audited private String name; @ManyToOne @JoinColumn(name = "bank_id") @Audited private Bank bank; @Column(name = "branch_code") @Audited private Integer branchCode; /** * Set the unique identifier for the object. * * @param primaryId The primary key to set. */ @Override public void setPrimaryId(Integer primaryId) { this.primaryId = primaryId; } /** * Returns the unique identifier of the object. * * @return The primary key value. */ @Override public Integer getPrimaryId() { return primaryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Bank getBank() { return bank; } public void setBank(Bank bank) { this.bank = bank; } public Integer getBranchCode() { return branchCode; } public void setBranchCode(Integer branchCode) { this.branchCode = branchCode; } @Override public String toString() { return "BankBranch{" + "primaryId=" + primaryId + ", name='" + name + '\'' + ", bank=" + bank + ", branchCode=" + branchCode + '}'; } }<file_sep>/gateway-api/src/main/java/s2/portal/ws/system/rest/BankBranchResource.java package s2.portal.ws.system.rest; import s2.portal.data.audit.Revision; import s2.portal.data.system.BankBranch; import s2.portal.service.BankBranchService; import s2.portal.ws.common.json.ValidationResponse; import s2.portal.ws.common.rest.BaseResource; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Collection; /** * @author <NAME> * @since October 2016 */ @RestController @RequestMapping("/api/bank/branches") public class BankBranchResource extends BaseResource { @Autowired private BankBranchService bankBranchService; @RequestMapping(value = "/bank/{bankId}/branchCode/{branchCode}", method = RequestMethod.GET) public ResponseEntity<BankBranch> findByBranchCode(@PathVariable String bankId, @PathVariable String branchCode) { return ResponseEntity.ok(bankBranchService.findByBranchCode(Integer.parseInt(bankId), Integer.parseInt(branchCode))); } @RequestMapping(value = "/bank/{bankId}", method = RequestMethod.GET) public ResponseEntity<Collection<BankBranch>> findByBank(@PathVariable Integer bankId) { return ResponseEntity.ok(bankBranchService.findByBank(bankId)); } @RequestMapping(value = "/id/{id}", method = RequestMethod.GET) public ResponseEntity<BankBranch> findById(@PathVariable Integer id) { return ResponseEntity.ok(bankBranchService.findById(id)); } @RequestMapping(value = "", method = RequestMethod.GET) public ResponseEntity<Collection<BankBranch>> findAll() { return ResponseEntity.ok(bankBranchService.findAll()); } @RequestMapping(value = "", method = RequestMethod.POST) public ResponseEntity<BankBranch> save(@RequestBody BankBranch entity) { return ResponseEntity.ok(bankBranchService.save(entity)); } @RequestMapping(value = "/id/{id}", method = RequestMethod.DELETE) public ResponseEntity<BankBranch> delete(@PathVariable Integer id) { final BankBranch entity = bankBranchService.findById(id); return ResponseEntity.ok(bankBranchService.delete(entity)); } @RequestMapping(value = "/createdBy/id/{id}", method = RequestMethod.GET) public ResponseEntity<Revision> findCreatedBy(@PathVariable Integer id) { final BankBranch entity = bankBranchService.findById(id); return ResponseEntity.ok(bankBranchService.findCreatedBy(entity)); } @RequestMapping(value = "/modifiedBy/id/{id}", method = RequestMethod.GET) public ResponseEntity<Revision> findModifiedBy(@PathVariable Integer id) { final BankBranch entity = bankBranchService.findById(id); return ResponseEntity.ok(bankBranchService.findModifiedBy(entity)); } @RequestMapping(value = "/validate", method = RequestMethod.GET) public ResponseEntity<ValidationResponse> validate(@RequestParam("id") Integer id, @RequestParam("name") String name) { name = StringUtils.trimToEmpty(name); final BankBranch bankBranch = bankBranchService.findByName(name); if (bankBranch != null && !bankBranch.getPrimaryId().equals(id)) { return ResponseEntity.ok(new ValidationResponse(false, "Value is not unique")); } else { return ResponseEntity.ok(new ValidationResponse(true)); } } }<file_sep>/business-api/src/main/java/s2/portal/bpm/client/json/CalculateLeaveDaysResponse.java package s2.portal.bpm.client.json; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import s2.portal.data.user.Leave; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author <NAME> * @since September 2018 */ public class CalculateLeaveDaysResponse implements Serializable { private static final long serialVersionUID = -7686945919844420466L; private Leave leave; private List<String> decisions = new ArrayList<>(); private int daysBetween; public CalculateLeaveDaysResponse(int daysBetween) { this.daysBetween = daysBetween; } @JsonGetter public int getDaysBetween() { return daysBetween; } @JsonIgnore public void minusDays(int days) { daysBetween -= days; if (daysBetween < 0) daysBetween = 0; } public Leave getLeave() { return leave; } public void setLeave(Leave leave) { this.leave = leave; } public List<String> getDecisions() { return decisions; } public void setDecisions(List<String> decisions) { this.decisions = decisions; } @JsonIgnore public void addDecisions(String decision) { this.decisions.add(decision); } }
04d0beed4af3a879562c354b78f79238a718dbd8
[ "SQL", "Markdown", "Maven POM", "Java", "Text", "Dockerfile" ]
71
Java
jjrun1/s2-portal
bc7f1b248c7fc4d34c680a667b597b0d4b73d045
d9fa042882fd639783e9ae061690cb5b8c710c02
refs/heads/master
<repo_name>ddsky/zeroclickinfo-spice<file_sep>/share/spice/spoonacular/spoonacular.js (function (env) { "use strict"; env.ddg_spice_spoonacular = function(api_result){ var query = DDG.get_query(), query_encoded = DDG.get_query_encoded(); var searchTerm = query.replace(/recipes|recipe/i,'').trim(); Spice.add({ id: "spoonacular", name: "Recipes", data: api_result, meta: { sourceName: 'spoonacular', itemType: 'Recipes', sourceIconUrl: 'https://spoonacular.com/favicon.ico', sourceUrl: 'https://spoonacular.com/' + encodeURIComponent(searchTerm.replace(/ /g,'-')) }, template_group: 'info', templates: { item: Spice.spoonacular.spoonacular, item_detail: Spice.spoonacular.spoonacular_detail, detail: Spice.spoonacular.spoonacular_detail, options: { moreAt: true, aux: false } } }); }; /* * Create the image link of the recipe. */ Handlebars.registerHelper("makeImage", function(id, image) { "use strict"; var url = "https://webknox.com/recipeImages/"+id+"-240x150"; // get the file ending var ending = image.match(/\..{2,4}$/)[0]; return url + ending; }); /* * Create the big image link of the recipe. */ Handlebars.registerHelper("makeBigImage", function(id, image) { "use strict"; var url = "https://webknox.com/recipeImages/"+id+"-312x231"; // get the file ending var ending = image.match(/\..{2,4}$/)[0]; return url + ending; }); /* * Helper for Handlebarsjs to allow for conditions with comparison. */ Handlebars.registerHelper("ifCond", function(v1, operator, v2, options) { switch (operator) { case '==': return (v1 == v2) ? options.fn(this) : options.inverse(this); case '===': return (v1 === v2) ? options.fn(this) : options.inverse(this); case '<': return (v1 < v2) ? options.fn(this) : options.inverse(this); case '<=': return (v1 <= v2) ? options.fn(this) : options.inverse(this); case '>': return (v1 > v2) ? options.fn(this) : options.inverse(this); case '>=': return (v1 >= v2) ? options.fn(this) : options.inverse(this); case '&&': return (v1 && v2) ? options.fn(this) : options.inverse(this); case '||': return (v1 || v2) ? options.fn(this) : options.inverse(this); default: return options.inverse(this); } }); /* * Format ranking values. */ Handlebars.registerHelper("format", function(rankingValue) { "use strict"; // get non number content var text = rankingValue.match(/[^0-9]+/gi)[0]; var number = rankingValue.replace(text,'') var r = new Number(number).toLocaleString('en'); if (text == '$') { r = text+r+' per serving'; } else if (text == 'min') { r = r+' '+text + 'utes to make'; } else { r = r+' '+text; } return r; }); /* * Format aggregate likes values. */ Handlebars.registerHelper("formatLikes", function(likes) { "use strict"; return new Number(likes).toLocaleString('en'); }); /* * Get the image of the badge. */ Handlebars.registerHelper("badge", function(type) { "use strict"; return DDG.get_asset_path("spoonacular", type+"-badge.png").replace("//", "/"); }); /* * Create the link to the recipe. */ Handlebars.registerHelper("recipeLink", function(id, title) { "use strict"; // modify the title to spoonacular's title format (unlike encodeURI, some characters will simply be dropped) var safeTitle = title.replace(/\'/g,'').replace(/\"/g,'').replace(/&/g,'').replace(/\?/g,'').replace(/ /g,'-'); return "https://spoonacular.com/"+safeTitle+"-"+id; }); /* * Iterate over the badges of the recipe. Skip "vegetarian" if the recipe is "vegan". Also limit the number of badges to 4 to make it fit next to the recipe image. */ Handlebars.registerHelper('iterateBadges', function(context, options) { var ret = ''; var skipVegetarian = false; var max = 4; for (var i = 0; i < context.length; i++) { if (context[i] == 'vegan') { skipVegetarian = true; max = 5; } } for (var i = 0; i < Math.min(context.length,max); i++) { if (context[i] == 'vegetarian' && skipVegetarian) { continue; } ret = ret + options.fn(context[i]); } return ret; }); }(this));
544a82eda33f5d34782e99f7306e582eca4b0195
[ "JavaScript" ]
1
JavaScript
ddsky/zeroclickinfo-spice
fa8d8fdcc24d7ec837053e0b181b4858a342b67d
03f92fde2a82a93788a475690d61f75592b870f6
refs/heads/master
<repo_name>IvanShumilov/HWRoom<file_sep>/app/src/main/java/ia/shumilov/sberbank/ru/hwroom/activityes/ShowSettingNote.java package ia.shumilov.sberbank.ru.hwroom.activityes; import android.arch.persistence.room.Room; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import ia.shumilov.sberbank.ru.hwroom.R; import ia.shumilov.sberbank.ru.hwroom.database.NotesDatabase; import ia.shumilov.sberbank.ru.hwroom.database.SettingNote; import ia.shumilov.sberbank.ru.hwroom.database.SettingNoteDAO; import static ia.shumilov.sberbank.ru.hwroom.activityes.StartActivity.ID_NOTE; public class ShowSettingNote extends AppCompatActivity { private static final String COLORS_ARRAY = "colors"; private static final String TEXT_SIZE_ARRAY = "textSize"; private Spinner mSpinner_text_color; private Spinner mSpinner_title_color; private Spinner mSpinner_text_size; private SettingNoteDAO mSettingNoteDAO; private int mColorTextBack; private int mColorTitleBack; private int mSizeText; private int mNote_id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting_note); // получаем id записи у которой вызвана форма mNote_id = getIntent().getIntExtra(ID_NOTE, 0); // инициализируем базу initDB(); // проверяем есть ли запись к note checkRowInBD(); // экзепляр настроек по ноте SettingNote settingNote = mSettingNoteDAO.getSettingNoteByNoteId(mNote_id); // Получаем экземпляр элемента Spinner mSpinner_text_color = findViewById(R.id.setting_note_spinner_color); mSpinner_title_color = findViewById(R.id.setting_note_spinner_color_title); mSpinner_text_size = findViewById(R.id.setting_note_spinner_textSize); // Настраиваем адаптер ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this, R.array.colors, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Вызываем адаптер mSpinner_text_color.setAdapter(adapter); Integer position = getSelectedSpin(settingNote.mColorBack, COLORS_ARRAY); if (position != null) { mSpinner_text_color.setSelection(position); } mSpinner_title_color.setAdapter(adapter); position = getSelectedSpin(settingNote.mColorTitleBack, COLORS_ARRAY); if (position != null) { mSpinner_title_color.setSelection(position); } // фдаптер для размера adapter = ArrayAdapter.createFromResource(this, R.array.textSize, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item); // вызываем для текста адаптер mSpinner_text_size.setAdapter(adapter); position = getSelectedSpin(settingNote.mTextSize, TEXT_SIZE_ARRAY); if (position != null) { mSpinner_text_size.setSelection(position); } // обработка нового выбора адаптеров mSpinner_text_color.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mColorTextBack = Color.parseColor(((TextView) view).getText().toString()); mSpinner_text_color.setBackgroundColor(mColorTextBack); } @Override public void onNothingSelected(AdapterView<?> parent) { mColorTextBack = Color.parseColor("#FFFFFF"); } }); mSpinner_title_color.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mColorTitleBack = Color.parseColor(((TextView) view).getText().toString()); mSpinner_title_color.setBackgroundColor(mColorTitleBack); } @Override public void onNothingSelected(AdapterView<?> parent) { mColorTitleBack = Color.parseColor("#000000"); } }); mSpinner_text_size.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mSizeText = Integer.parseInt(((TextView) view).getText().toString()); } @Override public void onNothingSelected(AdapterView<?> parent) { mSizeText = 8; } }); } private void checkRowInBD() { int idLast = 1; for (SettingNote settingNote : mSettingNoteDAO.getSettingNotes()) { idLast = Math.max(idLast, settingNote.id); if (settingNote.mNoteID == mNote_id) { return; } } mSettingNoteDAO.insert(new SettingNote(idLast+1, mColorTextBack, mColorTitleBack, mSizeText, mNote_id)); } private void initDB() { NotesDatabase db = Room.databaseBuilder(getApplicationContext(), NotesDatabase.class, "notes_database") .allowMainThreadQueries() .build(); mSettingNoteDAO = db.getSettingNoteDAO(); } @Override protected void onPause() { super.onPause(); SettingNote settingNote = mSettingNoteDAO.getSettingNoteByNoteId(mNote_id); if (settingNote != null) { settingNote.mColorBack = mColorTextBack; settingNote.mColorTitleBack = mColorTitleBack; settingNote.mTextSize = mSizeText; mSettingNoteDAO.update(settingNote); } else { int idLast = 1; for (SettingNote n : mSettingNoteDAO.getSettingNotes()) { idLast = Math.max(idLast, n.id); } mSettingNoteDAO.insert(new SettingNote(idLast+1, mColorTextBack, mColorTitleBack, mSizeText, mNote_id)); } } private Integer getSelectedSpin(int value, String name_array) { List<String> array; switch (name_array) { case "colors": { array = Arrays.asList(getResources().getStringArray(R.array.colors)); for (int i = 0; i < array.size(); i++) { if (value == Color.parseColor(array.get(i))) { return i; } } break; } case "textSize": { array = Arrays.asList(getResources().getStringArray(R.array.textSize)); for (int i = 0; i < array.size(); i++) { if (value == Integer.parseInt(array.get(i))) { return i; } } break; } } return null; } } <file_sep>/app/src/main/java/ia/shumilov/sberbank/ru/hwroom/database/SettingNoteDAO.java package ia.shumilov.sberbank.ru.hwroom.database; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.OnConflictStrategy; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; import java.util.List; @Dao public interface SettingNoteDAO { @Query("select * from setting where id = :id") SettingNote getSettingNoteById(long id); @Query("select * from setting") List<SettingNote> getSettingNotes(); @Update void update(SettingNote settingNote); @Query("select * from setting where note_id = :id") SettingNote getSettingNoteByNoteId(int id); @Insert(onConflict = OnConflictStrategy.REPLACE) long insert(SettingNote settingNote); @Delete void delete(SettingNote settingNote); } <file_sep>/app/src/main/java/ia/shumilov/sberbank/ru/hwroom/activityes/StartActivity.java package ia.shumilov.sberbank.ru.hwroom.activityes; import android.app.ListActivity; import android.arch.persistence.room.Room; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import ia.shumilov.sberbank.ru.hwroom.R; import ia.shumilov.sberbank.ru.hwroom.database.NoteDAO; import ia.shumilov.sberbank.ru.hwroom.database.Notes; import ia.shumilov.sberbank.ru.hwroom.database.NotesDatabase; import ia.shumilov.sberbank.ru.hwroom.database.SettingNote; public class StartActivity extends ListActivity { private NotesDatabase mDataBase; private NoteDAO mNoteDAO; public static final String ID_NOTE = "id_note_in_bd"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // create BD mDataBase = Room.databaseBuilder(getApplicationContext(), NotesDatabase.class, "notes_database") .allowMainThreadQueries() .build(); mNoteDAO = mDataBase.getNoteDAO(); // add item in mDataBase if (mNoteDAO.getNotes().size() < 1) { for (int i = 1; i < 10; i++) { mNoteDAO.insert(new Notes(i, "First Note " + i, "mText number one" + i)); } } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Intent intent = new Intent(this, ShowNote.class); if (((TextView) v).getText().toString().equalsIgnoreCase(getResources().getString(R.string.btnAddNote))) { intent.putExtra(ID_NOTE, -1); } else { intent.putExtra(ID_NOTE, getIdNote(((TextView) v).getText().toString())); } startActivity(intent); } private int getIdNote(String title) { for (Notes notes : mNoteDAO.getNotes()) { if (title.equalsIgnoreCase(notes.mTitle)) { return notes.id; } } return 0; } @Override protected void onResume() { super.onResume(); // create adapter List<String> listTitle = new ArrayList<>(); listTitle.add(getResources().getString(R.string.btnAddNote) ); for (Notes notes : mNoteDAO.getNotes()) { listTitle.add(notes.mTitle); } ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listTitle); // show adapter setListAdapter(mAdapter); } }
63bd6854482df2c525f831671d9f8d413580c7d5
[ "Java" ]
3
Java
IvanShumilov/HWRoom
c1be5f98464b51a3c77dcb23cf56990b1375d22b
07e37bbd4402f7250ac323af1e84b9759a3aa580
refs/heads/master
<file_sep><?php // Constantes conexión con la base de datos define("server", 'localhost'); define("user", 'tutosWeb'); define("pass", '<PASSWORD>'); define("mainDataBase", 'tutosWeb'); // Variable que indica el status de la conexión a la base de datos $errorDbConexion = false; function userLogin($data,$dbLink){ // Bandera de logueo $respuestaLogin = false; // validar si hay datos en los parametros if(!empty($data) && !empty($dbLink)){ $consulta = sprintf("SELECT * FROM tbl_users WHERE usr_email='%s' AND usr_pass='%s' AND usr_activo=1 LIMIT 1", trim($data['usr_email']),md5(trim($data['usr_pass']))); // Ejecutamos la cosnulta $respuesta = $dbLink -> query($consulta); // verificamos si es exitoso el login if($respuesta -> num_rows != 0){ $userData = $respuesta -> fetch_assoc(); $respuestaLogin = true; $_SESSION['userLogin'] = true; $_SESSION['userNombre'] = $userData['usr_nombre'].' '.$userData['usr_apellidos']; $_SESSION['userID'] = $userData['idUsuario']; } } return $respuestaLogin; } // Función para verificar la existencia del correo electrónico en la tabla de usuarios function verificaCorreo($data,$dbLink){ // Bandera de logueo $response = false; // validar si hay datos en los parametros if(!empty($data) && !empty($dbLink)){ $consulta = sprintf("SELECT * FROM tbl_users WHERE usr_email='%s' AND usr_activo=1 LIMIT 1", trim($data)); // Ejecutamos la cosnulta $respuesta = $dbLink -> query($consulta); // verificamos si es exitoso el login if($respuesta -> num_rows != 0){ $response = true; } } return $response; } // Función para crear una cadena aleatoria function creaPassword( $length = 10 ) { $key = ""; $pattern = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789"; for($i = 0 ; $i < $length ; $i++ ) { $key .= $pattern[rand(0,53)]; } return $key; } // Actualizar la contraseña del usuario en la tabla function actualizaClave($data,$dbLink){ $consulta = sprintf("UPDATE tbl_users SET usr_pass='%s' WHERE usr_email='%s' LIMIT 1", md5($data['usr_pass']),$data['rec_correo']); // Ejecutamos la cosnulta $respuesta = $dbLink -> query($consulta); if($dbLink -> affected_rows == 1){ return true; } else{ return false; } } // función para realizar envío de correo electrónico function mandaCorreo($mail,$data=''){ $response = false; $destNombre = 'Recuperación de Contraseña'; $body = ' <div> <p></strong> su contraseña de acceso ha sido modificada </strong>, A continuación le indicamos como accesar al sistema.</p> <p><strong>DATOS DEL USUARIO</strong></p> <p><strong>Usuario: '. $data['rec_correo'] . '</p> <p><strong>Clave: '. $data['usr_pass'] . '</p> </div> '; $mail->IsSMTP(); // telling the class to use SMTP $mail->Host = "mail.worldcargoexport.com"; // SMTP server // $mail->SMTPDebug = 2; // enables SMTP debug information (for testing) // 1 = errors and messages // 2 = messages only $mail->SMTPAuth = true; // enable SMTP authentication $mail->Host = "mail.worldcargoexport.com"; // sets the SMTP server $mail->Port = 26; // set the SMTP port for the GMAIL server $mail->Username = "<EMAIL>"; // SMTP account username $mail->Password = "<PASSWORD>"; // SMTP account password $mail->SetFrom('<EMAIL>', '.:: Interfaz de Usuario ::.'); $mail->AddReplyTo('<EMAIL>', '.:: Interfaz de Usuario ::.'); $mail->Subject = utf8_decode(".:: Interfaz de Usuario ::. Recuperación de contraseña"); $mail->AltBody = "Para ver el mensaje, utilice un cliente de correo electrónico compatible con HTML!!!!"; // optional, comment out and test $mail->MsgHTML($body); $address = $data['rec_correo']; $mail->AddAddress($address, $destNombre); // $mail->AddBCC('<EMAIL>','<NAME>'); if($mail->Send()) { $response = true; } return $response; } // Verificar constantes para conexión al servidor if(defined('server') && defined('user') && defined('pass') && defined('mainDataBase')) { // Conexión con la base de datos $mysqli = new mysqli(server, user, pass, mainDataBase); // Verificamos si hay error al conectar if (mysqli_connect_error()) { $errorDbConexion = true; } else{ // Evitando problemas con acentos $mysqli -> query('SET NAMES "utf8"'); } } ?><file_sep><?php session_name('demoUI'); session_start(); // array de salida $appResponse = array( "respuesta" => false, "mensaje" => "Error en la aplicación", "contenido" => "" ); $root = '../'; // Verificamos las variables post y que exista la variable accion if(isset($_POST) && !empty($_POST) && isset($_POST['accion'])){ // incluimos el archivo de funciones y conexión a la base de datos include('mainFunctions.inc.php'); if($errorDbConexion == false){ switch ($_POST['accion']) { case 'login': $appResponse['respuesta'] = userLogin($_POST,$mysqli); $appResponse['mensaje'] = "Usuario Encontrado"; break; case 'recuperaPass': // verificar variable de correo que no este vacía if(!empty($_POST['rec_correo'])){ // Verificamos que exista la cuentad e correo electrónico en nuestra tabla de usuarios if(verificaCorreo($_POST['rec_correo'],$mysqli)){ // Crear clave de acceso $_POST['usr_pass'] = <PASSWORD>(); // Actulizamos el password en la tabla if(actualizaClave($_POST,$mysqli)){ // Enviamos por correo electrónico la clave // Cargamos e inicializamos el phpmailer require_once($root.'php_libs/PHPMailer_v5.1/class.phpmailer.php'); // Creamos el objeto mail $mail = new PHPMailer(); if(mandaCorreo($mail,$_POST)){ $appResponse['respuesta'] = true; $appResponse['mensaje'] = "Se envió correctamente la clave de aceso"; }else{ $appResponse['mensaje'] = "Se creo correctamente la contraseña pero no se realizó el evnío de la misma por correo electrónico"; } } else{ $appResponse['mensaje'] = "No se puede actualziar la contraseña del usuario"; } } else{ $appResponse['mensaje'] = "Usuario no encontrado"; } } break; case 'administracion': $appResponse = array( "respuesta" => true, "mensaje" => "", "contenido" => ' <section> <ul class="breadcrumb"> <li><a href="index.php">Inicio</a> <span class="divider">/</span></li> <li>Administración</li> </ul> </section> <div class="hero-unit"> <h1>Administración</h1> <p>Esta sección se esta cargando por medio de ajax con la función $.ajax() de jquery.</p> <p> <a class="btn btn-primary btn-large"> Leer más... </a> </p> </div> ' ); break; default: $appResponse['mensaje'] = "Opción no disponible"; break; } }else{ $appResponse['mensaje'] = "Error al conectar con la base de datos"; } } else{ $appResponse['mensaje'] = "Variables no definidas"; } // Retorno de JSON echo json_encode($appResponse); ?><file_sep><?php session_name('demoUI'); session_start(); // Directorio Raíz de la app // Es utilizado en templateEngine.inc.php $root = ''; // Incluimos el template engine include('includes/templateEngine.inc.php'); $twig->display('layout_login.html'); ?><file_sep><?php session_name('demoUI'); session_start(); // Directorio Raíz de la app // Es utilizado en templateEngine.inc.php $root = ''; if(!empty($_SESSION) && $_SESSION['userLogin'] == true){ // Incluimos el template engine include('includes/templateEngine.inc.php'); // Cargamos la plantilla $twig->display('layout_catalogo.html',array( "userName" => $_SESSION['userNombre'], "userID" => $_SESSION['userID'] )); } else{ header("Location:login.php"); } ?>
fa94fccf13606f05d00dba46ec6939d5f0a5be16
[ "PHP" ]
4
PHP
CazaresLuis/ui_php_y_mysql_ajax
a747220d8c37a2bd90c49508d45dfcfacdbb0e46
09422f7fcc5c3841c80cfae8cd1d43844ca12be1
refs/heads/master
<repo_name>BlinfoldKing/Nature-of-Code<file_sep>/README.md # Nature-of-Code my implementation and practice based of the book "Nature of Code" by Shiffman <file_sep>/sketches/chapter2/chp2.js function draw() { if(isReset) reset() ellipse(0, 0, 100) }<file_sep>/sketches/chapter3/chp3.js function draw() { if(isReset) reset() }
2de4dda52c192faa2472562ba5253a1991229474
[ "Markdown", "JavaScript" ]
3
Markdown
BlinfoldKing/Nature-of-Code
c69a0e1020b50291fe4e333eee635dd8a9d8fef8
e1e8c744ed2f0e28aa188207f95ce3c6a4463aff
refs/heads/integration
<file_sep>Geocoder.configure(lookup: :test, ip_lookup: :test) Geocoder::Lookup::Test.set_default_stub( [{ "coordinates" => [55.79288, 49.11048], "address" => "Bauman St, Kazan, Russia" }] ) Geocoder::Lookup::Test.add_stub( [55.78787607694294, 49.12356007675169], [{ "coordinates" => [55.78787607694294, 49.12356007675169], "address" => "Ulitsa Butlerova, 4, Kazan, Russia" }] ) Geocoder::Lookup::Test.add_stub( [55.78778545536969, 49.122609570622444], [{ "coordinates" => [55.78778545536969, 49.122609570622444], "address" => "Profsoyuznaya Ulitsa, 50, Kazan, Russia" }] ) Geocoder::Lookup::Test.add_stub( [55.754270, 37.621277], [{ "coordinates" => [55.754270, 37.621277], "address" => "Red Square, 3, Moscow, Russia" }] ) <file_sep>class NearestCoffeeHousesQuery DISTANCE = 10 # km attr_reader :relation, :location delegate :coordinates, to: :location private :relation, :location, :coordinates def initialize(relation, location) @relation = relation @location = location end def all relation.near(coordinates, DISTANCE, units: :km) end end <file_sep>require "rails_helper" feature "Destroy Coffee House" do include_context :user_signed_in background do create :coffee_house, :kazan_butlerova, owner: current_user, name: "Sweety Coffee" create :coffee_house, :kazan_profsoyuznaya, owner: current_user, name: "Coffee House" end scenario "User destroys coffee house" do visit manage_coffee_houses_path expect(page).to have_content("Sweety Coffee") within("tr", text: "Sweety Coffee") do click_link "delete" end expect(page).to have_content("Coffee house was successfully destroyed.") expect(page).to have_no_content("Sweety Coffee") end end <file_sep>require "rails_helper" feature "Show Coffee House" do include_context :user_signed_in let(:coffee_house) do create :coffee_house, :kazan_profsoyuznaya, owner: current_user, name: "Coffee House", description: "We give very HOT COFFEE" end scenario "User sees coffee house" do visit manage_coffee_house_path(coffee_house) expect(page).to have_content("Coffee House") expect(page).to have_content("We give very HOT COFFEE") expect(page).to have_content("Where to find us: Profsoyuznaya Ulitsa, 50, Kazan, Russia") expect(page).to have_link("Add Coffee") end end <file_sep>class Manage::CoffeesController < Manage::BaseController expose_decorated :coffee_house expose_decorated :coffees, :fetch_coffees expose_decorated :coffee, parent: :coffee_house def new end def create coffee.save respond_with(:manage, coffee_house, coffee) end def show end def edit end def update coffee.update(coffee_params) respond_with(:manage, coffee_house, coffee) end def destroy coffee.destroy respond_with(coffee, location: manage_coffee_house_path(coffee_house)) end private def coffee_params params.require(:coffee).permit(:name, :kind, :volume, :price, :description) end def fetch_coffees coffee_house.coffees.order(created_at: :desc) end def authorize_resource! authorize! coffee end end <file_sep>require "rails_helper" describe Omniauth::AuthenticateUser do let(:expected_interactors) do [ Omniauth::PrepareAuthData, Omniauth::FindUser, Omniauth::CreateUser, Omniauth::ConfirmUser, Omniauth::ConnectProvider ] end it "organize interactors" do expect(described_class.organized).to eq(expected_interactors) end end <file_sep>shared_context :facebook_with_valid_credentials do background do OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new( provider: "facebook", uid: "12345", info: { email: "<EMAIL>", name: "<NAME>" } ) end end shared_context :facebook_with_invalid_credentials do background do OmniAuth.config.mock_auth[:facebook] = :invalid_credentials end end shared_context :google_with_valid_credentials do background do OmniAuth.config.mock_auth[:google_oauth2] = OmniAuth::AuthHash.new( provider: "google_oauth2", uid: "12345", info: { email: "<EMAIL>", name: "<NAME>" } ) end end shared_context :google_with_invalid_credentials do background do OmniAuth.config.mock_auth[:google_oauth2] = :invalid_credentials end end <file_sep>module MapHelpers def choose_location_on_map(model_name:, latitude:, longitude:) find("input##{model_name}_latitude", visible: false).set(latitude) find("input##{model_name}_longitude", visible: false).set(longitude) end end <file_sep>require "rails_helper" feature "Index Coffee House" do let!(:coffee_like) do create :coffee_house, :kazan_butlerova, name: "Coffee Like", description: "Сoffee to go" end let!(:beanhearts) do create :coffee_house, :kazan_profsoyuznaya, name: "Beanhearts", description: "The best place to spend an evening with friends" end scenario "Visitor sees list of coffee houses" do visit coffee_houses_path within "tbody" do expect(page).to have_selector("tr", count: 2) expect(page).to have_table_row(number: 1, values: ["Beanhearts", "Profsoyuznaya Ulitsa, 50, Kazan, Russia"]) expect(page).to have_table_row(number: 2, values: ["Coffee Like", "Ulitsa Butlerova, 4, Kazan, Russia"]) end end scenario "Visitor search coffee house" do visit coffee_houses_path fill_in "Search", with: "Bean" click_button "Search" within "tbody" do expect(page).to have_selector("tr", count: 1) expect(page).to have_table_row(number: 1, values: ["Beanhearts", "Profsoyuznaya Ulitsa, 50, Kazan, Russia"]) end end end <file_sep>class Omniauth::PrepareAuthData include Interactor REQUIRED_PARAMS = %i[provider uid email name].freeze delegate :auth_params, to: :context delegate :provider, :uid, to: :auth_params def call context.auth_data = prepare_auth_data context.fail!(error: I18n.t("interactors.error.invalid_auth_data")) unless valid_auth_data? end private def prepare_auth_data send("#{provider}_auth_data") end def valid_auth_data? REQUIRED_PARAMS.all? { |key| valid_value?(key) } end def valid_value?(key) context.auth_data[key].to_s.present? end def facebook_auth_data { provider: provider, uid: uid, email: auth_params.dig(:info, :email), name: auth_params.dig(:info, :name) } end def google_oauth2_auth_data { provider: provider, uid: uid, email: auth_params.dig(:info, :email), name: auth_params.dig(:info, :name) } end end <file_sep>module Geolocation extend ActiveSupport::Concern included do helper_method :current_coordinates end def current_location if client_coordinates_exist? Geocoder.search(client_coordinates).first else request.location end end def current_coordinates if client_coordinates_exist? client_coordinates else request.location.coordinates end end private def client_coordinates [cookies[:latitude], cookies[:longitude]] end def client_coordinates_exist? cookies[:latitude].present? && cookies[:longitude].present? end end <file_sep>class CreateCoffeeHouses < ActiveRecord::Migration[5.1] def change create_table :coffee_houses do |t| t.string :name, null: false t.float :latitude, null: false t.float :longitude, null: false t.string :address, null: false t.string :description t.belongs_to :owner, null: false, foreign_key: { to_table: :users }, index: true, on_delete: :cascade t.timestamps end add_index :coffee_houses, %i[latitude longitude] end end <file_sep>require "rails_helper" feature "Show Coffee House" do let(:coffee_house) do create :coffee_house, :kazan_profsoyuznaya, name: "Coffee House", description: "We give very HOT COFFEE" end background do create :coffee, name: "Cappuccino", kind: "hot_coffee", volume: 300, price: 4, coffee_house: coffee_house create :coffee, name: "Frappuccino", kind: "cold_coffee", volume: 400, price: 5, coffee_house: coffee_house create :coffee, name: "Latte", kind: "hot_coffee", volume: 500, price: 4, coffee_house: coffee_house create :coffee, name: "Mocco", kind: "hot_coffee", volume: 500, price: 6, coffee_house: coffee_house end scenario "Visitor sees coffee house" do visit coffee_house_path(coffee_house) expect(page).to have_content("Coffee House") expect(page).to have_content("We give very HOT COFFEE") expect(page).to have_content("Where to find us: Profsoyuznaya Ulitsa, 50, Kazan, Russia") within "tbody" do expect(page).to have_selector("tr", count: 4) expect(page).to have_table_row(number: 1, values: ["Mocco", "Hot Coffee", "500 mL", "$6.00"]) expect(page).to have_table_row(number: 2, values: ["Latte", "Hot Coffee", "500 mL", "$4.00"]) expect(page).to have_table_row(number: 3, values: ["Frappuccino", "Cold Coffee", "400 mL", "$5.00"]) expect(page).to have_table_row(number: 4, values: ["Cappuccino", "Hot Coffee", "300 mL", "$4.00"]) end end end <file_sep>class CoffeeHouse < ApplicationRecord include PgSearch belongs_to :owner, class_name: "User" has_many :coffees, dependent: :destroy geocoded_by :address reverse_geocoded_by :latitude, :longitude before_validation :reverse_geocode, if: :geoposition_changed? validates :name, :latitude, :longitude, :address, presence: true pg_search_scope :search_by_text_fields, against: %i[name description], associated_against: { coffees: %i[name description] }, using: { tsearch: { prefix: true } } def geoposition_changed? new_record? || address_changed? || latitude_changed? || longitude_changed? end end <file_sep>require "rails_helper" describe Omniauth::FindUser do describe ".call" do subject(:interactor_call) { described_class.call(auth_data: auth_data) } let(:found_user) { interactor_call.user } let(:auth_data) do { provider: "facebook", uid: "12345", email: "<EMAIL>" } end context "when user does not have provider" do let!(:user) { create :user, email: "<EMAIL>", full_name: "<NAME>" } it "finds user by email" do expect(found_user.email).to eq("<EMAIL>") expect(found_user.full_name).to eq("<NAME>") end end context "when user have provider" do let!(:user) { create :user, email: "<EMAIL>", full_name: "<NAME>", providers: [provider] } let(:provider) { create :facebook_provider } it "finds user by provider" do expect(found_user.email).to eq("<EMAIL>") expect(found_user.full_name).to eq("<NAME>") end end context "when such user does not exist" do let(:auth_data) do { provider: "facebook", uid: "another uid", info: { email: "<EMAIL>" } } end it "does not find user" do expect(found_user).to be_nil end end end end <file_sep>require "rails_helper" require "geocoder/results/ipinfo_io" describe NearestCoffeeHousesQuery do subject(:query) { described_class.new(relation, location) } let(:relation) { CoffeeHouse.all } let(:location) { instance_double(Geocoder::Result::IpinfoIo, coordinates: kazan_coordinates) } let(:kazan_coordinates) { [55.788258, 49.119290] } let!(:coffee_house_within_radius) { create :coffee_house, :kazan_butlerova } let!(:coffee_house_beyond_radius) { create :coffee_house, :moscow_red_square } describe "#all" do subject(:all) { query.all } it { is_expected.to eq([coffee_house_within_radius]) } end end <file_sep>class CreateCoffee < ActiveRecord::Migration[5.1] def change create_table :coffees do |t| t.string :name, null: false t.string :kind, null: false t.integer :volume, null: false t.decimal :price, null: false, precision: 10, scale: 2 t.string :description t.belongs_to :coffee_house, null: false, foreign_key: true, index: true, on_delete: :cascade t.timestamps end end end <file_sep>FactoryGirl.define do factory :provider, aliases: %i[facebook_provider] do name "facebook" uid { SecureRandom.uuid } association :user, strategy: :build end end <file_sep>FactoryGirl.define do factory :coffee_house do name Faker::Company.name description Faker::Lorem.paragraphs latitude 55.78787607694294 longitude 49.12356007675169 address "Ulitsa Butlerova, 4, Kazan, Russia" association :owner, factory: :user trait :kazan_butlerova do latitude 55.78787607694294 longitude 49.12356007675169 address "Ulitsa Butlerova, 4, Kazan, Russia" end trait :kazan_profsoyuznaya do latitude 55.78778545536969 longitude 49.122609570622444 address "Profsoyuznaya Ulitsa, 50, Kazan, Russia" end trait :moscow_red_square do latitude 55.754270 longitude 37.621277 address "Red Square, 3, Moscow, Russia" end end end <file_sep>class Coffee < ApplicationRecord enum kind: { hot_coffee: "hot_coffee", cold_coffee: "cold_coffee", coffee_drink: "coffee_drink", copyright_coffee: "copyright_coffee" } belongs_to :coffee_house has_one :owner, through: :coffee_house validates :name, :kind, :volume, :price, presence: true validates :volume, numericality: { only_integer: true, greater_than: 0 } validates :price, numericality: { greater_than: 0 } def self.translated_kinds I18n.t("activerecord.attributes.coffee.kinds").invert.to_a end end <file_sep>require "rails_helper" feature "Index Coffee House" do include_context :user_signed_in background do create :coffee_house, :kazan_butlerova, owner: current_user, name: "Sweety Coffee" create :coffee_house, :kazan_profsoyuznaya, owner: current_user, name: "Coffee House" end scenario "User sees list of coffee houses" do visit manage_coffee_houses_path within "tbody" do expect(page).to have_selector("tr", count: 2) expect(page).to have_table_row( number: 1, values: ["Coffee House", "Profsoyuznaya Ulitsa, 50, Kazan, Russia", "edit", "delete"] ) expect(page).to have_table_row( number: 2, values: ["Sweety Coffee", "Ulitsa Butlerova, 4, Kazan, Russia", "edit", "delete"] ) end end end <file_sep>class CoffeeHousesQuery attr_reader :location, :keywords delegate :coordinates, to: :location private :location, :coordinates def initialize(location, keywords) @location = location @keywords = keywords end def all keywords.blank? ? nearest_coffee_houses : search_coffee_houses end def nearest_coffee_houses CoffeeHouse.near(coordinates) end def search_coffee_houses CoffeeHouse.search_by_text_fields(keywords) end end <file_sep>module ActionPolicyDraper extend ActiveSupport::Concern def policy_for(record:, **opts) record = record.model while record.is_a?(Draper::Decorator) super(record: record, **opts) end end <file_sep>// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery2 //= require jquery-ujs //= require foundation //= require cookie //= require current_user //= require current_coordinates //= require ckeditor/init //= require location_input //= require coffee_house_map //= require common_map //= require_tree ../templates //= require_tree . $(document).foundation(); $(".coffee-house__map").initCoffeeHouseMap(); <file_sep>const KAZAN_LATITUDE = 55.788258; const KAZAN_LONGITUDE = 49.119290; class CurrentCoordinates { constructor(coordinates = []) { this.latitude = coordinates[0] || KAZAN_LATITUDE; this.longitude = coordinates[1] || KAZAN_LONGITUDE; this.getCurrentPosition(); } getCurrentPosition() { if (navigator.geolocation) { const options = { maximumAge: 1000 }; navigator.geolocation.getCurrentPosition(position => { this.latitude = position.coords.latitude; this.longitude = position.coords.longitude; cookie.set('latitude', this.latitude, { path: "/" }); cookie.set('longitude', this.longitude, { path: "/" }); const event = new Event('position:update'); document.dispatchEvent(event); }, () => { cookie.remove('latitude'); cookie.remove('longitude'); }, options); } } } App.currentCoordinates = new CurrentCoordinates(App.currentCoordinatesData); <file_sep>brew "postgresql" brew "graphviz" <file_sep>require "rails_helper" describe Omniauth::ConfirmUser do describe ".call" do subject(:interactor_call) { described_class.call(user: user).user } let(:user) { create :user, :not_confirmed } it { is_expected.to be_confirmed } context "when user is confirmed" do let(:user) { create :user } it { is_expected.to be_confirmed } end end end <file_sep>require "rails_helper" describe Omniauth::PrepareAuthData do describe ".call" do subject(:interactor_call) { described_class.call(auth_params: auth_params) } let(:auth_data) { interactor_call.auth_data } context "when auth with facebook" do let(:auth_params) do OmniAuth::AuthHash.new( provider: "facebook", uid: "12345", info: { email: "<EMAIL>", name: "<NAME>" } ) end let(:expeted_auth_data) do { provider: "facebook", uid: "12345", email: "<EMAIL>", name: "<NAME>" } end it "prepares facebook auth params" do is_expected.to be_success expect(auth_data).to eq(expeted_auth_data) end context "when auth params are invalid" do let(:auth_params) do OmniAuth::AuthHash.new( provider: "facebook", uid: "12345", info: { email: "", name: "" } ) end it "can not prepare auth params" do is_expected.to be_failure expect(interactor_call.error).to eq("Can not create a user with the provided data") end end context "when auth params without required data" do let(:auth_params) do OmniAuth::AuthHash.new( provider: "facebook", uid: "12345" ) end it "can not prepare auth params" do is_expected.to be_failure expect(interactor_call.error).to eq("Can not create a user with the provided data") end end end context "when auth with google" do let(:auth_params) do OmniAuth::AuthHash.new( provider: "google_oauth2", uid: "12345", info: { email: "<EMAIL>", name: "<NAME>" } ) end let(:expeted_auth_data) do { provider: "google_oauth2", uid: "12345", email: "<EMAIL>", name: "<NAME>" } end it "prepares google auth params" do is_expected.to be_success expect(auth_data).to eq(expeted_auth_data) end context "when auth params are invalid" do let(:auth_params) do OmniAuth::AuthHash.new( provider: "google_oauth2", uid: "12345", info: { email: "", name: "" } ) end it "can not prepare auth params" do is_expected.to be_failure expect(interactor_call.error).to eq("Can not create a user with the provided data") end end context "when auth params without required data" do let(:auth_params) do OmniAuth::AuthHash.new( provider: "google_oauth2", uid: "12345" ) end it "can not prepare auth params" do is_expected.to be_failure expect(interactor_call.error).to eq("Can not create a user with the provided data") end end end end end <file_sep>class Omniauth::FindUser include Interactor delegate :auth_data, to: :context def call context.user = find_user_by_provider || find_user_by_email end private def find_user_by_provider @find_user_by_provider ||= Provider.find_by(name: auth_data[:provider], uid: auth_data[:uid])&.user end def find_user_by_email @find_user_by_email ||= User.find_by(email: auth_data[:email]) end end <file_sep>require "rails_helper" feature "Destroy Coffee" do include_context :user_signed_in let(:coffee_house) { create :coffee_house, name: "Coffee Like", owner: current_user } background do create :coffee, coffee_house: coffee_house, name: "Cappuccino", kind: "hot_coffee", volume: 300, price: 4, description: "Classic cappuccino" create :coffee, coffee_house: coffee_house, name: "Latte", kind: "hot_coffee", volume: 500, price: 4, description: "Classic latte" end scenario "User destroys coffee" do visit manage_coffee_house_path(coffee_house) expect(page).to have_content("Cappuccino") within("tr", text: "Cappuccino") do click_link "delete" end expect(page).to have_content("Coffee was successfully destroyed.") expect(page).to have_no_content("Cappuccino") end end <file_sep>class CoffeePolicy < ApplicationPolicy authorize :user, allow_nil: true def index? true end def show? true end end <file_sep>Dir[Rails.root.join("spec", "support", "helpers", "**", "*.rb")].each { |f| require f } RSpec.configure do |config| config.with_options(type: :feature) do |feature| feature.include MapHelpers end end <file_sep>class PagesController < ApplicationController expose_decorated :coffee_houses, :nearest_coffee_houses def index end private def nearest_coffee_houses NearestCoffeeHousesQuery.new(fetch_coffee_houses, current_location).all.limit(25) end def fetch_coffee_houses CoffeeHouse.all end def authorize_resource! authorize! CoffeeHouse end end <file_sep>RSpec::Matchers.define :have_table_row do |number:, values:| match do |page| row = page.find("tr:nth-child(#{number})") expect(row.all("td").map(&:text)).to eq(values) end end <file_sep>require "rails_helper" feature "Show Coffee" do let(:coffee_house) { create :coffee_house, name: "Coffee Like" } let(:coffee) do create :coffee, coffee_house: coffee_house, name: "Cappuccino", kind: "hot_coffee", volume: 300, price: 4, description: "Classic cappuccino" end scenario "Visitor sees coffee" do visit coffee_path(coffee) expect(page).to have_link("Coffee Like") expect(page).to have_content("Coffee House: Coffee Like") expect(page).to have_content("Type: Hot Coffee") expect(page).to have_content("Volume: 300 mL") expect(page).to have_content("Price: $4.00") expect(page).to have_content("Classic cappuccino") end end <file_sep>class Provider < ApplicationRecord NAMES = %w[ facebook google_oauth2 ].freeze belongs_to :user validates :name, presence: true, inclusion: { in: NAMES }, uniqueness: { scope: :user_id } validates :uid, presence: true, uniqueness: { scope: :name } end <file_sep>module Authorization extend ActiveSupport::Concern prepend ActionPolicyDraper included do before_action :authorize_resource!, unless: :devise_controller? verify_authorized unless: :devise_controller? end def authorize_resource! raise NotImplementedError end end <file_sep>class CreateProviders < ActiveRecord::Migration[5.1] def change create_table(:providers) do |t| t.string :name, null: false t.string :uid, null: false t.belongs_to :user, null: false, foreign_key: true, index: false, on_delete: :cascade end add_index :providers, %i[uid name], unique: true add_index :providers, %i[user_id name], unique: true end end <file_sep>class FilterCoffeeForm include ActiveModel::Model attr_accessor :kind, :volume_from, :volume_to, :price_from, :price_to validates :volume_from, numericality: { only_integer: true, allow_blank: true } validates :volume_to, numericality: { only_integer: true, allow_blank: true } validates :price_from, numericality: { allow_blank: true } validates :price_to, numericality: { allow_blank: true } end <file_sep>require "rails_helper" describe FilterCoffeesQuery do subject(:query) { described_class.new(relation, filter_params) } let!(:cappuccino) { create :coffee, kind: "hot_coffee", volume: 300, price: 4 } let!(:frappuccino) { create :coffee, kind: "cold_coffee", volume: 400, price: 5 } let!(:latte) { create :coffee, kind: "hot_coffee", volume: 500, price: 4 } let!(:mocco) { create :coffee, kind: "hot_coffee", volume: 500, price: 6 } let(:relation) { Coffee.order(created_at: :desc) } let(:filter_params) { nil } describe "#all" do subject(:all) { query.all } it { is_expected.to eq([mocco, latte, frappuccino, cappuccino]) } context "when filter by kind" do let(:filter_params) do { kind: "hot_coffee" } end it { is_expected.to eq([mocco, latte, cappuccino]) } end context "when filter by volume" do let(:filter_params) do { volume_from: 250, volume_to: 450 } end it { is_expected.to eq([frappuccino, cappuccino]) } end context "when filter by price" do let(:filter_params) do { price_from: 4.5, price_to: 10 } end it { is_expected.to eq([mocco, frappuccino]) } end context "when full filter" do let(:filter_params) do { kind: "hot_coffee", volume_from: 350, volume_to: 550, price_from: 4.5, price_to: 10 } end it { is_expected.to eq([mocco]) } end end end <file_sep>class CoffeeDecorator < ApplicationDecorator include ActionView::Helpers::NumberHelper delegate :id, :name, :kind, :volume, :price, :coffee_house_id delegate :name, to: :coffee_house, prefix: true decorates_association :coffee_house def humanized_kind I18n.t("activerecord.attributes.coffee.kinds.#{object.kind}") end def humanized_volume "#{object.volume} mL" end def humanized_price number_to_currency(object.price) end def description object.description&.html_safe end end <file_sep>require "rails_helper" require "geocoder/results/ipinfo_io" describe CoffeeHousesQuery do subject(:query) { described_class.new(location, keywords) } let(:location) { instance_double(Geocoder::Result::IpinfoIo, coordinates: coordinates) } let(:coordinates) { [beanhearts.latitude, beanhearts.longitude] } let(:keywords) { "" } let!(:coffee_like) do create :coffee_house, :kazan_butlerova, name: "Coffee Like", description: "Сoffee to go" end let!(:beanhearts) do create :coffee_house, :kazan_profsoyuznaya, name: "Beanhearts", description: "The best place to spend an evening with friends" end let!(:cappuccino) do create :coffee, name: "Cappuccino", coffee_house: coffee_like, description: "Composition of coffee: espresso, milk" end let!(:cappuccino) do create :coffee, name: "Cappuccino", coffee_house: beanhearts, description: "Composition of coffee: espresso, soy milk" end let!(:latte) do create :coffee, name: "Latte", coffee_house: coffee_like, description: "Composition of coffee: espresso, milk, cream" end describe "#all" do subject(:all) { query.all } it { is_expected.to eq([beanhearts, coffee_like]) } context "when search with keywords" do context "when search by coffee house name" do let(:keywords) { "beanhearts" } it { is_expected.to eq([beanhearts]) } end context "when search by coffee house description" do let(:keywords) { "coffee to go" } it { is_expected.to eq([coffee_like]) } end context "when search by coffee name" do let(:keywords) { "latte" } it { is_expected.to eq([coffee_like]) } end context "when search by coffee description" do let(:keywords) { "soy milk" } it { is_expected.to eq([beanhearts]) } end end end end <file_sep>class Omniauth::ConfirmUser include Interactor delegate :user, to: :context def call user.confirm unless user.confirmed? end end <file_sep>class Omniauth::ConnectProvider include Interactor delegate :user, :auth_data, to: :context def call context.provider = connect_provider end private def connect_provider user.providers.find_or_create_by(provider_params) end def provider_params { name: auth_data[:provider], uid: auth_data[:uid] } end end <file_sep>class CoffeeHousesController < ApplicationController expose_decorated :coffee_houses, :fetch_coffee_houses expose_decorated :coffee_house expose_decorated :coffees, :fetch_coffees def index end def show end private def fetch_coffee_houses CoffeeHousesQuery.new(current_location, keywords).all.page(page) end def fetch_coffees coffee_house.coffees.order(created_at: :desc) end def page params[:page] end def keywords params.dig(:query, :keywords) end def authorize_resource! authorize! coffee_house end end <file_sep>require "rails_helper" describe Omniauth::ConnectProvider do describe ".call" do subject(:interactor_call) { described_class.call(user: user, auth_data: auth_data) } let(:user) { create :user, email: "<EMAIL>", full_name: "<NAME>" } let(:auth_data) do { provider: "facebook", uid: "12345", email: "<EMAIL>", name: "<NAME>" } end let(:connected_provider) { interactor_call.provider } it { expect { interactor_call }.to change(Provider, :count).by(1) } it "connects new provider for user" do expect(connected_provider).to be_persisted expect(connected_provider.name).to eq("facebook") expect(connected_provider.uid).to eq("12345") end context "when user with this provider already exists" do let!(:existed_provider) { create :facebook_provider, uid: "12345", user: user } it { expect { interactor_call }.not_to change(Provider, :count) } it "finds provider" do expect(connected_provider).to be_persisted expect(connected_provider.name).to eq("facebook") expect(connected_provider.uid).to eq("12345") end end end end <file_sep>require "rails_helper" feature "Create Coffee House" do include_context :user_signed_in scenario "User creates coffee house" do visit new_manage_coffee_house_path fill_in "Name", with: "<NAME>" choose_location_on_map(model_name: "coffee_house", latitude: 55.78787607694294, longitude: 49.12356007675169) fill_in "Description", with: "We give very HOT COFFEE" click_button "Create" expect(page).to have_content("Coffee house was successfully created.") end scenario "User creates coffee house with invalid data" do visit new_manage_coffee_house_path click_button "Create" expect(page).to have_content("Coffee house could not be created.") end end <file_sep>class CoffeesController < ApplicationController expose_decorated :coffees, :filtered_coffees expose_decorated :coffee expose :filter_coffee_form, -> { FilterCoffeeForm.new(filter_coffee_form_params) } def index coffees end def show end private def filtered_coffees FilterCoffeesQuery.new(fetch_coffees, filter_params).all.page(page) end def fetch_coffees Coffee.order(created_at: :desc) end def filter_params filter_coffee_form.valid? ? filter_coffee_form_params.to_h : {} end def filter_coffee_form_params params.permit(filter_coffee_form: %i[kind volume_from volume_to price_from price_to]).dig(:filter_coffee_form) end def page params[:page] end def authorize_resource! authorize! coffee end end <file_sep>class Manage::CoffeeHousesController < Manage::BaseController expose_decorated :coffee_houses, :fetch_coffee_houses expose_decorated :coffee_house, parent: :current_user expose_decorated :coffees, from: :coffee_house def index end def new end def create coffee_house.save respond_with(:manage, coffee_house) end def show end def edit end def update coffee_house.update(coffee_house_params) respond_with(:manage, coffee_house) end def destroy coffee_house.destroy respond_with(:manage, coffee_house) end private def coffee_house_params params.require(:coffee_house).permit(:name, :latitude, :longitude, :description) end def fetch_coffee_houses current_user.coffee_houses.order(created_at: :desc) end def authorize_resource! authorize! coffee_house end end <file_sep>class ApplicationPolicy < ActionPolicy::Base alias_rule :new?, to: :create? alias_rule :edit?, to: :update? end <file_sep>require "rails_helper" describe Omniauth::CreateUser do describe ".call" do subject(:interactor_call) { described_class.call(user: user, auth_data: auth_data) } let(:user) { nil } let(:auth_data) do { provider: "facebook", uid: "12345", email: "<EMAIL>", name: "<NAME>" } end let(:created_user) { interactor_call.user } it { is_expected.to be_success } it "creates new user" do expect(created_user).to be_persisted expect(created_user.email).to eq("<EMAIL>") expect(created_user.full_name).to eq("<NAME>") expect(created_user).to be_confirmed end context "when user already exists" do let!(:user) { create :user, email: "<EMAIL>" } it { is_expected.to be_success } it "does not create new user" do expect { interactor_call }.not_to change(User, :count) expect(created_user).to be_present end end context "when auth data is invalid" do let(:auth_data) do { provider: "facebook", uid: "12345", name: "<NAME>" } end it { is_expected.to be_failure } it "does not create new user" do expect(interactor_call.error).to eq("Can not create a user with the provided data") expect { interactor_call }.not_to change(User, :count) expect(created_user).to be_new_record end end end end <file_sep>module Users class OmniauthCallbacksController < Devise::OmniauthCallbacksController def facebook authenticate_with("Facebook") end def google_oauth2 authenticate_with("Google") end private def authenticate_with(kind) if authenticate_user.success? sign_in_and_redirect authenticate_user.user, event: :authentication set_flash_message(:notice, :success, kind: kind) else redirect_to(new_user_registration_path, alert: authenticate_user.error) end end def authenticate_user @authenticate_user ||= Omniauth::AuthenticateUser.call(auth_params: auth_params) end def auth_params request.env["omniauth.auth"] end end end <file_sep>require "rails_helper" feature "Index Coffee" do include_context :user_signed_in let(:coffee_house) { create :coffee_house, name: "Coffee Like", owner: current_user } background do create :coffee, coffee_house: coffee_house, name: "Cappuccino", kind: "hot_coffee", volume: 300, price: 4, description: "Classic cappuccino" create :coffee, coffee_house: coffee_house, name: "Latte", kind: "hot_coffee", volume: 500, price: 4, description: "Classic latte" end scenario "User sees list of coffee" do visit manage_coffee_house_path(coffee_house) within "tbody" do expect(page).to have_selector("tr", count: 2) expect(page).to have_table_row( number: 1, values: ["Cappuccino", "Hot Coffee", "300 mL", "$4.00", "edit", "delete"] ) expect(page).to have_table_row( number: 2, values: ["Latte", "Hot Coffee", "500 mL", "$4.00", "edit", "delete"] ) end end end <file_sep>require "rails_helper" feature "Update Coffee House" do include_context :user_signed_in let(:coffee_house) { create :coffee_house, owner: current_user } scenario "User updates coffee house" do visit edit_manage_coffee_house_path(coffee_house) fill_in "Name", with: "<NAME>" choose_location_on_map(model_name: "coffee_house", latitude: 55.78778545536969, longitude: 49.122609570622444) fill_in "Description", with: "We give very HOT COFFEE" click_button "Update" expect(page).to have_content("Coffee house was successfully updated.") end scenario "User updates coffee house with invalid data" do visit edit_manage_coffee_house_path(coffee_house) fill_in "Name", with: "" click_button "Update" expect(page).to have_content("Coffee house could not be updated.") end end <file_sep>class Omniauth::CreateUser include Interactor delegate :auth_data, to: :context delegate :user, to: :context, allow_nil: true def call return if user context.user = create_user context.fail!(error: I18n.t("interactors.error.invalid_auth_data")) if user.invalid? end private def create_user @create_user ||= User.create(user_params) end def user_params { email: auth_data[:email], password: <PASSWORD>], full_name: auth_data[:name], confirmed_at: Time.current } end end <file_sep>require "rails_helper" feature "Sign In" do let(:user) { create :user } let(:unconfirmed_user) { create :user, :not_confirmed } scenario "Visitor signs in with valid credentials" do visit new_user_session_path fill_form(:user, email: user.email, password: <PASSWORD>) click_button "Sign in" expect(page).to have_content("Signed in successfully.") end scenario "Visitor signs in with invalid credentials" do visit new_user_session_path fill_form(:user, email: user.email, password: "<PASSWORD>") click_button "Sign in" expect(page).to have_content("Sign in") expect(page).to have_content("Invalid Email or password") end scenario "Visitor signs in with unconfirmed email address" do visit new_user_session_path fill_form(:user, email: unconfirmed_user.email, password: <PASSWORD>) click_button "Sign in" expect(page).to have_content("You have to confirm your email address before continuing.") end context "when visitor has facebook account" do include_context :facebook_with_valid_credentials scenario "Visitor signs in with facebook" do visit new_user_session_path click_link "Sign in with Facebook" expect(page).to have_content("Successfully authenticated from Facebook account.") end context "when credentials is invalid" do include_context :facebook_with_invalid_credentials scenario "Visitor cannot signs in with facebook" do visit new_user_session_path click_link "Sign in with Facebook" expect(page).to have_content("Could not authenticate you from Facebook because \"Invalid credentials\".") end end end context "when visitor has google account" do include_context :google_with_valid_credentials scenario "Visitor signs in with google" do visit new_user_session_path click_link "Sign in with Google Oauth2" expect(page).to have_content("Successfully authenticated from Google account.") end context "when credentials are invalid" do include_context :google_with_invalid_credentials scenario "Visitor cannot signs in with google" do visit new_user_session_path click_link "Sign in with Google Oauth2" expect(page).to have_content("Could not authenticate you from GoogleOauth2 because \"Invalid credentials\".") end end end end <file_sep>class Omniauth::AuthenticateUser include Interactor::Organizer organize Omniauth::PrepareAuthData, Omniauth::FindUser, Omniauth::CreateUser, Omniauth::ConfirmUser, Omniauth::ConnectProvider end <file_sep>const LATITUDE_INPUT_SELECTOR = "#coffee_house_latitude"; const LONGITUDE_INPUT_SELECTOR = "#coffee_house_longitude"; class LocationInput { constructor($locationInput) { this.locationInput = $locationInput; this.latitudeInput = $(LATITUDE_INPUT_SELECTOR); this.longitudeInput = $(LONGITUDE_INPUT_SELECTOR); this.setupMap(); } setupMap() { this.map = new google.maps.Map(this.locationInput, this.mapOptions()); this.map.addListener("click", event => { this.latitudeInput.val(event.latLng.lat); this.longitudeInput.val(event.latLng.lng); if (this.marker) { this.marker.setPosition(event.latLng); } else { this.marker = new (google.maps.Marker)({ position: event.latLng, map: this.map }); } }); this.addCurrentMarker(); } mapOptions() { return { zoom: 15, center: this.centerLatLng(), }; } addCurrentMarker() { if (this.isNewForm()) { return; } return this.marker = new (google.maps.Marker)({ position: new google.maps.LatLng(this.latitudeInput.val(), this.longitudeInput.val()), map: this.map }); } centerLatLng() { const isNewForm = this.isNewForm(); const latitude = isNewForm ? App.currentCoordinates.latitude : this.latitudeInput.val(); const longitude = isNewForm ? App.currentCoordinates.longitude : this.longitudeInput.val(); return new google.maps.LatLng(latitude, longitude); } isNewForm() { return (this.latitudeInput.val().length === 0) && (this.longitudeInput.val().length === 0); } } const LOCATION_INPUT_SELECTOR = "location-input"; const $locationInputs = document.getElementsByClassName(LOCATION_INPUT_SELECTOR); [...$locationInputs].forEach(($locationInput) => { new LocationInput($locationInput); }); <file_sep>require "rails_helper" feature "Update Coffee" do include_context :user_signed_in let(:coffee_house) { create :coffee_house, name: "Coffee Like", owner: current_user } let(:coffee) { create :coffee, coffee_house: coffee_house } scenario "User updates coffee" do visit edit_manage_coffee_house_coffee_path(coffee_house, coffee) fill_in "Name", with: "Cappuccino" select "Hot Coffee", from: "Type" fill_in "Volume", with: "300" fill_in "Price", with: "4" fill_in "Description", with: "Classic cappuccino" click_button "Update" expect(page).to have_content("Coffee was successfully updated.") end scenario "User updates coffee with invalid data" do visit edit_manage_coffee_house_coffee_path(coffee_house, coffee) fill_in "Name", with: "" click_button "Update" expect(page).to have_content("Coffee could not be updated.") end end <file_sep>require "selenium/webdriver" Capybara.register_driver :headless_chrome do |app| options = Selenium::WebDriver::Chrome::Options.new(args: %w[disable-gpu headless window-size=1440,1280]) Capybara::Selenium::Driver.new(app, browser: :chrome, options: options) end Capybara.register_driver :chrome do |app| options = Selenium::WebDriver::Chrome::Options.new(args: %w[disable-gpu]) Capybara::Selenium::Driver.new(app, browser: :chrome, options: options) end Capybara.configure do |config| config.match = :prefer_exact config.javascript_driver = :headless_chrome config.default_max_wait_time = 5 config.asset_host = "http://#{ENV.fetch('HOST')}" end <file_sep># frozen_string_literal: true # Uncomment this and change the path if necessary to include your own # components. # See https://github.com/plataformatec/simple_form#custom-components to know # more about custom components. # Dir[Rails.root.join('lib/components/**/*.rb')].each { |f| require f } # # Use this setup block to configure all options available in SimpleForm. SimpleForm.setup do |config| config.wrappers :vertical_form do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :minlength b.optional :pattern b.optional :min_max b.optional :readonly b.use :label, error_class: "is-invalid-label" b.use :input, error_class: "is-invalid-input" b.use :error, wrap_with: { tag: :small, class: "form-error is-visible" } b.use :hint, wrap_with: { tag: :p, class: "help-text" } end config.wrappers :horizontal_form, class: "grid-x grid-padding-x" do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :minlength b.optional :pattern b.optional :min_max b.optional :readonly b.wrapper :label_wrapper, class: "small-3 cell" do |ba| ba.use :label, class: "text-right", error_class: "is-invalid-label" end b.wrapper :input_wrapper, class: "small-9 cell" do |ba| ba.use :input, error_class: "is-invalid-input" ba.use :error, wrap_with: { tag: :small, class: "form-error is-visible" } ba.use :hint, wrap_with: { tag: :p, class: "help-text" } end end config.wrappers :group_form do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :minlength b.optional :pattern b.optional :min_max b.optional :readonly b.wrapper :group, class: "input-group" do |ba| ba.use :label, class: "input-group-label", error_class: "is-invalid-label" ba.use :input, class: "input-group-field", error_class: "is-invalid-input" end b.use :error, wrap_with: { tag: :small, class: "form-error is-visible" } b.use :hint, wrap_with: { tag: :p, class: "help-text" } end # CSS class for buttons config.button_class = "button" # You can wrap each item in a collection of radio/check boxes with a tag, # defaulting to :span. config.item_wrapper_tag = nil # CSS class to add for error notification helper. config.error_notification_class = "alert-box alert" # The default wrapper to be used by the FormBuilder. config.default_wrapper = :vertical_form # You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none. config.collection_wrapper_tag = :fieldset end <file_sep>Rails.application.routes.draw do devise_for :users, controllers: { registrations: "users/registrations", omniauth_callbacks: "users/omniauth_callbacks" } root to: "pages#index" resources :coffee_houses, only: %i[index show] resources :coffees, only: %i[index show] namespace :manage do resources :coffee_houses do resources :coffees, only: %i[new create show edit update destroy] end end end <file_sep>require "rails_helper" feature "Index Coffee" do background do create :coffee, name: "Cappuccino", kind: "hot_coffee", volume: 300, price: 4 create :coffee, name: "Frappuccino", kind: "cold_coffee", volume: 400, price: 5 create :coffee, name: "Latte", kind: "hot_coffee", volume: 500, price: 4 create :coffee, name: "Mocco", kind: "hot_coffee", volume: 500, price: 6 end scenario "Visitor sees list of coffee" do visit coffees_path within "tbody" do expect(page).to have_selector("tr", count: 4) expect(page).to have_table_row(number: 1, values: ["Mocco", "Hot Coffee", "500 mL", "$6.00"]) expect(page).to have_table_row(number: 2, values: ["Latte", "Hot Coffee", "500 mL", "$4.00"]) expect(page).to have_table_row(number: 3, values: ["Frappuccino", "Cold Coffee", "400 mL", "$5.00"]) expect(page).to have_table_row(number: 4, values: ["Cappuccino", "Hot Coffee", "300 mL", "$4.00"]) end end scenario "Visitor filter coffee" do visit coffees_path select "Hot Coffee", from: "Type" fill_in "Volume from", with: "300" fill_in "Volume to", with: "600" fill_in "Price from", with: "4" fill_in "Price to", with: "5" click_button "Search" within "tbody" do expect(page).to have_selector("tr", count: 2) expect(page).to have_table_row(number: 1, values: ["Latte", "Hot Coffee", "500 mL", "$4.00"]) expect(page).to have_table_row(number: 2, values: ["Cappuccino", "Hot Coffee", "300 mL", "$4.00"]) end end end <file_sep>class CoffeeHouseDecorator < ApplicationDecorator delegate :id, :name, :latitude, :longitude, :address delegate :full_name, to: :owner, prefix: true decorates_association :owner decorates_association :coffees def description object.description&.html_safe end end <file_sep>require "rails_helper" feature "Create Coffee" do include_context :user_signed_in let(:coffee_house) { create :coffee_house, name: "Coffee Like", owner: current_user } scenario "User creates coffee" do visit new_manage_coffee_house_coffee_path(coffee_house) fill_in "Name", with: "Cappuccino" select "Hot Coffee", from: "Type" fill_in "Volume", with: "300" fill_in "Price", with: "4" fill_in "Description", with: "Classic cappuccino" click_button "Create" expect(page).to have_content("Coffee was successfully created.") end scenario "User creates coffee with invalid data" do visit new_manage_coffee_house_coffee_path(coffee_house) click_button "Create" expect(page).to have_content("Coffee could not be created.") end end <file_sep>FactoryGirl.define do factory :coffee do name Faker::Coffee.blend_name kind "hot_coffee" volume 500 price 200 description Faker::Coffee.notes association :coffee_house end end <file_sep>class FilterCoffeesQuery ALLOWED_PARAMS = %i[kind volume_from volume_to price_from price_to].freeze attr_reader :relation, :filter_params private :relation, :filter_params def initialize(relation, filter_params = {}) @relation = relation @filter_params = filter_params end def all return relation unless filter_params filter_params.slice(*ALLOWED_PARAMS).reduce(relation) do |relation, (key, value)| value.blank? ? relation : send("by_#{key}", relation, value) end end private def by_kind(relation, kind) relation.where(kind: kind) end def by_volume_from(relation, volume_from) relation.where("volume >= ?", volume_from) end def by_volume_to(relation, volume_to) relation.where("volume <= ?", volume_to) end def by_price_from(relation, price_from) relation.where("price >= ?", price_from) end def by_price_to(relation, price_to) relation.where("price <= ?", price_to) end end
9d384ded3c1fb4d43c16e5fab2a1c4803b3d6da8
[ "JavaScript", "Ruby" ]
67
Ruby
Ryazapov/hot-coffee
42ecccf1a81176bd436ab1d060cd9ac6030067f6
743a448f917f706116741d24029b0186c3bb8653
refs/heads/master
<file_sep>package game.controllers.examples; import game.controllers.HeroController; import game.system._Game; import game.models.Game; import java.util.List; public final class RandomNonRevHero implements HeroController { private int action; public int getAction() { return action; } public void init() { } public void shutdown() { } public void update(Game game,long timeDue) { List<Integer> directions = game.getHero().getPossibleDirs(false); //set flag as false to prevent reversals action = directions.get(Game.rng.nextInt(directions.size())); } }<file_sep>package game.system; import game.models.Node; import game.models.Enemy; import java.util.List; public class _Enemy extends _Actor implements Enemy { public int getEdibleTime() { return edibleTime; } public int getLairTime() { return lairTime; } public boolean isEdible() { return edibleTime > 0; } public List<Integer> getPossibleDirs() { return getPossibleDirs(false); } public int getNextDir(Node to, boolean approach) { return location.getNextDir(to, approach, false, direction); } public List<Node> getPath(Node to) { return getPath(to, false); } public List<Node> getPossibleLocations() { return getPossibleLocations(false); } public Node getTarget(List<Node> targets, boolean nearest) { return getTarget(targets, nearest, false); } public boolean requiresAction() { return (location.isJunction() && edibleTime == 0 || edibleTime % _Game.ENEMY_SPEED_REDUCTION != 0); } protected int edibleTime, lairTime; protected _Enemy(Node location, int direction, int _lairTime) { super(location, direction); edibleTime = 0; lairTime = _lairTime; } protected _Enemy clone() { return (_Enemy)super.clone(); } } <file_sep>package game.models; import game.system._Node; public interface Actor extends Cloneable { public Node getLocation(); public int getDirection(); } <file_sep>package game.controllers; import game.models.Game; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; /* * Allows a human player to play the game using the arrow key of the keyboard. */ public final class Human extends KeyAdapter implements HeroController { private int key; private int action; public void init() { } public void update(Game game,long dueTime) { if (key == KeyEvent.VK_UP) action = 0; else if (key == KeyEvent.VK_RIGHT) action = 1; else if (key == KeyEvent.VK_DOWN) action = 2; else if (key == KeyEvent.VK_LEFT) action = 3; } public void shutdown() { } public int getAction() { return action; } public void keyPressed(KeyEvent e) { key=e.getKeyCode(); } }<file_sep>package game.controllers.examples; import java.awt.Color; import java.util.ArrayList; import java.util.List; import game.controllers.HeroController; import game.models.Game; import game.view.GameView; import game.models.Node; import game.models.Enemy; import game.models.Hero; /* * Same as NearestPillHero but does some visuals to illustrate what can be done. * Please note: the visuals are just to highlight different functionalities and may * not make sense from a controller's point of view (i.e., they might not be useful) * Comment/un-comment code below as desired (drawing all visuals would probably be too much). */ public final class NearestPillHeroVS implements HeroController { private int action; public int getAction() { return action; } public void init() { } public void shutdown() { } public void update(Game game,long timeDue) { List<Node> pills = game.getCurMaze().getPillNodes(); List<Node> powerPills = game.getCurMaze().getPowerPillNodes(); Hero hero = game.getHero(); ArrayList<Node> targets = new ArrayList<Node>(); for (Node pill : pills) if(game.checkPill(pill)) targets.add(pill); for(Node pill : powerPills) if(game.checkPowerPill(pill)) targets.add(pill); Node nearest = hero.getTarget(targets,true); //add the path that Ms Pac-Man is following // GameView.addPoints(game,Color.GREEN,game.getPath(current,nearest)); //add the path from Ms Pac-Man to the first power pill GameView.addPoints(game, Color.CYAN, hero.getPath(powerPills.get(0))); //add the path AND ghost path from Ghost 0 to the first power pill (to illustrate the differences) // if(game.getLairTime(0)==0) // { // GameView.addPoints(game,Color.ORANGE,game.getPath(game.getCurEnemyLoc(0),powerPills[0])); // GameView.addPoints(game,Color.YELLOW,game.getEnemyPath(0,powerPills[0])); // } //add the path from Ghost 0 to the closest power pill // if(game.getLairTime(0)==0) // GameView.addPoints(game,Color.WHITE,game.getEnemyPath(0,game.getEnemyTarget(0,powerPills,true))); //add lines connecting Ms Pac-Man and the power pills // for(int i=0;i<powerPills.length;i++) // GameView.addLines(game,Color.CYAN,current,powerPills[i]); //add lines to the ghosts (if not in lair) - green if edible, red otherwise for(int i = 0; i< Game.NUM_ENEMY; i++) { Enemy enemy = game.getEnemy(i); if(enemy.getLairTime() == 0) if(enemy.isEdible()) GameView.addLines(game, Color.GREEN, hero.getLocation(), enemy.getLocation()); else GameView.addLines(game, Color.RED, hero.getLocation(), enemy.getLocation()); } action = game.getHero().getNextDir(nearest, true); } }<file_sep>/* * * Code written by <NAME>, based on earlier implementations of the game by * <NAME> and <NAME>. * * Code refactored and updated by <NAME> at the University of Florida (2017). * * You may use and distribute this code freely for non-commercial purposes. This notice * needs to be included in all distributions. Deviations from the original should be * clearly documented. We welcome any comments and suggestions regarding the code. */ package game.system; import game.models.*; import java.util.Random; import java.util.HashSet; import java.util.List; import java.util.ArrayList; /* * Simple implementation of the game. The class Game contains all code relating to the * game; the class GameView displays the game. Controllers must implement HeroController * and EnemyController respectively. The game may be executed using Exec. */ public class _Game implements Game { //File names for data public static String[] nodeNames = {"a","b","c","d"}; public static String[] distNames = {"da","db","dc","dd"}; public static String pathMazes = "data"; //Static stuff (mazes are immutable - hence static) protected static _Maze[] mazes = new _Maze[NUM_MAZES]; //Variables (game state): HashSet<Node> pills, powerPills; // protected BitSet pills,powerPills; //level-specific protected int curMaze,totLevel,levelTime,totalTime,score, enemyEatMultiplier; protected boolean gameOver; // Actors protected _Hero hero; protected _Enemy[] enemies; protected int livesRemaining; protected boolean extraLife; ///////////////////////////////////////////////////////////////////////////// ///////////////// Constructors and Initializers ////////////////////////// ///////////////////////////////////////////////////////////////////////////// //Constructor protected _Game(){} //loads the mazes and store them protected void init() { for(int i=0;i<mazes.length;i++) if(mazes[i]==null) mazes[i]=new _Maze(i); } //Creates an exact copy of the game public Game copy() { _Game copy=new _Game(); copy.pills= (HashSet<Node>) pills.clone(); copy.powerPills = (HashSet<Node>) powerPills.clone(); copy.curMaze=curMaze; copy.totLevel=totLevel; copy.levelTime=levelTime; copy.totalTime=totalTime; copy.score=score; copy.enemyEatMultiplier = enemyEatMultiplier; copy.gameOver=gameOver; copy.hero = hero.clone(); copy.livesRemaining=livesRemaining; copy.extraLife=extraLife; copy.enemies = new _Enemy[enemies.length]; for (int index = 0; index < enemies.length; index++) copy.enemies[index] = enemies[index].clone(); return copy; } //If the hero has been eaten or a new level has been reached protected void reset(boolean newLevel) { if(newLevel) { curMaze=(curMaze+1)% _Game.NUM_MAZES; totLevel++; levelTime=0; pills.addAll(mazes[curMaze].getPillNodes()); powerPills.addAll(mazes[curMaze].getPowerPillNodes()); } hero = new _Hero(mazes[curMaze].getInitialHeroPosition(), _Game.INITIAL_HERO_DIR); for (int index = 0; index < enemies.length; index++) { enemies[index] = new _Enemy(mazes[curMaze].lairPosition, _Game.INITIAL_ENEMY_DIRS[index], (int)(_Game.LAIR_TIMES[index]*(Math.pow(LAIR_REDUCTION,totLevel)))); } enemyEatMultiplier = 1; } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////// Game Play ////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// //Central method that advances the game state public int[] advanceGame(int heroDir, int[] enemyDirs) { updateHero(heroDir); //move the hero eatPill(); //eat a pill boolean reverse=eatPowerPill(); //eat a power pill updateEnemies(enemyDirs,reverse); //move enemies //This is primarily done for the replays as reset (as possibly called by feast()) sets the //last directions to the initial ones, not the ones taken int[] actionsTakens = { hero.direction, enemies[0].direction, enemies[1].direction, enemies[2].direction, enemies[3].direction }; feast(); //enemies eat the hero or vice versa for(int i = 0; i < enemies.length; i++) { if (enemies[i].lairTime > 0) { enemies[i].lairTime--; if (enemies[i].lairTime == 0) enemies[i].location = mazes[curMaze].initialEnemiesPosition; } } if(!extraLife && score>=EXTRA_LIFE_SCORE) //award 1 extra life at 10000 points { extraLife=true; livesRemaining++; } totalTime++; levelTime++; checkLevelState(); //check if level/game is over return actionsTakens; } public Hero getHero() { return hero.clone(); } public Enemy getEnemy(int whichEnemy) { return enemies[whichEnemy].clone(); } public List<Enemy> getEnemies() { ArrayList<Enemy> result = new ArrayList<Enemy>(); for (_Enemy enemy : enemies) result.add(enemy.clone()); return result; } //Updates the location of the hero protected void updateHero(int direction) { direction = checkHeroDir(direction); hero.direction = direction; hero.location = hero.location.getNeighbor(direction); } //Checks the direction supplied by the controller and substitutes for a legal one if necessary protected int checkHeroDir(int direction) { List<Node> neighbors = hero.location.getNeighbors(); int oldDirection = hero.direction; if((direction > 3 || direction < 0 || neighbors.get(direction) == null) && (oldDirection > 3 || oldDirection < 0 || neighbors.get(oldDirection) == null)) return 4; if(direction < 0 || direction > 3) direction = oldDirection; if(neighbors.get(direction) == null) if(neighbors.get(oldDirection) != null) direction = oldDirection; else { List<Integer> options = hero.getPossibleDirs(true); direction = options.get(Game.rng.nextInt(options.size())); } return direction; } //Updates the locations of the enemies protected void updateEnemies(int[] directions, boolean reverse) { // if(directions==null) // directions=Arrays.copyOf(lastEnemyDirs, lastEnemyDirs.length); for(int i = 0; i < enemies.length; i++) { if(reverse && enemies[i].lairTime == 0) { enemies[i].direction = Node.getReverse(enemies[i].direction); enemies[i].location = enemies[i].location.getNeighbor(enemies[i].direction); } else if(enemies[i].lairTime == 0 && (enemies[i].edibleTime == 0 || enemies[i].edibleTime % ENEMY_SPEED_REDUCTION !=0)) { directions[i] = checkEnemyDir(i, directions[i]); enemies[i].direction = directions[i]; enemies[i].location = enemies[i].location.getNeighbor(directions[i]); } } } //Checks the directions supplied by the controller and substitutes for a legal ones if necessary protected int checkEnemyDir(int whichEnemy, int direction) { if(direction < 0 || direction > 3) direction = enemies[whichEnemy].direction; List<Node> neighbors = enemies[whichEnemy].getPossibleLocations(); if(neighbors.get(direction) == null) { if(neighbors.get(enemies[whichEnemy].direction) != null) direction = enemies[whichEnemy].direction; else { List<Integer> options = enemies[whichEnemy].getPossibleDirs(); direction = options.get(Game.rng.nextInt(options.size())); } } return direction; } //Eats a pill protected void eatPill() { if (pills.contains(hero.location)) { score += Game.PILL_SCORE; pills.remove(hero.location); } } //Eats a power pill - turns enemies edible (blue) protected boolean eatPowerPill() { boolean reverse = false; if(powerPills.contains(hero.location)) { score += Game.POWER_PILL_SCORE; enemyEatMultiplier =1; powerPills.remove(hero.location); //This ensures that only enemies outside the lair (i.e., inside the maze) turn edible int newEdibleTime=(int)(Game.EDIBLE_TIME * (Math.pow(Game.EDIBLE_TIME_REDUCTION, totLevel))); for(int i = 0; i< NUM_ENEMY; i++) if(enemies[i].lairTime == 0) enemies[i].edibleTime = newEdibleTime; else enemies[i].edibleTime = 0; //This turns all enemies edible, independent on whether they are in the lair or not // Arrays.fill(edibleTimes,(int)(_Game.EDIBLE_TIME*(Math.pow(_Game.EDIBLE_TIME_REDUCTION,totLevel)))); reverse = true; } else if (levelTime > 1 && Game.rng.nextDouble() < Game.ENEMY_REVERSAL) //random enemy reversal reverse=true; return reverse; } //This is where the characters of the game eat one another if possible protected void feast() { for(int i = 0; i < enemies.length; i++) { int distance=hero.location.getPathDistance(enemies[i].location); if(distance <= Game.EAT_DISTANCE && distance != -1) { if(enemies[i].edibleTime > 0) //hero eats enemy { score+= Game.ENEMY_EAT_SCORE * enemyEatMultiplier; enemyEatMultiplier *=2; enemies[i].edibleTime = 0; enemies[i].lairTime = (int)(Game.COMMON_LAIR_TIME*(Math.pow(Game.LAIR_REDUCTION,totLevel))); enemies[i].location = mazes[curMaze].lairPosition; enemies[i].direction = Game.INITIAL_ENEMY_DIRS[i]; } else //enemy eats hero { livesRemaining--; if(livesRemaining<=0) { gameOver=true; return; } else reset(false); } } } for(int i = 0; i < enemies.length;i++) if(enemies[i].edibleTime > 0) enemies[i].edibleTime--; } //Checks the state of the level/game and advances to the next level or terminates the game protected void checkLevelState() { //if all pills have been eaten or the time is up... if((pills.isEmpty() && powerPills.isEmpty()) || levelTime>=LEVEL_LIMIT) { //award any remaining pills to the hero score+= _Game.PILL_SCORE * pills.size() + Game.POWER_PILL_SCORE * powerPills.size(); //put a cap on the total number of levels played if(totLevel+1== _Game.MAX_LEVELS) { gameOver=true; return; } else reset(true); } } ///////////////////////////////////////////////////////////////////////////// /////////////////////////// Getter Methods //////////////////////////////// ///////////////////////////////////////////////////////////////////////////// //Whether the game is over or not public boolean gameOver() { return gameOver; } //Whether the pill specified is still there public boolean checkPill(Node location) { return pills.contains(location); } //Whether the power pill specified is still there public boolean checkPowerPill(Node location) { return powerPills.contains(location); } public List<Node> getPillList() { return new ArrayList<Node>(pills); } public List<Node> getPowerPillList() { return new ArrayList<Node>(powerPills); } //The current level public int getCurLevel() { return totLevel; } //The current maze # (1-4) public int getCurMazeNum() { return curMaze; } //The current maze object public Maze getCurMaze() { return mazes[curMaze]; } //Lives that remain for the hero public int getLivesRemaining() { return livesRemaining; } //Returns the score of the game public int getScore() { return score; } //Returns the time of the current level (important with respect to LEVEL_LIMIT) public int getLevelTime() { return levelTime; } //Total time the game has been played for (at most LEVEL_LIMIT*MAX_LEVELS) public int getTotalTime() { return totalTime; } //Returns the pill index of the node. If it is -1, the node has no pill. Otherwise one can //use the bitset to check whether the pill has already been eaten // public int getPillIndex(Node node) // { // return node.getPillIndex(); // } //Returns the power pill index of the node. If it is -1, the node has no pill. Otherwise one //can use the bitset to check whether the pill has already been eaten // public int getPowerPillIndex(Node node) // { // return node.getPowerPillIndex(); // } }<file_sep>/* * Generalized maze game version adapted and object-oriented model written by * <NAME> at the University of Florida (2017). * * Generalized update based on "Ms Pac-Man versus Ghost Team Competition" by * <NAME>, <NAME> and <NAME> of the University of Essex. * Original code written by <NAME>, based on earlier implementations of * the game by <NAME> and <NAME>. * * You may use and distribute this code freely for non-commercial purposes. This notice * needs to be included in all distributions. Deviations from the original should be * clearly documented. We welcome any comments and suggestions regarding the code. */ package game.models; import java.util.Random; import java.util.List; /* * This interface defines the contract between the game engine and the controllers. It provides all * the methods a controller may use to (a) query the game state, (b) compute game-related attributes * and (c) test moves by using a forward model (i.e., copy() followed by advanceGame()). */ public interface Game { public int getScore(); // Returns the score of the game public int getCurLevel(); // Returns the current level public int getLevelTime(); // Returns the time for which the CURRENT level has been played public int getTotalTime(); // Returns the time for which the game has been played (across all levels) public int getLivesRemaining(); // Returns the number of lives remaining for the hero public List<Node> getPillList(); // Get a list of all available pills in the current level public List<Node> getPowerPillList(); // Get a list of all available power pills in the current level public boolean checkPill(Node location); // Checks if the location specified is a pill / is still available public boolean checkPowerPill(Node location); // Checks if the location specified is a power pill / is still available public Hero getHero(); // Returns a copy of the hero object public Enemy getEnemy(int whichEnemy); // Returns a copy of a specific enemy number public List<Enemy> getEnemies(); // Returns a copy of the enemy array public Game copy(); // Returns an exact copy of the game (forward model) public Maze getCurMaze(); // Returns the current maze information public static Random rng = new Random(0); // Random number generator with fixed seed public int[] advanceGame(int heroDir, int[] enemyDirs); // Advances the game using the actions (directions) supplied; returns all directions played [Hero, Enemy1, Enemy2, Enemy3, Enemy4] public boolean gameOver(); // Returns true if the hero has lost all her lives or if MAX_LEVELS has been reached //These constants specify the exact nature of the game public class Direction { public static final int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, EMPTY = -1; } //directions // Points public static final int PILL_SCORE = 10; public static final int POWER_PILL_SCORE = 50; public static final int ENEMY_EAT_SCORE = 200; // Timing public static final int EDIBLE_TIME = 200; //initial time an enemy is edible for (decreases as level number increases) public static final float EDIBLE_TIME_REDUCTION = 0.9f; //reduction factor by which edible time decreases as level number increases public static final int[] LAIR_TIMES = {40, 60, 80, 100}; //time spend in the lair by each enemy at the start of a level public static final int COMMON_LAIR_TIME = 40; //time spend in lair after being eaten public static final float LAIR_REDUCTION = 0.9f; //reduction factor by which lair times decrease as level number increases public static final int LEVEL_LIMIT = 3000; //time limit for a level public static final int DELAY = 40; //delay (in milliseconds) between game advancements // Initial Game State public static final int NUM_LIVES = 3; //total number of lives the hero has (current + NUM_LIVES-1 spares) public static final int INITIAL_HERO_DIR = 3; //initial direction taken by the hero public static final int[] INITIAL_ENEMY_DIRS = {3, 1, 3, 1}; //initial directions for the enemies (after leaving the lair) public static final int ENEMY_SPEED_REDUCTION = 2; //difference in speed when enemies are edible (every ENEMY_SPEED_REDUCTION, an enemy remains stationary) // Misc. configurations for game public static final float ENEMY_REVERSAL = 0.0015f; //probability of a global enemy reversal event public static final int EXTRA_LIFE_SCORE = 10000; //extra life is awarded when this many points have been collected public static final int EAT_DISTANCE = 2; //distance in the connected graph considered close enough for an eating event to take place public static final int NUM_ENEMY = 4; //number of enemies in the game public static final int NUM_MAZES = 4; //number of different mazes in the game public static final int MAX_LEVELS = 16; //maximum number of levels played before the end of the game public enum DM{PATH,EUCLID,MANHATTEN}; //simple enumeration for use with the direction methods }
f5c2509c98d3599438e1e587ed26a1113ed56cb6
[ "Java" ]
7
Java
erikhiggy/pakupaku
2542084634e68324eda636e838eb8db6b7d60975
f4089aedc880d53f0f6890a0c3fc6072db395fb2
refs/heads/master
<file_sep>/* P3 materials example - see SetMaterial and fragment shader CPE 471 Cal Poly Z. Wood + <NAME> */ #include <iostream> #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include <Math.h> #include "GLSL.h" #include "Program.h" #include "MatrixStack.h" #include "Shape.h" #include "BoundingSphere.h" #include "Texture.h" #define NUM_SHAPES 2 using namespace std; using namespace Eigen; GLFWwindow *window; // Main application window string RESOURCE_DIR = ""; // Where the resources are loaded from shared_ptr<Program> prog, floorprog; shared_ptr<Shape> bathing, mars, shape1, shape2, flashlightShape; Texture floortexture; GLint h_floortexture; int g_GiboLen; int g_width, g_height, changeDir; int gMat = 0; int mode = 1; float zOffset = 0; float xOffset = 0; float phi = 0; float theta = -M_PI_2; float eyeX, eyeY, eyeZ, targetX, targetY, targetZ; float radius = 2.0; float marsX = -4; float marsZ = 2; float bathingX = 2; float bathingZ = -4; BoundingSphere spheres [NUM_SHAPES]; Vector3f u, v, w, gaze, target, eye, flashlight, targetDir, targetTrans; GLuint GrndBuffObj, GrndNorBuffObj, GrndTexBuffObj, GIndxBuffObj; static void error_callback(int error, const char *description) { cerr << description << endl; } bool hasCollisions(Vector3f eye) { for (int i = 0; i < NUM_SHAPES; i++) { if(spheres[i].willCollide(eye)) { return true; } } return false; } bool wallCollide(Vector3f eye) { if (eye[0] < -35 || eye[0] > 35 || eye[1] < -35 || eye[1] > 35 || eye[2] < -35 || eye[2] > 35) { return true; } return false; } /* code to define the ground plane */ static void initGeom() { float g_groundSize = 1000; float g_groundY = -0.5; // A x-z plane at y = g_groundY of dimension [-g_groundSize, g_groundSize]^2 float GrndPos[] = { -g_groundSize, g_groundY, -g_groundSize, -g_groundSize, g_groundY, g_groundSize, g_groundSize, g_groundY, g_groundSize, g_groundSize, g_groundY, -g_groundSize }; float GrndNorm[] = { 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 }; static GLfloat GrndTex[] = { 0,0, 0,400, 400,400, 400,0 }; unsigned short idx[] = {0, 1, 2, 0, 2, 3}; GLuint VertexArrayID; //generate the VAO glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); g_GiboLen = 6; glGenBuffers(1, &GrndBuffObj); glBindBuffer(GL_ARRAY_BUFFER, GrndBuffObj); glBufferData(GL_ARRAY_BUFFER, sizeof(GrndPos), GrndPos, GL_STATIC_DRAW); glGenBuffers(1, &GrndNorBuffObj); glBindBuffer(GL_ARRAY_BUFFER, GrndNorBuffObj); glBufferData(GL_ARRAY_BUFFER, sizeof(GrndNorm), GrndNorm, GL_STATIC_DRAW); glGenBuffers(1, &GrndTexBuffObj); glBindBuffer(GL_ARRAY_BUFFER, GrndTexBuffObj); glBufferData(GL_ARRAY_BUFFER, sizeof(GrndTex), GrndTex, GL_STATIC_DRAW); glGenBuffers(1, &GIndxBuffObj); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GIndxBuffObj); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(idx), idx, GL_STATIC_DRAW); } static void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) { // don't allow camera to "fly" or "dig into ground" Vector3f newW; newW[0] = w[0]; newW[2] = w[2]; newW[1] = w[1] - (w.dot(Vector3f(0,1,0))); printf("eye %f %f %f\n", eye[0], eye[1], eye[2]); if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } else if (key == GLFW_KEY_W && !hasCollisions(eye - .7*newW) && !wallCollide(eye - .7*newW)) { eye = eye - .7*newW; targetTrans = targetTrans - .7*newW; flashlight = flashlight - .7*newW; } else if (key == GLFW_KEY_S && !hasCollisions(eye + .7*newW) && !wallCollide(eye + .7*newW)) { eye = eye + .7*newW; targetTrans = targetTrans + .7*newW; flashlight = flashlight + .7*newW; } else if (key == GLFW_KEY_A && !hasCollisions(eye - .7*u) && !wallCollide(eye - .7*u)) { eye = eye - .7*u; targetTrans = targetTrans - .7*u; flashlight = flashlight - .7*u; } else if (key == GLFW_KEY_D && !hasCollisions(eye + .7*u) && !wallCollide(eye + .7*u)) { eye = eye + .7*u; targetTrans = targetTrans + .7*u; flashlight = flashlight + .7*u; } } static void scroll_fun(GLFWwindow *window, double dX, double dY) { glfwGetWindowSize (window, &g_width, &g_height); phi -= dY*M_PI/g_height; theta -= dX*M_PI/g_width; targetDir = Vector3f(cos(phi)*cos(theta), sin(phi), cos(phi)*cos(M_PI_2-theta)); } static void mouse_callback(GLFWwindow *window, int button, int action, int mods) { double posX, posY; if (action == GLFW_PRESS) { glfwGetCursorPos(window, &posX, &posY); cout << "Pos X " << posX << " Pos Y " << posY << endl; } } static void resize_callback(GLFWwindow *window, int width, int height) { g_width = width; g_height = height; glViewport(0, 0, width, height); } // helper function to set materials void SetMaterial(int i, shared_ptr<Program> prog) { switch (i) { case 0: // blue petals glUniform3f(prog->getUniform("MatAmb"), 0.02, 0.04, 0.2); glUniform3f(prog->getUniform("MatDif"), 0.0, 0.16, 2.9); glUniform3f(prog->getUniform("MatSpec"), 0.14, 2.2, 1.8); glUniform1f(prog->getUniform("Shine"), 0.1); break; case 1: // red petals glUniform3f(prog->getUniform("MatAmb"), 4.53, 0.13, 0.14); glUniform3f(prog->getUniform("MatDif"), 4.4, 0.1, 0.1); glUniform3f(prog->getUniform("MatSpec"), 4.3, 0.7, 0.4); glUniform1f(prog->getUniform("Shine"), 2.1); break; case 2: // yellow pollen/petals glUniform3f(prog->getUniform("MatAmb"), 4.3294, 4.2235, 0.02745); glUniform3f(prog->getUniform("MatDif"), 2.7804, 2.5686, 0.11373); glUniform3f(prog->getUniform("MatSpec"), 4.9922, 4.941176, 0.80784); glUniform1f(prog->getUniform("Shine"), 3.1); break; case 3: // brown for the doggies glUniform3f(prog->getUniform("MatAmb"), 0.1913, 0.0735, 0.0225); glUniform3f(prog->getUniform("MatDif"), 0.7038, 0.27048, 0.0828); glUniform3f(prog->getUniform("MatSpec"), 0.257, 0.1376, 0.08601); glUniform1f(prog->getUniform("Shine"), 1.2); break; case 4: // pink petals glUniform3f(prog->getUniform("MatAmb"), 0.55, 0.13, 0.24); glUniform3f(prog->getUniform("MatDif"), 0.8804, 0.6686, 0.66373); glUniform3f(prog->getUniform("MatSpec"), 0.09922, 0.0941176, 0.080784); glUniform1f(prog->getUniform("Shine"), 0.1); break; case 5: // floor glUniform3f(prog->getUniform("MatAmb"), 0.05, 0.11, 0.04); glUniform3f(prog->getUniform("MatDif"), 0.01, 0.13, 0.01); glUniform3f(prog->getUniform("MatSpec"), 0.09922, 0.0941176, 0.080784); glUniform1f(prog->getUniform("Shine"), 0.01); break; case 6: // marble glUniform3f(prog->getUniform("MatAmb"), 0.05, 0.11, 0.04); glUniform3f(prog->getUniform("MatDif"), 1.01, 1.13, 1.01); glUniform3f(prog->getUniform("MatSpec"), 0.09922, 0.0941176, 0.080784); glUniform1f(prog->getUniform("Shine"), 2.01); break; } } static void init() { GLSL::checkVersion(); // Set background color. glClearColor(0, 0, 0, 1.0f); // Enable z-buffer test. glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CCW); // Initialize mesh. flashlightShape = make_shared<Shape>(); flashlightShape->loadMesh(RESOURCE_DIR + "Flashlight.obj"); flashlightShape->resize(); flashlightShape->init(); shape1 = make_shared<Shape>(); shape1->loadMesh(RESOURCE_DIR + "sphere.obj"); shape1->resize(); shape1->init(); shape2 = make_shared<Shape>(); shape2->loadMesh(RESOURCE_DIR + "cube.obj"); shape2->resize(); shape2->init(); bathing = make_shared<Shape>(); bathing->loadMesh(RESOURCE_DIR + "nymph1.obj"); bathing->resize(); bathing->init(); mars = make_shared<Shape>(); mars->loadMesh(RESOURCE_DIR + "mars.obj"); mars->resize(); mars->init(); // Initialize the GLSL program. prog = make_shared<Program>(); prog->setVerbose(true); prog->setShaderNames(RESOURCE_DIR + "simple_vert.glsl", RESOURCE_DIR + "simple_frag.glsl"); prog->init(); prog->addUniform("P"); prog->addUniform("V"); prog->addUniform("MV"); prog->addUniform("MatAmb"); prog->addUniform("MatDif"); prog->addUniform("MatSpec"); prog->addUniform("Shine"); prog->addUniform("lightPos"); prog->addAttribute("vertPos"); prog->addAttribute("vertNor"); prog->addAttribute("vertTex"); floorprog = make_shared<Program>(); floorprog->setVerbose(true); floorprog->setShaderNames(RESOURCE_DIR + "floor_vert.glsl", RESOURCE_DIR + "floor_frag.glsl"); floorprog->init(); floortexture.setFilename(RESOURCE_DIR + "white_cinder_blocks.bmp"); floortexture.setUnit(0); floortexture.setName("FloorTexture"); floortexture.init(); floorprog->addUniform("P"); floorprog->addUniform("MV"); floorprog->addUniform("V"); floorprog->addUniform("lightPos"); floorprog->addUniform("FloorTexture"); floorprog->addAttribute("vertPos"); floorprog->addAttribute("vertNor"); floorprog->addAttribute("vertTex"); floorprog->addTexture(&floortexture); //spheres[0] = BoundingSphere(Vector3f((bathing->maxX + bathing->minX)/2 + bathingX, 7, (bathing->maxZ + bathing->minZ)/2 + bathingZ), // (bathing->maxX - bathing->minX) * 5); spheres[0] = BoundingSphere(Vector3f(bathingX*5, 7, bathingZ*5), (bathing->maxX - bathing->minX)); spheres[1] = BoundingSphere(Vector3f(marsX*5, 7, marsZ*5), (mars->maxX - mars->minX)); //spheres[1] = BoundingSphere(Vector3f((mars->maxX + mars->minX)/2 + marsX, 7, (mars->maxZ + mars->minZ)/2 + marsZ), // (mars->maxX - mars->minX) * 5); targetDir = Vector3f(cos(phi)*cos(theta), sin(phi), cos(phi)*cos(M_PI_2-theta)); targetTrans = Vector3f(0, 7, 0); eye = Vector3f(0, 7, 0); glfwSetScrollCallback (window, scroll_fun); } static void render() { // Get current frame buffer size. int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); // Clear framebuffer. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); float aspect = width/(float)height; auto P = make_shared<MatrixStack>(); auto MV = make_shared<MatrixStack>(); auto V = make_shared<MatrixStack>(); // Apply perspective projection. P->pushMatrix(); P->perspective(45.0f, aspect, 0.01f, 100.0f); // Draw a stack of cubes with indiviudal transforms prog->bind(); glUniformMatrix4fv(prog->getUniform("P"), 1, GL_FALSE, P->topMatrix().data()); target = targetTrans + targetDir; gaze = target - eye; w = (-gaze).normalized(); u = (Vector3f(0,1,0).cross(w)).normalized(); v = w.cross(u); V->loadIdentity(); glUniformMatrix4fv(prog->getUniform("V"), 1, GL_FALSE, V->topMatrix().data()); V->lookAt(eye, target, Vector3f(0, 1, 0)); glUniformMatrix4fv(prog->getUniform("V"), 1, GL_FALSE, V->topMatrix().data()); glUniform3f(prog->getUniform("lightPos"), eye[0], eye[1], eye[2]); // WALLS SetMaterial(3, prog); // WALL 1 MV->pushMatrix(); MV->loadIdentity(); MV->scale(Vector3f(.2, 50, 100)); MV->translate(Vector3f(-200, 0, 0)); glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE, MV->topMatrix().data()); shape2->draw(prog); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); MV->popMatrix(); // WALL 2 MV->pushMatrix(); MV->loadIdentity(); MV->scale(Vector3f(.2, 50, 100)); MV->translate(Vector3f(200, 0, 0)); glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE, MV->topMatrix().data()); shape2->draw(prog); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); MV->popMatrix(); // WALL 3 MV->pushMatrix(); MV->loadIdentity(); MV->scale(Vector3f(100, 50, .2)); MV->translate(Vector3f(0, 0, 200)); glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE, MV->topMatrix().data()); shape2->draw(prog); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); MV->popMatrix(); // WALL 4 MV->pushMatrix(); MV->loadIdentity(); MV->scale(Vector3f(100, 50, .2)); MV->translate(Vector3f(0, 0, -200)); glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE, MV->topMatrix().data()); shape2->draw(prog); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); MV->popMatrix(); // END WALLS // BEG STATUES // bathing lady SetMaterial(6, prog); MV->pushMatrix(); MV->loadIdentity(); MV->scale(Vector3f(5, 5, 5)); MV->translate(Vector3f(bathingX, 1, bathingZ)); MV->rotate(180, Vector3f(0, 0, 1)); MV->rotate(180, Vector3f(0, 1, 0)); glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE, MV->topMatrix().data()); bathing->draw(prog); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); MV->popMatrix(); // mars MV->pushMatrix(); MV->loadIdentity(); MV->scale(Vector3f(5, 5, 5)); MV->translate(Vector3f(marsX, 1, marsZ)); MV->rotate(180, Vector3f(0, 0, 1)); glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE, MV->topMatrix().data()); mars->draw(prog); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); MV->popMatrix(); // END STATUES // flashlight V->pushMatrix(); V->loadIdentity(); glUniformMatrix4fv(prog->getUniform("V"), 1, GL_FALSE, V->topMatrix().data()); MV->pushMatrix(); MV->loadIdentity(); MV->translate(Vector3f(1, 6, -3)); MV->rotate(targetDir[0], Vector3f(1, 0, 0)); MV->rotate(targetDir[1], Vector3f(0, 1, 0)); MV->rotate(targetDir[2], Vector3f(0, 0, 1)); MV->rotate(180, Vector3f(0, 1, 0)); glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE, MV->topMatrix().data()); flashlightShape->draw(prog); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); MV->popMatrix(); V->popMatrix(); prog->unbind(); floorprog->bind(); /* draw floor */ MV->pushMatrix(); MV->loadIdentity(); glUniformMatrix4fv(floorprog->getUniform("V"), 1, GL_FALSE, V->topMatrix().data()); glUniformMatrix4fv(floorprog->getUniform("MV"), 1, GL_FALSE, MV->topMatrix().data()); glUniformMatrix4fv(floorprog->getUniform("P"), 1, GL_FALSE, P->topMatrix().data()); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, GrndBuffObj); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, GrndNorBuffObj); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, GrndTexBuffObj); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0); // draw! glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GIndxBuffObj); glDrawElements(GL_TRIANGLES, g_GiboLen, GL_UNSIGNED_SHORT, 0); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); MV->popMatrix(); floorprog->unbind(); // Pop matrix stacks. P->popMatrix(); } int main(int argc, char **argv) { if(argc < 2) { cout << "Please specify the resource directory." << endl; return 0; } RESOURCE_DIR = argv[1] + string("/"); // Set error callback. glfwSetErrorCallback(error_callback); // Initialize the library. if(!glfwInit()) { return -1; } //request the highest possible version of OGL - important for mac glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); // Create a windowed mode window and its OpenGL context. window = glfwCreateWindow(640, 480, "<NAME>", NULL, NULL); if(!window) { glfwTerminate(); return -1; } // Make the window's context current. glfwMakeContextCurrent(window); // Initialize GLEW. glewExperimental = true; if(glewInit() != GLEW_OK) { cerr << "Failed to initialize GLEW" << endl; return -1; } //weird bootstrap of glGetError glGetError(); cout << "OpenGL version: " << glGetString(GL_VERSION) << endl; cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl; // Set vsync. glfwSwapInterval(1); // Set keyboard callback. glfwSetKeyCallback(window, key_callback); //set the mouse call back glfwSetMouseButtonCallback(window, mouse_callback); //set the window resize call back glfwSetFramebufferSizeCallback(window, resize_callback); // Initialize scene. Note geometry initialized in init now init(); initGeom(); // Loop until the user closes the window. while(!glfwWindowShouldClose(window)) { // Render scene. render(); // Swap front and back buffers. glfwSwapBuffers(window); // Poll for and process events. glfwPollEvents(); } // Quit program. glfwDestroyWindow(window); glfwTerminate(); return 0; } /* Cool Looking Vases (V) http://www.turbosquid.com/3d-models/free-vase-turquoise-3d-model/571678 http://www.turbosquid.com/3d-models/free-ceramic-pottery-vase-3d-model/627797 Skeleton Statue (S) http://www.turbosquid.com/3d-models/free-obj-mode-scan-ligier-richier/969915 Greek/Roman Sculptures (R) Mars http://www.turbosquid.com/3d-models/scan-statue-mars-obj-free/942970 Mercury http://www.turbosquid.com/3d-models/free-obj-mode-scan-statue-mercury/943904 Hermes http://www.turbosquid.com/3d-models/free-obj-mode-scan-statue-hermes/1006366 Venus w/ Cupid http://www.turbosquid.com/3d-models/free-obj-model-scan-statue-venus-kissing/955680 Hunter w/ Dog http://www.turbosquid.com/3d-models/free-scan-statue-hunter-dog-3d-model/791511 Marble Player http://www.turbosquid.com/3d-models/scan-statue-marble-player-obj-free/943887 David by Michelangelo https://sketchfab.com/models/8f4827cf36964a17b90bad11f48298ac */<file_sep>#pragma once #ifndef _BOUNDING_SPHERE_H_ #define _BOUNDING_SPHERE_H_ #define EIGEN_DONT_ALIGN_STATICALLY #include <Eigen/Dense> #include <string> #include <vector> #include <memory> class Program; class BoundingSphere { public: BoundingSphere(); BoundingSphere(Eigen::Vector3f bcenter, float bradius); virtual ~BoundingSphere(); bool willCollide(Eigen::Vector3f eye); private: Eigen::Vector3f center; float radius; }; #endif <file_sep>#include "BoundingSphere.h" #include <iostream> #define EIGEN_DONT_ALIGN_STATICALLY #include <Eigen/Dense> #include "GLSL.h" #include "Program.h" using namespace std; BoundingSphere::BoundingSphere() {} BoundingSphere::BoundingSphere(Eigen::Vector3f bcenter, float bradius) { center = bcenter; radius = bradius; } BoundingSphere::~BoundingSphere() { } bool BoundingSphere::willCollide(Eigen::Vector3f eye) { Eigen::Vector3f eyeCopy; eyeCopy[0] = eye[0]; eyeCopy[1] = 1; eyeCopy[2] = eye[2]; Eigen::Vector3f distVec = eye-center; float dist = sqrt(distVec[0]*distVec[0] + distVec[1]*distVec[1] + distVec[2]*distVec[2]); if (dist > radius + 1) { return false; } return true; }
531dd9c0d129108de95aa745b2309f2503726c57
[ "C++" ]
3
C++
negiusti/Final-Project-471
4640c9deec94515ee30d91f664d04aaea1004104
5fefbc89d66751c79731185ac6623f3ce76932c5
refs/heads/master
<repo_name>pahlevikun/TMdb<file_sep>/app/src/main/java/com/udacity/themoviestage1/DetailActivity.java package com.udacity.themoviestage1; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Intent; import android.net.Uri; import android.support.design.widget.AppBarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.squareup.picasso.Picasso; import com.udacity.themoviestage1.adapter.MovieAdapter; import com.udacity.themoviestage1.adapter.RecommendAdapter; import com.udacity.themoviestage1.config.APIConfig; import com.udacity.themoviestage1.contentprovider.Provider; import com.udacity.themoviestage1.pojo.Movie; import com.udacity.themoviestage1.pojo.Recommend; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class DetailActivity extends AppCompatActivity { private String title, shareBody,url,backdrop_path,idMovie; private FloatingActionButton floatingActionButton; private TextView tvTitle, tvVote, tvDate, tvPlot; private ImageView ivBackground, ivDetail; private Button btVideo; private ProgressDialog loading; private Movie movie; private RecyclerView recyclerView; private ArrayList<Recommend> valueList = new ArrayList<>(); private RecommendAdapter adapter; private LinearLayoutManager layoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButtonDetail); tvTitle = (TextView) findViewById(R.id.textViewTitleDetail); tvVote = (TextView) findViewById(R.id.textViewVoteDetail); tvDate = (TextView) findViewById(R.id.textViewDateDetail); tvPlot = (TextView) findViewById(R.id.textViewPlotDetail); ivBackground = (ImageView) findViewById(R.id.imageViewBackDetail); ivDetail = (ImageView) findViewById(R.id.imageViewInfoDetail); btVideo = (Button) findViewById(R.id.buttonVideo); AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayoutDetail); if (android.os.Build.VERSION.SDK_INT >= 21) { appBarLayout.setElevation(0); } appBarLayout.bringToFront(); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); layoutManager = new GridLayoutManager(DetailActivity.this,2); recyclerView.setLayoutManager(layoutManager); adapter = new RecommendAdapter(DetailActivity.this,valueList); recyclerView.setAdapter(adapter); Intent intent = getIntent(); if(intent != null){ if(intent.hasExtra("parcel")){ movie = intent.getParcelableExtra("parcel"); idMovie = movie.idMovie; Log.d("Hasil"," "+movie.idMovie); title = movie.title; url = APIConfig.DETAIL + idMovie + "?api_key=" + getString(R.string.API_KEY); }else if (intent.hasExtra("kunci")){ title = intent.getStringExtra("judul"); url = APIConfig.DETAIL + intent.getStringExtra("kunci") + "?api_key=" + getString(R.string.API_KEY); }else if (intent.hasExtra("recommend")){ title = intent.getStringExtra("judul"); idMovie = intent.getStringExtra("idMovie"); url = APIConfig.DETAIL + idMovie + "?api_key=" + getString(R.string.API_KEY); }else{ finish(); } } getDetail(url); floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share "+title+" Information"); intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); startActivity(Intent.createChooser(intent,"Share via")); } }); btVideo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getKey(movie.idMovie); } }); } private void getDetail(String url) { loading = ProgressDialog.show(DetailActivity.this,"Please wait","Now loading...",false,false); RequestQueue queue = Volley.newRequestQueue(DetailActivity.this); StringRequest postRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jObj = new JSONObject(response); Log.d("RESPON",""+response); String release_date = jObj.getString("release_date"); String voting = jObj.getString("vote_average"); String overview = jObj.getString("overview"); String poster_path = jObj.getString("poster_path"); backdrop_path = jObj.getString("backdrop_path"); if(backdrop_path.isEmpty()||backdrop_path.equals(null)||backdrop_path==null||backdrop_path.equals("null")){ ivBackground.setBackgroundResource(R.color.colorPrimary); }else{ Picasso.with(DetailActivity.this).load(APIConfig.BASE_BACKDROP+backdrop_path).into(ivBackground); } Picasso.with(DetailActivity.this).load(APIConfig.BASE_IMAGE+poster_path).into(ivDetail); if(overview.length()==0){ tvPlot.setText("Plot not available"); }else { tvDate.setText(release_date); tvPlot.setText(overview); tvVote.setText(voting); tvTitle.setText(title); } setTitle(title); shareBody = title+"\nRelease date : "+release_date+"\nPlot : "+overview; addMovie(title,poster_path,voting); } catch (JSONException e) {hideDialog(); Toast.makeText(DetailActivity.this, "JSON Error : " + e.getMessage(), Toast.LENGTH_LONG).show(); finish(); } } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { Toast.makeText(DetailActivity.this, "Can't connect to Server", Toast.LENGTH_LONG).show(); hideDialog(); finish(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); return headers; } }; int socketTimeout = 20000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); postRequest.setRetryPolicy(policy); queue.add(postRequest); } private void getKey(final String id) { loading = ProgressDialog.show(DetailActivity.this,"Please wait","Now loading...",false,false); RequestQueue queue = Volley.newRequestQueue(DetailActivity.this); String url = APIConfig.DETAIL + id + "/videos?api_key=" + getString(R.string.API_KEY); StringRequest postRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { hideDialog(); try { JSONObject jObj = new JSONObject(response); JSONArray results = jObj.getJSONArray("results"); JSONObject i = results.getJSONObject(0); String key = i.getString("key"); Intent intent = new Intent(DetailActivity.this, VideoActivity.class); intent.putExtra("key",key); intent.putExtra("id",id); startActivity(intent); } catch (JSONException e) { Toast.makeText(DetailActivity.this, "JSON Error : " + e.getMessage(), Toast.LENGTH_LONG).show(); finish(); } } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { Toast.makeText(DetailActivity.this, "Can't connect to Server", Toast.LENGTH_LONG).show(); hideDialog(); finish(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); return headers; } }; int socketTimeout = 20000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); postRequest.setRetryPolicy(policy); queue.add(postRequest); } private void addMovie(final String title, final String poster, final String rating) { RequestQueue queue = Volley.newRequestQueue(DetailActivity.this); StringRequest postRequest = new StringRequest(Request.Method.POST, APIConfig.API_ADD, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); getRecommend(); } catch (JSONException e) { Toast.makeText(DetailActivity.this, "JSON Error : " + e.getMessage(), Toast.LENGTH_LONG).show(); hideDialog(); finish(); } } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { Toast.makeText(DetailActivity.this, "Can't connect to Server", Toast.LENGTH_LONG).show(); hideDialog(); finish(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("id",idMovie); params.put("title",title); params.put("poster",poster); params.put("rating",rating); params.put("interest","1"); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); return headers; } }; int socketTimeout = 20000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); postRequest.setRetryPolicy(policy); queue.add(postRequest); } private void getRecommend() { RequestQueue queue = Volley.newRequestQueue(DetailActivity.this); StringRequest postRequest = new StringRequest(Request.Method.GET, APIConfig.API_GET, new Response.Listener<String>() { @Override public void onResponse(String response) { hideDialog(); try { JSONObject jObj = new JSONObject(response); Log.d("RESPON",""+response); JSONObject interest = jObj.getJSONObject("interest"); JSONArray data = interest.getJSONArray("data"); for (int i=0; i<data.length();i++){ JSONObject film = data.getJSONObject(i); String id = film.getString("id"); String nama = film.getString("title"); String poster = film.getString("poster"); valueList.add(new Recommend(id,nama,poster)); } JSONObject rating = jObj.getJSONObject("rating"); JSONArray data2 = rating.getJSONArray("data"); for (int i=0; i<data2.length();i++){ JSONObject film = data2.getJSONObject(i); String id = film.getString("id"); String nama = film.getString("title"); String poster = film.getString("poster"); valueList.add(new Recommend(id,nama,poster)); } } catch (JSONException e) { Toast.makeText(DetailActivity.this, "JSON Error : " + e.getMessage(), Toast.LENGTH_LONG).show(); } adapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { Toast.makeText(DetailActivity.this, "Can't connect to Server", Toast.LENGTH_LONG).show(); hideDialog(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); return headers; } }; int socketTimeout = 20000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); postRequest.setRetryPolicy(policy); queue.add(postRequest); } private void hideDialog() { if (loading.isShowing()) loading.dismiss(); } public boolean onCreateOptionsMenu(android.view.Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.fav, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id==android.R.id.home) { finish(); return true; }else if(id==R.id.action_fav) { try{ ContentValues values = new ContentValues(); values.put(Provider.TITLE, title); values.put(Provider.MOVIE, id); values.put(Provider.IMAGE, backdrop_path); Uri uri = getContentResolver().insert(Provider.CONTENT_URI, values); Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show(); }catch (Exception e){ Toast.makeText(this, "You already add it to Favorite!", Toast.LENGTH_SHORT).show(); } //provider.insert(title,id,backdrop_path); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { finish(); } } <file_sep>/app/src/main/java/com/udacity/themoviestage1/pojo/Recommend.java package com.udacity.themoviestage1.pojo; /** * Created by farhan on 9/29/17. */ public class Recommend { private int _id; private String id, judul, poster; public Recommend() { } public Recommend(int _id, String id, String judul, String poster) { this._id = _id; this.id = id; this.judul = judul; this.poster = poster; } public Recommend(String id, String judul, String poster) { this.id = id; this.judul = judul; this.poster = poster; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getJudul() { return judul; } public void setJudul(String judul) { this.judul = judul; } public String getPoster() { return poster; } public void setPoster(String poster) { this.poster = poster; } } <file_sep>/app/src/main/java/com/udacity/themoviestage1/VideoActivity.java package com.udacity.themoviestage1; import android.app.ActionBar; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MenuItem; import android.widget.ScrollView; import android.widget.Toast; import android.widget.Toolbar; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; import com.udacity.themoviestage1.adapter.ReviewAdapter; import com.udacity.themoviestage1.adapter.TrailerAdapter; import com.udacity.themoviestage1.config.APIConfig; import com.udacity.themoviestage1.contentprovider.Provider; import com.udacity.themoviestage1.pojo.Review; import com.udacity.themoviestage1.pojo.Trailer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class VideoActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener { private static final int RECOVERY_DIALOG_REQUEST = 1; private String idMovie,id; private ProgressDialog loading; private RecyclerView recyclerView, recyclerView2; private ArrayList<Review> valueList = new ArrayList<>(); private ArrayList<Trailer> trailerList = new ArrayList<>(); private ReviewAdapter adapter; private TrailerAdapter trailerAdapter; private YouTubePlayerView youTubeView; private ScrollView scrollView; private Bundle savedInstance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video); Intent intent = getIntent(); idMovie = intent.getStringExtra("key"); id = intent.getStringExtra("id"); youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view); scrollView = (ScrollView) findViewById(R.id.scrollView); String url = APIConfig.DETAIL + id + "/reviews?api_key=" + getString(R.string.API_KEY); getNew(url); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(VideoActivity.this); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); adapter = new ReviewAdapter(VideoActivity.this,valueList); recyclerView.setAdapter(adapter); recyclerView2 = (RecyclerView) findViewById(R.id.recyclerView2); RecyclerView.LayoutManager mLayoutManager2 = new LinearLayoutManager(VideoActivity.this); recyclerView2.setLayoutManager(mLayoutManager2); recyclerView2.setItemAnimator(new DefaultItemAnimator()); trailerAdapter = new TrailerAdapter(VideoActivity.this,trailerList); recyclerView2.setAdapter(trailerAdapter); recyclerView.setNestedScrollingEnabled(false); recyclerView2.setNestedScrollingEnabled(false); } // two static variable, public static int scrollX = 0; public static int scrollY = -1; @Override protected void onPause() { super.onPause(); scrollX = scrollView.getScrollX(); scrollY = scrollView.getScrollY(); } @Override protected void onResume() { super.onResume(); scrollView.post(new Runnable() { @Override public void run() { scrollView.scrollTo(scrollX, scrollY); } }); } protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putIntArray("ARTICLE_SCROLL_POSITION", new int[]{ scrollView.getScrollX(), scrollView.getScrollY()}); Log.d("SCROLL", ""+scrollView.getScrollX()+scrollView.getScrollY()); } protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); final int[] position = savedInstanceState.getIntArray("ARTICLE_SCROLL_POSITION"); if(position != null) scrollView.post(new Runnable() { public void run() {scrollView.scrollTo(position[0], position[1]); } }); Log.d("SCROLL",""+position[0]+" "+position[1]); } private void getNew(String url) { loading = ProgressDialog.show(VideoActivity.this,"Please wait","Now loading...",false,false); RequestQueue queue = Volley.newRequestQueue(VideoActivity.this); StringRequest postRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jObj = new JSONObject(response); Log.d("RESPON",""+response); JSONArray results = jObj.getJSONArray("results"); for (int i = 0; i < results.length(); i++){ JSONObject data = results.getJSONObject(i); String author = data.getString("author"); String contens = data.getString("content"); String urls = data.getString("url"); valueList.add(new Review(String.valueOf(i),author,contens,urls)); } youTubeView.initialize(getString(R.string.YOUTUBE_KEY), VideoActivity.this); String url = APIConfig.DETAIL + id + "?append_to_response=videos&api_key=" + getString(R.string.API_KEY); getTrailer(url); } catch (JSONException e) { hideDialog(); Toast.makeText(VideoActivity.this, "JSON Error : " + e.getMessage(), Toast.LENGTH_LONG).show(); } adapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { Toast.makeText(VideoActivity.this, "Can't connect to Server", Toast.LENGTH_LONG).show(); hideDialog(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); return headers; } }; int socketTimeout = 20000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); postRequest.setRetryPolicy(policy); queue.add(postRequest); } private void getTrailer(String url) { RequestQueue queue = Volley.newRequestQueue(VideoActivity.this); StringRequest postRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { hideDialog(); try { JSONObject jObj = new JSONObject(response); Log.d("RESPON",""+response); JSONObject video = jObj.getJSONObject("videos"); JSONArray results = video.getJSONArray("results"); for (int i = 0; i < results.length(); i++){ JSONObject data = results.getJSONObject(i); String key = data.getString("key"); String name = data.getString("name"); trailerList.add(new Trailer(String.valueOf(i),key,name)); } Log.d("RESPON"," "+trailerList.size()); } catch (JSONException e) { Toast.makeText(VideoActivity.this, "JSON Error : " + e.getMessage(), Toast.LENGTH_LONG).show(); } adapter.notifyDataSetChanged(); trailerAdapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { Toast.makeText(VideoActivity.this, "Can't connect to Server", Toast.LENGTH_LONG).show(); hideDialog(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); return headers; } }; int socketTimeout = 20000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); postRequest.setRetryPolicy(policy); queue.add(postRequest); } private void hideDialog() { if (loading.isShowing()) loading.dismiss(); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) { if (errorReason.isUserRecoverableError()) { errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show(); } else { String errorMessage = String.format(getString(R.string.error_player), errorReason.toString()); Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show(); } } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) { if (!wasRestored) { player.loadVideo(idMovie); player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RECOVERY_DIALOG_REQUEST) { getYouTubePlayerProvider().initialize(getString(R.string.YOUTUBE_KEY), this); } } private YouTubePlayer.Provider getYouTubePlayerProvider() { return (YouTubePlayerView) findViewById(R.id.youtube_view); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id==android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { finish(); } } <file_sep>/app/src/main/java/com/udacity/themoviestage1/adapter/TrailerAdapter.java package com.udacity.themoviestage1.adapter; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.udacity.themoviestage1.R; import com.udacity.themoviestage1.pojo.Review; import com.udacity.themoviestage1.pojo.Trailer; import java.util.ArrayList; /** * Created by farhan on 6/30/17. */ public class TrailerAdapter extends RecyclerView.Adapter<TrailerAdapter.ViewHolder> { private ArrayList<Trailer> movieData; private Context context; private Review movie; public TrailerAdapter(Context context, ArrayList<Trailer> movieData) { this.movieData = movieData; this.context = context; } @Override public TrailerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_trailer, viewGroup, false); return new ViewHolder(view); } @Override public void onBindViewHolder(TrailerAdapter.ViewHolder viewHolder, final int i) { viewHolder.textView1.setText(movieData.get(i).getJudul()); viewHolder.textView1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = "https://www.youtube.com/watch?v="+movieData.get(i).getKey(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); context.startActivity(intent); } }); } @Override public int getItemCount() { return movieData.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ private TextView textView1; public ViewHolder(View view) { super(view); textView1 = (TextView) view.findViewById(R.id.textViewReview1); } } } <file_sep>/app/src/main/java/com/udacity/themoviestage1/SearchActivity.java package com.udacity.themoviestage1; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.udacity.themoviestage1.adapter.GenreAdapter; import com.udacity.themoviestage1.adapter.MovieAdapter; import com.udacity.themoviestage1.config.APIConfig; import com.udacity.themoviestage1.config.AprioriFrequentItemsetGenerator; import com.udacity.themoviestage1.pojo.Genre; import com.udacity.themoviestage1.pojo.Movie; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class SearchActivity extends AppCompatActivity { private ProgressDialog loading; private RecyclerView recyclerView, recyclerSuggest; private ArrayList<Genre> valueList = new ArrayList<>(); private ArrayList<Genre> genreList = new ArrayList<>(); private GenreAdapter adapter, adapter2; private RecyclerView.LayoutManager layoutManager; private EditText etSearch; private Button btSearch; private int i = 0; private String[] parts; private TextView tvReko1, tvReko2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerSuggest = (RecyclerView) findViewById(R.id.recyclerViewSuggest); btSearch = (Button) findViewById(R.id.buttonSearch); etSearch = (EditText) findViewById(R.id.editTextSearch); tvReko1 = (TextView) findViewById(R.id.tvRekomen1); tvReko2 = (TextView) findViewById(R.id.tvRekomen2); recyclerSuggest.setHasFixedSize(true); layoutManager = new GridLayoutManager(SearchActivity.this, 2); recyclerSuggest.setLayoutManager(layoutManager); adapter2 = new GenreAdapter(SearchActivity.this, genreList); recyclerSuggest.setAdapter(adapter2); recyclerView.setHasFixedSize(true); layoutManager = new GridLayoutManager(SearchActivity.this, 2); recyclerView.setLayoutManager(layoutManager); adapter = new GenreAdapter(SearchActivity.this, valueList); recyclerView.setAdapter(adapter); btSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String param = etSearch.getText().toString().trim(); param = param.replace(" ","+"); String url = APIConfig.SEARCH + getString(R.string.API_KEY) + "&query=" +param; Log.d("HASIL"," "+url); InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); getSearch(url); } }); } private void getSearch(String url) { loading = ProgressDialog.show(SearchActivity.this, "Please wait", "Now loading...", false, false); RequestQueue queue = Volley.newRequestQueue(SearchActivity.this); StringRequest postRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { hideDialog(); try { JSONObject jObj = new JSONObject(response); Log.d("RESPON", "" + response); valueList.clear(); genreList.clear(); JSONArray results = jObj.getJSONArray("results"); int genreSimpan; for (int i = 0; i < results.length(); i++) { JSONObject data = results.getJSONObject(i); String idMovie = data.getString("id"); String title = data.getString("title"); String popularity = data.getString("popularity"); String poster_path = data.getString("poster_path"); String original_language = data.getString("original_language"); String original_title = data.getString("original_title"); String release_date = data.getString("release_date"); JSONArray genre = data.getJSONArray("genre_ids"); if (genre.length()==0){ genreSimpan = 0; }else { genreSimpan = genre.getInt(0); } Log.d("HASIL"," genre "+genreSimpan+" "+genre); valueList.add(new Genre(String.valueOf(i), idMovie, title, popularity, poster_path, original_language, original_title, release_date,genreSimpan)); } int[] genreArray = new int[valueList.size()]; for (int j=0;j<valueList.size();j++){ genreArray[j] = valueList.get(j).getGenre(); } int batasan = getPopularElement(genreArray); for (int k=0;k<valueList.size();k++){ //for (int k=0;k<3;k++){ Log.d("HASIL","ke-"+k+" "+valueList.get(i).getGenre()+" batasan "+batasan); if (valueList.get(k).getGenre()==batasan){ if (genreList.size()<4){ genreList.add(new Genre(String.valueOf(k), valueList.get(k).getIdMovie(), valueList.get(k).getTitle(), valueList.get(k).getPopularity(), valueList.get(k).getPoster_path(), valueList.get(k).getOriginal_language(), valueList.get(k).getOriginal_title(), valueList.get(k).getRealease_date(), valueList.get(k).getGenre())); } } } Log.d("HASIL", " " + valueList.size()+" "+genreList.size()); } catch (JSONException e) { Toast.makeText(SearchActivity.this, "JSON Error : " + e.getMessage(), Toast.LENGTH_LONG).show(); } adapter.notifyDataSetChanged(); adapter2.notifyDataSetChanged(); if (valueList.size()!=0){ tvReko1.setVisibility(View.VISIBLE); tvReko2.setVisibility(View.VISIBLE); }else{ tvReko1.setVisibility(View.GONE); tvReko2.setVisibility(View.GONE); } } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { Toast.makeText(SearchActivity.this, "Can't connect to Server", Toast.LENGTH_LONG).show(); hideDialog(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); return headers; } }; int socketTimeout = 20000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); postRequest.setRetryPolicy(policy); queue.add(postRequest); } public int getPopularElement(int[] a) { int count = 1, tempCount; int popular = a[0]; int temp = 0; for (int i = 0; i < (a.length - 1); i++) { temp = a[i]; tempCount = 0; for (int j = 1; j < a.length; j++) { if (temp == a[j]) tempCount++; } if (tempCount > count) { popular = temp; count = tempCount; } } return popular; } private void hideDialog() { if (loading.isShowing()) loading.dismiss(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { finish(); } } <file_sep>/app/src/main/java/com/udacity/themoviestage1/pojo/Content.java package com.udacity.themoviestage1.pojo; import android.os.Parcel; import android.os.Parcelable; /** * Created by farhan on 6/30/17. */ public class Content implements Parcelable { public String id; public String key; public String movie; public String poster; public Content(){ } public Content(String id, String key, String movie, String poster){ this.id = id; this.key = key; this.movie = movie; this.poster = poster; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.id); dest.writeString(this.key); dest.writeString(this.movie); dest.writeString(this.poster); } protected Content(Parcel in) { this.id = in.readString(); this.key = in.readString(); this.movie = in.readString(); this.poster = in.readString(); } public static final Creator<Content> CREATOR = new Creator<Content>() { @Override public Content createFromParcel(Parcel source) { return new Content(source); } @Override public Content[] newArray(int size) { return new Content[size]; } }; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getMovie() { return movie; } public void setMovie(String movie) { this.movie = movie; } public String getPoster() { return poster; } public void setPoster(String poster) { this.poster = poster; } public static Creator<Content> getCREATOR() { return CREATOR; } } <file_sep>/app/src/main/java/com/udacity/themoviestage1/pojo/Markers.java package com.udacity.themoviestage1.pojo; import com.google.android.gms.maps.model.LatLng; /** * Created by farhan on 8/8/17. */ public class Markers { private int id; private String nama, lat, lng, url; public Markers() { } public Markers(int id, String nama, String lat, String lng, String url) { this.id = id; this.nama = nama; this.lat = lat; this.lng = lng; this.url = url; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNama() { return nama; } public void setNama(String nama) { this.nama = nama; } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat; } public String getLng() { return lng; } public void setLng(String lng) { this.lng = lng; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } <file_sep>/app/src/main/java/com/udacity/themoviestage1/adapter/RecommendAdapter.java package com.udacity.themoviestage1.adapter; import android.content.Context; import android.content.Intent; import android.support.v7.widget.CardView; 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 com.squareup.picasso.Picasso; import com.udacity.themoviestage1.DetailActivity; import com.udacity.themoviestage1.R; import com.udacity.themoviestage1.config.APIConfig; import com.udacity.themoviestage1.pojo.Movie; import com.udacity.themoviestage1.pojo.Recommend; import java.util.ArrayList; /** * Created by farhan on 6/30/17. */ public class RecommendAdapter extends RecyclerView.Adapter<RecommendAdapter.ViewHolder> { private ArrayList<Recommend> movieData; private Context context; private Movie movie; public RecommendAdapter(Context context, ArrayList<Recommend> movieData) { this.movieData = movieData; this.context = context; } @Override public RecommendAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_movie, viewGroup, false); return new ViewHolder(view); } @Override public void onBindViewHolder(RecommendAdapter.ViewHolder viewHolder, final int i) { viewHolder.textView1.setText(movieData.get(i).getJudul()); viewHolder.textView2.setVisibility(View.GONE); Picasso.with(context) .load(APIConfig.BASE_IMAGE+movieData.get(i).getPoster()) .error(R.drawable.ic_image) .into(viewHolder.imageView); viewHolder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(context, DetailActivity.class); intent.putExtra("judul",movieData.get(i).getJudul()); intent.putExtra("idMovie",movieData.get(i).getId()); intent.putExtra("recommend","recommend"); context.startActivity(intent); } }); } @Override public int getItemCount() { return movieData.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ private TextView textView1,textView2; private ImageView imageView; private CardView cardView; public ViewHolder(View view) { super(view); textView1 = (TextView) view.findViewById(R.id.textViewMovie1); textView2 = (TextView) view.findViewById(R.id.textViewMovie2); imageView = (ImageView) view.findViewById(R.id.imageViewMovie); cardView = (CardView) view.findViewById(R.id.cardViewMovie); } } } <file_sep>/app/src/main/java/com/udacity/themoviestage1/pojo/Movie.java package com.udacity.themoviestage1.pojo; import android.os.Parcel; import android.os.Parcelable; /** * Created by farhan on 6/30/17. */ public class Movie implements Parcelable { public String id; public String idMovie; public String title; public String popularity; public String poster_path; public String original_language; public String original_title; public String realease_date; public Movie(){ } public Movie(String id, String idMovie, String title, String popularity, String poster_path, String original_language, String original_title, String realease_date){ this.id = id; this.idMovie = idMovie; this.title = title; this.popularity = popularity; this.poster_path = poster_path; this.original_language = original_language; this.original_title = original_title; this.realease_date = realease_date; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.id); dest.writeString(this.idMovie); dest.writeString(this.title); dest.writeString(this.popularity); dest.writeString(this.poster_path); dest.writeString(this.original_language); dest.writeString(this.original_title); dest.writeString(this.realease_date); } protected Movie(Parcel in) { this.id = in.readString(); this.idMovie = in.readString(); this.title = in.readString(); this.popularity = in.readString(); this.poster_path = in.readString(); this.original_language = in.readString(); this.original_title = in.readString(); this.realease_date = in.readString(); } public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() { @Override public Movie createFromParcel(Parcel source) { return new Movie(source); } @Override public Movie[] newArray(int size) { return new Movie[size]; } }; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getIdMovie() { return idMovie; } public void setIdMovie(String idMovie) { this.idMovie = idMovie; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPopularity() { return popularity; } public void setPopularity(String popularity) { this.popularity = popularity; } public String getPoster_path() { return poster_path; } public void setPoster_path(String poster_path) { this.poster_path = poster_path; } public String getOriginal_language() { return original_language; } public void setOriginal_language(String original_language) { this.original_language = original_language; } public String getOriginal_title() { return original_title; } public void setOriginal_title(String original_title) { this.original_title = original_title; } public String getRealease_date() { return realease_date; } public void setRealease_date(String realease_date) { this.realease_date = realease_date; } } <file_sep>/app/src/main/java/com/udacity/themoviestage1/fragment/NewReleaseFragment.java package com.udacity.themoviestage1.fragment; /** * Created by farhan on 6/30/17. */ import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.udacity.themoviestage1.R; import com.udacity.themoviestage1.adapter.GenreAdapter; import com.udacity.themoviestage1.adapter.MovieAdapter; import com.udacity.themoviestage1.adapter.RecommendAdapter; import com.udacity.themoviestage1.config.APIConfig; import com.udacity.themoviestage1.pojo.Genre; import com.udacity.themoviestage1.pojo.Movie; import com.udacity.themoviestage1.pojo.Recommend; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class NewReleaseFragment extends Fragment { private ProgressDialog loading; private RecyclerView recyclerView; private ArrayList<Movie> valueList = new ArrayList<>(); private MovieAdapter adapter; private LinearLayoutManager layoutManager; private RecyclerView recyclerView2; private ArrayList<Genre> valueList2 = new ArrayList<>(); private ArrayList<Genre> genreList = new ArrayList<>(); private GenreAdapter adapter2; private LinearLayoutManager layoutManager2; public NewReleaseFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_movie, container, false); String url = APIConfig.MAIN_NEW + getString(R.string.API_KEY); getNew(url); recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); layoutManager = new GridLayoutManager(getActivity(), calculateNoOfColumns(getActivity())); recyclerView.setLayoutManager(layoutManager); adapter = new MovieAdapter(getActivity(), valueList); recyclerView.setAdapter(adapter); recyclerView2 = (RecyclerView) view.findViewById(R.id.recyclerView2); recyclerView2.setHasFixedSize(true); layoutManager2 = new GridLayoutManager(getActivity(), calculateNoOfColumns(getActivity())); recyclerView2.setLayoutManager(layoutManager2); adapter2 = new GenreAdapter(getActivity(), genreList); recyclerView2.setAdapter(adapter2); return view; } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putInt("Nilai", 1); int position = 0; if (layoutManager != null) { position = layoutManager.findFirstVisibleItemPosition(); } savedInstanceState.putString("position", "" + position); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { final int position = Integer.parseInt(savedInstanceState.getString("position")); new Handler().postDelayed(new Runnable() { @Override public void run() { recyclerView.scrollToPosition(position); } }, 200); } } private void getNew(String url) { loading = ProgressDialog.show(getActivity(), "Please wait", "Now loading...", false, false); RequestQueue queue = Volley.newRequestQueue(getActivity()); StringRequest postRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { hideDialog(); try { JSONObject jObj = new JSONObject(response); Log.d("RESPON", "" + response); int genreSimpan = 0; JSONArray results = jObj.getJSONArray("results"); for (int i = 0; i < results.length(); i++) { JSONObject data = results.getJSONObject(i); String idMovie = data.getString("id"); String title = data.getString("title"); String popularity = data.getString("popularity"); String poster_path = data.getString("poster_path"); String original_language = data.getString("original_language"); String original_title = data.getString("original_title"); String release_date = data.getString("release_date"); valueList.add(new Movie(String.valueOf(i), idMovie, title, popularity, poster_path, original_language, original_title, release_date)); JSONArray genre = data.getJSONArray("genre_ids"); if (genre.length() == 0) { genreSimpan = 0; } else { genreSimpan = genre.getInt(0); } Log.d("HASIL", " genre " + genreSimpan + " " + genre); valueList2.add(new Genre(String.valueOf(i), idMovie, title, popularity, poster_path, original_language, original_title, release_date, genreSimpan)); } int[] genreArray = new int[valueList2.size()]; for (int j = 0; j < valueList2.size(); j++) { genreArray[j] = valueList2.get(j).getGenre(); } int batasan = getPopularElement(genreArray); for (int k = 0; k < valueList2.size(); k++) { //for (int k=0;k<3;k++){ Log.d("HASIL", "ke-" + k + " " + valueList2.get(k).getGenre() + " batasan " + batasan); if (valueList2.get(k).getGenre() == batasan) { if (genreList.size() < 4) { genreList.add(new Genre(String.valueOf(k), valueList2.get(k).getIdMovie(), valueList2.get(k).getTitle(), valueList2.get(k).getPopularity(), valueList2.get(k).getPoster_path(), valueList2.get(k).getOriginal_language(), valueList2.get(k).getOriginal_title(), valueList2.get(k).getRealease_date(), valueList2.get(k).getGenre())); } } } Log.d("TAG", "HASIL " + genreList.size() + " " + valueList.size()); } catch (JSONException e) { hideDialog(); Toast.makeText(getActivity(), "JSON Error : " + e.getMessage(), Toast.LENGTH_LONG).show(); } adapter.notifyDataSetChanged(); adapter2.notifyDataSetChanged(); } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { Toast.makeText(getActivity(), "Can't connect to Server", Toast.LENGTH_LONG).show(); hideDialog(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); return headers; } }; int socketTimeout = 20000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); postRequest.setRetryPolicy(policy); queue.add(postRequest); } public int getPopularElement(int[] a) { int count = 1, tempCount; int popular = a[0]; int temp = 0; for (int i = 0; i < (a.length - 1); i++) { temp = a[i]; tempCount = 0; for (int j = 1; j < a.length; j++) { if (temp == a[j]) tempCount++; } if (tempCount > count) { popular = temp; count = tempCount; } } return popular; } // private void getRecommend() { // // RequestQueue queue = Volley.newRequestQueue(getActivity()); // // StringRequest postRequest = new StringRequest(Request.Method.GET, APIConfig.API_GET, new Response.Listener<String>() { // // @Override // public void onResponse(String response) { // hideDialog(); // // try { // JSONObject jObj = new JSONObject(response); // Log.d("RESPON",""+response); // // JSONObject interest = jObj.getJSONObject("interest"); // JSONArray data = interest.getJSONArray("data"); // for (int i=0; i<data.length();i++){ // JSONObject film = data.getJSONObject(i); // String id = film.getString("id"); // String nama = film.getString("title"); // String poster = film.getString("poster"); // valueList2.add(new Recommend(id,nama,poster)); // } // // JSONObject rating = jObj.getJSONObject("rating"); // JSONArray data2 = rating.getJSONArray("data"); // for (int i=0; i<data2.length();i++){ // JSONObject film = data2.getJSONObject(i); // String id = film.getString("id"); // String nama = film.getString("title"); // String poster = film.getString("poster"); // valueList2.add(new Recommend(id,nama,poster)); // } // // } catch (JSONException e) { // Toast.makeText(getActivity(), "JSON Error : " + e.getMessage(), Toast.LENGTH_LONG).show(); // } // adapter2.notifyDataSetChanged(); // } // }, new Response.ErrorListener() { // public void onErrorResponse(VolleyError error) { // Toast.makeText(getActivity(), "Can't connect to Server", Toast.LENGTH_LONG).show(); // hideDialog(); // } // }) { // @Override // protected Map<String, String> getParams() { // Map<String, String> params = new HashMap<String, String>(); // return params; // } // @Override // public Map<String, String> getHeaders() throws AuthFailureError { // Map<String, String> headers = new HashMap<String, String>(); // return headers; // } // }; // // int socketTimeout = 20000; // RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, // DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); // postRequest.setRetryPolicy(policy); // queue.add(postRequest); // } private void hideDialog() { if (loading.isShowing()) loading.dismiss(); } public static int calculateNoOfColumns(Context context) { DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); float dpWidth = displayMetrics.widthPixels / displayMetrics.density; int scalingFactor = 180; int noOfColumns = (int) (dpWidth / scalingFactor); return noOfColumns; } }
fcb6fa755976fc91cb27b061068fe2c8da69d92b
[ "Java" ]
10
Java
pahlevikun/TMdb
622a36f204ca86f51b610bf7bddd951888a2ff1d
79b788f4ea1b050fd68f18222cbef4f0ef9e8a01
refs/heads/master
<file_sep>ServiceManagerID=e8a07142-c74c-4f32-ad79-0d53b9853c8e TransportName=TCP PeerTypeId=HARDWARE_SERVER UserName=thomm Port=3121 Host=127.0.0.1 OSName=Windows 10 ID=Local AgentID=e8a07142-c74c-4f32-ad79-0d53b9853c8e Name=Local ServiceManagerID=e8a07142-c74c-4f32-ad79-0d53b9853c8e TransportName=TCP PeerTypeId=LINUX_TCF_AGENT UserName=thomm Port=1534 Host=192.168.0.1 OSName=Windows 10 ID=Linux Agent AgentID=e8a07142-c74c-4f32-ad79-0d53b9853c8e Name=Linux Agent ServiceManagerID=e8a07142-c74c-4f32-ad79-0d53b9853c8e TransportName=TCP PeerTypeId=QEMU_TCF_GDB_CLIENT UserName=thomm Port=1138 Host=127.0.0.1 OSName=Windows 10 ID=QEMU AgentID=e8a07142-c74c-4f32-ad79-0d53b9853c8e Name=QEMU <file_sep>/****************************************************************************** * * Copyright (C) 2009 - 2014 Xilinx, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Use of the Software is limited solely to applications: * (a) running on a Xilinx device, or * (b) that interact with a Xilinx device through a bus or interconnect. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * XILINX BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Except as contained in this notice, the name of the Xilinx shall not be used * in advertising or otherwise to promote the sale, use or other dealings in * this Software without prior written authorization from Xilinx. * ******************************************************************************/ /* * helloworld.c: simple test application * * This application configures UART 16550 to baud rate 9600. * PS7 UART (Zynq) is not initialized by this application, since * bootrom/bsp configures it to baud rate 115200 * * ------------------------------------------------ * | UART TYPE BAUD RATE | * ------------------------------------------------ * uartns550 9600 * uartlite Configurable only in HW design * ps7_uart 115200 (configured by bootrom/bsp) */ #include <stdio.h> #include "platform.h" #include "xil_printf.h" #include <xil_io.h> #include "xparameters.h" #include "xscugic.h" #include <stdlib.h> XScuGic Interrupt; XScuGic_Config *IntCfg; // Check the status of a setup function int Check(int status) { if (status != XST_SUCCESS) { return XST_FAILURE; } return XST_SUCCESS; } // Initialize the AXI DMA void initializeDMA(void) { unsigned int temp; temp = Xil_In32(XPAR_AXI_DMA_0_BASEADDR + 0x30); //read data from memory temp = temp | 0x1001; // enable DMA and interrupt on complete Xil_Out32(XPAR_AXI_DMA_0_BASEADDR + 0x30, temp); //write altered data back into memory } void DMATransfer( unsigned int destAddress, unsigned int length) { // Write starting address to the DMA starting address register Xil_Out32(XPAR_AXI_DMA_0_BASEADDR + 0x48, destAddress); // Write the length of the data (in Bytes) that will go into the DRAM into the DMA register Xil_Out32(XPAR_AXI_DMA_0_BASEADDR + 0x58, length); // Triggers the transfer } // DMA Transfer when an interrupt occurs void InterruptHandler(void) { u32 temp; //Clear interrupt temp = Xil_In32(XPAR_AXI_DMA_0_BASEADDR + 0x34); temp = temp | 0x10000; Xil_Out32(XPAR_AXI_DMA_0_BASEADDR + 0x34, temp); //Initialize the DMA data transfer DMATransfer(0xa000000, 2048); } /* Initialize the interrupt system * Parameters in all caps come from the xparameters header file that is created from the hardware */ int initializeInterrupt(void) { int status; //Lookup device ID pointer IntCfg = XScuGic_LookupConfig(XPAR_PS7_SCUGIC_0_DEVICE_ID); if (NULL == IntCfg) { return XST_FAILURE; //Verify the pointer was looked up successfully } /*Initialize the configuration with the instance variable, address pointer, and base address in virtual memory to match it to its physical address */ status = XScuGic_CfgInitialize(&Interrupt, IntCfg, IntCfg -> CpuBaseAddress); Check(status); //Verify the interrupt configuration was successful //Register an interrupt to the interrupt instance previously setup Xil_ExceptionRegisterHandler(XIL_EXCEPTION_ID_INT, (Xil_ExceptionHandler) XScuGic_InterruptHandler, &Interrupt); Xil_ExceptionEnable(); //Enable the interrupt exception //Create the connection between the interrupt source and the handler that is run when an interrupt from this source occurs status = XScuGic_Connect(&Interrupt, XPAR_FABRIC_AXI_DMA_0_S2MM_INTROUT_INTR, (Xil_ExceptionHandler)InterruptHandler, NULL); Check(status); //Verify the interrupt was connected properly //Enable the interrupt source XScuGic_Enable(&Interrupt, XPAR_FABRIC_AXI_DMA_0_S2MM_INTROUT_INTR); } int main() { //int *ptr; init_platform(); // enable the DMA and interrupt initializeDMA(); // Setup the interrupt and specify actions the execute when the interrupt occurs initializeInterrupt(); //ptr = (int*)malloc(256); // Allocate a memory location for the data //xil_printf("Enter a character."); //getchar(); Xil_Out32(XPAR_GPIO_0_BASEADDR, 1); // Start collecting data DMATransfer(0xa000000, 2048); //xil_printf("The data was sent to %p", ptr); return 0; } <file_sep>#Mon May 07 14:14:54 EDT 2018 org.eclipse.core.runtime=2 org.eclipse.platform=4.6.1.v20160907-1200
baa77142a3de97e07129bdd92e8cb13d25b187c7
[ "C", "INI" ]
3
INI
thommauldin/SPI_ADC_Driver
4488f4365185e660cf793366b590ca36575d6a74
fb773c5c1946ce6f68136b4fdc0603b69ee41b36
refs/heads/master
<file_sep>#!/bin/bash rm -rf result mkdir result cd src javac Main.java time bash ../test.sh echo -e "\n### 期待値との差異 ###" diff ../data/out ../result qnum=$(ls ../data/in/ | wc -l) oknum=$(($qnum - $(diff ../data/out/ ../result/ | grep -o -i diff | wc -l))) if [ $oknum -eq $qnum ]; then echo "差異なし" fi echo -e "\n### 正答数 ###" echo $oknum / $qnum<file_sep># 第一回 社内勉強会 コードレビュー会 問題文はAtCoder様で開催されたコンテストの過去問より出題しています。 https://atcoder.jp/ # 問題文 すぬけ君は1〜Nの整数が等確率で出るN面サイコロと表と裏が等確率で出るコインを持っています。すぬけ君は、このサイコロとコインを使って今から次のようなゲームをします。 1. まず、サイコロを1回振り、出た目を現在の得点とする。 2. 得点が1以上K−1以下である限り、すぬけ君はコインを振り続ける。表が出たら得点は2倍になり、裏が出たら得点は0になる。 3. 得点が0になった、もしくはK以上になった時点でゲームが終了する。このとき、得点がK以上である場合すぬけ君の勝ち、0である場合すぬけ君の負けである。 NとKが与えられるので、このゲームですぬけ君が勝つ確率を求めてください。 # 制約 - 1≤N≤10^5 - 1≤K≤10^5 - 入力はすべて整数 # 入力 入力は以下の形式で標準入力から与えられる。 ``` N K ``` # 出力 すぬけ君が勝つ確率を出力せよ。 確率は小数点第10位以下を四捨五入し、小数点第9位まで出力する。 # 入力例 1 ``` 3 10 ``` # 出力例 1 ``` 0.145833333 ``` サイコロの出た目が1のとき、得点が10以上になるためには、4回コインを振って4連続で表が出る必要があります。 この確率は、1/3×(1/2)^4=1/48です。 サイコロの出た目が2のとき、得点が10以上になるためには、3回コインを振って3連続で表が出る必要があります。 この確率は、1/3×(1/2)^3=1/24です。 サイコロの出た目が3のとき、得点が10以上になるためには、2回コインを振って2連続で表が出る必要があります。 この確率は、1/3×(1/2)^2=1/12です。 よって、すぬけ君が勝つ確率は、1/48+1/24+1/12=7/48≃0.1458333333です。 # 入力例 2 ``` 100000 5 ``` # 出力例 2 ``` 0.999973750 ``` # プログラムの実装 - src/Main.javaを実装してください。(コンパイルやjarの作成は不要です。) - シェルを動かせる環境がある人は `try.sh` を実行してテストを行うことができます。 (シェルを動かす環境がない人は自分でテスト実行してください) <file_sep>#!/bin/bash for file in `ls ../data/in/*.txt`; do cat $file java Main `cat $file` > ../result/`basename $file` cat ../result/`basename $file` done
762b331d1a80bf49e9895450e232a6deb1e1bb36
[ "Markdown", "Shell" ]
3
Shell
asjuri/CodeReview1
2d222774a428bf7aa7fe167376357876c22cec5c
47c533679ddebfa4e499f08a4b1e81e72b7e5158
refs/heads/master
<repo_name>AkshadaRK/Dotnet<file_sep>/database/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace database { class Program { static void Main(string[] args) { Dc d = new Dc(); while (true) { Console.WriteLine("1.Add 2.Search 3.delete 4.view 5.sort "); int ch =int.Parse( Console.ReadLine()); switch (ch) { case 1: d.Add += new DBdelegate(Addmsg); d.insert(); break; case 3: d.Delete+= new DBdelegate(Deletemsg); d.delete(); break; case 2: d.search(); break; case 4: d.view(); break; case 5: d.sort(); break; } } } public static void Addmsg() { Console.WriteLine("New Record is added"); } public static void Deletemsg() { Console.WriteLine(" Record is deleted"); } } } <file_sep>/database/Dc.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Configuration; using MySql.Data.MySqlClient; //this is dot net project namespace database { public delegate void DBdelegate(); class Dc { public event DBdelegate Add; public event DBdelegate Delete; MySqlConnection CN; MySqlCommand CMD; public void insert() { CN = new MySqlConnection(ConfigurationManager.ConnectionStrings["InfowayMySqlConStr"].ConnectionString); Console.WriteLine("Enter Emp ID"); int empid = int.Parse(Console.ReadLine()); Console.WriteLine("Enter Emp Name"); String empname = Console.ReadLine(); Console.WriteLine("enter city"); String empcity = Console.ReadLine(); CN.Open(); CMD = new MySqlCommand("insert into emp1 values(@empid,@empname,@empcity)", CN); CMD.CommandType = CommandType.Text; CMD.Parameters.AddWithValue("empid", empid); CMD.Parameters.AddWithValue("empname", empname); CMD.Parameters.AddWithValue("empcity", empcity); int i = CMD.ExecuteNonQuery(); Console.WriteLine("Commands executed! Total rows affected are " +i); Console.WriteLine("Done!"); if (i == 1) { if (Add!=null) { Add(); } } Console.ReadLine(); Console.Clear(); CN.Close(); } public void view() { CN = new MySqlConnection(ConfigurationManager. ConnectionStrings["InfowayMySqlConStr"].ConnectionString); CN.Open(); CMD = new MySqlCommand("select * from emp1 ", CN); CMD.CommandType = CommandType.Text; using (MySqlDataReader reader = CMD.ExecuteReader()) { Console.WriteLine("Emp Id\t\t\t Name \t\t\t City\t"); while (reader.Read()) { Console.WriteLine(String.Format ("{0} \t\t\t | {1} \t\t\t |{2}\t", reader[0], reader[1], reader[2])); } } Console.WriteLine("Commands executed! Total rows affected are " + CMD.ExecuteNonQuery()); Console.WriteLine("Done!"); Console.ReadLine(); Console.Clear(); CN.Close(); } public void sort() { CN = new MySqlConnection(ConfigurationManager. ConnectionStrings["InfowayMySqlConStr"].ConnectionString); CN.Open(); CMD = new MySqlCommand("select * from emp1 order by empname ", CN); CMD.CommandType = CommandType.Text; using (MySqlDataReader reader = CMD.ExecuteReader()) { Console.WriteLine("Emp Id\t\t\t Name \t\t\t City\t"); while (reader.Read()) { Console.WriteLine(String.Format ("{0} \t\t\t | {1} \t\t\t |{2}\t", reader[0], reader[1], reader[2])); } } Console.WriteLine("Commands executed! Total rows affected are " + CMD.ExecuteNonQuery()); Console.WriteLine("Done!"); Console.ReadLine(); Console.Clear(); CN.Close(); } public void search() { CN = new MySqlConnection (ConfigurationManager.ConnectionStrings["InfowayMySqlConStr"]. ConnectionString); CN.Open(); Console.WriteLine("Enter Emp ID"); int empid = int.Parse(Console.ReadLine()); CMD = new MySqlCommand("select * from emp1 where " + "empid1=@empid", CN); CMD.Parameters.AddWithValue("empid", empid); CMD.CommandType = CommandType.Text; using (MySqlDataReader reader = CMD.ExecuteReader()) { Console.WriteLine("Emp Id\t\t\t Name \t\t\t City\t"); while (reader.Read()) { Console.WriteLine(String.Format("{0} \t\t\t | {1} \t\t\t |{2}\t", reader[0], reader[1], reader[2])); } } Console.WriteLine("Commands executed! Total rows affected are " + CMD.ExecuteNonQuery()); Console.WriteLine("Done!"); Console.ReadLine(); Console.Clear(); CN.Close(); } public void delete() { CN = new MySqlConnection(ConfigurationManager.ConnectionStrings["InfowayMySqlConStr"].ConnectionString); CN.Open(); Console.WriteLine("Enter Emp ID You Want To delete"); int empid = int.Parse(Console.ReadLine()); CMD = new MySqlCommand("Delete from emp1 where empid1=@empid", CN); CMD.Parameters.AddWithValue("empid", empid); int i = CMD.ExecuteNonQuery(); Console.WriteLine("Commands executed! Total rows affected are " +i); Console.WriteLine("Done!"); if (i == 1) { if (Delete!= null) { Delete(); } } Console.ReadLine(); Console.Clear(); CN.Close(); } } }
7e43b862b76eac81d8b94bdc847221678020f3ce
[ "C#" ]
2
C#
AkshadaRK/Dotnet
4c82df1a4a23f83a8347321558e2ffee099e73cb
4e19615f867bb6b3604aec6a4799885e8c31ac11
refs/heads/master
<repo_name>svaarala/minisphere<file_sep>/src/debugger/source.h #ifndef SSJ__SOURCE_H__INCLUDED #define SSJ__SOURCE_H__INCLUDED typedef struct source source_t; source_t* source_new (const char* text); void source_free (source_t* src); int source_cloc (const source_t* src); const char* source_get_line (const source_t* src, int line_index); void source_print (const source_t* src, int lineno, int num_lines, int active_lineno); #endif // SSJ__SOURCE_H__INCLUDED <file_sep>/src/engine/utility.c #include "minisphere.h" #include "api.h" #include "utility.h" const path_t* enginepath(void) { static path_t* retval = NULL; ALLEGRO_PATH* al_path; if (retval == NULL) { al_path = al_get_standard_path(ALLEGRO_RESOURCES_PATH); retval = path_new_dir(al_path_cstr(al_path, '/')); al_destroy_path(al_path); } return retval; } const path_t* homepath(void) { static path_t* retval = NULL; ALLEGRO_PATH* al_path; if (retval == NULL) { al_path = al_get_standard_path(ALLEGRO_USER_DOCUMENTS_PATH); retval = path_new_dir(al_path_cstr(al_path, '/')); al_destroy_path(al_path); } path_mkdir(retval); return retval; } const char* systempath(const char* filename) { static char retval[SPHERE_PATH_MAX]; retval[SPHERE_PATH_MAX - 1] = '\0'; snprintf(retval, SPHERE_PATH_MAX - 1, "#/%s", filename); return retval; } bool is_cpu_little_endian(void) { uint8_t lead_byte; uint16_t value; value = 812; lead_byte = *(uint8_t*)&value; return lead_byte == 44; } lstring_t* read_lstring(sfs_file_t* file, bool trim_null) { long file_pos; uint16_t length; file_pos = sfs_ftell(file); if (sfs_fread(&length, 2, 1, file) != 1) goto on_error; return read_lstring_raw(file, length, trim_null); on_error: sfs_fseek(file, file_pos, SEEK_CUR); return NULL; } lstring_t* read_lstring_raw(sfs_file_t* file, size_t length, bool trim_null) { char* buffer = NULL; long file_pos; lstring_t* string; file_pos = sfs_ftell(file); if (!(buffer = malloc(length + 1))) goto on_error; if (sfs_fread(buffer, 1, length, file) != length) goto on_error; buffer[length] = '\0'; if (trim_null) length = strchr(buffer, '\0') - buffer; string = lstr_from_buf(buffer, length); free(buffer); return string; on_error: free(buffer); sfs_fseek(file, file_pos, SEEK_CUR); return NULL; } char* strnewf(const char* fmt, ...) { va_list ap, apc; char* buffer; int buf_size; va_start(ap, fmt); va_copy(apc, ap); buf_size = vsnprintf(NULL, 0, fmt, apc) + 1; va_end(apc); buffer = malloc(buf_size); va_copy(apc, ap); vsnprintf(buffer, buf_size, fmt, apc); va_end(apc); va_end(ap); return buffer; } void duk_push_lstring_t(duk_context* ctx, const lstring_t* string) { duk_push_lstring(ctx, lstr_cstr(string), lstr_len(string)); } lstring_t* duk_require_lstring_t(duk_context* ctx, duk_idx_t index) { const char* buffer; size_t length; buffer = duk_require_lstring(ctx, index, &length); return lstr_from_buf(buffer, length); } const char* duk_require_path(duk_context* ctx, duk_idx_t index, const char* origin_name, bool legacy) { static int s_index = 0; static path_t* s_paths[10]; const char* pathname; path_t* path; pathname = duk_require_string(ctx, index); path = make_sfs_path(pathname, origin_name, legacy); if ((path_num_hops(path) > 0 && path_hop_cmp(path, 0, "..")) || path_is_rooted(path)) { duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "FS sandbox violation (`%s`)", pathname); } if (s_paths[s_index] != NULL) path_free(s_paths[s_index]); s_paths[s_index] = path; s_index = (s_index + 1) % 10; return path_cstr(path); } <file_sep>/src/engine/obsmap.h #ifndef MINISPHERE__OBSMAP_H__INCLUDED #define MINISPHERE__OBSMAP_H__INCLUDED typedef struct obsmap obsmap_t; obsmap_t* obsmap_new (void); void obsmap_free (obsmap_t* obsmap); bool obsmap_add_line (obsmap_t* obsmap, rect_t line); bool obsmap_test_line (const obsmap_t* obsmap, rect_t line); bool obsmap_test_rect (const obsmap_t* obsmap, rect_t rect); #endif // MINISPHERE__OBSMAP_H__INCLUDED <file_sep>/src/engine/audialis.h #ifndef MINISPHERE__AUDIALIS_H__INCLUDED #define MINISPHERE__AUDIALIS_H__INCLUDED typedef struct mixer mixer_t; typedef struct sound sound_t; typedef struct stream stream_t; void initialize_audialis (void); void shutdown_audialis (void); void update_audialis (void); mixer_t* get_default_mixer (void); mixer_t* mixer_new (int frequency, int bits, int channels); mixer_t* mixer_ref (mixer_t* mixer); void mixer_free (mixer_t* mixer); float mixer_get_gain (mixer_t* mixer); void mixer_set_gain (mixer_t* mixer, float gain); sound_t* sound_load (const char* path, mixer_t* mixer); sound_t* sound_ref (sound_t* sound); void sound_free (sound_t* sound); double sound_len (sound_t* sound); bool sound_playing (sound_t* sound); double sound_tell (sound_t* sound); float sound_get_gain (sound_t* sound); bool sound_get_looping (sound_t* sound); mixer_t* sound_get_mixer (sound_t* sound); float sound_get_pan (sound_t* sound); float sound_get_pitch (sound_t* sound); void sound_set_gain (sound_t* sound, float gain); void sound_set_looping (sound_t* sound, bool is_looping); void sound_set_mixer (sound_t* sound, mixer_t* mixer); void sound_set_pan (sound_t* sound, float pan); void sound_set_pitch (sound_t* sound, float pitch); void sound_play (sound_t* sound); bool sound_reload (sound_t* sound); void sound_seek (sound_t* sound, double position); void sound_stop (sound_t* sound, bool rewind); stream_t* stream_new (int frequency, int bits, int channels); stream_t* stream_ref (stream_t* stream); void stream_free (stream_t* stream); bool stream_playing (const stream_t* stream); mixer_t* stream_get_mixer (stream_t* stream); void stream_set_mixer (stream_t* stream, mixer_t* mixer); void stream_buffer (stream_t* stream, const void* data, size_t size); void stream_pause (stream_t* stream); void stream_play (stream_t* stream); void stream_stop (stream_t* stream); void init_audialis_api (void); #endif // MINISPHERE__AUDIALIS_H__INCLUDED <file_sep>/src/engine/bytearray.h #ifndef MINISPHERE__BYTEARRAY_H__INCLUDED #define MINISPHERE__BYTEARRAY_H__INCLUDED typedef struct bytearray bytearray_t; bytearray_t* new_bytearray (int size); bytearray_t* bytearray_from_buffer (const void* buffer, int size); bytearray_t* bytearray_from_lstring (const lstring_t* string); bytearray_t* ref_bytearray (bytearray_t* array); void free_bytearray (bytearray_t* array); uint8_t get_byte (bytearray_t* array, int index); uint8_t* get_bytearray_buffer (bytearray_t* array); int get_bytearray_size (bytearray_t* array); void set_byte (bytearray_t* array, int index, uint8_t value); bytearray_t* concat_bytearrays (bytearray_t* array1, bytearray_t* array2); bytearray_t* deflate_bytearray (bytearray_t* array, int level); bytearray_t* inflate_bytearray (bytearray_t* array, int max_size); bool resize_bytearray (bytearray_t* array, int new_size); bytearray_t* slice_bytearray (bytearray_t* array, int start, int length); void init_bytearray_api (void); void duk_push_sphere_bytearray (duk_context* ctx, bytearray_t* array); bytearray_t* duk_require_sphere_bytearray (duk_context* ctx, duk_idx_t index); #endif // MINISPHERE__BYTEARRAY_H__INCLUDED <file_sep>/src/engine/windowstyle.c #include "minisphere.h" #include "api.h" #include "color.h" #include "image.h" #include "windowstyle.h" static duk_ret_t js_GetSystemWindowStyle (duk_context* ctx); static duk_ret_t js_LoadWindowStyle (duk_context* ctx); static duk_ret_t js_new_WindowStyle (duk_context* ctx); static duk_ret_t js_WindowStyle_finalize (duk_context* ctx); static duk_ret_t js_WindowStyle_get_colorMask (duk_context* ctx); static duk_ret_t js_WindowStyle_set_colorMask (duk_context* ctx); static duk_ret_t js_WindowStyle_toString (duk_context* ctx); static duk_ret_t js_WindowStyle_drawWindow (duk_context* ctx); static windowstyle_t* s_sys_winstyle = NULL; enum wstyle_bg_type { WSTYLE_BG_TILE, WSTYLE_BG_STRETCH, WSTYLE_BG_GRADIENT, WSTYLE_BG_TILE_GRADIENT, WSTYLE_BG_STRETCH_GRADIENT }; struct windowstyle { int refcount; int bg_style; color_t gradient[4]; image_t* images[9]; }; #pragma pack(push, 1) struct rws_rgba { uint8_t r, g, b, a; }; struct rws_header { uint8_t signature[4]; int16_t version; uint8_t edge_w_h; uint8_t background_mode; struct rws_rgba corner_colors[4]; uint8_t edge_offsets[4]; uint8_t reserved[36]; }; #pragma pack(pop) windowstyle_t* load_windowstyle(const char* filename) { sfs_file_t* file; image_t* image; struct rws_header rws; int16_t w, h; windowstyle_t* winstyle = NULL; int i; if (!(file = sfs_fopen(g_fs, filename, NULL, "rb"))) goto on_error; if ((winstyle = calloc(1, sizeof(windowstyle_t))) == NULL) goto on_error; if (sfs_fread(&rws, sizeof(struct rws_header), 1, file) != 1) goto on_error; if (memcmp(rws.signature, ".rws", 4) != 0) goto on_error; switch (rws.version) { case 1: for (i = 0; i < 9; ++i) { if (!(image = read_image(file, rws.edge_w_h, rws.edge_w_h))) goto on_error; winstyle->images[i] = image; } break; case 2: for (i = 0; i < 9; ++i) { if (sfs_fread(&w, 2, 1, file) != 1 || sfs_fread(&h, 2, 1, file) != 1) goto on_error; if (!(image = read_image(file, w, h))) goto on_error; winstyle->images[i] = image; } break; default: // invalid version number goto on_error; } sfs_fclose(file); winstyle->bg_style = rws.background_mode; for (i = 0; i < 4; ++i) { winstyle->gradient[i] = color_new( rws.corner_colors[i].r, rws.corner_colors[i].g, rws.corner_colors[i].b, rws.corner_colors[i].a); } return ref_windowstyle(winstyle); on_error: if (file != NULL) sfs_fclose(file); if (winstyle != NULL) { for (i = 0; i < 9; ++i) free_image(winstyle->images[i]); free(winstyle); } return NULL; } windowstyle_t* ref_windowstyle(windowstyle_t* winstyle) { ++winstyle->refcount; return winstyle; } void free_windowstyle(windowstyle_t* winstyle) { int i; if (winstyle == NULL || --winstyle->refcount > 0) return; for (i = 0; i < 9; ++i) { free_image(winstyle->images[i]); } free(winstyle); } void draw_window(windowstyle_t* winstyle, color_t mask, int x, int y, int width, int height) { color_t gradient[4]; int w[9], h[9]; int i; // 0 - upper left // 1 - top // 2 - upper right // 3 - right // 4 - lower right // 5 - bottom // 6 - lower left // 7 - left // 8 - background for (i = 0; i < 9; ++i) { w[i] = get_image_width(winstyle->images[i]); h[i] = get_image_height(winstyle->images[i]); } for (i = 0; i < 4; ++i) { gradient[i].r = mask.r * winstyle->gradient[i].r / 255; gradient[i].g = mask.g * winstyle->gradient[i].g / 255; gradient[i].b = mask.b * winstyle->gradient[i].b / 255; gradient[i].alpha = mask.alpha * winstyle->gradient[i].alpha / 255; } ALLEGRO_VERTEX verts[] = { { x, y, 0, 0, 0, nativecolor(gradient[0]) }, { x + width, y, 0, 0, 0, nativecolor(gradient[1]) }, { x, y + height, 0, 0, 0, nativecolor(gradient[2]) }, { x + width, y + height, 0, 0, 0, nativecolor(gradient[3]) }, }; switch (winstyle->bg_style) { case WSTYLE_BG_TILE: draw_image_tiled_masked(winstyle->images[8], mask, x, y, width, height); break; case WSTYLE_BG_STRETCH: draw_image_scaled_masked(winstyle->images[8], mask, x, y, width, height); break; case WSTYLE_BG_GRADIENT: al_draw_prim(verts, NULL, NULL, 0, 4, ALLEGRO_PRIM_TRIANGLE_STRIP); break; case WSTYLE_BG_TILE_GRADIENT: draw_image_tiled_masked(winstyle->images[8], mask, x, y, width, height); al_draw_prim(verts, NULL, NULL, 0, 4, ALLEGRO_PRIM_TRIANGLE_STRIP); break; case WSTYLE_BG_STRETCH_GRADIENT: draw_image_scaled_masked(winstyle->images[8], mask, x, y, width, height); al_draw_prim(verts, NULL, NULL, 0, 4, ALLEGRO_PRIM_TRIANGLE_STRIP); break; } draw_image_masked(winstyle->images[0], mask, x - w[0], y - h[0]); draw_image_masked(winstyle->images[2], mask, x + width, y - h[2]); draw_image_masked(winstyle->images[4], mask, x + width, y + height); draw_image_masked(winstyle->images[6], mask, x - w[6], y + height); draw_image_tiled_masked(winstyle->images[1], mask, x, y - h[1], width, h[1]); draw_image_tiled_masked(winstyle->images[3], mask, x + width, y, w[3], height); draw_image_tiled_masked(winstyle->images[5], mask, x, y + height, width, h[5]); draw_image_tiled_masked(winstyle->images[7], mask, x - w[7], y, w[7], height); } void init_windowstyle_api(void) { const char* filename; // load system window style if (g_sys_conf != NULL) { filename = kev_read_string(g_sys_conf, "WindowStyle", "system.rws"); s_sys_winstyle = load_windowstyle(systempath(filename)); } // WindowStyle API functions api_register_method(g_duk, NULL, "GetSystemWindowStyle", js_GetSystemWindowStyle); // WindowStyle object api_register_method(g_duk, NULL, "LoadWindowStyle", js_LoadWindowStyle); api_register_ctor(g_duk, "WindowStyle", js_new_WindowStyle, js_WindowStyle_finalize); api_register_prop(g_duk, "WindowStyle", "colorMask", js_WindowStyle_get_colorMask, js_WindowStyle_set_colorMask); api_register_method(g_duk, "WindowStyle", "toString", js_WindowStyle_toString); api_register_method(g_duk, "WindowStyle", "getColorMask", js_WindowStyle_get_colorMask); api_register_method(g_duk, "WindowStyle", "setColorMask", js_WindowStyle_set_colorMask); api_register_method(g_duk, "WindowStyle", "drawWindow", js_WindowStyle_drawWindow); } void duk_push_sphere_windowstyle(duk_context* ctx, windowstyle_t* winstyle) { duk_push_sphere_obj(ctx, "WindowStyle", ref_windowstyle(winstyle)); duk_push_sphere_color(ctx, color_new(255, 255, 255, 255)); duk_put_prop_string(ctx, -2, "\xFF" "color_mask"); } static duk_ret_t js_GetSystemWindowStyle(duk_context* ctx) { if (s_sys_winstyle == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetSystemWindowStyle(): missing system window style"); duk_push_sphere_windowstyle(ctx, s_sys_winstyle); return 1; } static duk_ret_t js_LoadWindowStyle(duk_context* ctx) { const char* filename; windowstyle_t* winstyle; filename = duk_require_path(ctx, 0, "windowstyles", true); if (!(winstyle = load_windowstyle(filename))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "LoadWindowStyle(): unable to load windowstyle file `%s`", filename); duk_push_sphere_windowstyle(ctx, winstyle); free_windowstyle(winstyle); return 1; } static duk_ret_t js_new_WindowStyle(duk_context* ctx) { const char* filename; windowstyle_t* winstyle; filename = duk_require_path(ctx, 0, NULL, false); if (!(winstyle = load_windowstyle(filename))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "WindowStyle(): unable to load windowstyle file `%s`", filename); duk_push_sphere_windowstyle(ctx, winstyle); free_windowstyle(winstyle); return 1; } static duk_ret_t js_WindowStyle_finalize(duk_context* ctx) { windowstyle_t* winstyle; winstyle = duk_require_sphere_obj(ctx, 0, "WindowStyle"); free_windowstyle(winstyle); return 0; } static duk_ret_t js_WindowStyle_toString(duk_context* ctx) { duk_push_string(ctx, "[object windowstyle]"); return 1; } static duk_ret_t js_WindowStyle_get_colorMask(duk_context* ctx) { duk_push_this(ctx); duk_require_sphere_obj(ctx, -1, "WindowStyle"); duk_get_prop_string(ctx, -2, "\xFF" "color_mask"); duk_remove(ctx, -2); return 1; } static duk_ret_t js_WindowStyle_set_colorMask(duk_context* ctx) { color_t mask = duk_require_sphere_color(ctx, 0); duk_push_this(ctx); duk_require_sphere_obj(ctx, -1, "WindowStyle"); duk_push_sphere_color(ctx, mask); duk_put_prop_string(ctx, -2, "\xFF" "color_mask"); duk_pop(ctx); return 0; } static duk_ret_t js_WindowStyle_drawWindow(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int w = duk_require_int(ctx, 2); int h = duk_require_int(ctx, 3); color_t mask; windowstyle_t* winstyle; duk_push_this(ctx); winstyle = duk_require_sphere_obj(ctx, -1, "WindowStyle"); duk_get_prop_string(ctx, -1, "\xFF" "color_mask"); mask = duk_require_sphere_color(ctx, -1); duk_pop(ctx); duk_pop(ctx); draw_window(winstyle, mask, x, y, w, h); return 0; } <file_sep>/src/engine/spriteset.h #ifndef MINISPHERE__SPRITESET_H__INCLUDED #define MINISPHERE__SPRITESET_H__INCLUDED #include "image.h" typedef struct spriteset spriteset_t; typedef struct spriteset_base spriteset_base_t; typedef struct spriteset_pose spriteset_pose_t; typedef struct spriteset_frame spriteset_frame_t; struct spriteset_frame { int image_idx; int delay; }; struct spriteset_pose { lstring_t* name; int num_frames; spriteset_frame_t *frames; }; struct spriteset { int refcount; unsigned int id; rect_t base; char* filename; int num_images; int num_poses; image_t* *images; spriteset_pose_t *poses; }; void initialize_spritesets (void); void shutdown_spritesets (void); spriteset_t* clone_spriteset (const spriteset_t* spriteset); spriteset_t* load_spriteset (const char* filename); spriteset_t* ref_spriteset (spriteset_t* spriteset); void free_spriteset (spriteset_t* spriteset); rect_t get_sprite_base (const spriteset_t* spriteset); int get_sprite_frame_delay (const spriteset_t* spriteset, const char* pose_name, int frame_index); void get_sprite_size (const spriteset_t* spriteset, int* out_width, int* out_height); void get_spriteset_info (const spriteset_t* spriteset, int* out_num_images, int* out_num_poses); bool get_spriteset_pose_info (const spriteset_t* spriteset, const char* pose_name, int* out_num_frames); void draw_sprite (const spriteset_t* spriteset, color_t mask, bool is_flipped, double theta, double scale_x, double scale_y, const char* pose_name, float x, float y, int frame_index); void init_spriteset_api (duk_context* ctx); void duk_push_sphere_spriteset (duk_context* ctx, spriteset_t* spriteset); #endif // MINISPHERE__SPRITESET_H__INCLUDED <file_sep>/src/compiler/readme.md Cell v2.0-WIP ============= Cell is a scriptable compiler for Sphere games. Like minisphere, it uses JavaScript to control the compilation process and is based on Duktape. Command Line Options -------------------- * `--version`: Prints version information and exits. * `--make-package`, `-p`: Creates a Sphere SPK package in the output directory from the compiled game. * `--out <pathname>`: Sets the directory where the game will be compiled. If this is a relative path, it is relative to the current directory. The default output directory is "dist". <file_sep>/src/debugger/message.c #include "ssj.h" #include "message.h" #include "dvalue.h" struct message { message_tag_t tag; vector_t* dvalues; }; message_t* message_new(message_tag_t tag) { message_t* o; o = calloc(1, sizeof(message_t)); o->dvalues = vector_new(sizeof(dvalue_t*)); o->tag = tag; return o; } void message_free(message_t* o) { iter_t iter; if (o== NULL) return; iter = vector_enum(o->dvalues); while (vector_next(&iter)) { dvalue_t* dvalue = *(dvalue_t**)iter.ptr; dvalue_free(dvalue); } vector_free(o->dvalues); free(o); } int message_len(const message_t* o) { return (int)vector_len(o->dvalues); } message_tag_t message_tag(const message_t* o) { return o->tag; } dvalue_tag_t message_get_atom_tag(const message_t* o, int index) { dvalue_t* dvalue; dvalue = *(dvalue_t**)vector_get(o->dvalues, index); return dvalue_tag(dvalue); } const dvalue_t* message_get_dvalue(const message_t* o, int index) { return *(dvalue_t**)vector_get(o->dvalues, index); } double message_get_float(const message_t* o, int index) { dvalue_t* dvalue; dvalue = *(dvalue_t**)vector_get(o->dvalues, index); return dvalue_as_float(dvalue); } int message_get_int(const message_t* o, int index) { dvalue_t* dvalue; dvalue = *(dvalue_t**)vector_get(o->dvalues, index); return dvalue_as_int(dvalue); } const char* message_get_string(const message_t* o, int index) { dvalue_t* dvalue; dvalue = *(dvalue_t**)vector_get(o->dvalues, index); return dvalue_as_cstr(dvalue); } void message_add_dvalue(message_t* o, const dvalue_t* dvalue) { dvalue_t* dup; dup = dvalue_dup(dvalue); vector_push(o->dvalues, &dup); } void message_add_float(message_t* o, double value) { dvalue_t* dvalue; dvalue = dvalue_new_float(value); vector_push(o->dvalues, &dvalue); } void message_add_heapptr(message_t* o, remote_ptr_t heapptr) { dvalue_t* dvalue; dvalue = dvalue_new_heapptr(heapptr); vector_push(o->dvalues, &dvalue); } void message_add_int(message_t* o, int value) { dvalue_t* dvalue; dvalue = dvalue_new_int(value); vector_push(o->dvalues, &dvalue); } void message_add_string(message_t* o, const char* value) { dvalue_t* dvalue; dvalue = dvalue_new_string(value); vector_push(o->dvalues, &dvalue); } message_t* message_recv(socket_t* socket) { message_t* obj; dvalue_t* dvalue; iter_t iter; obj = calloc(1, sizeof(message_t)); obj->dvalues = vector_new(sizeof(dvalue_t*)); if (!(dvalue = dvalue_recv(socket))) goto lost_dvalue; obj->tag = dvalue_tag(dvalue) == DVALUE_REQ ? MESSAGE_REQ : dvalue_tag(dvalue) == DVALUE_REP ? MESSAGE_REP : dvalue_tag(dvalue) == DVALUE_ERR ? MESSAGE_ERR : dvalue_tag(dvalue) == DVALUE_NFY ? MESSAGE_NFY : MESSAGE_UNKNOWN; dvalue_free(dvalue); if (!(dvalue = dvalue_recv(socket))) goto lost_dvalue; while (dvalue_tag(dvalue) != DVALUE_EOM) { vector_push(obj->dvalues, &dvalue); if (!(dvalue = dvalue_recv(socket))) goto lost_dvalue; } dvalue_free(dvalue); return obj; lost_dvalue: if (obj != NULL) { iter = vector_enum(obj->dvalues); while (dvalue = vector_next(&iter)) dvalue_free(dvalue); vector_free(obj->dvalues); free(obj); } return NULL; } bool message_send(const message_t* o, socket_t* socket) { dvalue_t* dvalue; dvalue_tag_t lead_tag; iter_t iter; dvalue_t* *p_dvalue; lead_tag = o->tag == MESSAGE_REQ ? DVALUE_REQ : o->tag == MESSAGE_REP ? DVALUE_REP : o->tag == MESSAGE_ERR ? DVALUE_ERR : o->tag == MESSAGE_NFY ? DVALUE_NFY : DVALUE_EOM; dvalue = dvalue_new(lead_tag); dvalue_send(dvalue, socket); dvalue_free(dvalue); iter = vector_enum(o->dvalues); while (p_dvalue = vector_next(&iter)) dvalue_send(*p_dvalue, socket); dvalue = dvalue_new(DVALUE_EOM); dvalue_send(dvalue, socket); dvalue_free(dvalue); return socket_is_live(socket); } <file_sep>/src/engine/transpiler.h #ifndef MINISPHERE__TRANSPILER_H__INCLUDED #define MINISPHERE__TRANSPILER_H__INCLUDED #include "spherefs.h" void initialize_transpiler (void); void shutdown_transpiler (void); bool transpile_to_js (lstring_t** p_source, const char* filename); #endif // MINISPHERE__TRANSPILER_H__INCLUDED <file_sep>/src/engine/bytearray.c #include "minisphere.h" #include "api.h" #include "bytearray.h" static duk_ret_t js_CreateStringFromByteArray (duk_context* ctx); static duk_ret_t js_HashByteArray (duk_context* ctx); static duk_ret_t js_CreateByteArray (duk_context* ctx); static duk_ret_t js_CreateByteArrayFromString (duk_context* ctx); static duk_ret_t js_DeflateByteArray (duk_context* ctx); static duk_ret_t js_InflateByteArray (duk_context* ctx); static duk_ret_t js_new_ByteArray (duk_context* ctx); static duk_ret_t js_ByteArray_finalize (duk_context* ctx); static duk_ret_t js_ByteArray_get_length (duk_context* ctx); static duk_ret_t js_ByteArray_toString (duk_context* ctx); static duk_ret_t js_ByteArray_getProp (duk_context* ctx); static duk_ret_t js_ByteArray_setProp (duk_context* ctx); static duk_ret_t js_ByteArray_concat (duk_context* ctx); static duk_ret_t js_ByteArray_deflate (duk_context* ctx); static duk_ret_t js_ByteArray_inflate (duk_context* ctx); static duk_ret_t js_ByteArray_resize (duk_context* ctx); static duk_ret_t js_ByteArray_slice (duk_context* ctx); struct bytearray { int refcount; unsigned int id; uint8_t* buffer; int size; }; static unsigned int s_next_array_id = 0; bytearray_t* new_bytearray(int size) { bytearray_t* array; console_log(3, "creating new bytearray #%u size %i bytes", size, s_next_array_id); array = calloc(1, sizeof(bytearray_t)); if (!(array->buffer = calloc(size, 1))) goto on_error; array->size = size; array->id = s_next_array_id++; return ref_bytearray(array); on_error: free(array); return NULL; } bytearray_t* bytearray_from_buffer(const void* buffer, int size) { bytearray_t* array; console_log(3, "creating bytearray from %i-byte buffer", size); if (!(array = new_bytearray(size))) return NULL; memcpy(array->buffer, buffer, size); return array; } bytearray_t* bytearray_from_lstring(const lstring_t* string) { bytearray_t* array; console_log(3, "creating bytearray from %u-byte string", lstr_len(string)); if (lstr_len(string) <= 65) // log short strings only console_log(4, " String: \"%s\"", lstr_cstr(string)); if (lstr_len(string) > INT_MAX) return NULL; if (!(array = new_bytearray((int)lstr_len(string)))) return NULL; memcpy(array->buffer, lstr_cstr(string), lstr_len(string)); return array; } bytearray_t* ref_bytearray(bytearray_t* array) { ++array->refcount; return array; } void free_bytearray(bytearray_t* array) { if (array == NULL || --array->refcount > 0) return; console_log(3, "disposing bytearray #%u no longer in use", array->id); free(array->buffer); free(array); } uint8_t get_byte(bytearray_t* array, int index) { return array->buffer[index]; } uint8_t* get_bytearray_buffer(bytearray_t* array) { return array->buffer; } int get_bytearray_size(bytearray_t* array) { return array->size; } void set_byte(bytearray_t* array, int index, uint8_t value) { array->buffer[index] = value; } bytearray_t* concat_bytearrays(bytearray_t* array1, bytearray_t* array2) { bytearray_t* new_array; int new_size; console_log(3, "concatenating ByteArrays %u and %u", s_next_array_id, array1->id, array2->id); new_size = array1->size + array2->size; if (!(new_array = new_bytearray(new_size))) return NULL; memcpy(new_array->buffer, array1->buffer, array1->size); memcpy(new_array->buffer + array1->size, array2->buffer, array2->size); return new_array; } bytearray_t* deflate_bytearray(bytearray_t* array, int level) { static const int CHUNK_SIZE = 65536; uint8_t* buffer = NULL; int flush_flag; int result; bytearray_t* new_array; uint8_t* new_buffer; int n_chunks = 0; size_t out_size; z_stream z; console_log(3, "deflating bytearray #%u from source bytearray #%u", s_next_array_id, array->id); memset(&z, 0, sizeof(z_stream)); z.next_in = (Bytef*)array->buffer; z.avail_in = array->size; if (deflateInit(&z, level) != Z_OK) goto on_error; flush_flag = Z_NO_FLUSH; do { if (z.avail_out == 0) { if (!(new_buffer = realloc(buffer, ++n_chunks * CHUNK_SIZE))) // resize buffer goto on_error; z.next_out = new_buffer + (n_chunks - 1) * CHUNK_SIZE; z.avail_out = CHUNK_SIZE; buffer = new_buffer; } result = deflate(&z, flush_flag); if (z.avail_out > 0) flush_flag = Z_FINISH; } while (result != Z_STREAM_END); if ((out_size = CHUNK_SIZE * n_chunks - z.avail_out) > INT_MAX) goto on_error; deflateEnd(&z); // create a byte array from the deflated data new_array = calloc(1, sizeof(bytearray_t)); new_array->id = s_next_array_id++; new_array->buffer = buffer; new_array->size = (int)out_size; return ref_bytearray(new_array); on_error: deflateEnd(&z); free(buffer); return NULL; } bytearray_t* inflate_bytearray(bytearray_t* array, int max_size) { uint8_t* buffer = NULL; size_t chunk_size; int flush_flag; int result; bytearray_t* new_array; uint8_t* new_buffer; int n_chunks = 0; size_t out_size; z_stream z; console_log(3, "inflating bytearray #%u from source bytearray #%u", s_next_array_id, array->id); memset(&z, 0, sizeof(z_stream)); z.next_in = (Bytef*)array->buffer; z.avail_in = array->size; if (inflateInit(&z) != Z_OK) goto on_error; flush_flag = Z_NO_FLUSH; chunk_size = max_size != 0 ? max_size : 65536; do { if (z.avail_out == 0) { if (buffer != NULL && max_size != 0) goto on_error; if (!(new_buffer = realloc(buffer, ++n_chunks * chunk_size))) // resize buffer goto on_error; z.next_out = new_buffer + (n_chunks - 1) * chunk_size; z.avail_out = (uInt)chunk_size; buffer = new_buffer; } if ((result = inflate(&z, flush_flag)) == Z_DATA_ERROR) goto on_error; if (z.avail_out > 0) flush_flag = Z_FINISH; } while (result != Z_STREAM_END); if ((out_size = chunk_size * n_chunks - z.avail_out) > INT_MAX) goto on_error; inflateEnd(&z); // create a byte array from the deflated data new_array = calloc(1, sizeof(bytearray_t)); new_array->id = s_next_array_id++; new_array->buffer = buffer; new_array->size = (int)out_size; return ref_bytearray(new_array); on_error: inflateEnd(&z); free(buffer); return NULL; } bool resize_bytearray(bytearray_t* array, int new_size) { uint8_t* new_buffer; // resize buffer, filling any new slots with zero bytes if (!(new_buffer = realloc(array->buffer, new_size))) return false; if (new_size > array->size) memset(new_buffer + array->size, 0, new_size - array->size); array->buffer = new_buffer; array->size = new_size; return true; } bytearray_t* slice_bytearray(bytearray_t* array, int start, int length) { bytearray_t* new_array; console_log(3, "copying %i-byte slice from bytearray #%u", length, array->id); if (!(new_array = new_bytearray(length))) return NULL; memcpy(new_array->buffer, array->buffer + start, length); return new_array; } void init_bytearray_api(void) { // core ByteArray API api_register_method(g_duk, NULL, "CreateStringFromByteArray", js_CreateStringFromByteArray); api_register_method(g_duk, NULL, "HashByteArray", js_HashByteArray); // ByteArray object api_register_method(g_duk, NULL, "CreateByteArray", js_CreateByteArray); api_register_method(g_duk, NULL, "CreateByteArrayFromString", js_CreateByteArrayFromString); api_register_ctor(g_duk, "ByteArray", js_new_ByteArray, js_ByteArray_finalize); api_register_prop(g_duk, "ByteArray", "length", js_ByteArray_get_length, NULL); api_register_prop(g_duk, "ByteArray", "size", js_ByteArray_get_length, NULL); api_register_method(g_duk, "ByteArray", "toString", js_ByteArray_toString); api_register_method(g_duk, "ByteArray", "concat", js_ByteArray_concat); api_register_method(g_duk, "ByteArray", "deflate", js_ByteArray_deflate); api_register_method(g_duk, "ByteArray", "inflate", js_ByteArray_inflate); api_register_method(g_duk, "ByteArray", "slice", js_ByteArray_slice); } void duk_push_sphere_bytearray(duk_context* ctx, bytearray_t* array) { duk_idx_t obj_index; duk_push_sphere_obj(ctx, "ByteArray", ref_bytearray(array)); obj_index = duk_normalize_index(ctx, -1); // return proxy object so we can catch array accesses duk_push_global_object(ctx); duk_get_prop_string(ctx, -1, "Proxy"); duk_dup(ctx, obj_index); duk_push_object(ctx); duk_push_c_function(ctx, js_ByteArray_getProp, DUK_VARARGS); duk_put_prop_string(ctx, -2, "get"); duk_push_c_function(ctx, js_ByteArray_setProp, DUK_VARARGS); duk_put_prop_string(ctx, -2, "set"); duk_new(ctx, 2); duk_get_prototype(ctx, obj_index); duk_set_prototype(ctx, -2); duk_remove(ctx, -2); duk_remove(ctx, -2); } bytearray_t* duk_require_sphere_bytearray(duk_context* ctx, duk_idx_t index) { return duk_require_sphere_obj(ctx, index, "ByteArray"); } static duk_ret_t js_CreateStringFromByteArray(duk_context* ctx) { bytearray_t* array = duk_require_sphere_bytearray(ctx, 0); duk_push_lstring(ctx, (char*)array->buffer, array->size); return 1; } static duk_ret_t js_DeflateByteArray(duk_context* ctx) { int n_args = duk_get_top(ctx); bytearray_t* array = duk_require_sphere_bytearray(ctx, 0); int level = n_args >= 2 ? duk_require_int(ctx, 1) : -1; bytearray_t* new_array; if ((level < 0 || level > 9) && n_args >= 2) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "DeflateByteArray(): compression level must be [0-9] (got: %i)", level); if (!(new_array = deflate_bytearray(array, level))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "DeflateByteArray(): unable to deflate source ByteArray"); duk_push_sphere_bytearray(ctx, new_array); return 1; } static duk_ret_t js_HashByteArray(duk_context* ctx) { duk_require_sphere_bytearray(ctx, 0); // TODO: implement byte array hashing duk_error_ni(ctx, -1, DUK_ERR_ERROR, "HashByteArray(): function is not implemented"); } static duk_ret_t js_InflateByteArray(duk_context* ctx) { int n_args = duk_get_top(ctx); bytearray_t* array = duk_require_sphere_bytearray(ctx, 0); int max_size = n_args >= 2 ? duk_require_int(ctx, 1) : 0; bytearray_t* new_array; if (max_size < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "InflateByteArray(): buffer size must not be negative (got: %d)", max_size); if (!(new_array = inflate_bytearray(array, max_size))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "InflateByteArray(): unable to inflate source ByteArray"); duk_push_sphere_bytearray(ctx, new_array); return 1; } static duk_ret_t js_CreateByteArray(duk_context* ctx) { duk_require_number(ctx, 0); js_new_ByteArray(ctx); return 1; } static duk_ret_t js_CreateByteArrayFromString(duk_context* ctx) { duk_require_string(ctx, 0); js_new_ByteArray(ctx); return 1; } static duk_ret_t js_new_ByteArray(duk_context* ctx) { bytearray_t* array; lstring_t* string; int size; if (duk_is_string(ctx, 0)) { string = duk_require_lstring_t(ctx, 0); if (lstr_len(string) > INT_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ByteArray(): input string is too long"); if (!(array = bytearray_from_lstring(string))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ByteArray(): unable to create byte array from string"); lstr_free(string); } else { size = duk_require_int(ctx, 0); if (size < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ByteArray(): size must not be negative (got: %d)", size); if (!(array = new_bytearray(size))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ByteArray(): unable to create new byte array"); } duk_push_sphere_bytearray(ctx, array); free_bytearray(array); return 1; } static duk_ret_t js_ByteArray_finalize(duk_context* ctx) { bytearray_t* array; array = duk_require_sphere_bytearray(ctx, 0); free_bytearray(array); return 0; } static duk_ret_t js_ByteArray_get_length(duk_context* ctx) { bytearray_t* array; duk_push_this(ctx); array = duk_require_sphere_bytearray(ctx, -1); duk_pop(ctx); duk_push_int(ctx, get_bytearray_size(array)); return 1; } static duk_ret_t js_ByteArray_toString(duk_context* ctx) { duk_push_string(ctx, "[object byte_array]"); return 1; } static duk_ret_t js_ByteArray_getProp(duk_context* ctx) { bytearray_t* array; int index; int size; array = duk_require_sphere_bytearray(ctx, 0); if (duk_is_number(ctx, 1)) { index = duk_to_int(ctx, 1); size = get_bytearray_size(array); if (index < 0 || index >= size) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ByteArray[]: index `%d` out of bounds (size: %i)", index, size); duk_push_uint(ctx, get_byte(array, index)); return 1; } else { duk_dup(ctx, 1); duk_get_prop(ctx, 0); return 1; } } static duk_ret_t js_ByteArray_setProp(duk_context* ctx) { bytearray_t* array; int index; int size; array = duk_require_sphere_bytearray(ctx, 0); if (duk_is_number(ctx, 1)) { index = duk_to_int(ctx, 1); size = get_bytearray_size(array); if (index < 0 || index >= size) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ByteArray[]: index `%d` out of bounds (size: %i)", index, size); set_byte(array, index, duk_require_uint(ctx, 2)); return 0; } else { duk_dup(ctx, 1); duk_dup(ctx, 2); duk_put_prop(ctx, 0); return 0; } } static duk_ret_t js_ByteArray_concat(duk_context* ctx) { bytearray_t* array2 = duk_require_sphere_bytearray(ctx, 0); bytearray_t* array; bytearray_t* new_array; duk_push_this(ctx); array = duk_require_sphere_bytearray(ctx, -1); duk_pop(ctx); if (array->size + array2->size > INT_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ByteArray:concat(): unable to concatenate, final size would exceed 2 GB (size1: %u, size2: %u)", array->size, array2->size); if (!(new_array = concat_bytearrays(array, array2))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ByteArray:concat(): unable to create concatenated byte array"); duk_push_sphere_bytearray(ctx, new_array); return 1; } static duk_ret_t js_ByteArray_deflate(duk_context* ctx) { int n_args = duk_get_top(ctx); int level = n_args >= 1 ? duk_require_int(ctx, 0) : -1; bytearray_t* array; bytearray_t* new_array; duk_push_this(ctx); array = duk_require_sphere_bytearray(ctx, -1); duk_pop(ctx); if ((level < 0 || level > 9) && n_args >= 1) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ByteArray:deflate(): compression level must be [0-9] (got: %d)", level); if (!(new_array = deflate_bytearray(array, level))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ByteArray:deflate(): unable to deflate source ByteArray"); duk_push_sphere_bytearray(ctx, new_array); return 1; } static duk_ret_t js_ByteArray_inflate(duk_context* ctx) { bytearray_t* array; bytearray_t* new_array; int n_args = duk_get_top(ctx); int max_size = n_args >= 1 ? duk_require_int(ctx, 0) : 0; duk_push_this(ctx); array = duk_require_sphere_bytearray(ctx, -1); duk_pop(ctx); if (max_size < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ByteArray:inflate(): buffer size must not be negative (got: %d)", max_size); if (!(new_array = inflate_bytearray(array, max_size))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ByteArray:inflate(): unable to inflate source ByteArray"); duk_push_sphere_bytearray(ctx, new_array); return 1; } static duk_ret_t js_ByteArray_resize(duk_context* ctx) { int new_size = duk_require_int(ctx, 0); bytearray_t* array; duk_push_this(ctx); array = duk_require_sphere_bytearray(ctx, -1); duk_pop(ctx); if (new_size < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ByteArray:resize(): size must not be negative (got: %d)", new_size); resize_bytearray(array, new_size); return 0; } static duk_ret_t js_ByteArray_slice(duk_context* ctx) { int n_args = duk_get_top(ctx); int start = duk_require_int(ctx, 0); int end = (n_args >= 2) ? duk_require_int(ctx, 1) : INT_MAX; bytearray_t* array; int end_norm; bytearray_t* new_array; duk_push_this(ctx); array = duk_require_sphere_bytearray(ctx, -1); duk_pop(ctx); end_norm = fmin(end >= 0 ? end : array->size + end, array->size); if (end_norm < start || end_norm > array->size) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ByteArray:slice(): start and/or end values out of bounds (start: %i, end: %i, size: %i)", start, end_norm, array->size); if (!(new_array = slice_bytearray(array, start, end_norm - start))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ByteArray:slice(): unable to create sliced byte array"); duk_push_sphere_bytearray(ctx, new_array); return 1; } <file_sep>/assets/system/modules/miniRT/binary.js /** * miniRT/binary CommonJS module * allows loading structured data from binary files based on a JSON schema * (c) 2015-2016 <NAME> **/ if (typeof exports === 'undefined') { throw new TypeError("script must be loaded with require()"); } const link = require('link'); var binary = module.exports = (function() { return { load: load, read: read, }; function load(filename, schema) { if (!Array.isArray(schema)) throw new TypeError("expected an Array object for `schema`"); var stream = new FileStream(filename, 'rb'); var object = binary.read(stream, schema); stream.close(); return object; } function read(stream, schema) { if (!Array.isArray(schema)) throw new TypeError("expected an Array object for `schema`"); return _readObject(stream, schema, null); } function _fixup(value, data) { // this fixes up backreferences in the schema, for example '@numPigs'. // because files are loaded sequentially, references can only be to // earlier fields. if (typeof value == 'string' && value[0] == '@') return data[value.substr(1)]; else return value; } function _readField(stream, fieldType, data) { var dataSize = _fixup(fieldType.size, data); var itemCount = _fixup(fieldType.count, data); // read a value or object from the stream var value; switch (fieldType.type) { case 'switch': var control = data[fieldType.field]; var checkType = null; for (var i = 0; i < fieldType.cases.length; ++i) { var checkType = fieldType.cases[i]; if (('value' in checkType && typeof control == typeof checkType.value && control === checkType.value) || ('range' in checkType && typeof control == 'number' && control >= checkType.range[0] && control <= checkType.range[1])) { break; } checkType = null; } if (checkType != null) value = _readField(stream, checkType, data); else throw new Error("binary field `" + fieldType.field + "` is invalid"); break; case 'array': value = []; for (var i = 0; i < itemCount; ++i) { value[i] = _readField(stream, fieldType.subtype, data); } break; case 'bool': value = stream.readUInt(1) != 0; break; case 'double': value = stream.readDouble(); break; case 'doubleLE': value = stream.readDouble(true); break; case 'float': value = stream.readFloat(); break; case 'floatLE': value = stream.readFloat(true); break; case 'fstring': value = stream.readString(dataSize); break; case 'image': var width = _fixup(fieldType.width, data); var height = _fixup(fieldType.height, data); if (typeof width != 'number' || typeof height != 'number') throw new Error("missing or invalid width/height for `image` field"); var pixelData = stream.read(width * height * 4); value = new Image(width, height, pixelData); break; case 'int': value = stream.readInt(dataSize); break; case 'intLE': value = stream.readInt(dataSize, true); break; case 'object': value = _readObject(stream, fieldType.schema, data); break; case 'pstring': value = stream.readPString(dataSize); break; case 'pstringLE': value = stream.readPString(dataSize, true); break; case 'raw': value = stream.read(dataSize); break; case 'reserved': var buf = stream.read(dataSize); value = undefined; break; case 'uint': value = stream.readUInt(dataSize); break; case 'uintLE': value = stream.readUInt(dataSize, true); break; default: throw new TypeError("unknown field type `" + fieldType.type + "` in schema"); } // verify the value we got against the schema var isValidValue = true; if (Array.isArray(fieldType.values)) { if (!link(fieldType.values).contains(value)) { isValidValue = false; } } else if (Array.isArray(fieldType.range) && fieldType.range.length == 2 && typeof fieldType.range[0] === typeof value && typeof fieldType.range[1] === typeof value) { if (value < fieldType.range[0] || value > fieldType.range[1]) { isValidValue = false; } } // if the value passes muster, return it. otherwise, throw. if (!isValidValue) { throw new Error("binary field `" + fieldType.id + "` is invalid"); } return value; } function _readObject(stream, schema, parentObj) { var object = Object.create(parentObj); for (var i = 0; i < schema.length; ++i) { var fieldType = schema[i]; var value = _readField(stream, fieldType, object); if ('id' in fieldType) { object[fieldType.id] = value; } } return object; } })(); <file_sep>/src/engine/color.c #include "minisphere.h" #include "api.h" #include "color.h" static duk_ret_t js_BlendColors (duk_context* ctx); static duk_ret_t js_BlendColorsWeighted (duk_context* ctx); static duk_ret_t js_CreateColor (duk_context* ctx); static duk_ret_t js_new_Color (duk_context* ctx); static duk_ret_t js_Color_toString (duk_context* ctx); static duk_ret_t js_Color_clone (duk_context* ctx); static duk_ret_t js_CreateColorMatrix (duk_context* ctx); static duk_ret_t js_new_ColorMatrix (duk_context* ctx); static duk_ret_t js_ColorMatrix_toString (duk_context* ctx); static duk_ret_t js_ColorMatrix_apply (duk_context* ctx); ALLEGRO_COLOR nativecolor(color_t color) { return al_map_rgba(color.r, color.g, color.b, color.alpha); } color_t color_new(uint8_t r, uint8_t g, uint8_t b, uint8_t alpha) { color_t color; color.r = r; color.g = g; color.b = b; color.alpha = alpha; return color; } color_t color_lerp(color_t color, color_t other, float w1, float w2) { color_t blend; float sigma; sigma = w1 + w2; blend.r = (color.r * w1 + other.r * w2) / sigma; blend.g = (color.g * w1 + other.g * w2) / sigma; blend.b = (color.b * w1 + other.b * w2) / sigma; blend.alpha = (color.alpha * w1 + other.alpha * w2) / sigma; return blend; } colormatrix_t colormatrix_new(int rn, int rr, int rg, int rb, int gn, int gr, int gg, int gb, int bn, int br, int bg, int bb) { colormatrix_t matrix = { rn, rr, rg, rb, gn, gr, gg, gb, bn, br, bg, bb, }; return matrix; } colormatrix_t colormatrix_lerp(colormatrix_t mat, colormatrix_t other, int w1, int w2) { colormatrix_t blend; int sigma; sigma = w1 + w2; blend.rn = (mat.rn * w1 + other.rn * w2) / sigma; blend.rr = (mat.rr * w1 + other.rr * w2) / sigma; blend.rg = (mat.rg * w1 + other.rg * w2) / sigma; blend.rb = (mat.rb * w1 + other.rb * w2) / sigma; blend.gn = (mat.gn * w1 + other.gn * w2) / sigma; blend.gr = (mat.gr * w1 + other.gr * w2) / sigma; blend.gg = (mat.gg * w1 + other.gg * w2) / sigma; blend.gb = (mat.gb * w1 + other.gb * w2) / sigma; blend.bn = (mat.bn * w1 + other.bn * w2) / sigma; blend.br = (mat.br * w1 + other.br * w2) / sigma; blend.bg = (mat.bg * w1 + other.bg * w2) / sigma; blend.bb = (mat.bb * w1 + other.bb * w2) / sigma; return blend; } color_t color_transform(color_t color, colormatrix_t mat) { int r, g, b; r = mat.rn + (mat.rr * color.r + mat.rg * color.g + mat.rb * color.b) / 255; g = mat.gn + (mat.gr * color.r + mat.gg * color.g + mat.gb * color.b) / 255; b = mat.bn + (mat.br * color.r + mat.bg * color.g + mat.bb * color.b) / 255; r = r < 0 ? 0 : r > 255 ? 255 : r; g = g < 0 ? 0 : g > 255 ? 255 : g; b = b < 0 ? 0 : b > 255 ? 255 : b; return color_new(r, g, b, color.alpha); } void init_color_api(void) { api_register_method(g_duk, NULL, "BlendColors", js_BlendColors); api_register_method(g_duk, NULL, "BlendColorsWeighted", js_BlendColorsWeighted); api_register_method(g_duk, NULL, "CreateColor", js_CreateColor); api_register_method(g_duk, NULL, "CreateColorMatrix", js_CreateColorMatrix); // register Color methods and properties api_register_ctor(g_duk, "Color", js_new_Color, NULL); api_register_method(g_duk, "Color", "toString", js_Color_toString); api_register_method(g_duk, "Color", "clone", js_Color_clone); // register ColorMatrix methods and properties api_register_ctor(g_duk, "ColorMatrix", js_new_ColorMatrix, NULL); api_register_method(g_duk, "ColorMatrix", "toString", js_ColorMatrix_toString); api_register_method(g_duk, "ColorMatrix", "apply", js_ColorMatrix_apply); } void duk_push_sphere_color(duk_context* ctx, color_t color) { duk_push_global_object(ctx); duk_get_prop_string(ctx, -1, "Color"); duk_push_number(ctx, color.r); duk_push_number(ctx, color.g); duk_push_number(ctx, color.b); duk_push_number(ctx, color.alpha); duk_new(ctx, 4); duk_remove(ctx, -2); } color_t duk_require_sphere_color(duk_context* ctx, duk_idx_t index) { int r, g, b; int alpha; duk_require_sphere_obj(ctx, index, "Color"); duk_get_prop_string(ctx, index, "red"); r = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "green"); g = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "blue"); b = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "alpha"); alpha = duk_get_int(ctx, -1); duk_pop(ctx); r = r < 0 ? 0 : r > 255 ? 255 : r; g = g < 0 ? 0 : g > 255 ? 255 : g; b = b < 0 ? 0 : b > 255 ? 255 : b; alpha = alpha < 0 ? 0 : alpha > 255 ? 255 : alpha; return color_new(r, g, b, alpha); } colormatrix_t duk_require_sphere_colormatrix(duk_context* ctx, duk_idx_t index) { colormatrix_t matrix; duk_require_sphere_obj(ctx, index, "ColorMatrix"); duk_get_prop_string(ctx, index, "rn"); matrix.rn = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "rr"); matrix.rr = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "rg"); matrix.rg = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "rb"); matrix.rb = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "gn"); matrix.gn = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "gr"); matrix.gr = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "gg"); matrix.gg = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "gb"); matrix.gb = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "bn"); matrix.bn = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "br"); matrix.br = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "bg"); matrix.bg = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, index, "bb"); matrix.bb = duk_get_int(ctx, -1); duk_pop(ctx); return matrix; } static duk_ret_t js_BlendColors(duk_context* ctx) { color_t color1 = duk_require_sphere_color(ctx, 0); color_t color2 = duk_require_sphere_color(ctx, 1); duk_push_sphere_color(ctx, color_lerp(color1, color2, 1, 1)); return 1; } static duk_ret_t js_BlendColorsWeighted(duk_context* ctx) { color_t color1 = duk_require_sphere_color(ctx, 0); color_t color2 = duk_require_sphere_color(ctx, 1); float w1 = duk_require_number(ctx, 2); float w2 = duk_require_number(ctx, 3); if (w1 < 0.0 || w2 < 0.0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "BlendColorsWeighted(): weights cannot be negative ({ w1: %f, w2: %f })", w1, w2); duk_push_sphere_color(ctx, color_lerp(color1, color2, w1, w2)); return 1; } static duk_ret_t js_CreateColor(duk_context* ctx) { return js_new_Color(ctx); } static duk_ret_t js_new_Color(duk_context* ctx) { int n_args = duk_get_top(ctx); int r = duk_require_int(ctx, 0); int g = duk_require_int(ctx, 1); int b = duk_require_int(ctx, 2); int alpha = n_args >= 4 ? duk_require_int(ctx, 3) : 255; // clamp components to 8-bit [0-255] r = r < 0 ? 0 : r > 255 ? 255 : r; g = g < 0 ? 0 : g > 255 ? 255 : g; b = b < 0 ? 0 : b > 255 ? 255 : b; alpha = alpha < 0 ? 0 : alpha > 255 ? 255 : alpha; // construct a Color object duk_push_sphere_obj(ctx, "Color", NULL); duk_push_int(ctx, r); duk_put_prop_string(ctx, -2, "red"); duk_push_int(ctx, g); duk_put_prop_string(ctx, -2, "green"); duk_push_int(ctx, b); duk_put_prop_string(ctx, -2, "blue"); duk_push_int(ctx, alpha); duk_put_prop_string(ctx, -2, "alpha"); return 1; } static duk_ret_t js_Color_toString(duk_context* ctx) { duk_push_string(ctx, "[object color]"); return 1; } static duk_ret_t js_Color_clone(duk_context* ctx) { color_t color; duk_push_this(ctx); color = duk_require_sphere_color(ctx, -1); duk_pop(ctx); duk_push_sphere_color(ctx, color); return 1; } static duk_ret_t js_CreateColorMatrix(duk_context* ctx) { return js_new_ColorMatrix(ctx); } static duk_ret_t js_new_ColorMatrix(duk_context* ctx) { int rn = duk_require_int(ctx, 0); int rr = duk_require_int(ctx, 1); int rg = duk_require_int(ctx, 2); int rb = duk_require_int(ctx, 3); int gn = duk_require_int(ctx, 4); int gr = duk_require_int(ctx, 5); int gg = duk_require_int(ctx, 6); int gb = duk_require_int(ctx, 7); int bn = duk_require_int(ctx, 8); int br = duk_require_int(ctx, 9); int bg = duk_require_int(ctx, 10); int bb = duk_require_int(ctx, 11); // construct a ColorMatrix object duk_push_sphere_obj(ctx, "ColorMatrix", NULL); duk_push_int(ctx, rn); duk_put_prop_string(ctx, -2, "rn"); duk_push_int(ctx, rr); duk_put_prop_string(ctx, -2, "rr"); duk_push_int(ctx, rg); duk_put_prop_string(ctx, -2, "rg"); duk_push_int(ctx, rb); duk_put_prop_string(ctx, -2, "rb"); duk_push_int(ctx, gn); duk_put_prop_string(ctx, -2, "gn"); duk_push_int(ctx, gr); duk_put_prop_string(ctx, -2, "gr"); duk_push_int(ctx, gg); duk_put_prop_string(ctx, -2, "gg"); duk_push_int(ctx, gb); duk_put_prop_string(ctx, -2, "gb"); duk_push_int(ctx, bn); duk_put_prop_string(ctx, -2, "bn"); duk_push_int(ctx, br); duk_put_prop_string(ctx, -2, "br"); duk_push_int(ctx, bg); duk_put_prop_string(ctx, -2, "bg"); duk_push_int(ctx, bb); duk_put_prop_string(ctx, -2, "bb"); return 1; } static duk_ret_t js_ColorMatrix_toString(duk_context* ctx) { duk_push_string(ctx, "[object colormatrix]"); return 1; } static duk_ret_t js_ColorMatrix_apply(duk_context* ctx) { color_t color = duk_require_sphere_color(ctx, 0); colormatrix_t matrix; duk_push_this(ctx); matrix = duk_require_sphere_colormatrix(ctx, -1); duk_pop(ctx); duk_push_sphere_color(ctx, color_transform(color, matrix)); return 1; } <file_sep>/src/debugger/source.c #include "ssj.h" #include "source.h" struct source { vector_t* lines; }; static char* read_line(const char** p_string) { char* buffer; size_t buf_size; char ch; bool have_line = false; size_t length; buffer = malloc(buf_size = 256); length = 0; while (!have_line) { if (length + 1 >= buf_size) buffer = realloc(buffer, buf_size *= 2); if ((ch = *(*p_string)) == '\0') goto hit_eof; ++(*p_string); switch (ch) { case '\n': have_line = true; break; case '\r': have_line = true; if (*(*p_string) == '\n') // CR LF? ++(*p_string); break; default: buffer[length++] = ch; } } hit_eof: buffer[length] = '\0'; if (*(*p_string) == '\0' && length == 0) { free(buffer); return NULL; } else return buffer; } source_t* source_new(const char* text) { char* line_text; vector_t* lines; source_t* source = NULL; const char* p_source; p_source = text; lines = vector_new(sizeof(char*)); while (line_text = read_line(&p_source)) vector_push(lines, &line_text); source = calloc(1, sizeof(source_t)); source->lines = lines; return source; } void source_free(source_t* source) { iter_t it; char* *p_line; if (source == NULL) return; it = vector_enum(source->lines); while (p_line = vector_next(&it)) free(*p_line); vector_free(source->lines); free(source); } int source_cloc(const source_t* source) { return (int)vector_len(source->lines); } const char* source_get_line(const source_t* source, int line_index) { if (line_index < 0 || line_index >= source_cloc(source)) return NULL; return *(char**)vector_get(source->lines, line_index); } void source_print(const source_t* source, int lineno, int num_lines, int active_lineno) { const char* arrow; int line_count; int median; int start, end; const char* text; int i; line_count = source_cloc(source); median = num_lines / 2; start = lineno > median ? lineno - (median + 1) : 0; end = start + num_lines < line_count ? start + num_lines : line_count; for (i = start; i < end; ++i) { text = source_get_line(source, i); arrow = i + 1 == active_lineno ? "=>" : " "; if (num_lines == 1) printf("%d %s\n", i + 1, text); else { if (i + 1 == active_lineno) printf("\33[0;1m"); printf("%s %4d %s\n", arrow, i + 1, text); printf("\33[m"); } } } <file_sep>/src/engine/screen.c // note: due to Allegro's architecture, this is far from a perfect abstraction. avoid the // temptation to create multiple screen objects for any reason as this will not work properly // and will almost certainly blow up in your face. :o) #include "minisphere.h" #include "screen.h" #include "api.h" #include "debugger.h" #include "image.h" #include "matrix.h" static duk_ret_t js_GetClippingRectangle (duk_context* ctx); static duk_ret_t js_SetClippingRectangle (duk_context* ctx); static duk_ret_t js_ApplyColorMask (duk_context* ctx); static duk_ret_t js_GradientCircle (duk_context* ctx); static duk_ret_t js_GradientRectangle (duk_context* ctx); static duk_ret_t js_Line (duk_context* ctx); static duk_ret_t js_LineSeries (duk_context* ctx); static duk_ret_t js_OutlinedCircle (duk_context* ctx); static duk_ret_t js_OutlinedRectangle (duk_context* ctx); static duk_ret_t js_OutlinedRoundRectangle (duk_context* ctx); static duk_ret_t js_Point (duk_context* ctx); static duk_ret_t js_PointSeries (duk_context* ctx); static duk_ret_t js_Rectangle (duk_context* ctx); static duk_ret_t js_RoundRectangle (duk_context* ctx); static duk_ret_t js_Triangle (duk_context* ctx); enum line_series_type { LINE_MULTIPLE, LINE_STRIP, LINE_LOOP }; struct screen { bool avoid_sleep; rect_t clip_rect; ALLEGRO_DISPLAY* display; int fps_flips; int fps_frames; double fps_poll_time; bool fullscreen; bool have_shaders; double last_flip_time; int max_skips; double next_frame_time; int num_flips; int num_frames; int num_skips; bool show_fps; bool skip_frame; bool take_screenshot; bool use_shaders; int x_offset; float x_scale; int x_size; int y_offset; float y_scale; int y_size; }; static void refresh_display (screen_t* obj); screen_t* screen_new(const char* title, image_t* icon, int x_size, int y_size, int frameskip, bool avoid_sleep) { ALLEGRO_DISPLAY* display; ALLEGRO_BITMAP* icon_bitmap; screen_t* obj; int bitmap_flags; bool use_shaders = false; int x_scale; int y_scale; console_log(1, "initializing render context at %dx%d", x_size, y_size); x_scale = x_size <= 400 && y_size <= 300 ? 2.0 : 1.0; y_scale = x_scale; #ifdef MINISPHERE_USE_SHADERS al_set_new_display_flags(ALLEGRO_OPENGL | ALLEGRO_PROGRAMMABLE_PIPELINE); if (display = al_create_display(x_size * x_scale, y_size * y_scale)) use_shaders = true; else { al_set_new_display_flags(ALLEGRO_OPENGL); display = al_create_display(x_size * x_scale, y_size * y_scale); } #else al_set_new_display_flags(ALLEGRO_OPENGL); display = al_create_display(x_size * x_scale, y_size * y_scale); #endif if (display == NULL) { fprintf(stderr, "FATAL: unable to initialize render context!"); return NULL; } console_log(1, " shader support: %s", use_shaders ? "yes" : "no"); al_set_window_title(display, title); if (icon != NULL) { bitmap_flags = al_get_new_bitmap_flags(); al_set_new_bitmap_flags( ALLEGRO_NO_PREMULTIPLIED_ALPHA | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR | bitmap_flags); icon = clone_image(icon); rescale_image(icon, 32, 32); icon_bitmap = get_image_bitmap(icon); al_set_new_bitmap_flags(bitmap_flags); al_set_display_icon(display, icon_bitmap); } obj = calloc(1, sizeof(screen_t)); obj->display = display; obj->x_size = x_size; obj->y_size = y_size; obj->max_skips = frameskip; obj->avoid_sleep = avoid_sleep; obj->have_shaders = use_shaders; obj->fps_poll_time = al_get_time() + 1.0; obj->next_frame_time = al_get_time(); obj->last_flip_time = obj->next_frame_time; #ifdef MINISPHERE_SPHERUN obj->show_fps = true; #endif screen_set_clipping(obj, new_rect(0, 0, x_size, y_size)); refresh_display(obj); return obj; } void screen_free(screen_t* obj) { if (obj == NULL) return; console_log(1, "shutting down render context"); al_destroy_display(obj->display); free(obj); } ALLEGRO_DISPLAY* screen_display(const screen_t* obj) { return obj->display; } bool screen_have_shaders(const screen_t* screen) { return screen->have_shaders; } bool screen_is_skipframe(const screen_t* obj) { return obj->skip_frame; } rect_t screen_get_clipping(screen_t* obj) { return obj->clip_rect; } int screen_get_frameskip(const screen_t* obj) { return obj->max_skips; } void screen_get_mouse_xy(const screen_t* obj, int* o_x, int* o_y) { ALLEGRO_MOUSE_STATE mouse_state; al_get_mouse_state(&mouse_state); *o_x = (mouse_state.x - obj->x_offset) / obj->x_scale; *o_y = (mouse_state.y - obj->y_offset) / obj->y_scale; } void screen_set_clipping(screen_t* obj, rect_t clip_rect) { obj->clip_rect = clip_rect; clip_rect.x1 = clip_rect.x1 * obj->x_scale + obj->x_offset; clip_rect.y1 = clip_rect.y1 * obj->y_scale + obj->y_offset; clip_rect.x2 = clip_rect.x2 * obj->x_scale + obj->x_offset; clip_rect.y2 = clip_rect.y2 * obj->y_scale + obj->y_offset; al_set_clipping_rectangle(clip_rect.x1, clip_rect.y1, clip_rect.x2 - clip_rect.x1, clip_rect.y2 - clip_rect.y1); } void screen_set_frameskip(screen_t* obj, int max_skips) { obj->max_skips = max_skips; } void screen_set_mouse_xy(screen_t* obj, int x, int y) { x = x * obj->x_scale + obj->x_offset; y = y * obj->y_scale + obj->y_offset; al_set_mouse_xy(obj->display, x, y); } void screen_draw_status(screen_t* obj, const char* text) { rect_t bounds; int screen_cx; int screen_cy; ALLEGRO_TRANSFORM trans; int width; int height; screen_cx = al_get_display_width(obj->display); screen_cy = al_get_display_height(obj->display); width = get_text_width(g_sys_font, text) + 20; height = get_font_line_height(g_sys_font) + 10; bounds.x1 = 8 + obj->x_offset; bounds.y1 = screen_cy - obj->y_offset - height - 8; bounds.x2 = bounds.x1 + width; bounds.y2 = bounds.y1 + height; al_identity_transform(&trans); al_use_transform(&trans); al_draw_filled_rounded_rectangle(bounds.x1, bounds.y1, bounds.x2, bounds.y2, 4, 4, al_map_rgba(16, 16, 16, 192)); draw_text(g_sys_font, color_new(0, 0, 0, 255), (bounds.x1 + bounds.x2) / 2 + 1, bounds.y1 + 6, TEXT_ALIGN_CENTER, text); draw_text(g_sys_font, color_new(255, 255, 255, 255), (bounds.x2 + bounds.x1) / 2, bounds.y1 + 5, TEXT_ALIGN_CENTER, text); screen_transform(obj, NULL); } void screen_flip(screen_t* obj, int framerate) { char* filename; char fps_text[20]; const char* game_filename; const path_t* game_path; bool is_backbuffer_valid; time_t now; ALLEGRO_STATE old_state; path_t* path; const char* pathstr; int screen_cx; int screen_cy; int serial = 1; ALLEGRO_BITMAP* snapshot; double time_left; char timestamp[100]; ALLEGRO_TRANSFORM trans; int x, y; size_t i; // update FPS with 1s granularity if (al_get_time() >= obj->fps_poll_time) { obj->fps_flips = obj->num_flips; obj->fps_frames = obj->num_frames; obj->num_frames = obj->num_flips = 0; obj->fps_poll_time = al_get_time() + 1.0; } // flip the backbuffer, unless the preceeding frame was skipped is_backbuffer_valid = !obj->skip_frame; screen_cx = al_get_display_width(obj->display); screen_cy = al_get_display_height(obj->display); if (is_backbuffer_valid) { if (obj->take_screenshot) { al_store_state(&old_state, ALLEGRO_STATE_NEW_BITMAP_PARAMETERS); al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ANY_24_NO_ALPHA); snapshot = al_clone_bitmap(al_get_backbuffer(obj->display)); al_restore_state(&old_state); game_path = get_game_path(g_fs); game_filename = path_is_file(game_path) ? path_filename_cstr(game_path) : path_hop_cstr(game_path, path_num_hops(game_path) - 1); path = path_rebase(path_new("minisphere/screens/"), homepath()); path_mkdir(path); time(&now); strftime(timestamp, 100, "%Y%m%d", localtime(&now)); do { filename = strnewf("%s-%s-%d.png", game_filename, timestamp, serial++); for (i = 0; filename[i] != '\0'; ++i) filename[i]; path_strip(path); path_append(path, filename); pathstr = path_cstr(path); free(filename); } while (al_filename_exists(pathstr)); al_save_bitmap(pathstr, snapshot); al_destroy_bitmap(snapshot); path_free(path); obj->take_screenshot = false; } if (is_debugger_attached()) screen_draw_status(obj, "SSJ"); if (obj->show_fps) { if (framerate > 0) sprintf(fps_text, "%d/%d fps", obj->fps_flips, obj->fps_frames); else sprintf(fps_text, "%d fps", obj->fps_flips); x = screen_cx - obj->x_offset - 108; y = screen_cy - obj->y_offset - 24; al_identity_transform(&trans); al_use_transform(&trans); al_draw_filled_rounded_rectangle(x, y, x + 100, y + 16, 4, 4, al_map_rgba(16, 16, 16, 192)); draw_text(g_sys_font, color_new(0, 0, 0, 255), x + 51, y + 3, TEXT_ALIGN_CENTER, fps_text); draw_text(g_sys_font, color_new(255, 255, 255, 255), x + 50, y + 2, TEXT_ALIGN_CENTER, fps_text); screen_transform(g_screen, NULL); } al_flip_display(); obj->last_flip_time = al_get_time(); obj->num_skips = 0; ++obj->num_flips; } else { ++obj->num_skips; } // if framerate is nonzero and we're backed up on frames, skip frames until we // catch up. there is a cap on consecutive frameskips to avoid the situation where // the engine "can't catch up" (due to a slow machine, overloaded CPU, etc.). better // that we lag instead of never rendering anything at all. if (framerate > 0) { obj->skip_frame = obj->num_skips < obj->max_skips && obj->last_flip_time > obj->next_frame_time; do { // kill time while we wait for the next frame time_left = obj->next_frame_time - al_get_time(); if (!obj->avoid_sleep && time_left > 0.001) // engine may stall with < 1ms timeout al_wait_for_event_timed(g_events, NULL, time_left); do_events(); } while (al_get_time() < obj->next_frame_time); if (!is_backbuffer_valid && !obj->skip_frame) // did we just finish skipping frames? obj->next_frame_time = al_get_time() + 1.0 / framerate; else obj->next_frame_time += 1.0 / framerate; } else { obj->skip_frame = false; do_events(); obj->next_frame_time = al_get_time(); obj->next_frame_time = al_get_time(); } ++obj->num_frames; if (!obj->skip_frame) { // disable clipping momentarily so we can clear the letterbox area. // this prevents artifacts which manifest with some graphics drivers. al_set_clipping_rectangle(0, 0, screen_cx, screen_cy); al_clear_to_color(al_map_rgba(0, 0, 0, 255)); screen_set_clipping(obj, obj->clip_rect); } } image_t* screen_grab(screen_t* obj, int x, int y, int width, int height) { ALLEGRO_BITMAP* backbuffer; image_t* image; int scale_width; int scale_height; x = x * obj->x_scale + obj->x_offset; y = y * obj->y_scale + obj->y_offset; scale_width = width * obj->x_scale; scale_height = height * obj->y_scale; if (!(image = create_image(scale_width, scale_height))) goto on_error; backbuffer = al_get_backbuffer(obj->display); al_set_target_bitmap(get_image_bitmap(image)); al_draw_bitmap_region(backbuffer, x, y, scale_width, scale_height, 0, 0, 0x0); al_set_target_backbuffer(obj->display); if (!rescale_image(image, width, height)) goto on_error; return image; on_error: free_image(image); return NULL; } void screen_queue_screenshot(screen_t* obj) { obj->take_screenshot = true; } void screen_resize(screen_t* obj, int x_size, int y_size) { obj->x_size = x_size; obj->y_size = y_size; refresh_display(obj); } void screen_show_mouse(screen_t* obj, bool visible) { if (visible) al_show_mouse_cursor(obj->display); else al_hide_mouse_cursor(obj->display); } void screen_toggle_fps(screen_t* obj) { obj->show_fps = !obj->show_fps; } void screen_toggle_fullscreen(screen_t* obj) { obj->fullscreen = !obj->fullscreen; refresh_display(obj); } void screen_transform(screen_t* obj, const matrix_t* matrix) { ALLEGRO_TRANSFORM transform; al_identity_transform(&transform); if (matrix != NULL) al_compose_transform(&transform, matrix_transform(matrix)); if (al_get_target_bitmap() == al_get_backbuffer(obj->display)) { al_scale_transform(&transform, obj->x_scale, obj->y_scale); al_translate_transform(&transform, obj->x_offset, obj->y_offset); } al_use_transform(&transform); } void screen_unskip_frame(screen_t* obj) { obj->skip_frame = false; al_clear_to_color(al_map_rgba(0, 0, 0, 255)); } static void refresh_display(screen_t* obj) { ALLEGRO_MONITOR_INFO monitor; int real_width; int real_height; al_set_display_flag(obj->display, ALLEGRO_FULLSCREEN_WINDOW, obj->fullscreen); if (obj->fullscreen) { real_width = al_get_display_width(obj->display); real_height = al_get_display_height(obj->display); obj->x_scale = (float)real_width / obj->x_size; obj->y_scale = (float)real_height / obj->y_size; if (obj->x_scale > obj->y_scale) { obj->x_scale = obj->y_scale; obj->x_offset = (real_width - obj->x_size * obj->x_scale) / 2; obj->y_offset = 0.0; } else { obj->y_scale = obj->x_scale; obj->y_offset = (real_height - obj->y_size * obj->y_scale) / 2; obj->x_offset = 0.0; } } else { obj->x_scale = obj->x_size <= 400 && obj->y_size <= 300 ? 2.0 : 1.0; obj->y_scale = obj->x_scale; obj->x_offset = obj->y_offset = 0.0; // size and recenter the window al_resize_display(obj->display, obj->x_size * obj->x_scale, obj->y_size * obj->y_scale); al_get_monitor_info(0, &monitor); al_set_window_position(obj->display, (monitor.x1 + monitor.x2) / 2 - obj->x_size * obj->x_scale / 2, (monitor.y1 + monitor.y2) / 2 - obj->y_size * obj->y_scale / 2); } screen_transform(obj, NULL); screen_set_clipping(obj, obj->clip_rect); } void init_screen_api(void) { api_register_method(g_duk, NULL, "GetClippingRectangle", js_GetClippingRectangle); api_register_method(g_duk, NULL, "SetClippingRectangle", js_SetClippingRectangle); api_register_method(g_duk, NULL, "ApplyColorMask", js_ApplyColorMask); api_register_method(g_duk, NULL, "GradientCircle", js_GradientCircle); api_register_method(g_duk, NULL, "GradientRectangle", js_GradientRectangle); api_register_method(g_duk, NULL, "Line", js_Line); api_register_method(g_duk, NULL, "LineSeries", js_LineSeries); api_register_method(g_duk, NULL, "OutlinedCircle", js_OutlinedCircle); api_register_method(g_duk, NULL, "OutlinedRectangle", js_OutlinedRectangle); api_register_method(g_duk, NULL, "OutlinedRoundRectangle", js_OutlinedRoundRectangle); api_register_method(g_duk, NULL, "Point", js_Point); api_register_method(g_duk, NULL, "PointSeries", js_PointSeries); api_register_method(g_duk, NULL, "Rectangle", js_Rectangle); api_register_method(g_duk, NULL, "RoundRectangle", js_RoundRectangle); api_register_method(g_duk, NULL, "Triangle", js_Triangle); // line series types api_register_const(g_duk, "LINE_MULTIPLE", LINE_MULTIPLE); api_register_const(g_duk, "LINE_STRIP", LINE_STRIP); api_register_const(g_duk, "LINE_LOOP", LINE_LOOP); } static duk_ret_t js_GetClippingRectangle(duk_context* ctx) { rect_t clip; clip = screen_get_clipping(g_screen); duk_push_object(ctx); duk_push_int(ctx, clip.x1); duk_put_prop_string(ctx, -2, "x"); duk_push_int(ctx, clip.y1); duk_put_prop_string(ctx, -2, "y"); duk_push_int(ctx, clip.x2 - clip.x1); duk_put_prop_string(ctx, -2, "width"); duk_push_int(ctx, clip.y2 - clip.y1); duk_put_prop_string(ctx, -2, "height"); return 1; } static duk_ret_t js_SetClippingRectangle(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int width = duk_require_int(ctx, 2); int height = duk_require_int(ctx, 3); screen_set_clipping(g_screen, new_rect(x, y, x + width, y + height)); return 0; } static duk_ret_t js_ApplyColorMask(duk_context* ctx) { color_t color; color = duk_require_sphere_color(ctx, 0); if (!screen_is_skipframe(g_screen)) al_draw_filled_rectangle(0, 0, g_res_x, g_res_y, nativecolor(color)); return 0; } static duk_ret_t js_GradientCircle(duk_context* ctx) { static ALLEGRO_VERTEX s_vbuf[128]; int x = duk_require_number(ctx, 0); int y = duk_require_number(ctx, 1); int radius = duk_require_number(ctx, 2); color_t in_color = duk_require_sphere_color(ctx, 3); color_t out_color = duk_require_sphere_color(ctx, 4); double phi; int vcount; int i; if (screen_is_skipframe(g_screen)) return 0; vcount = fmin(radius, 126); s_vbuf[0].x = x; s_vbuf[0].y = y; s_vbuf[0].z = 0; s_vbuf[0].color = nativecolor(in_color); for (i = 0; i < vcount; ++i) { phi = 2 * M_PI * i / vcount; s_vbuf[i + 1].x = x + cos(phi) * radius; s_vbuf[i + 1].y = y - sin(phi) * radius; s_vbuf[i + 1].z = 0; s_vbuf[i + 1].color = nativecolor(out_color); } s_vbuf[i + 1].x = x + cos(0) * radius; s_vbuf[i + 1].y = y - sin(0) * radius; s_vbuf[i + 1].z = 0; s_vbuf[i + 1].color = nativecolor(out_color); al_draw_prim(s_vbuf, NULL, NULL, 0, vcount + 2, ALLEGRO_PRIM_TRIANGLE_FAN); return 0; } static duk_ret_t js_GradientRectangle(duk_context* ctx) { int x1 = duk_require_int(ctx, 0); int y1 = duk_require_int(ctx, 1); int x2 = x1 + duk_require_int(ctx, 2); int y2 = y1 + duk_require_int(ctx, 3); color_t color_ul = duk_require_sphere_color(ctx, 4); color_t color_ur = duk_require_sphere_color(ctx, 5); color_t color_lr = duk_require_sphere_color(ctx, 6); color_t color_ll = duk_require_sphere_color(ctx, 7); if (!screen_is_skipframe(g_screen)) { ALLEGRO_VERTEX verts[] = { { x1, y1, 0, 0, 0, nativecolor(color_ul) }, { x2, y1, 0, 0, 0, nativecolor(color_ur) }, { x1, y2, 0, 0, 0, nativecolor(color_ll) }, { x2, y2, 0, 0, 0, nativecolor(color_lr) } }; al_draw_prim(verts, NULL, NULL, 0, 4, ALLEGRO_PRIM_TRIANGLE_STRIP); } return 0; } static duk_ret_t js_Line(duk_context* ctx) { float x1 = duk_require_int(ctx, 0) + 0.5; float y1 = duk_require_int(ctx, 1) + 0.5; float x2 = duk_require_int(ctx, 2) + 0.5; float y2 = duk_require_int(ctx, 3) + 0.5; color_t color = duk_require_sphere_color(ctx, 4); if (!screen_is_skipframe(g_screen)) al_draw_line(x1, y1, x2, y2, nativecolor(color), 1); return 0; } static duk_ret_t js_LineSeries(duk_context* ctx) { int n_args = duk_get_top(ctx); color_t color = duk_require_sphere_color(ctx, 1); int type = n_args >= 3 ? duk_require_int(ctx, 2) : LINE_MULTIPLE; size_t num_points; int x, y; ALLEGRO_VERTEX* vertices; ALLEGRO_COLOR vtx_color; size_t i; if (!duk_is_array(ctx, 0)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "LineSeries(): first argument must be an array"); duk_get_prop_string(ctx, 0, "length"); num_points = duk_get_uint(ctx, 0); duk_pop(ctx); if (num_points < 2) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "LineSeries(): two or more vertices required"); if (num_points > INT_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "LineSeries(): too many vertices"); if ((vertices = calloc(num_points, sizeof(ALLEGRO_VERTEX))) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "LineSeries(): unable to allocate vertex buffer"); vtx_color = nativecolor(color); for (i = 0; i < num_points; ++i) { duk_get_prop_index(ctx, 0, (duk_uarridx_t)i); duk_get_prop_string(ctx, 0, "x"); x = duk_require_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, 0, "y"); y = duk_require_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); vertices[i].x = x + 0.5; vertices[i].y = y + 0.5; vertices[i].color = vtx_color; } al_draw_prim(vertices, NULL, NULL, 0, (int)num_points, type == LINE_STRIP ? ALLEGRO_PRIM_LINE_STRIP : type == LINE_LOOP ? ALLEGRO_PRIM_LINE_LOOP : ALLEGRO_PRIM_LINE_LIST ); free(vertices); return 0; } static duk_ret_t js_OutlinedCircle(duk_context* ctx) { float x = duk_require_int(ctx, 0) + 0.5; float y = duk_require_int(ctx, 1) + 0.5; float radius = duk_require_int(ctx, 2); color_t color = duk_require_sphere_color(ctx, 3); if (!screen_is_skipframe(g_screen)) al_draw_circle(x, y, radius, nativecolor(color), 1); return 0; } static duk_ret_t js_OutlinedRectangle(duk_context* ctx) { int n_args = duk_get_top(ctx); float x1 = duk_require_int(ctx, 0) + 0.5; float y1 = duk_require_int(ctx, 1) + 0.5; float x2 = x1 + duk_require_int(ctx, 2) - 1; float y2 = y1 + duk_require_int(ctx, 3) - 1; color_t color = duk_require_sphere_color(ctx, 4); int thickness = n_args >= 6 ? duk_require_int(ctx, 5) : 1; if (!screen_is_skipframe(g_screen)) al_draw_rectangle(x1, y1, x2, y2, nativecolor(color), thickness); return 0; } static duk_ret_t js_OutlinedRoundRectangle(duk_context* ctx) { int n_args = duk_get_top(ctx); float x = duk_require_int(ctx, 0) + 0.5; float y = duk_require_int(ctx, 1) + 0.5; int w = duk_require_int(ctx, 2); int h = duk_require_int(ctx, 3); float radius = duk_require_number(ctx, 4); color_t color = duk_require_sphere_color(ctx, 5); int thickness = n_args >= 7 ? duk_require_int(ctx, 6) : 1; if (!screen_is_skipframe(g_screen)) al_draw_rounded_rectangle(x, y, x + w - 1, y + h - 1, radius, radius, nativecolor(color), thickness); return 0; } static duk_ret_t js_Point(duk_context* ctx) { float x = duk_require_int(ctx, 0) + 0.5; float y = duk_require_int(ctx, 1) + 0.5; color_t color = duk_require_sphere_color(ctx, 2); if (!screen_is_skipframe(g_screen)) al_draw_pixel(x, y, nativecolor(color)); return 0; } static duk_ret_t js_PointSeries(duk_context* ctx) { color_t color = duk_require_sphere_color(ctx, 1); size_t num_points; int x, y; ALLEGRO_VERTEX* vertices; ALLEGRO_COLOR vtx_color; size_t i; if (!duk_is_array(ctx, 0)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "PointSeries(): first argument must be an array"); duk_get_prop_string(ctx, 0, "length"); num_points = duk_get_uint(ctx, 0); duk_pop(ctx); if (num_points < 1) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "PointSeries(): one or more vertices required"); if (num_points > INT_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "PointSeries(): too many vertices"); if ((vertices = calloc(num_points, sizeof(ALLEGRO_VERTEX))) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "PointSeries(): unable to allocate vertex buffer"); vtx_color = nativecolor(color); for (i = 0; i < num_points; ++i) { duk_get_prop_index(ctx, 0, (duk_uarridx_t)i); duk_get_prop_string(ctx, 0, "x"); x = duk_require_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, 0, "y"); y = duk_require_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); vertices[i].x = x + 0.5; vertices[i].y = y + 0.5; vertices[i].color = vtx_color; } al_draw_prim(vertices, NULL, NULL, 0, (int)num_points, ALLEGRO_PRIM_POINT_LIST); free(vertices); return 0; } static duk_ret_t js_Rectangle(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int w = duk_require_int(ctx, 2); int h = duk_require_int(ctx, 3); color_t color = duk_require_sphere_color(ctx, 4); if (!screen_is_skipframe(g_screen)) al_draw_filled_rectangle(x, y, x + w, y + h, nativecolor(color)); return 0; } static duk_ret_t js_RoundRectangle(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int w = duk_require_int(ctx, 2); int h = duk_require_int(ctx, 3); float radius = duk_require_number(ctx, 4); color_t color = duk_require_sphere_color(ctx, 5); if (!screen_is_skipframe(g_screen)) al_draw_filled_rounded_rectangle(x, y, x + w, y + h, radius, radius, nativecolor(color)); return 0; } static duk_ret_t js_Triangle(duk_context* ctx) { int x1 = duk_require_int(ctx, 0); int y1 = duk_require_int(ctx, 1); int x2 = duk_require_int(ctx, 2); int y2 = duk_require_int(ctx, 3); int x3 = duk_require_int(ctx, 4); int y3 = duk_require_int(ctx, 5); color_t color = duk_require_sphere_color(ctx, 6); if (!screen_is_skipframe(g_screen)) al_draw_filled_triangle(x1, y1, x2, y2, x3, y3, nativecolor(color)); return 0; } <file_sep>/src/plugin/Forms/ObjectViewer.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using minisphere.Gdk.Debugger; using minisphere.Gdk.Plugins; using minisphere.Gdk.Properties; namespace minisphere.Gdk.Forms { partial class ObjectViewer : Form { private Inferior _inferior; private DValue _value; public ObjectViewer(Inferior inferior, string objectName, DValue value) { InitializeComponent(); ObjectNameTextBox.Text = string.Format("eval('{0}') = {1};", objectName.Replace(@"\", @"\\").Replace("'", @"\'").Replace("\n", @"\n").Replace("\r", @"\r"), value.ToString()); TreeIconImageList.Images.Add("object", Resources.StackIcon); TreeIconImageList.Images.Add("prop", Resources.VisibleIcon); TreeIconImageList.Images.Add("hiddenProp", Resources.InvisibleIcon); _inferior = inferior; _value = value; } private async void this_Load(object sender, EventArgs e) { PropTree.BeginUpdate(); PropTree.Nodes.Clear(); var trunk = PropTree.Nodes.Add(_value.ToString()); trunk.ImageKey = "object"; if (_value.Tag == DValueTag.HeapPtr) await PopulateTreeNode(trunk, (HeapPtr)_value); trunk.Expand(); PropTree.EndUpdate(); } private void PropTree_AfterSelect(object sender, TreeViewEventArgs e) { if (e.Node.Tag != null) { PropDesc desc = (PropDesc)e.Node.Tag; WritableCheckBox.Enabled = !desc.Flags.HasFlag(PropFlags.Accessor); EnumerableCheckBox.Enabled = true; ConfigurableCheckBox.Enabled = true; AccessorCheckBox.Enabled = true; WritableCheckBox.Checked = desc.Flags.HasFlag(PropFlags.Writable); EnumerableCheckBox.Checked = desc.Flags.HasFlag(PropFlags.Enumerable); ConfigurableCheckBox.Checked = desc.Flags.HasFlag(PropFlags.Configurable); AccessorCheckBox.Checked = desc.Flags.HasFlag(PropFlags.Accessor); } else { WritableCheckBox.Enabled = WritableCheckBox.Checked = false; EnumerableCheckBox.Enabled = EnumerableCheckBox.Checked = false; ConfigurableCheckBox.Enabled = ConfigurableCheckBox.Checked = false; AccessorCheckBox.Enabled = AccessorCheckBox.Enabled = false; } } private async void PropTree_BeforeExpand(object sender, TreeViewCancelEventArgs e) { if (e.Node.Tag == null || e.Node.Nodes[0].Text != "") return; PropDesc propDesc = (PropDesc)e.Node.Tag; if (propDesc.Value.Tag == DValueTag.HeapPtr) await PopulateTreeNode(e.Node, (HeapPtr)propDesc.Value); } private void PropTree_MouseMove(object sender, MouseEventArgs e) { var ht = PropTree.HitTest(e.Location); PropTree.Cursor = ht.Node != null && ht.Node.Bounds.Contains(e.Location) ? Cursors.Hand : Cursors.Default; } private async Task PopulateTreeNode(TreeNode node, HeapPtr ptr) { PropTree.BeginUpdate(); var props = await _inferior.GetObjPropDescRange(ptr, 0, int.MaxValue); foreach (var key in props.Keys) { if (props[key].Flags.HasFlag(PropFlags.Accessor)) { DValue getter = props[key].Getter; DValue setter = props[key].Setter; var nodeText = string.Format("{0} = get: {1}, set: {2}", key, getter.ToString(), setter.ToString()); var valueNode = node.Nodes.Add(nodeText); valueNode.ImageKey = props[key].Flags.HasFlag(PropFlags.Enumerable) ? "prop" : "hiddenProp"; valueNode.SelectedImageKey = valueNode.ImageKey; valueNode.Tag = props[key]; } else { DValue value = props[key].Value; var nodeText = string.Format("{0} = {1}", key, value.ToString()); var valueNode = node.Nodes.Add(nodeText); valueNode.ImageKey = props[key].Flags.HasFlag(PropFlags.Enumerable) ? "prop" : "hiddenProp"; valueNode.SelectedImageKey = valueNode.ImageKey; valueNode.Tag = props[key]; if (value.Tag == DValueTag.HeapPtr) { valueNode.Nodes.Add(""); } } } if (node.Nodes.Count > 0 && node.Nodes[0].Text == "") node.Nodes.RemoveAt(0); PropTree.EndUpdate(); } } } <file_sep>/src/engine/atlas.h #ifndef MINISPHERE__ATLAS_H__INCLUDED #define MINISPHERE__ATLAS_H__INCLUDED #include "image.h" typedef struct atlas atlas_t; atlas_t* atlas_new (int num_images, int max_width, int max_height); void atlas_free (atlas_t* atlas); image_t* atlas_image (const atlas_t* atlas); rect_t atlas_xy (const atlas_t* atlas, int image_index); image_t* atlas_load (atlas_t* atlas, sfs_file_t* file, int index, int width, int height); void atlas_lock (atlas_t* atlas); void atlas_unlock (atlas_t* atlas); #endif // MINISPHERE__ATLAS_H__INCLUDED <file_sep>/src/engine/input.h #ifndef MINISPHERE__INPUT_H__INCLUDED #define MINISPHERE__INPUT_H__INCLUDED typedef enum player_key { PLAYER_KEY_MENU, PLAYER_KEY_UP, PLAYER_KEY_DOWN, PLAYER_KEY_LEFT, PLAYER_KEY_RIGHT, PLAYER_KEY_A, PLAYER_KEY_B, PLAYER_KEY_X, PLAYER_KEY_Y, PLAYER_KEY_MAX } player_key_t; void initialize_input (void); void shutdown_input (void); bool is_any_key_down (void); bool is_joy_button_down (int joy_index, int button); bool is_key_down (int keycode); float get_joy_axis (int joy_index, int axis_index); int get_joy_axis_count (int joy_index); int get_joy_button_count (int joy_index); int get_player_key (int player, player_key_t vkey); void set_player_key (int player, player_key_t vkey, int keycode); void attach_input_display (void); void clear_key_queue (void); void load_key_map (void); void save_key_map (void); void update_bound_keys (bool use_map_keys); void update_input (void); void init_input_api (void); #endif // MINISPHERE__INPUT_H__INCLUDED <file_sep>/src/engine/spriteset.c #include "minisphere.h" #include "api.h" #include "atlas.h" #include "image.h" #include "vector.h" #include "spriteset.h" #pragma pack(push, 1) struct rss_header { uint8_t signature[4]; int16_t version; int16_t num_images; int16_t frame_width; int16_t frame_height; int16_t num_directions; int16_t base_x1; int16_t base_y1; int16_t base_x2; int16_t base_y2; uint8_t reserved[106]; }; struct rss_dir_v2 { int16_t num_frames; uint8_t reserved[62]; }; struct rss_dir_v3 { int16_t num_frames; uint8_t reserved[6]; }; struct rss_frame_v2 { int16_t width; int16_t height; int16_t delay; uint8_t reserved[26]; }; struct rss_frame_v3 { int16_t image_idx; int16_t delay; uint8_t reserved[4]; }; #pragma pack(pop) static duk_ret_t js_LoadSpriteset (duk_context* ctx); static duk_ret_t js_new_Spriteset (duk_context* ctx); static duk_ret_t js_Spriteset_finalize (duk_context* ctx); static duk_ret_t js_Spriteset_get_filename (duk_context* ctx); static duk_ret_t js_Spriteset_toString (duk_context* ctx); static duk_ret_t js_Spriteset_clone (duk_context* ctx); static duk_ret_t js_Spriteset_get_image (duk_context* ctx); static duk_ret_t js_Spriteset_set_image (duk_context* ctx); static const spriteset_pose_t* find_sprite_pose (const spriteset_t* spriteset, const char* pose_name); static vector_t* s_load_cache; static unsigned int s_next_spriteset_id = 0; static unsigned int s_num_cache_hits = 0; void initialize_spritesets(void) { console_log(1, "initializing spriteset manager"); s_load_cache = vector_new(sizeof(spriteset_t*)); } void shutdown_spritesets(void) { iter_t iter; spriteset_t** p_spriteset; console_log(1, "shutting down spriteset manager"); console_log(2, " objects created: %u", s_next_spriteset_id); console_log(2, " cache hits: %u", s_num_cache_hits); if (s_load_cache != NULL) { iter = vector_enum(s_load_cache); while (p_spriteset = vector_next(&iter)) free_spriteset(*p_spriteset); vector_free(s_load_cache); } } spriteset_t* clone_spriteset(const spriteset_t* spriteset) { spriteset_t* clone = NULL; int i, j; console_log(2, "cloning spriteset #%u from source spriteset #%u", s_next_spriteset_id, spriteset->id); clone = calloc(1, sizeof(spriteset_t)); clone->base = spriteset->base; clone->num_images = spriteset->num_images; clone->num_poses = spriteset->num_poses; if (!(clone->images = calloc(clone->num_images, sizeof(image_t*)))) goto on_error; for (i = 0; i < spriteset->num_images; ++i) clone->images[i] = ref_image(spriteset->images[i]); if (!(clone->poses = calloc(clone->num_poses, sizeof(spriteset_pose_t)))) goto on_error; for (i = 0; i < spriteset->num_poses; ++i) { if ((clone->poses[i].name = lstr_dup(spriteset->poses[i].name)) == NULL) goto on_error; clone->poses[i].num_frames = spriteset->poses[i].num_frames; if ((clone->poses[i].frames = calloc(clone->poses[i].num_frames, sizeof(spriteset_frame_t))) == NULL) goto on_error; for (j = 0; j < spriteset->poses[i].num_frames; ++j) clone->poses[i].frames[j] = spriteset->poses[i].frames[j]; } clone->id = s_next_spriteset_id++; return ref_spriteset(clone); on_error: if (clone != NULL) { for (i = 0; i < clone->num_images; ++i) free_image(clone->images[i]); if (clone->poses != NULL) for (i = 0; i < clone->num_poses; ++i) { lstr_free(clone->poses[i].name); free(clone->poses[i].frames); } free(clone); } return NULL; } spriteset_t* load_spriteset(const char* filename) { // HERE BE DRAGONS! // the Sphere .rss spriteset format is a nightmare. there are 3 different versions // and RSSv2 is the worst, requiring 2 passes to load properly. as a result this // function ended up being way more massive than it has any right to be. const char* const def_dir_names[8] = { "north", "northeast", "east", "southeast", "south", "southwest", "west", "northwest" }; atlas_t* atlas = NULL; struct rss_dir_v2 dir_v2; struct rss_dir_v3 dir_v3; char extra_v2_dir_name[32]; struct rss_frame_v2 frame_v2; struct rss_frame_v3 frame_v3; sfs_file_t* file = NULL; int image_index; int max_width = 0, max_height = 0; struct rss_header rss; long skip_size; spriteset_t* spriteset = NULL; long v2_data_offset; spriteset_t* *p_spriteset; iter_t iter; int i, j; // check load cache to see if we loaded this file once already if (s_load_cache != NULL) { iter = vector_enum(s_load_cache); while (p_spriteset = vector_next(&iter)) { if (strcmp(filename, (*p_spriteset)->filename) == 0) { console_log(2, "using cached spriteset #%u for `%s`", (*p_spriteset)->id, filename); ++s_num_cache_hits; return clone_spriteset(*p_spriteset); } } } else s_load_cache = vector_new(sizeof(spriteset_t*)); // filename not in load cache, load the spriteset console_log(2, "loading spriteset #%u as `%s`", s_next_spriteset_id, filename); spriteset = calloc(1, sizeof(spriteset_t)); if (!(file = sfs_fopen(g_fs, filename, NULL, "rb"))) goto on_error; if (sfs_fread(&rss, sizeof(struct rss_header), 1, file) != 1) goto on_error; if (memcmp(rss.signature, ".rss", 4) != 0) goto on_error; if (!(spriteset->filename = strdup(filename))) goto on_error; spriteset->base.x1 = rss.base_x1; spriteset->base.y1 = rss.base_y1; spriteset->base.x2 = rss.base_x2; spriteset->base.y2 = rss.base_y2; normalize_rect(&spriteset->base); switch (rss.version) { case 1: // RSSv1, very simple spriteset->num_images = rss.num_images; spriteset->num_poses = 8; spriteset->poses = calloc(spriteset->num_poses, sizeof(spriteset_pose_t)); for (i = 0; i < spriteset->num_poses; ++i) spriteset->poses[i].name = lstr_newf("%s", def_dir_names[i]); if ((spriteset->images = calloc(spriteset->num_images, sizeof(image_t*))) == NULL) goto on_error; if (!(atlas = atlas_new(spriteset->num_images, rss.frame_width, rss.frame_height))) goto on_error; atlas_lock(atlas); for (i = 0; i < spriteset->num_images; ++i) { if (!(spriteset->images[i] = atlas_load(atlas, file, i, rss.frame_width, rss.frame_height))) goto on_error; } atlas_unlock(atlas); atlas_free(atlas); for (i = 0; i < spriteset->num_poses; ++i) { if ((spriteset->poses[i].frames = calloc(8, sizeof(spriteset_frame_t))) == NULL) goto on_error; for (j = 0; j < 8; ++j) { spriteset->poses[i].frames[j].image_idx = j + i * 8; spriteset->poses[i].frames[j].delay = 8; } } break; case 2: // RSSv2, requires 2 passes spriteset->num_poses = rss.num_directions; if (!(spriteset->poses = calloc(spriteset->num_poses, sizeof(spriteset_pose_t)))) goto on_error; // pass 1 - prepare structures, calculate number of images v2_data_offset = sfs_ftell(file); spriteset->num_images = 0; for (i = 0; i < rss.num_directions; ++i) { if (sfs_fread(&dir_v2, sizeof(struct rss_dir_v2), 1, file) != 1) goto on_error; spriteset->num_images += dir_v2.num_frames; sprintf(extra_v2_dir_name, "extra %i", i); spriteset->poses[i].name = lstr_newf("%s", i < 8 ? def_dir_names[i] : extra_v2_dir_name); spriteset->poses[i].num_frames = dir_v2.num_frames; if (!(spriteset->poses[i].frames = calloc(dir_v2.num_frames, sizeof(spriteset_frame_t)))) goto on_error; for (j = 0; j < dir_v2.num_frames; ++j) { // skip over frame and image data if (sfs_fread(&frame_v2, sizeof(struct rss_frame_v2), 1, file) != 1) goto on_error; max_width = fmax(rss.frame_width != 0 ? rss.frame_width : frame_v2.width, max_width); max_height = fmax(rss.frame_height != 0 ? rss.frame_height : frame_v2.height, max_height); skip_size = (rss.frame_width != 0 ? rss.frame_width : frame_v2.width) * (rss.frame_height != 0 ? rss.frame_height : frame_v2.height) * 4; sfs_fseek(file, skip_size, SFS_SEEK_CUR); } } if (!(spriteset->images = calloc(spriteset->num_images, sizeof(image_t*)))) goto on_error; // pass 2 - read images and frame data if (!(atlas = atlas_new(spriteset->num_images, max_width, max_height))) goto on_error; sfs_fseek(file, v2_data_offset, SFS_SEEK_SET); image_index = 0; atlas_lock(atlas); for (i = 0; i < rss.num_directions; ++i) { if (sfs_fread(&dir_v2, sizeof(struct rss_dir_v2), 1, file) != 1) goto on_error; for (j = 0; j < dir_v2.num_frames; ++j) { if (sfs_fread(&frame_v2, sizeof(struct rss_frame_v2), 1, file) != 1) goto on_error; spriteset->images[image_index] = atlas_load(atlas, file, image_index, rss.frame_width != 0 ? rss.frame_width : frame_v2.width, rss.frame_height != 0 ? rss.frame_height : frame_v2.height); spriteset->poses[i].frames[j].image_idx = image_index; spriteset->poses[i].frames[j].delay = frame_v2.delay; ++image_index; } } atlas_unlock(atlas); atlas_free(atlas); break; case 3: // RSSv3, can be done in a single pass thankfully spriteset->num_images = rss.num_images; spriteset->num_poses = rss.num_directions; if ((spriteset->images = calloc(spriteset->num_images, sizeof(image_t*))) == NULL) goto on_error; if ((spriteset->poses = calloc(spriteset->num_poses, sizeof(spriteset_pose_t))) == NULL) goto on_error; if (!(atlas = atlas_new(spriteset->num_images, rss.frame_width, rss.frame_height))) goto on_error; atlas_lock(atlas); for (i = 0; i < rss.num_images; ++i) { if (!(spriteset->images[i] = atlas_load(atlas, file, i, rss.frame_width, rss.frame_height))) goto on_error; } atlas_unlock(atlas); atlas_free(atlas); for (i = 0; i < rss.num_directions; ++i) { if (sfs_fread(&dir_v3, sizeof(struct rss_dir_v3), 1, file) != 1) goto on_error; if ((spriteset->poses[i].name = read_lstring(file, true)) == NULL) goto on_error; spriteset->poses[i].num_frames = dir_v3.num_frames; if ((spriteset->poses[i].frames = calloc(dir_v3.num_frames, sizeof(spriteset_frame_t))) == NULL) goto on_error; for (j = 0; j < spriteset->poses[i].num_frames; ++j) { if (sfs_fread(&frame_v3, sizeof(struct rss_frame_v3), 1, file) != 1) goto on_error; spriteset->poses[i].frames[j].image_idx = frame_v3.image_idx; spriteset->poses[i].frames[j].delay = frame_v3.delay; } } break; default: // invalid RSS version goto on_error; } sfs_fclose(file); if (s_load_cache != NULL) { while (vector_len(s_load_cache) >= 10) { p_spriteset = vector_get(s_load_cache, 0); free_spriteset(*p_spriteset); vector_remove(s_load_cache, 0); } ref_spriteset(spriteset); vector_push(s_load_cache, &spriteset); } spriteset->id = s_next_spriteset_id++; return ref_spriteset(spriteset); on_error: console_log(2, "failed to load spriteset #%u", s_next_spriteset_id); if (file != NULL) sfs_fclose(file); if (spriteset != NULL) { if (spriteset->poses != NULL) { for (i = 0; i < spriteset->num_poses; ++i) { lstr_free(spriteset->poses[i].name); free(spriteset->poses[i].frames); } free(spriteset->poses); } free(spriteset); } if (atlas != NULL) { atlas_unlock(atlas); atlas_free(atlas); } return NULL; } spriteset_t* ref_spriteset(spriteset_t* spriteset) { ++spriteset->refcount; return spriteset; } void free_spriteset(spriteset_t* spriteset) { int i; if (spriteset == NULL || --spriteset->refcount > 0) return; console_log(3, "disposing spriteset #%u no longer in use", spriteset->id); for (i = 0; i < spriteset->num_images; ++i) free_image(spriteset->images[i]); free(spriteset->images); for (i = 0; i < spriteset->num_poses; ++i) { free(spriteset->poses[i].frames); lstr_free(spriteset->poses[i].name); } free(spriteset->poses); free(spriteset->filename); free(spriteset); } rect_t get_sprite_base(const spriteset_t* spriteset) { return spriteset->base; } int get_sprite_frame_delay(const spriteset_t* spriteset, const char* pose_name, int frame_index) { const spriteset_pose_t* pose; if ((pose = find_sprite_pose(spriteset, pose_name)) == NULL) return 0; frame_index %= pose->num_frames; return pose->frames[frame_index].delay; } void get_sprite_size(const spriteset_t* spriteset, int* out_width, int* out_height) { image_t* image; image = spriteset->images[0]; if (out_width) *out_width = get_image_width(image); if (out_height) *out_height = get_image_height(image); } void get_spriteset_info(const spriteset_t* spriteset, int* out_num_images, int* out_num_poses) { if (out_num_images) *out_num_images = spriteset->num_images; if (out_num_poses) *out_num_poses = spriteset->num_poses; } image_t* get_spriteset_image(const spriteset_t* spriteset, int image_index) { return spriteset->images[image_index]; } bool get_spriteset_pose_info(const spriteset_t* spriteset, const char* pose_name, int* out_num_frames) { const spriteset_pose_t* pose; if ((pose = find_sprite_pose(spriteset, pose_name)) == NULL) return false; *out_num_frames = pose->num_frames; return true; } void set_spriteset_image(const spriteset_t* spriteset, int image_index, image_t* image) { image_t* old_image; old_image = spriteset->images[image_index]; spriteset->images[image_index] = ref_image(image); free_image(old_image); } void draw_sprite(const spriteset_t* spriteset, color_t mask, bool is_flipped, double theta, double scale_x, double scale_y, const char* pose_name, float x, float y, int frame_index) { rect_t base; image_t* image; int image_index; int image_w, image_h; const spriteset_pose_t* pose; float scale_w, scale_h; if ((pose = find_sprite_pose(spriteset, pose_name)) == NULL) return; frame_index = frame_index % pose->num_frames; image_index = pose->frames[frame_index].image_idx; base = zoom_rect(spriteset->base, scale_x, scale_y); x -= (base.x1 + base.x2) / 2; if (!is_flipped) y -= (base.y1 + base.y2) / 2; image = spriteset->images[image_index]; image_w = get_image_width(image); image_h = get_image_height(image); scale_w = image_w * scale_x; scale_h = image_h * scale_y; if (x + scale_w <= 0 || x >= g_res_x || y + scale_h <= 0 || y >= g_res_y) return; al_draw_tinted_scaled_rotated_bitmap(get_image_bitmap(image), al_map_rgba(mask.r, mask.g, mask.b, mask.alpha), (float)image_w / 2, (float)image_h / 2, x + scale_w / 2, y + scale_h / 2, scale_x, scale_y, theta, is_flipped ? ALLEGRO_FLIP_VERTICAL : 0x0); } static const spriteset_pose_t* find_sprite_pose(const spriteset_t* spriteset, const char* pose_name) { const char* alt_name; const char* name_to_find; const spriteset_pose_t* pose = NULL; int i; alt_name = strcasecmp(pose_name, "northeast") == 0 ? "north" : strcasecmp(pose_name, "southeast") == 0 ? "south" : strcasecmp(pose_name, "southwest") == 0 ? "south" : strcasecmp(pose_name, "northwest") == 0 ? "north" : ""; name_to_find = pose_name; while (pose == NULL) { for (i = 0; i < spriteset->num_poses; ++i) { if (strcasecmp(name_to_find, lstr_cstr(spriteset->poses[i].name)) == 0) { pose = &spriteset->poses[i]; break; } } if (name_to_find != alt_name) name_to_find = alt_name; else break; } return pose != NULL ? pose : &spriteset->poses[0]; } void init_spriteset_api(duk_context* ctx) { api_register_method(ctx, NULL, "LoadSpriteset", js_LoadSpriteset); api_register_ctor(ctx, "Spriteset", js_new_Spriteset, js_Spriteset_finalize); api_register_prop(ctx, "Spriteset", "filename", js_Spriteset_get_filename, NULL); api_register_method(ctx, "Spriteset", "toString", js_Spriteset_toString); api_register_method(ctx, "Spriteset", "clone", js_Spriteset_clone); } void duk_push_sphere_spriteset(duk_context* ctx, spriteset_t* spriteset) { char prop_name[20]; int i, j; duk_push_sphere_obj(ctx, "Spriteset", ref_spriteset(spriteset)); // Spriteset:base duk_push_object(ctx); duk_push_int(ctx, spriteset->base.x1); duk_put_prop_string(ctx, -2, "x1"); duk_push_int(ctx, spriteset->base.y1); duk_put_prop_string(ctx, -2, "y1"); duk_push_int(ctx, spriteset->base.x2); duk_put_prop_string(ctx, -2, "x2"); duk_push_int(ctx, spriteset->base.y2); duk_put_prop_string(ctx, -2, "y2"); duk_put_prop_string(ctx, -2, "base"); // Spriteset:images duk_push_array(ctx); for (i = 0; i < spriteset->num_images; ++i) { sprintf(prop_name, "%i", i); duk_push_string(ctx, prop_name); duk_push_c_function(ctx, js_Spriteset_get_image, DUK_VARARGS); duk_get_prop_string(ctx, -1, "bind"); duk_dup(ctx, -2); duk_dup(ctx, -6); duk_call_method(ctx, 1); duk_remove(ctx, -2); duk_push_c_function(ctx, js_Spriteset_set_image, DUK_VARARGS); duk_get_prop_string(ctx, -1, "bind"); duk_dup(ctx, -2); duk_dup(ctx, -7); duk_call_method(ctx, 1); duk_remove(ctx, -2); duk_def_prop(ctx, -4, DUK_DEFPROP_HAVE_GETTER | DUK_DEFPROP_HAVE_SETTER | DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE); } duk_put_prop_string(ctx, -2, "images"); // Spriteset:directions duk_push_array(ctx); for (i = 0; i < spriteset->num_poses; ++i) { duk_push_object(ctx); duk_push_lstring_t(ctx, spriteset->poses[i].name); duk_put_prop_string(ctx, -2, "name"); duk_push_array(ctx); for (j = 0; j < spriteset->poses[i].num_frames; ++j) { duk_push_object(ctx); duk_push_int(ctx, spriteset->poses[i].frames[j].image_idx); duk_put_prop_string(ctx, -2, "index"); duk_push_int(ctx, spriteset->poses[i].frames[j].delay); duk_put_prop_string(ctx, -2, "delay"); duk_put_prop_index(ctx, -2, j); } duk_put_prop_string(ctx, -2, "frames"); duk_put_prop_index(ctx, -2, i); } duk_put_prop_string(ctx, -2, "directions"); } static duk_ret_t js_LoadSpriteset(duk_context* ctx) { const char* filename; spriteset_t* spriteset; filename = duk_require_path(ctx, 0, "spritesets", true); if ((spriteset = load_spriteset(filename)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Spriteset(): unable to load spriteset file `%s`", filename); duk_push_sphere_spriteset(ctx, spriteset); free_spriteset(spriteset); return 1; } static duk_ret_t js_new_Spriteset(duk_context* ctx) { const char* filename; spriteset_t* spriteset; filename = duk_require_path(ctx, 0, NULL, false); if ((spriteset = load_spriteset(filename)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Spriteset(): unable to load spriteset file `%s`", filename); duk_push_sphere_spriteset(ctx, spriteset); free_spriteset(spriteset); return 1; } static duk_ret_t js_Spriteset_finalize(duk_context* ctx) { spriteset_t* spriteset; spriteset = duk_require_sphere_obj(ctx, 0, "Spriteset"); free_spriteset(spriteset); return 0; } static duk_ret_t js_Spriteset_get_filename(duk_context* ctx) { spriteset_t* spriteset; duk_push_this(ctx); spriteset = duk_require_sphere_obj(ctx, -1, "Spriteset"); duk_pop(ctx); duk_push_string(ctx, spriteset->filename); return 1; } static duk_ret_t js_Spriteset_toString(duk_context* ctx) { duk_push_string(ctx, "[object spriteset]"); return 1; } static duk_ret_t js_Spriteset_clone(duk_context* ctx) { spriteset_t* new_spriteset; spriteset_t* spriteset; duk_push_this(ctx); spriteset = duk_require_sphere_obj(ctx, -1, "Spriteset"); duk_pop(ctx); if ((new_spriteset = clone_spriteset(spriteset)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Spriteset:clone(): unable to create new spriteset"); duk_push_sphere_spriteset(ctx, new_spriteset); free_spriteset(new_spriteset); return 1; } static duk_ret_t js_Spriteset_get_image(duk_context* ctx) { duk_uarridx_t index = duk_to_int(ctx, 0); spriteset_t* spriteset; duk_push_this(ctx); spriteset = duk_require_sphere_obj(ctx, -1, "Spriteset"); duk_pop(ctx); duk_push_sphere_image(ctx, get_spriteset_image(spriteset, index)); return 1; } static duk_ret_t js_Spriteset_set_image(duk_context* ctx) { image_t* image = duk_require_sphere_image(ctx, 0); duk_uarridx_t index = duk_to_int(ctx, 1); spriteset_t* spriteset; duk_push_this(ctx); spriteset = duk_require_sphere_obj(ctx, -1, "Spriteset"); duk_pop(ctx); set_spriteset_image(spriteset, index, image); return 0; } <file_sep>/src/debugger/parser.c #include "ssj.h" #include "parser.h" struct token { token_tag_t tag; char* string; int line_no; double number; }; struct command { int num_tokens; struct token *tokens; }; command_t* command_parse(const char* string) { command_t* obj; int array_len = 8; int index = 0; size_t length; char next_char; double number_value; char quote[2]; char* string_value; const char *p_ch; char *p_tail; struct token *tokens; tokens = malloc(array_len * sizeof(struct token)); p_ch = string; while (*p_ch != '\0') { while (*p_ch == ' ' || *p_ch == '\t') ++p_ch; // skip whitespace if (*p_ch == '\0') break; // avoid parsing the NUL terminator as a token if (index >= array_len) { array_len *= 2; tokens = realloc(tokens, array_len * sizeof(struct token)); } memset(&tokens[index], 0, sizeof(struct token)); if (*p_ch >= '0' && *p_ch <= '9') { length = strspn(p_ch, "0123456789."); number_value = strtod(p_ch, &p_tail); next_char = *p_tail; if (next_char != '\0' && next_char != ' ' && next_char != '\t') goto syntax_error; tokens[index].tag = TOK_NUMBER; tokens[index].number = number_value; p_ch += length; } else if (*p_ch == '"' || *p_ch == '\'') { sprintf(quote, "%c", *p_ch); length = strcspn(p_ch + 1, quote); next_char = *(p_ch + 1 + length); if (next_char != quote[0]) goto syntax_error; string_value = malloc(length + 1); strncpy(string_value, p_ch + 1, length); string_value[length] = '\0'; tokens[index].tag = TOK_STRING; tokens[index].string = string_value; p_ch += length + 2; } else { length = strcspn(p_ch, " \t'\":"); next_char = *(p_ch + length); string_value = malloc(length + 1); strncpy(string_value, p_ch, length); string_value[length] = '\0'; tokens[index].tag = TOK_STRING; tokens[index].string = string_value; p_ch += length; } if (tokens[index].tag == TOK_STRING && *p_ch == ':') { // a string token followed immediately by a colon with no intervening whitespace // should be parsed instead as a filename/linenumber pair. length = strspn(p_ch + 1, "0123456789"); number_value = strtod(p_ch + 1, &p_tail); next_char = *p_tail; if (next_char != '\0' && next_char != ' ' && next_char != '\t') goto syntax_error; tokens[index].tag = TOK_FILE_LINE; tokens[index].line_no = (int)number_value; p_ch += length + 1; } ++index; } if (index > 0 && tokens[0].tag != TOK_STRING) goto syntax_error; obj = calloc(1, sizeof(command_t)); obj->num_tokens = index; obj->tokens = tokens; return obj; syntax_error: printf("syntax error in command line.\n"); return NULL; } void command_free(command_t* obj) { int i; if (obj == NULL) return; for (i = 0; i < obj->num_tokens; ++i) free(obj->tokens[i].string); free(obj->tokens); free(obj); } int command_len(const command_t* obj) { return obj->num_tokens; } token_tag_t command_get_tag(const command_t* obj, int index) { return obj->tokens[index].tag; } double command_get_float(const command_t* obj, int index) { return obj->tokens[index].tag == TOK_NUMBER ? obj->tokens[index].number : 0.0; } int command_get_int(const command_t* obj, int index) { return obj->tokens[index].tag == TOK_NUMBER ? (int)obj->tokens[index].number : obj->tokens[index].tag == TOK_FILE_LINE ? obj->tokens[index].line_no : 0; } const char* command_get_string(const command_t* obj, int index) { return obj->tokens[index].tag == TOK_STRING || obj->tokens[index].tag == TOK_FILE_LINE ? obj->tokens[index].string : NULL; } <file_sep>/README.md minisphere 3.1 ============== [![Build Status](https://travis-ci.org/fatcerberus/minisphere.svg?branch=master)] (https://travis-ci.org/fatcerberus/minisphere) minisphere is a drop-in replacement and successor to the Sphere game engine, written from the ground up in C. It boasts a high level of compatibility with most games written for Sphere 1.x, with better performance and new functionality. The majority of games will run with no modifications. Overview -------- Like Sphere, minisphere uses JavaScript for game coding. The engine exposes a collection of low-level functions through a standardized JavaScript API, leaving higher-level game logic entirely up to script. This allows any type of game to be made with minisphere; of course, this naturally requires more expertise than making a game with, say, RPG Maker or even Game Maker, but the ultimate flexibility you get in return is worth it. The engine uses Allegro 5 for graphics and sound and Duktape for JavaScript. As both of these are portable to various platforms, this allows minisphere to be compiled successfully on all three major platforms (Windows, Linux, and OS X)--and possibly others--with no changes to the source. Powerful JS Debugging --------------------- minisphere includes a powerful but easy-to-use command-line debugger, called SSJ. The debugger allows you to step through your game's code and inspect the internal state of the game--variables, call stack, objects, etc.--as it executes. And since minisphere uses JavaScript, the original source files aren't required to be present--SSJ can download source code directly from the minisphere instance being debugged. A symbolic debugger such as SSJ is an invaluable tool for development and is a minisphere exclusive: No similar tool was ever available for Sphere 1.x. Download ======== The latest stable minisphere release at the time of this writing is **minisphere 3.1.0**, released on Saturday, May 7, 2016. The binaries are provided through GitHub, and the latest version is always available for download here: * <https://github.com/fatcerberus/minisphere/releases> For an overview of breaking changes in the current major stable release series, refer to [`RELEASES.md`](RELEASES.md). License ======= minisphere and accompanying command-line tools are licensed under the terms of the BSD-3-clause license. Practically speaking, this means the engine can be used for any purpose, even commercially, with no restriction other than maintain the original copyright notice. <file_sep>/src/compiler/image.h #ifndef CELL__IMAGE_H__INCLUDED #define CELL__IMAGE_H__INCLUDED #include "path.h" #include <stdint.h> typedef struct image image_t; image_t* image_open (const path_t* path); void image_close (image_t* image); const uint32_t* image_get_pixelbuf (const image_t* image); const ptrdiff_t image_get_pitch (const image_t* image); int image_get_width (const image_t* image); int image_get_height (const image_t* image); #endif // CELL__IMAGE_H__INCLUDED <file_sep>/src/plugin/Debugger/Inferior.cs using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace minisphere.Gdk.Debugger { class ThrowEventArgs : EventArgs { public ThrowEventArgs(string message, string filename, int lineNumber, bool isFatal) { Message = message; FileName = filename; LineNumber = lineNumber; IsFatal = isFatal; } /// <summary> /// Gets the filename of the script throwing the error. /// </summary> public string FileName { get; private set; } /// <summary> /// Gets whether the error was fatal, i.e. unhandled. /// </summary> public bool IsFatal { get; private set; } /// <summary> /// Gets the line number where the error was thrown. /// </summary> public int LineNumber { get; private set; } /// <summary> /// Gets the string representation of the thrown value. /// </summary> public string Message { get; private set; } } class TraceEventArgs : EventArgs { public TraceEventArgs(string text) { Text = text; } public string Text { get; private set; } } /// <summary> /// Allows control of a Duktape debug target over TCP. /// </summary> class Inferior : IDisposable { private TcpClient tcp = new TcpClient() { NoDelay = true }; private Thread messenger = null; private object replyLock = new object(); private Queue<DMessage> requests = new Queue<DMessage>(); private Dictionary<DMessage, DMessage> replies = new Dictionary<DMessage, DMessage>(); /// <summary> /// Constructs an Inferior to control a Duktape debuggee. /// </summary> public Inferior() { } ~Inferior() { Dispose(); } /// <summary> /// Releases all resources used by the Inferior. /// </summary> public void Dispose() { messenger?.Abort(); Alert = null; Attached = null; Detached = null; Print = null; Status = null; Throw = null; tcp.Close(); } /// <summary> /// Fires when a script calls alert(). /// </summary> public event EventHandler<TraceEventArgs> Alert; /// <summary> /// Fires when the debugger is attached to a target. /// </summary> public event EventHandler Attached; /// <summary> /// Fires when the debugger is detached from a target. /// </summary> public event EventHandler Detached; /// <summary> /// Fires when a script calls print(). /// </summary> public event EventHandler<TraceEventArgs> Print; /// <summary> /// Fires when execution status (code position, etc.) has changed. /// </summary> public event EventHandler Status; /// <summary> /// Fires when an error is thrown by JavaScript code. /// </summary> public event EventHandler<ThrowEventArgs> Throw; /// <summary> /// Gets the target's application identification string. /// </summary> public string TargetID { get; private set; } /// <summary> /// Gets the target's Duktape version ID string. /// </summary> public string Version { get; private set; } /// <summary> /// Gets the filename reported in the last status update. /// </summary> public string FileName { get; private set; } /// <summary> /// Gets the line number being executed as of the last status update. /// </summary> public int LineNumber { get; private set; } /// <summary> /// Gets whether the target is actively executing code. /// </summary> public bool Running { get; private set; } public async Task Connect(string hostname, int port) { // connect to Duktape debug server await tcp.ConnectAsync(hostname, port); string line = ""; await Task.Run(() => { byte[] buffer = new byte[1]; while (buffer[0] != '\n') { tcp.Client.ReceiveAll(buffer); line += (char)buffer[0]; } }); string[] handshake = line.Trim().Split(new[] { ' ' }, 4); int debuggerVersion = int.Parse(handshake[0]); if (debuggerVersion != 1) throw new NotSupportedException("Error communicating with debug server"); Version = handshake[2]; TargetID = handshake[3]; // start the communication thread messenger = new Thread(ProcessMessages) { IsBackground = true }; messenger.Start(); Attached?.Invoke(this, EventArgs.Empty); } /// <summary> /// Sets a breakpoint. Execution will pause automatically if the breakpoint is hit. /// </summary> /// <param name="filename">The filename in which to place the breakpoint.</param> /// <param name="lineNumber">The line number of the breakpoint.</param> /// <returns>The index assigned to the breakpoint by Duktape.</returns> public async Task<int> AddBreak(string filename, int lineNumber) { var reply = await DoRequest(DValueTag.REQ, Request.AddBreak, filename, lineNumber); return (int)reply[1]; } /// <summary> /// Clears the breakpoint with the specified index. /// </summary> /// <param name="index">The index of the breakpoint to clear, as returned by AddBreak.</param> /// <returns></returns> public async Task DelBreak(int index) { await DoRequest(DValueTag.REQ, Request.DelBreak, index); } /// <summary> /// Requests that Duktape end the debug session. /// </summary> /// <returns></returns> public async Task Detach() { if (messenger == null) return; await DoRequest(DValueTag.REQ, Request.Detach); await Task.Run(() => messenger.Join()); tcp.Client.Disconnect(true); Detached?.Invoke(this, EventArgs.Empty); } /// <summary> /// Evaluates a JS expression and returns the JX-encoded result. /// </summary> /// <param name="expression">The expression or statement to evaluate.</param> /// <param name="stackOffset">The point in the stack to do the eval. -1 is active call, -2 the caller, etc..</param> /// <returns>The value produced by the expression.</returns> public async Task<DValue> Eval(string expression, int stackOffset = -1) { var reply = await DoRequest(DValueTag.REQ, Request.Eval, expression, stackOffset); return reply[2]; } /// <summary> /// Gets a list of function calls currently on the stack. Note that Duktape /// supports tail return, so this may not reflect all active calls. /// </summary> /// <returns> /// An array of 3-tuples naming the function, filename and current line number /// of each function call on the stack, from top to the bottom. /// </returns> public async Task<Tuple<string, string, int>[]> GetCallStack() { var reply = await DoRequest(DValueTag.REQ, Request.GetCallStack); var stack = new List<Tuple<string, string, int>>(); int count = (reply.Length - 1) / 4; for (int i = 0; i < count; ++i) { string filename = (string)reply[1 + i * 4]; string functionName = (string)reply[2 + i * 4]; int lineNumber = (int)reply[3 + i * 4]; int pc = (int)reply[4 + i * 4]; if (lineNumber == 0) filename = "(system call)"; stack.Add(Tuple.Create(functionName, filename, lineNumber)); } return stack.ToArray(); } /// <summary> /// Gets a list of local values and their values. Note that objects /// are not evaluated and are listed simply as "{ obj: 'ClassName' }". /// </summary> /// <param name="stackOffset">The call stack offset to get locals for, -1 being the current activation.</param> /// <returns></returns> public async Task<IReadOnlyDictionary<string, DValue>> GetLocals(int stackOffset = -1) { var reply = await DoRequest(DValueTag.REQ, Request.GetLocals, stackOffset); var vars = new Dictionary<string, DValue>(); int count = (reply.Length - 1) / 2; for (int i = 0; i < count; ++i) { string name = (string)reply[1 + i * 2]; DValue value = reply[2 + i * 2]; vars.Add(name, value); } return vars; } public async Task<Dictionary<string, PropDesc>> GetObjPropDescRange(HeapPtr ptr, int start, int end) { var reply = await DoRequest(DValueTag.REQ, Request.GetObjPropDescRange, ptr, start, end); var props = new Dictionary<string, PropDesc>(); int count = (reply.Length - 1) / 2; int i = 1; while (i < reply.Length) { PropFlags flags = (PropFlags)(int)reply[i++]; string name = reply[i++].ToString(); if (flags.HasFlag(PropFlags.Accessor)) { DValue getter = reply[i++]; DValue setter = reply[i++]; PropDesc propValue = new PropDesc(getter, setter, flags); if (!flags.HasFlag(PropFlags.Internal)) props.Add(name, propValue); } else { DValue value = reply[i++]; PropDesc propValue = new PropDesc(value, flags); if (!flags.HasFlag(PropFlags.Internal) && value.Tag != DValueTag.Unused) props.Add(name, propValue); } } return props; } /// <summary> /// Gets a list of currently set breakpoints. /// </summary> /// <returns> /// An array of 2-tuples specifying the location of each breakpoint /// as a filename/line number pair /// </returns> public async Task<Tuple<string, int>[]> ListBreak() { var reply = await DoRequest(DValueTag.REQ, Request.ListBreak); var count = (reply.Length - 1) / 2; List<Tuple<string, int>> list = new List<Tuple<string, int>>(); for (int i = 0; i < count; ++i) { var breakpoint = Tuple.Create( (string)reply[1 + i * 2], (int)reply[2 + i * 2]); list.Add(breakpoint); } return list.ToArray(); } /// <summary> /// Requests Duktape to pause execution and break into the debugger. /// This may take a second or so to register. /// </summary> /// <returns></returns> public async Task Pause() { await DoRequest(DValueTag.REQ, Request.Pause); } /// <summary> /// Resumes normal program execution. /// </summary> /// <returns></returns> public async Task Resume() { await DoRequest(DValueTag.REQ, Request.Resume); } /// <summary> /// Executes the next line of code. If a function is called, the debugger /// will break at the first statement in that function. /// </summary> /// <returns></returns> public async Task StepInto() { await DoRequest(DValueTag.REQ, Request.StepInto); } /// <summary> /// Resumes normal execution until the current function returns. /// </summary> /// <returns></returns> public async Task StepOut() { await DoRequest(DValueTag.REQ, Request.StepOut); } /// <summary> /// Executes the next line of code. /// </summary> /// <returns></returns> public async Task StepOver() { await DoRequest(DValueTag.REQ, Request.StepOver); } private async Task<DMessage> DoRequest(params dynamic[] values) { DMessage message = new DMessage(values); lock (replyLock) requests.Enqueue(message); message.Send(tcp.Client); return await Task.Run(() => { while (true) { lock (replyLock) { if (replies.ContainsKey(message)) { var reply = replies[message]; replies.Remove(message); return reply; } } Thread.Sleep(1); } }); } private void ProcessMessages() { while (true) { DMessage message = DMessage.Receive(tcp.Client); if (message == null) { // if DMessage.Receive() returns null, detach. tcp.Close(); Detached?.Invoke(this, EventArgs.Empty); return; } else if (message[0].Tag == DValueTag.NFY) { switch ((Notify)(int)message[1]) { case Notify.Status: FileName = (string)message[3]; LineNumber = (int)message[5]; Running = (int)message[2] == 0; Status?.Invoke(this, EventArgs.Empty); break; case Notify.Print: string printText = (string)message[2]; Print?.Invoke(this, new TraceEventArgs("p: " + printText)); break; case Notify.Alert: string alertText = (string)message[2]; Alert?.Invoke(this, new TraceEventArgs("a: " + alertText)); break; case Notify.Throw: Throw?.Invoke(this, new ThrowEventArgs( (string)message[3], (string)message[4], (int)message[5], (int)message[2] != 0)); break; case Notify.Detaching: tcp.Close(); Detached?.Invoke(this, EventArgs.Empty); return; case Notify.AppNotify: switch ((AppNotify)(int)message[2]) { case AppNotify.DebugPrint: string debugText = (string)message[3]; Print?.Invoke(this, new TraceEventArgs("t: " + debugText)); break; } break; } } else if (message[0].Tag == DValueTag.REP || message[0].Tag == DValueTag.ERR) { lock (replyLock) { DMessage request = requests.Dequeue(); replies.Add(request, message); } } } } } } <file_sep>/src/plugin/Debugger/PropDesc.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace minisphere.Gdk.Debugger { struct PropDesc { public PropDesc(DValue value, PropFlags flags) { Value = value; Getter = Setter = null; Flags = flags; } public PropDesc(DValue getter, DValue setter, PropFlags flags) { Value = null; Getter = getter; Setter = setter; Flags = flags; } public DValue Value; public DValue Getter; public DValue Setter; public PropFlags Flags; } [Flags] enum PropFlags { None = 0x0000, Writable = 0x0001, Enumerable = 0x0002, Configurable = 0x0004, Accessor = 0x0008, Virtual = 0x0010, Internal = 0x0100, } } <file_sep>/src/debugger/dvalue.h #ifndef SSJ__DVALUE_H__INCLUDED #define SSJ__DVALUE_H__INCLUDED #include "sockets.h" typedef struct dvalue dvalue_t; typedef struct remote_ptr { uintmax_t addr; uint8_t size; } remote_ptr_t; typedef enum dvalue_tag { DVALUE_EOM = 0x00, DVALUE_REQ = 0x01, DVALUE_REP = 0x02, DVALUE_ERR = 0x03, DVALUE_NFY = 0x04, DVALUE_INT = 0x10, DVALUE_STRING = 0x11, DVALUE_STRING16 = 0x12, DVALUE_BUFFER = 0x13, DVALUE_BUF16 = 0x14, DVALUE_UNUSED = 0x15, DVALUE_UNDEF = 0x16, DVALUE_NULL = 0x17, DVALUE_TRUE = 0x18, DVALUE_FALSE = 0x19, DVALUE_FLOAT = 0x1A, DVALUE_OBJ = 0x1B, DVALUE_PTR = 0x1C, DVALUE_LIGHTFUNC = 0x1D, DVALUE_HEAPPTR = 0x1E, } dvalue_tag_t; dvalue_t* dvalue_new (dvalue_tag_t tag); dvalue_t* dvalue_new_float (double value); dvalue_t* dvalue_new_heapptr (remote_ptr_t value); dvalue_t* dvalue_new_int (int value); dvalue_t* dvalue_new_string (const char* value); dvalue_t* dvalue_dup (const dvalue_t* obj); void dvalue_free (dvalue_t* obj); dvalue_tag_t dvalue_tag (const dvalue_t* obj); const char* dvalue_as_cstr (const dvalue_t* obj); remote_ptr_t dvalue_as_ptr (const dvalue_t* obj); double dvalue_as_float (const dvalue_t* obj); int dvalue_as_int (const dvalue_t* obj); void dvalue_print (const dvalue_t* obj, bool is_verbose); dvalue_t* dvalue_recv (socket_t* socket); bool dvalue_send (const dvalue_t* obj, socket_t* socket); #endif // SSJ__DVALUE_H__INCLUDED <file_sep>/src/debugger/backtrace.h #ifndef SSJ__BACKTRACE_H__INCLUDED #define SSJ__BACKTRACE_H__INCLUDED typedef struct backtrace backtrace_t; backtrace_t* backtrace_new (void); void backtrace_free (backtrace_t* obj); int backtrace_len (const backtrace_t* obj); const char* backtrace_get_call_name (const backtrace_t* obj, int index); const char* backtrace_get_filename (const backtrace_t* obj, int index); int backtrace_get_linenum (const backtrace_t* obj, int index); void backtrace_add (backtrace_t* obj, const char* call_name, const char* filename, int line_no); void backtrace_print (const backtrace_t* obj, int active_frame, bool show_all); #endif // SSJ__BACKTRACE_H__INCLUDED <file_sep>/src/engine/shader.c #include "minisphere.h" #include "shader.h" #include "api.h" #include "matrix.h" static duk_ret_t js_new_ShaderProgram (duk_context* ctx); static duk_ret_t js_ShaderProgram_finalize (duk_context* ctx); struct shader { unsigned int id; unsigned int refcount; #ifdef MINISPHERE_USE_SHADERS ALLEGRO_SHADER* program; #endif }; static bool s_have_shaders = false; static unsigned int s_next_id = 1; void initialize_shaders(bool enable_shading) { console_log(1, "initializing shader support"); #ifdef MINISPHERE_USE_SHADERS s_have_shaders = enable_shading; #endif shader_use(NULL); } void shutdown_shaders(void) { console_log(1, "shutting down shader manager"); } bool are_shaders_active(void) { return s_have_shaders; } shader_t* shader_new(const char* vs_filename, const char* fs_filename) { char* fs_source = NULL; char* vs_source = NULL; shader_t* shader; shader = calloc(1, sizeof(shader_t)); console_log(2, "compiling new shader program #%u", s_next_id); if (!(vs_source = sfs_fslurp(g_fs, vs_filename, NULL, NULL))) goto on_error; if (!(fs_source = sfs_fslurp(g_fs, fs_filename, NULL, NULL))) goto on_error; #ifdef MINISPHERE_USE_SHADERS if (!(shader->program = al_create_shader(ALLEGRO_SHADER_GLSL))) goto on_error; if (!al_attach_shader_source(shader->program, ALLEGRO_VERTEX_SHADER, vs_source)) { fprintf(stderr, "\nvertex shader compile log:\n%s\n", al_get_shader_log(shader->program)); goto on_error; } if (!al_attach_shader_source(shader->program, ALLEGRO_PIXEL_SHADER, fs_source)) { fprintf(stderr, "\nfragment shader compile log:\n%s\n", al_get_shader_log(shader->program)); goto on_error; } if (!al_build_shader(shader->program)) { fprintf(stderr, "\nerror building shader program:\n%s\n", al_get_shader_log(shader->program)); goto on_error; } #endif free(vs_source); free(fs_source); shader->id = s_next_id++; return shader_ref(shader); on_error: free(vs_source); free(fs_source); #ifdef MINISPHERE_USE_SHADERS if (shader->program != NULL) al_destroy_shader(shader->program); #endif free(shader); return NULL; } shader_t* shader_ref(shader_t* shader) { if (shader == NULL) return shader; ++shader->refcount; return shader; } void shader_free(shader_t* shader) { if (shader == NULL || --shader->refcount > 0) return; console_log(3, "disposing shader program #%u no longer in use", shader->id); #ifdef MINISPHERE_USE_SHADERS al_destroy_shader(shader->program); #endif free(shader); } bool shader_use(shader_t* shader) { #ifdef MINISPHERE_USE_SHADERS ALLEGRO_SHADER* al_shader; if (shader != NULL) console_log(4, "activating shader program #%u", shader->id); else console_log(4, "activating null shader"); if (s_have_shaders) { al_shader = shader != NULL ? shader->program : NULL; if (!al_use_shader(al_shader)) return false; return true; } else { // if shaders are not supported, degrade gracefully. this simplifies the rest // of the engine, which simply assumes shaders are always supported. return true; } #else return true; #endif } void init_shader_api(void) { api_register_ctor(g_duk, "ShaderProgram", js_new_ShaderProgram, js_ShaderProgram_finalize); } static duk_ret_t js_new_ShaderProgram(duk_context* ctx) { const char* fs_filename; const char* vs_filename; shader_t* shader; if (!duk_is_object(ctx, 0)) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "ShaderProgram(): JS object expected as argument"); if (duk_get_prop_string(ctx, 0, "vertex"), !duk_is_string(ctx, -1)) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "ShaderProgram(): 'vertex' property, string required"); if (duk_get_prop_string(ctx, 0, "fragment"), !duk_is_string(ctx, -1)) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "ShaderProgram(): 'fragment' property, string required"); duk_pop_2(ctx); if (!are_shaders_active()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ShaderProgram(): shaders not supported on this system"); duk_get_prop_string(ctx, 0, "vertex"); duk_get_prop_string(ctx, 0, "fragment"); vs_filename = duk_require_path(ctx, -2, NULL, false); fs_filename = duk_require_path(ctx, -1, NULL, false); duk_pop_2(ctx); if (!(shader = shader_new(vs_filename, fs_filename))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ShaderProgram(): failed to build shader from `%s`, `%s`", vs_filename, fs_filename); duk_push_sphere_obj(ctx, "ShaderProgram", shader); return 1; } static duk_ret_t js_ShaderProgram_finalize(duk_context* ctx) { shader_t* shader = duk_require_sphere_obj(ctx, 0, "ShaderProgram"); shader_free(shader); return 0; } <file_sep>/src/engine/atlas.c #include "minisphere.h" #include "image.h" #include "atlas.h" struct atlas { unsigned int id; image_t* image; rect_t size; int pitch; int max_width, max_height; image_lock_t* lock; }; static unsigned int s_next_atlas_id = 0; atlas_t* atlas_new(int num_images, int max_width, int max_height) { atlas_t* atlas; console_log(4, "creating atlas #%u at %ix%i per image", s_next_atlas_id, max_width, max_height); atlas = calloc(1, sizeof(atlas_t)); atlas->pitch = ceil(sqrt(num_images)); atlas->max_width = max_width; atlas->max_height = max_height; atlas->size = new_rect(0, 0, atlas->pitch * atlas->max_width, atlas->pitch * atlas->max_height); if (!(atlas->image = create_image(atlas->size.x2, atlas->size.y2))) goto on_error; atlas->id = s_next_atlas_id++; return atlas; on_error: console_log(4, "failed to create atlas #%u", s_next_atlas_id++); if (atlas != NULL) { free_image(atlas->image); free(atlas); } return NULL; } void atlas_free(atlas_t* atlas) { console_log(4, "disposing atlas #%u no longer in use", atlas->id); if (atlas->lock != NULL) unlock_image(atlas->image, atlas->lock); free_image(atlas->image); free(atlas); } image_t* atlas_image(const atlas_t* atlas) { return atlas->image; } float_rect_t atlas_uv(const atlas_t* atlas, int image_index) { float atlas_height; float atlas_width; float_rect_t uv; atlas_width = get_image_width(atlas->image); atlas_height = get_image_height(atlas->image); uv.x1 = (image_index % atlas->pitch) * atlas->max_width; uv.y1 = (image_index / atlas->pitch) * atlas->max_height; uv.x2 = uv.x1 + atlas->max_width; uv.y2 = uv.y1 + atlas->max_height; return uv; } rect_t atlas_xy(const atlas_t* atlas, int image_index) { float atlas_height; float atlas_width; rect_t xy; atlas_width = get_image_width(atlas->image); atlas_height = get_image_height(atlas->image); xy.x1 = (image_index % atlas->pitch) * atlas->max_width; xy.y1 = (image_index / atlas->pitch) * atlas->max_height; xy.x2 = xy.x1 + atlas->max_width; xy.y2 = xy.y1 + atlas->max_height; return xy; } void atlas_lock(atlas_t* atlas) { console_log(4, "locking atlas #%u for direct access", atlas->id); atlas->lock = lock_image(atlas->image); } void atlas_unlock(atlas_t* atlas) { console_log(4, "unlocking atlas #%u", atlas->id); unlock_image(atlas->image, atlas->lock); atlas->lock = NULL; } image_t* atlas_load(atlas_t* atlas, sfs_file_t* file, int index, int width, int height) { int off_x, off_y; if (width > atlas->max_width || height > atlas->max_height) return NULL; if (index >= atlas->pitch * atlas->pitch) return NULL; off_x = index % atlas->pitch * atlas->max_width; off_y = index / atlas->pitch * atlas->max_height; return read_subimage(file, atlas->image, off_x, off_y, width, height); } <file_sep>/src/engine/minisphere.h #ifdef _MSC_VER #define _CRT_NONSTDC_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #define _USE_MATH_DEFINES #endif #include <stdlib.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <limits.h> #include <math.h> #include <setjmp.h> #include <time.h> #include <sys/stat.h> #include <allegro5/allegro.h> #include <allegro5/allegro_audio.h> #include <allegro5/allegro_acodec.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_memfile.h> #include <allegro5/allegro_native_dialog.h> #include <allegro5/allegro_primitives.h> #include <zlib.h> #include "version.h" #include "duktape.h" #include "dyad.h" #include "console.h" #include "spherefs.h" #include "file.h" #include "font.h" #include "geometry.h" #include "screen.h" #include "lstring.h" #include "path.h" #include "script.h" #include "utility.h" #include "vector.h" #ifdef _MSC_VER #define strcasecmp stricmp #define snprintf _snprintf #endif #define SPHERE_PATH_MAX 1024 #if defined(__GNUC__) #define noreturn __attribute__((noreturn)) void #elif defined(__clang__) #define noreturn __attribute__((noreturn)) void #elif defined(_MSC_VER) #define noreturn __declspec(noreturn) void #else #define noreturn void #endif #if ALLEGRO_VERSION >= 5 && ALLEGRO_SUB_VERSION >= 2 #define MINISPHERE_USE_3D_TRANSFORM #define MINISPHERE_USE_CLIPBOARD #define MINISPHERE_USE_SHADERS #define MINISPHERE_USE_VERTEX_BUF #endif extern duk_context* g_duk; extern ALLEGRO_EVENT_QUEUE* g_events; extern sandbox_t* g_fs; extern int g_framerate; extern path_t* g_game_path; extern path_t* g_last_game_path; extern screen_t* g_screen; extern kevfile_t* g_sys_conf; extern font_t* g_sys_font; extern int g_res_x; extern int g_res_y; void delay (double time); void do_events (void); noreturn exit_game (bool force_shutdown); noreturn restart_engine (void); <file_sep>/src/debugger/sockets.c #include "ssj.h" #include "sockets.h" #include <dyad.h> struct socket { bool has_closed; dyad_Stream* stream; uint8_t* recv_buffer; int recv_size; int buf_size; }; static void dyad_on_stream_close(dyad_Event* e) { socket_t* obj; obj = e->udata; obj->has_closed = true; } static void dyad_on_stream_recv(dyad_Event* e) { socket_t* obj; bool need_resize = false; char* write_ptr; obj = e->udata; while (obj->recv_size + e->size > obj->buf_size) { obj->buf_size *= 2; need_resize = true; } if (need_resize) obj->recv_buffer = realloc(obj->recv_buffer, obj->buf_size); write_ptr = obj->recv_buffer + obj->recv_size; obj->recv_size += e->size; memcpy(write_ptr, e->data, e->size); } void sockets_init() { dyad_init(); dyad_setUpdateTimeout(0.05); } void sockets_deinit() { dyad_shutdown(); } socket_t* socket_connect(const char* hostname, int port, double timeout) { clock_t end_time; bool is_connected; socket_t* obj; int state; obj = calloc(1, sizeof(socket_t)); obj->stream = dyad_newStream(); dyad_addListener(obj->stream, DYAD_EVENT_DATA, dyad_on_stream_recv, obj); dyad_setNoDelay(obj->stream, true); obj->buf_size = 4096; obj->recv_buffer = malloc(obj->buf_size); is_connected = false; end_time = clock() + (clock_t)(timeout * CLOCKS_PER_SEC); do { state = dyad_getState(obj->stream); if (state == DYAD_STATE_CLOSED) dyad_connect(obj->stream, hostname, port); is_connected = state == DYAD_STATE_CONNECTED; if (clock() >= end_time) goto on_timeout; dyad_update(); } while (state != DYAD_STATE_CONNECTED); dyad_addListener(obj->stream, DYAD_EVENT_CLOSE, dyad_on_stream_close, obj); return obj; on_timeout: dyad_close(obj->stream); free(obj->recv_buffer); free(obj); return NULL; } void socket_close(socket_t* obj) { if (!obj->has_closed) { dyad_end(obj->stream); while (!obj->has_closed) dyad_update(); } free(obj->recv_buffer); free(obj); } bool socket_is_live(socket_t* obj) { return !obj->has_closed; } int socket_recv(socket_t* obj, void* buffer, int num_bytes) { while (obj->recv_size < num_bytes && !obj->has_closed) dyad_update(); if (obj->recv_size < num_bytes) return 0; else { memcpy(buffer, obj->recv_buffer, num_bytes); obj->recv_size -= num_bytes; memmove(obj->recv_buffer, obj->recv_buffer + num_bytes, obj->recv_size); return num_bytes; } } int socket_send(socket_t* obj, const void* data, int num_bytes) { if (obj->has_closed) return 0; dyad_write(obj->stream, data, num_bytes); if (num_bytes > 0) dyad_update(); return num_bytes; } <file_sep>/src/plugin/DockPanes/ConsolePane.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Sphere.Plugins; using Sphere.Plugins.Interfaces; using minisphere.Gdk.Properties; namespace minisphere.Gdk.DockPanes { partial class ConsolePane : UserControl, IDockPane { PluginConf _conf; List<string> _lines = new List<string>(); public ConsolePane(PluginConf conf) { InitializeComponent(); _conf = conf; } public bool ShowInViewMenu => true; public Control Control => this; public DockHint DockHint => DockHint.Bottom; public Bitmap DockIcon => Resources.ConsoleIcon; public void Clear() { _lines.Clear(); PrintTimer.Start(); } public void Print(string text) { _lines.Add(text); PrintTimer.Start(); } private void PrintTimer_Tick(object sender, EventArgs e) { PrintTimer.Stop(); textOutput.Text = string.Join("\r\n", _lines) + "\r\n"; textOutput.SelectionStart = textOutput.Text.Length; textOutput.SelectionLength = 0; textOutput.ScrollToCaret(); } } } <file_sep>/src/engine/galileo.c #include "minisphere.h" #include "api.h" #include "color.h" #include "shader.h" #include "vector.h" #include "galileo.h" static duk_ret_t js_GetDefaultShaderProgram (duk_context* ctx); static duk_ret_t js_new_Group (duk_context* ctx); static duk_ret_t js_Group_finalize (duk_context* ctx); static duk_ret_t js_Group_get_shader (duk_context* ctx); static duk_ret_t js_Group_get_transform (duk_context* ctx); static duk_ret_t js_Group_set_shader (duk_context* ctx); static duk_ret_t js_Group_set_transform (duk_context* ctx); static duk_ret_t js_Group_draw (duk_context* ctx); static duk_ret_t js_Group_setFloat (duk_context* ctx); static duk_ret_t js_Group_setInt (duk_context* ctx); static duk_ret_t js_Group_setMatrix (duk_context* ctx); static duk_ret_t js_new_Shape (duk_context* ctx); static duk_ret_t js_Shape_finalize (duk_context* ctx); static duk_ret_t js_Shape_get_texture (duk_context* ctx); static duk_ret_t js_Shape_set_texture (duk_context* ctx); static duk_ret_t js_Shape_draw (duk_context* ctx); static duk_ret_t js_new_Transform (duk_context* ctx); static duk_ret_t js_Transform_finalize (duk_context* ctx); static duk_ret_t js_Transform_compose (duk_context* ctx); static duk_ret_t js_Transform_identity (duk_context* ctx); static duk_ret_t js_Transform_rotate (duk_context* ctx); static duk_ret_t js_Transform_scale (duk_context* ctx); static duk_ret_t js_Transform_translate (duk_context* ctx); static void assign_default_uv (shape_t* shape); static void free_cached_uniform (group_t* group, const char* name); static bool have_vertex_buffer (const shape_t* shape); static void render_shape (shape_t* shape); enum uniform_type { UNIFORM_INT, UNIFORM_INT_VEC, UNIFORM_FLOAT, UNIFORM_FLOAT_VEC, UNIFORM_MATRIX, }; struct uniform { char name[256]; enum uniform_type type; union { ALLEGRO_TRANSFORM mat_value; int int_value; float float_value; }; }; struct shape { unsigned int refcount; unsigned int id; image_t* texture; shape_type_t type; ALLEGRO_VERTEX* sw_vbuf; int max_vertices; int num_vertices; vertex_t* vertices; #ifdef MINISPHERE_USE_VERTEX_BUF ALLEGRO_VERTEX_BUFFER* vbuf; #endif }; struct group { unsigned int refcount; unsigned int id; shader_t* shader; vector_t* shapes; matrix_t* transform; vector_t* uniforms; }; static shader_t* s_def_shader = NULL; static unsigned int s_next_group_id = 0; static unsigned int s_next_shape_id = 0; void initialize_galileo(void) { console_log(1, "initializing Galileo"); } void shutdown_galileo(void) { console_log(1, "shutting down Galileo"); shader_free(s_def_shader); } shader_t* get_default_shader(void) { const char* fs_filename; char* fs_pathname; const char* vs_filename; char* vs_pathname; if (s_def_shader == NULL) { console_log(3, "compiling Galileo default shaders"); vs_filename = kev_read_string(g_sys_conf, "GalileoVertShader", "shaders/galileo.vs.glsl"); fs_filename = kev_read_string(g_sys_conf, "GalileoFragShader", "shaders/galileo.fs.glsl"); vs_pathname = strdup(systempath(vs_filename)); fs_pathname = strdup(systempath(fs_filename)); s_def_shader = shader_new(vs_pathname, fs_pathname); free(vs_pathname); free(fs_pathname); } return s_def_shader; } vertex_t vertex(float x, float y, float z, float u, float v, color_t color) { vertex_t vertex; vertex.x = x; vertex.y = y; vertex.z = z; vertex.u = u; vertex.v = v; vertex.color = color; return vertex; } group_t* group_new(shader_t* shader) { group_t* group; console_log(4, "creating new group #%u", s_next_group_id); group = calloc(1, sizeof(group_t)); group->shapes = vector_new(sizeof(shape_t*)); group->transform = matrix_new(); group->shader = shader_ref(shader); group->uniforms = vector_new(sizeof(struct uniform)); group->id = s_next_group_id++; return group_ref(group); } group_t* group_ref(group_t* group) { if (group != NULL) ++group->refcount; return group; } void group_free(group_t* group) { shape_t** i_shape; iter_t iter; if (group == NULL || --group->refcount > 0) return; console_log(4, "disposing group #%u no longer in use", group->id); iter = vector_enum(group->shapes); while (i_shape = vector_next(&iter)) shape_free(*i_shape); vector_free(group->shapes); shader_free(group->shader); matrix_free(group->transform); vector_free(group->uniforms); free(group); } shader_t* group_get_shader(const group_t* group) { return group->shader; } matrix_t* group_get_transform(const group_t* group) { return group->transform; } void group_set_shader(group_t* group, shader_t* shader) { shader_t* old_shader; old_shader = group->shader; group->shader = shader_ref(shader); shader_free(old_shader); } void group_set_transform(group_t* group, matrix_t* transform) { matrix_t* old_transform; old_transform = group->transform; group->transform = matrix_ref(transform); matrix_free(old_transform); } bool group_add_shape(group_t* group, shape_t* shape) { console_log(4, "adding shape #%u to group #%u", shape->id, group->id); shape = shape_ref(shape); vector_push(group->shapes, &shape); return true; } void group_draw(const group_t* group, image_t* surface) { iter_t iter; struct uniform* p; if (surface != NULL) al_set_target_bitmap(get_image_bitmap(surface)); #if defined(MINISPHERE_USE_SHADERS) if (are_shaders_active()) { shader_use(group->shader != NULL ? group->shader : get_default_shader()); iter = vector_enum(group->uniforms); while (p = vector_next(&iter)) { switch (p->type) { case UNIFORM_FLOAT: al_set_shader_float(p->name, p->float_value); break; case UNIFORM_INT: al_set_shader_int(p->name, p->int_value); break; case UNIFORM_MATRIX: al_set_shader_matrix(p->name, &p->mat_value); break; } } } #endif screen_transform(g_screen, group->transform); iter = vector_enum(group->shapes); while (vector_next(&iter)) render_shape(*(shape_t**)iter.ptr); screen_transform(g_screen, NULL); #if defined(MINISPHERE_USE_SHADERS) shader_use(NULL); #endif if (surface != NULL) al_set_target_backbuffer(screen_display(g_screen)); } void group_put_float(group_t* group, const char* name, float value) { struct uniform unif; free_cached_uniform(group, name); strncpy(unif.name, name, 255); unif.name[255] = '\0'; unif.type = UNIFORM_FLOAT; unif.float_value = value; vector_push(group->uniforms, &unif); } void group_put_int(group_t* group, const char* name, int value) { struct uniform unif; free_cached_uniform(group, name); strncpy(unif.name, name, 255); unif.name[255] = '\0'; unif.type = UNIFORM_INT; unif.int_value = value; vector_push(group->uniforms, &unif); } void group_put_matrix(group_t* group, const char* name, const matrix_t* matrix) { struct uniform unif; free_cached_uniform(group, name); strncpy(unif.name, name, 255); unif.name[255] = '\0'; unif.type = UNIFORM_MATRIX; al_copy_transform(&unif.mat_value, matrix_transform(matrix)); vector_push(group->uniforms, &unif); } shape_t* shape_new(shape_type_t type, image_t* texture) { shape_t* shape; const char* type_name; type_name = type == SHAPE_POINTS ? "point list" : type == SHAPE_LINES ? "line list" : type == SHAPE_LINE_LOOP ? "line loop" : type == SHAPE_TRIANGLES ? "triangle list" : type == SHAPE_TRI_FAN ? "triangle fan" : type == SHAPE_TRI_STRIP ? "triangle strip" : "automatic"; console_log(4, "creating shape #%u as %s", s_next_shape_id, type_name); shape = calloc(1, sizeof(shape_t)); shape->texture = ref_image(texture); shape->type = type; shape->id = s_next_shape_id++; return shape_ref(shape); } shape_t* shape_ref(shape_t* shape) { if (shape != NULL) ++shape->refcount; return shape; } void shape_free(shape_t* shape) { if (shape == NULL || --shape->refcount > 0) return; console_log(4, "disposing shape #%u no longer in use", shape->id); free_image(shape->texture); #ifdef MINISPHERE_USE_VERTEX_BUF if (shape->vbuf != NULL) al_destroy_vertex_buffer(shape->vbuf); #endif free(shape->sw_vbuf); free(shape->vertices); free(shape); } float_rect_t shape_bounds(const shape_t* shape) { float_rect_t bounds; int i; if (shape->num_vertices < 1) return new_float_rect(0.0, 0.0, 0.0, 0.0); bounds = new_float_rect( shape->vertices[0].x, shape->vertices[0].y, shape->vertices[0].x, shape->vertices[0].y); for (i = 1; i < shape->num_vertices; ++i) { bounds.x1 = fmin(shape->vertices[i].x, bounds.x1); bounds.y1 = fmin(shape->vertices[i].y, bounds.y1); bounds.x2 = fmax(shape->vertices[i].x, bounds.x2); bounds.y2 = fmax(shape->vertices[i].y, bounds.y2); } return bounds; } image_t* shape_texture(const shape_t* shape) { return shape->texture; } void shape_set_texture(shape_t* shape, image_t* texture) { image_t* old_texture; old_texture = shape->texture; shape->texture = ref_image(texture); free_image(old_texture); shape_upload(shape); } bool shape_add_vertex(shape_t* shape, vertex_t vertex) { int new_max; vertex_t *new_buffer; if (shape->num_vertices + 1 > shape->max_vertices) { new_max = (shape->num_vertices + 1) * 2; if (!(new_buffer = realloc(shape->vertices, new_max * sizeof(vertex_t)))) return false; shape->vertices = new_buffer; shape->max_vertices = new_max; } ++shape->num_vertices; shape->vertices[shape->num_vertices - 1] = vertex; return true; } void shape_draw(shape_t* shape, matrix_t* matrix, image_t* surface) { if (surface != NULL) al_set_target_bitmap(get_image_bitmap(surface)); screen_transform(g_screen, matrix); render_shape(shape); screen_transform(g_screen, NULL); if (surface != NULL) al_set_target_backbuffer(screen_display(g_screen)); } void shape_upload(shape_t* shape) { ALLEGRO_BITMAP* bitmap; ALLEGRO_VERTEX* vertices = NULL; int i; console_log(3, "uploading shape #%u vertices to GPU", shape->id); #ifdef MINISPHERE_USE_VERTEX_BUF if (shape->vbuf != NULL) al_destroy_vertex_buffer(shape->vbuf); #endif free(shape->sw_vbuf); shape->sw_vbuf = NULL; bitmap = shape->texture != NULL ? get_image_bitmap(shape->texture) : NULL; // create a vertex buffer #ifdef MINISPHERE_USE_VERTEX_BUF if (shape->vbuf = al_create_vertex_buffer(NULL, NULL, shape->num_vertices, ALLEGRO_PRIM_BUFFER_STATIC)) vertices = al_lock_vertex_buffer(shape->vbuf, 0, shape->num_vertices, ALLEGRO_LOCK_WRITEONLY); #endif if (vertices == NULL) { // hardware buffer couldn't be created, fall back to software console_log(3, "unable to create a VBO for shape #%u", shape->id); if (!(shape->sw_vbuf = malloc(shape->num_vertices * sizeof(ALLEGRO_VERTEX)))) return; vertices = shape->sw_vbuf; } // upload vertices for (i = 0; i < shape->num_vertices; ++i) { vertices[i].x = shape->vertices[i].x; vertices[i].y = shape->vertices[i].y; vertices[i].z = shape->vertices[i].z; vertices[i].color = nativecolor(shape->vertices[i].color); vertices[i].u = shape->vertices[i].u; vertices[i].v = shape->vertices[i].v; } // unlock hardware buffer, if applicable #ifdef MINISPHERE_USE_VERTEX_BUF if (vertices != shape->sw_vbuf) al_unlock_vertex_buffer(shape->vbuf); else if (shape->vbuf != NULL) { al_destroy_vertex_buffer(shape->vbuf); shape->vbuf = NULL; } #endif } static void assign_default_uv(shape_t* shape) { // this assigns default UV coordinates to a shape's vertices. note that clockwise // winding from top left is assumed; if the shape is wound any other way, the // texture will be rotated accordingly. if this is not what you want, explicit U/V // coordinates should be supplied. double phi; int i; console_log(4, "auto-calculating U/V for shape #%u", shape->id); for (i = 0; i < shape->num_vertices; ++i) { // circumscribe the UV coordinate space. // the circumcircle is rotated 135 degrees counterclockwise, which ensures // that the top-left corner of a clockwise quad is mapped to (0,0). phi = 2 * M_PI * i / shape->num_vertices - M_PI_4 * 3; shape->vertices[i].u = cos(phi) * M_SQRT1_2 + 0.5; shape->vertices[i].v = sin(phi) * -M_SQRT1_2 + 0.5; } } static bool have_vertex_buffer(const shape_t* shape) { #ifdef MINISPHERE_USE_VERTEX_BUF return shape->vbuf != NULL || shape->sw_vbuf != NULL; #else return shape->sw_vbuf != NULL; #endif } static void free_cached_uniform(group_t* group, const char* name) { iter_t iter; struct uniform* p; iter = vector_enum(group->uniforms); while (p = vector_next(&iter)) { if (strcmp(p->name, name) == 0) iter_remove(&iter); } } static void render_shape(shape_t* shape) { ALLEGRO_BITMAP* bitmap; int draw_mode; if (shape->num_vertices == 0) return; if (!have_vertex_buffer(shape)) shape_upload(shape); if (shape->type == SHAPE_AUTO) draw_mode = shape->num_vertices == 1 ? ALLEGRO_PRIM_POINT_LIST : shape->num_vertices == 2 ? ALLEGRO_PRIM_LINE_LIST : ALLEGRO_PRIM_TRIANGLE_STRIP; else draw_mode = shape->type == SHAPE_LINES ? ALLEGRO_PRIM_LINE_LIST : shape->type == SHAPE_LINE_LOOP ? ALLEGRO_PRIM_LINE_LOOP : shape->type == SHAPE_LINE_STRIP ? ALLEGRO_PRIM_LINE_STRIP : shape->type == SHAPE_TRIANGLES ? ALLEGRO_PRIM_TRIANGLE_LIST : shape->type == SHAPE_TRI_STRIP ? ALLEGRO_PRIM_TRIANGLE_STRIP : shape->type == SHAPE_TRI_FAN ? ALLEGRO_PRIM_TRIANGLE_FAN : ALLEGRO_PRIM_POINT_LIST; bitmap = shape->texture != NULL ? get_image_bitmap(shape->texture) : NULL; #ifdef MINISPHERE_USE_VERTEX_BUF if (shape->vbuf != NULL) al_draw_vertex_buffer(shape->vbuf, bitmap, 0, shape->num_vertices, draw_mode); else al_draw_prim(shape->sw_vbuf, NULL, bitmap, 0, shape->num_vertices, draw_mode); #else al_draw_prim(shape->sw_vbuf, NULL, bitmap, 0, shape->num_vertices, draw_mode); #endif } void init_galileo_api(void) { api_register_function(g_duk, NULL, "GetDefaultShaderProgram", js_GetDefaultShaderProgram); api_register_ctor(g_duk, "Group", js_new_Group, js_Group_finalize); api_register_prop(g_duk, "Group", "shader", js_Group_get_shader, js_Group_set_shader); api_register_prop(g_duk, "Group", "transform", js_Group_get_transform, js_Group_set_transform); api_register_method(g_duk, "Group", "draw", js_Group_draw); api_register_method(g_duk, "Group", "setFloat", js_Group_setFloat); api_register_method(g_duk, "Group", "setInt", js_Group_setInt); api_register_method(g_duk, "Group", "setMatrix", js_Group_setMatrix); api_register_ctor(g_duk, "Shape", js_new_Shape, js_Shape_finalize); api_register_prop(g_duk, "Shape", "texture", js_Shape_get_texture, js_Shape_set_texture); api_register_method(g_duk, "Shape", "draw", js_Shape_draw); api_register_ctor(g_duk, "Transform", js_new_Transform, js_Transform_finalize); api_register_method(g_duk, "Transform", "compose", js_Transform_compose); api_register_method(g_duk, "Transform", "identity", js_Transform_identity); api_register_method(g_duk, "Transform", "rotate", js_Transform_rotate); api_register_method(g_duk, "Transform", "scale", js_Transform_scale); api_register_method(g_duk, "Transform", "translate", js_Transform_translate); api_register_const(g_duk, "SHAPE_AUTO", SHAPE_AUTO); api_register_const(g_duk, "SHAPE_POINTS", SHAPE_POINTS); api_register_const(g_duk, "SHAPE_LINES", SHAPE_LINES); api_register_const(g_duk, "SHAPE_LINE_LOOP", SHAPE_LINE_LOOP); api_register_const(g_duk, "SHAPE_LINE_STRIP", SHAPE_LINE_STRIP); api_register_const(g_duk, "SHAPE_TRIANGLES", SHAPE_TRIANGLES); api_register_const(g_duk, "SHAPE_TRI_STRIP", SHAPE_TRI_STRIP); api_register_const(g_duk, "SHAPE_TRI_FAN", SHAPE_TRI_FAN); } static duk_ret_t js_new_Group(duk_context* ctx) { group_t* group; int num_args; size_t num_shapes; shader_t* shader; shape_t* shape; duk_uarridx_t i; num_args = duk_get_top(ctx); duk_require_object_coercible(ctx, 0); shader = num_args >= 2 ? duk_require_sphere_obj(ctx, 1, "ShaderProgram") : get_default_shader(); if (!duk_is_array(ctx, 0)) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "argument 1 to Group() must be an array"); if (!(group = group_new(shader))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to create Galileo group"); num_shapes = duk_get_length(ctx, 0); for (i = 0; i < num_shapes; ++i) { duk_get_prop_index(ctx, 0, i); shape = duk_require_sphere_obj(ctx, -1, "Shape"); group_add_shape(group, shape); } duk_push_sphere_obj(ctx, "Group", group); return 1; } static duk_ret_t js_Group_finalize(duk_context* ctx) { group_t* group; group = duk_require_sphere_obj(ctx, 0, "Group"); group_free(group); return 0; } static duk_ret_t js_Group_get_shader(duk_context* ctx) { group_t* group; shader_t* shader; duk_push_this(ctx); group = duk_require_sphere_obj(ctx, -1, "Group"); shader = group_get_shader(group); duk_push_sphere_obj(ctx, "ShaderProgram", shader_ref(shader)); return 1; } static duk_ret_t js_Group_get_transform(duk_context* ctx) { group_t* group; matrix_t* matrix; duk_push_this(ctx); group = duk_require_sphere_obj(ctx, -1, "Group"); matrix = group_get_transform(group); duk_push_sphere_obj(ctx, "Transform", matrix_ref(matrix)); return 1; } static duk_ret_t js_Group_set_shader(duk_context* ctx) { group_t* group; shader_t* shader; duk_push_this(ctx); group = duk_require_sphere_obj(ctx, -1, "Group"); shader = duk_require_sphere_obj(ctx, 0, "ShaderProgram"); group_set_shader(group, shader); return 0; } static duk_ret_t js_Group_set_transform(duk_context* ctx) { group_t* group; matrix_t* transform; duk_push_this(ctx); group = duk_require_sphere_obj(ctx, -1, "Group"); transform = duk_require_sphere_obj(ctx, 0, "Transform"); group_set_transform(group, transform); return 0; } static duk_ret_t js_Group_draw(duk_context* ctx) { group_t* group; int num_args; image_t* surface; duk_push_this(ctx); num_args = duk_get_top(ctx) - 1; group = duk_require_sphere_obj(ctx, -1, "Group"); surface = num_args >= 1 ? duk_require_sphere_obj(ctx, 0, "Surface") : NULL; if (!screen_is_skipframe(g_screen)) group_draw(group, surface); return 0; } static duk_ret_t js_Group_setFloat(duk_context* ctx) { group_t* group; const char* name; float value; duk_push_this(ctx); group = duk_require_sphere_obj(ctx, -1, "Group"); name = duk_require_string(ctx, 0); value = duk_require_number(ctx, 1); group_put_float(group, name, value); return 1; } static duk_ret_t js_Group_setInt(duk_context* ctx) { group_t* group; const char* name; int value; duk_push_this(ctx); group = duk_require_sphere_obj(ctx, -1, "Group"); name = duk_require_string(ctx, 0); value = duk_require_int(ctx, 1); group_put_int(group, name, value); return 1; } static duk_ret_t js_Group_setMatrix(duk_context* ctx) { group_t* group; matrix_t* matrix; const char* name; duk_push_this(ctx); group = duk_require_sphere_obj(ctx, -1, "Group"); name = duk_require_string(ctx, 0); matrix = duk_require_sphere_obj(ctx, 1, "Transform"); group_put_matrix(group, name, matrix); return 1; } static duk_ret_t js_GetDefaultShaderProgram(duk_context* ctx) { shader_t* shader; if (!(shader = get_default_shader())) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetDefaultShaderProgram(): no default shader available or shader couldn't be built"); duk_push_sphere_obj(ctx, "ShaderProgram", shader_ref(shader)); return 1; } static duk_ret_t js_new_Shape(duk_context* ctx) { bool is_missing_uv = false; int num_args; size_t num_vertices; shape_t* shape; duk_idx_t stack_idx; image_t* texture; shape_type_t type; vertex_t vertex; duk_uarridx_t i; num_args = duk_get_top(ctx); duk_require_object_coercible(ctx, 0); texture = !duk_is_null(ctx, 1) ? duk_require_sphere_obj(ctx, 1, "Image") : NULL; type = num_args >= 3 ? duk_require_int(ctx, 2) : SHAPE_AUTO; if (!duk_is_array(ctx, 0)) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "Shape(): first argument must be an array"); if (type < 0 || type >= SHAPE_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Shape(): invalid shape type constant"); if (!(shape = shape_new(type, texture))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Shape(): unable to create shape object"); num_vertices = duk_get_length(ctx, 0); for (i = 0; i < num_vertices; ++i) { duk_get_prop_index(ctx, 0, i); stack_idx = duk_normalize_index(ctx, -1); vertex.x = duk_get_prop_string(ctx, stack_idx, "x") ? duk_require_number(ctx, -1) : 0.0; vertex.y = duk_get_prop_string(ctx, stack_idx, "y") ? duk_require_number(ctx, -1) : 0.0; vertex.z = duk_get_prop_string(ctx, stack_idx, "z") ? duk_require_number(ctx, -1) : 0.0; if (duk_get_prop_string(ctx, stack_idx, "u")) vertex.u = duk_require_number(ctx, -1); else is_missing_uv = true; if (duk_get_prop_string(ctx, stack_idx, "v")) vertex.v = duk_require_number(ctx, -1); else is_missing_uv = true; vertex.color = duk_get_prop_string(ctx, stack_idx, "color") ? duk_require_sphere_color(ctx, -1) : color_new(255, 255, 255, 255); duk_pop_n(ctx, 6); shape_add_vertex(shape, vertex); } if (is_missing_uv) assign_default_uv(shape); shape_upload(shape); duk_push_sphere_obj(ctx, "Shape", shape); return 1; } static duk_ret_t js_Shape_finalize(duk_context* ctx) { shape_t* shape; shape = duk_require_sphere_obj(ctx, 0, "Shape"); shape_free(shape); return 0; } static duk_ret_t js_Shape_get_texture(duk_context* ctx) { shape_t* shape; duk_push_this(ctx); shape = duk_require_sphere_obj(ctx, -1, "Shape"); duk_push_sphere_obj(ctx, "Image", ref_image(shape_texture(shape))); return 1; } static duk_ret_t js_Shape_set_texture(duk_context* ctx) { shape_t* shape; image_t* texture; duk_push_this(ctx); shape = duk_require_sphere_obj(ctx, -1, "Shape"); texture = duk_require_sphere_obj(ctx, 0, "Image"); shape_set_texture(shape, texture); return 0; } static duk_ret_t js_Shape_draw(duk_context* ctx) { int num_args; shape_t* shape; image_t* surface = NULL; matrix_t* transform = NULL; duk_push_this(ctx); num_args = duk_get_top(ctx) - 1; shape = duk_require_sphere_obj(ctx, -1, "Shape"); if (num_args >= 1) transform = duk_require_sphere_obj(ctx, 0, "Transform"); if (num_args >= 2) surface = duk_require_sphere_obj(ctx, 1, "Surface"); shader_use(get_default_shader()); shape_draw(shape, transform, surface); shader_use(NULL); return 0; } static duk_ret_t js_new_Transform(duk_context* ctx) { matrix_t* matrix; matrix = matrix_new(); duk_push_sphere_obj(ctx, "Transform", matrix); return 1; } static duk_ret_t js_Transform_finalize(duk_context* ctx) { matrix_t* matrix; matrix = duk_require_sphere_obj(ctx, 0, "Transform"); matrix_free(matrix); return 0; } static duk_ret_t js_Transform_compose(duk_context* ctx) { matrix_t* matrix; matrix_t* other; duk_push_this(ctx); matrix = duk_require_sphere_obj(ctx, -1, "Transform"); other = duk_require_sphere_obj(ctx, 0, "Transform"); matrix_compose(matrix, other); return 1; } static duk_ret_t js_Transform_identity(duk_context* ctx) { matrix_t* matrix; duk_push_this(ctx); matrix = duk_require_sphere_obj(ctx, -1, "Transform"); matrix_identity(matrix); return 1; } static duk_ret_t js_Transform_rotate(duk_context* ctx) { matrix_t* matrix; int num_args; float theta; float vx = 0.0; float vy = 0.0; float vz = 1.0; duk_push_this(ctx); num_args = duk_get_top(ctx) - 1; matrix = duk_require_sphere_obj(ctx, -1, "Transform"); theta = duk_require_number(ctx, 0); if (num_args >= 2) { vx = duk_require_number(ctx, 1); vy = duk_require_number(ctx, 2); vz = duk_require_number(ctx, 3); } matrix_rotate(matrix, theta, vx, vy, vz); return 1; } static duk_ret_t js_Transform_scale(duk_context* ctx) { matrix_t* matrix; int num_args; float sx; float sy; float sz = 1.0; duk_push_this(ctx); num_args = duk_get_top(ctx) - 1; matrix = duk_require_sphere_obj(ctx, -1, "Transform"); sx = duk_require_number(ctx, 0); sy = duk_require_number(ctx, 1); if (num_args >= 3) sz = duk_require_number(ctx, 2); matrix_scale(matrix, sx, sy, sz); return 1; } static duk_ret_t js_Transform_translate(duk_context* ctx) { matrix_t* matrix; int num_args; float dx; float dy; float dz = 0.0; duk_push_this(ctx); num_args = duk_get_top(ctx) - 1; matrix = duk_require_sphere_obj(ctx, -1, "Transform"); dx = duk_require_number(ctx, 0); dy = duk_require_number(ctx, 1); if (num_args >= 3) dz = duk_require_number(ctx, 2); matrix_translate(matrix, dx, dy, dz); return 1; } <file_sep>/src/engine/sockets.h typedef struct socket socket_t; socket_t* connect_to_host (const char* hostname, int port, size_t buffer_size); socket_t* listen_on_port (const char* hostname, int port, size_t buffer_size, int max_backlog); socket_t* ref_socket (socket_t* socket); void free_socket (socket_t* socket); bool is_socket_live (socket_t* socket); bool is_socket_server (socket_t* socket); const char* get_socket_host (socket_t* socket); int get_socket_port (socket_t* socket); socket_t* accept_next_socket (socket_t* listener); size_t peek_socket (const socket_t* socket); void pipe_socket (socket_t* socket, socket_t* destination); size_t read_socket (socket_t* socket, uint8_t* buffer, size_t n_bytes); void shutdown_socket (socket_t* socket); void write_socket (socket_t* socket, const uint8_t* data, size_t n_bytes); void init_sockets_api (void); <file_sep>/src/engine/audialis.c #include "minisphere.h" #include "api.h" #include "bytearray.h" #include "audialis.h" static duk_ret_t js_GetDefaultMixer (duk_context* ctx); static duk_ret_t js_new_Mixer (duk_context* ctx); static duk_ret_t js_Mixer_finalize (duk_context* ctx); static duk_ret_t js_Mixer_get_volume (duk_context* ctx); static duk_ret_t js_Mixer_set_volume (duk_context* ctx); static duk_ret_t js_LoadSound (duk_context* ctx); static duk_ret_t js_new_Sound (duk_context* ctx); static duk_ret_t js_Sound_finalize (duk_context* ctx); static duk_ret_t js_Sound_toString (duk_context* ctx); static duk_ret_t js_Sound_getVolume (duk_context* ctx); static duk_ret_t js_Sound_setVolume (duk_context* ctx); static duk_ret_t js_Sound_get_length (duk_context* ctx); static duk_ret_t js_Sound_get_mixer (duk_context* ctx); static duk_ret_t js_Sound_set_mixer (duk_context* ctx); static duk_ret_t js_Sound_get_pan (duk_context* ctx); static duk_ret_t js_Sound_set_pan (duk_context* ctx); static duk_ret_t js_Sound_get_pitch (duk_context* ctx); static duk_ret_t js_Sound_set_pitch (duk_context* ctx); static duk_ret_t js_Sound_get_playing (duk_context* ctx); static duk_ret_t js_Sound_get_position (duk_context* ctx); static duk_ret_t js_Sound_set_position (duk_context* ctx); static duk_ret_t js_Sound_get_repeat (duk_context* ctx); static duk_ret_t js_Sound_set_repeat (duk_context* ctx); static duk_ret_t js_Sound_get_seekable (duk_context* ctx); static duk_ret_t js_Sound_get_volume (duk_context* ctx); static duk_ret_t js_Sound_set_volume (duk_context* ctx); static duk_ret_t js_Sound_pause (duk_context* ctx); static duk_ret_t js_Sound_play (duk_context* ctx); static duk_ret_t js_Sound_reset (duk_context* ctx); static duk_ret_t js_Sound_stop (duk_context* ctx); static duk_ret_t js_new_SoundStream (duk_context* ctx); static duk_ret_t js_SoundStream_finalize (duk_context* ctx); static duk_ret_t js_SoundStream_get_bufferSize (duk_context* ctx); static duk_ret_t js_SoundStream_get_mixer (duk_context* ctx); static duk_ret_t js_SoundStream_set_mixer (duk_context* ctx); static duk_ret_t js_SoundStream_play (duk_context* ctx); static duk_ret_t js_SoundStream_pause (duk_context* ctx); static duk_ret_t js_SoundStream_stop (duk_context* ctx); static duk_ret_t js_SoundStream_write (duk_context* ctx); static void update_stream (stream_t* stream); struct mixer { unsigned int refcount; unsigned int id; ALLEGRO_MIXER* ptr; ALLEGRO_VOICE* voice; float gain; }; struct stream { unsigned int refcount; unsigned int id; ALLEGRO_AUDIO_STREAM* ptr; unsigned char* buffer; size_t buffer_size; size_t feed_size; size_t fragment_size; mixer_t* mixer; }; struct sound { unsigned int refcount; unsigned int id; void* file_data; size_t file_size; float gain; bool is_looping; mixer_t* mixer; char* path; float pan; float pitch; ALLEGRO_AUDIO_STREAM* stream; }; static bool s_have_sound; static ALLEGRO_AUDIO_DEPTH s_bit_depth; static ALLEGRO_CHANNEL_CONF s_channel_conf; static mixer_t* s_def_mixer; static unsigned int s_next_mixer_id = 0; static unsigned int s_next_sound_id = 0; static unsigned int s_next_stream_id = 0; static vector_t* s_playing_sounds; static vector_t* s_streams; void initialize_audialis(void) { console_log(1, "initializing Audialis"); s_have_sound = true; if (!al_install_audio() || !(s_def_mixer = mixer_new(44100, 16, 2))) { s_have_sound = false; console_log(1, " no audio is available"); return; } al_init_acodec_addon(); al_reserve_samples(10); s_streams = vector_new(sizeof(stream_t*)); s_playing_sounds = vector_new(sizeof(sound_t*)); } void shutdown_audialis(void) { iter_t iter; sound_t* *p_sound; console_log(1, "shutting down Audialis"); iter = vector_enum(s_playing_sounds); while (p_sound = vector_next(&iter)) sound_free(*p_sound); vector_free(s_playing_sounds); vector_free(s_streams); mixer_free(s_def_mixer); if (s_have_sound) al_uninstall_audio(); } void update_audialis(void) { sound_t* *p_sound; stream_t* *p_stream; iter_t iter; iter = vector_enum(s_streams); while (p_stream = vector_next(&iter)) update_stream(*p_stream); iter = vector_enum(s_playing_sounds); while (p_sound = vector_next(&iter)) { if (sound_playing(*p_sound)) continue; sound_free(*p_sound); iter_remove(&iter); } } mixer_t* get_default_mixer(void) { return s_def_mixer; } mixer_t* mixer_new(int frequency, int bits, int channels) { ALLEGRO_CHANNEL_CONF conf; ALLEGRO_AUDIO_DEPTH depth; mixer_t* mixer; console_log(2, "creating new mixer #%u at %i kHz", s_next_mixer_id, frequency / 1000); console_log(3, " format: %ich %i Hz, %i-bit", channels, frequency, bits); conf = channels == 2 ? ALLEGRO_CHANNEL_CONF_2 : channels == 3 ? ALLEGRO_CHANNEL_CONF_3 : channels == 4 ? ALLEGRO_CHANNEL_CONF_4 : channels == 5 ? ALLEGRO_CHANNEL_CONF_5_1 : channels == 6 ? ALLEGRO_CHANNEL_CONF_6_1 : channels == 7 ? ALLEGRO_CHANNEL_CONF_7_1 : ALLEGRO_CHANNEL_CONF_1; depth = bits == 16 ? ALLEGRO_AUDIO_DEPTH_INT16 : bits == 24 ? ALLEGRO_AUDIO_DEPTH_INT24 : bits == 32 ? ALLEGRO_AUDIO_DEPTH_FLOAT32 : ALLEGRO_AUDIO_DEPTH_UINT8; mixer = calloc(1, sizeof(mixer_t)); if (!(mixer->voice = al_create_voice(frequency, depth, conf))) goto on_error; if (!(mixer->ptr = al_create_mixer(frequency, ALLEGRO_AUDIO_DEPTH_FLOAT32, conf))) goto on_error; al_attach_mixer_to_voice(mixer->ptr, mixer->voice); al_set_mixer_gain(mixer->ptr, 1.0); al_set_voice_playing(mixer->voice, true); al_set_mixer_playing(mixer->ptr, true); mixer->gain = al_get_mixer_gain(mixer->ptr); mixer->id = s_next_mixer_id++; return mixer_ref(mixer); on_error: console_log(2, "failed to create mixer #%u", s_next_mixer_id++); if (mixer->ptr != NULL) al_destroy_mixer(mixer->ptr); if (mixer->voice != NULL) al_destroy_voice(mixer->voice); free(mixer); return NULL; } mixer_t* mixer_ref(mixer_t* mixer) { ++mixer->refcount; return mixer; } void mixer_free(mixer_t* mixer) { if (mixer == NULL || --mixer->refcount > 0) return; console_log(3, "disposing mixer #%u no longer in use", mixer->id); al_destroy_mixer(mixer->ptr); free(mixer); } float mixer_get_gain(mixer_t* mixer) { return mixer->gain; } void mixer_set_gain(mixer_t* mixer, float gain) { al_set_mixer_gain(mixer->ptr, gain); mixer->gain = gain; } sound_t* sound_load(const char* path, mixer_t* mixer) { sound_t* sound; console_log(2, "loading sound #%u as `%s`", s_next_sound_id, path); sound = calloc(1, sizeof(sound_t)); sound->path = strdup(path); if (!(sound->file_data = sfs_fslurp(g_fs, sound->path, NULL, &sound->file_size))) goto on_error; sound->mixer = mixer_ref(mixer); sound->gain = 1.0; sound->pan = 0.0; sound->pitch = 1.0; if (!sound_reload(sound)) goto on_error; sound->id = s_next_sound_id++; return sound_ref(sound); on_error: console_log(2, " failed to load sound #%u", s_next_sound_id); if (sound != NULL) { free(sound->path); free(sound); } return NULL; } sound_t* sound_ref(sound_t* sound) { ++sound->refcount; return sound; } void sound_free(sound_t* sound) { if (sound == NULL || --sound->refcount > 0) return; console_log(3, "disposing sound #%u no longer in use", sound->id); free(sound->file_data); if (sound->stream != NULL) al_destroy_audio_stream(sound->stream); mixer_free(sound->mixer); free(sound->path); free(sound); } double sound_len(sound_t* sound) { if (sound->stream != NULL) return al_get_audio_stream_length_secs(sound->stream); else return 0.0; } bool sound_playing(sound_t* sound) { if (sound->stream != NULL) return al_get_audio_stream_playing(sound->stream); else return false; } double sound_tell(sound_t* sound) { if (sound->stream != NULL) return al_get_audio_stream_position_secs(sound->stream); else return 0.0; } float sound_get_gain(sound_t* sound) { return sound->gain; } bool sound_get_looping(sound_t* sound) { return sound->is_looping; } mixer_t* sound_get_mixer(sound_t* sound) { return sound->mixer; } float sound_get_pan(sound_t* sound) { return sound->pan; } float sound_get_pitch(sound_t* sound) { return sound->pitch; } void sound_set_gain(sound_t* sound, float gain) { if (sound->stream != NULL) al_set_audio_stream_gain(sound->stream, gain); sound->gain = gain; } void sound_set_looping(sound_t* sound, bool is_looping) { int play_mode; play_mode = is_looping ? ALLEGRO_PLAYMODE_LOOP : ALLEGRO_PLAYMODE_ONCE; if (sound->stream != NULL) al_set_audio_stream_playmode(sound->stream, play_mode); sound->is_looping = is_looping; } void sound_set_mixer(sound_t* sound, mixer_t* mixer) { mixer_t* old_mixer; old_mixer = sound->mixer; sound->mixer = mixer_ref(mixer); al_attach_audio_stream_to_mixer(sound->stream, sound->mixer->ptr); mixer_free(old_mixer); } void sound_set_pan(sound_t* sound, float pan) { if (sound->stream != NULL) al_set_audio_stream_pan(sound->stream, pan); sound->pan = pan; } void sound_set_pitch(sound_t* sound, float pitch) { if (sound->stream != NULL) al_set_audio_stream_speed(sound->stream, pitch); sound->pitch = pitch; } void sound_play(sound_t* sound) { console_log(2, "playing sound #%u on mixer #%u", sound->id, sound->mixer->id); if (sound->stream != NULL) { al_set_audio_stream_playing(sound->stream, true); sound_ref(sound); vector_push(s_playing_sounds, &sound); } } bool sound_reload(sound_t* sound) { ALLEGRO_FILE* memfile; ALLEGRO_AUDIO_STREAM* new_stream = NULL; int play_mode; console_log(4, "reloading sound #%u", sound->id); new_stream = NULL; if (s_have_sound) { memfile = al_open_memfile(sound->file_data, sound->file_size, "rb"); if (!(new_stream = al_load_audio_stream_f(memfile, strrchr(sound->path, '.'), 4, 1024))) goto on_error; } if (s_have_sound && new_stream == NULL) return false; if (sound->stream != NULL) al_destroy_audio_stream(sound->stream); if ((sound->stream = new_stream) != NULL) { play_mode = sound->is_looping ? ALLEGRO_PLAYMODE_LOOP : ALLEGRO_PLAYMODE_ONCE; al_set_audio_stream_gain(sound->stream, sound->gain); al_set_audio_stream_pan(sound->stream, sound->pan); al_set_audio_stream_speed(sound->stream, sound->pitch); al_set_audio_stream_playmode(sound->stream, play_mode); al_attach_audio_stream_to_mixer(sound->stream, sound->mixer->ptr); al_set_audio_stream_playing(sound->stream, false); } return true; on_error: return false; } void sound_seek(sound_t* sound, double position) { if (sound->stream != NULL) al_seek_audio_stream_secs(sound->stream, position); } void sound_stop(sound_t* sound, bool rewind) { console_log(3, "stopping sound #%u %s", sound->id, rewind ? "and rewinding" : ""); if (sound->stream == NULL) return; al_set_audio_stream_playing(sound->stream, false); if (rewind) al_rewind_audio_stream(sound->stream); } stream_t* stream_new(int frequency, int bits, int channels) { ALLEGRO_CHANNEL_CONF conf; ALLEGRO_AUDIO_DEPTH depth_flag; size_t sample_size; stream_t* stream; console_log(2, "creating new stream #%u at %i kHz", s_next_stream_id, frequency / 1000); console_log(3, " format: %ich %i Hz, %i-bit", channels, frequency, bits); stream = calloc(1, sizeof(stream_t)); // create the underlying Allegro stream depth_flag = bits == 8 ? ALLEGRO_AUDIO_DEPTH_UINT8 : bits == 24 ? ALLEGRO_AUDIO_DEPTH_INT24 : bits == 32 ? ALLEGRO_AUDIO_DEPTH_FLOAT32 : ALLEGRO_AUDIO_DEPTH_INT16; conf = channels == 2 ? ALLEGRO_CHANNEL_CONF_2 : channels == 3 ? ALLEGRO_CHANNEL_CONF_3 : channels == 4 ? ALLEGRO_CHANNEL_CONF_4 : channels == 5 ? ALLEGRO_CHANNEL_CONF_5_1 : channels == 6 ? ALLEGRO_CHANNEL_CONF_6_1 : channels == 7 ? ALLEGRO_CHANNEL_CONF_7_1 : ALLEGRO_CHANNEL_CONF_1; if (!(stream->ptr = al_create_audio_stream(4, 1024, frequency, depth_flag, conf))) goto on_error; stream->mixer = mixer_ref(s_def_mixer); al_set_audio_stream_playing(stream->ptr, false); al_attach_audio_stream_to_mixer(stream->ptr, stream->mixer->ptr); // allocate an initial stream buffer sample_size = bits == 8 ? 1 : bits == 16 ? 2 : bits == 24 ? 3 : bits == 32 ? 4 : 0; stream->fragment_size = 1024 * sample_size; stream->buffer_size = frequency * sample_size; // 1 second stream->buffer = malloc(stream->buffer_size); stream->id = s_next_stream_id++; vector_push(s_streams, &stream); return stream_ref(stream); on_error: console_log(2, "failed to create stream #%u", s_next_stream_id); free(stream); return NULL; } stream_t* stream_ref(stream_t* stream) { ++stream->refcount; return stream; } void stream_free(stream_t* stream) { stream_t* *p_stream; iter_t iter; if (stream == NULL || --stream->refcount > 0) return; console_log(3, "disposing stream #%u no longer in use", stream->id); al_drain_audio_stream(stream->ptr); al_destroy_audio_stream(stream->ptr); mixer_free(stream->mixer); free(stream->buffer); free(stream); iter = vector_enum(s_streams); while (p_stream = vector_next(&iter)) { if (*p_stream == stream) { vector_remove(s_streams, iter.index); break; } } } bool stream_playing(const stream_t* stream) { return al_get_audio_stream_playing(stream->ptr); } mixer_t* stream_get_mixer(stream_t* stream) { return stream->mixer; } void stream_set_mixer(stream_t* stream, mixer_t* mixer) { mixer_t* old_mixer; old_mixer = stream->mixer; stream->mixer = mixer_ref(mixer); al_attach_audio_stream_to_mixer(stream->ptr, stream->mixer->ptr); mixer_free(old_mixer); } void stream_buffer(stream_t* stream, const void* data, size_t size) { size_t needed_size; console_log(4, "buffering %zu bytes into stream #%u", size, stream->id); needed_size = stream->feed_size + size; if (needed_size > stream->buffer_size) { // buffer is too small, double size until large enough while (needed_size > stream->buffer_size) stream->buffer_size *= 2; stream->buffer = realloc(stream->buffer, stream->buffer_size); } memcpy(stream->buffer + stream->feed_size, data, size); stream->feed_size += size; } void stream_pause(stream_t* stream) { al_set_audio_stream_playing(stream->ptr, false); } void stream_play(stream_t* stream) { al_set_audio_stream_playing(stream->ptr, true); } void stream_stop(stream_t* stream) { al_drain_audio_stream(stream->ptr); free(stream->buffer); stream->buffer = NULL; stream->feed_size = 0; } static void update_stream(stream_t* stream) { void* buffer; if (stream->feed_size <= stream->fragment_size) return; if (!(buffer = al_get_audio_stream_fragment(stream->ptr))) return; memcpy(buffer, stream->buffer, stream->fragment_size); stream->feed_size -= stream->fragment_size; memmove(stream->buffer, stream->buffer + stream->fragment_size, stream->feed_size); al_set_audio_stream_fragment(stream->ptr, buffer); } void init_audialis_api(void) { // core Audialis API functions api_register_method(g_duk, NULL, "GetDefaultMixer", js_GetDefaultMixer); // Mixer object api_register_ctor(g_duk, "Mixer", js_new_Mixer, js_Mixer_finalize); api_register_prop(g_duk, "Mixer", "volume", js_Mixer_get_volume, js_Mixer_set_volume); // SoundStream object api_register_ctor(g_duk, "SoundStream", js_new_SoundStream, js_SoundStream_finalize); api_register_prop(g_duk, "SoundStream", "bufferSize", js_SoundStream_get_bufferSize, NULL); api_register_prop(g_duk, "SoundStream", "mixer", js_SoundStream_get_mixer, js_SoundStream_set_mixer); api_register_method(g_duk, "SoundStream", "pause", js_SoundStream_pause); api_register_method(g_duk, "SoundStream", "play", js_SoundStream_play); api_register_method(g_duk, "SoundStream", "stop", js_SoundStream_stop); api_register_method(g_duk, "SoundStream", "write", js_SoundStream_write); // Sound object api_register_method(g_duk, NULL, "LoadSound", js_LoadSound); api_register_ctor(g_duk, "Sound", js_new_Sound, js_Sound_finalize); api_register_method(g_duk, "Sound", "toString", js_Sound_toString); api_register_prop(g_duk, "Sound", "length", js_Sound_get_length, NULL); api_register_prop(g_duk, "Sound", "mixer", js_Sound_get_mixer, js_Sound_set_mixer); api_register_prop(g_duk, "Sound", "pan", js_Sound_get_pan, js_Sound_set_pan); api_register_prop(g_duk, "Sound", "pitch", js_Sound_get_pitch, js_Sound_set_pitch); api_register_prop(g_duk, "Sound", "playing", js_Sound_get_playing, NULL); api_register_prop(g_duk, "Sound", "position", js_Sound_get_position, js_Sound_set_position); api_register_prop(g_duk, "Sound", "repeat", js_Sound_get_repeat, js_Sound_set_repeat); api_register_prop(g_duk, "Sound", "seekable", js_Sound_get_seekable, NULL); api_register_prop(g_duk, "Sound", "volume", js_Sound_get_volume, js_Sound_set_volume); api_register_method(g_duk, "Sound", "isPlaying", js_Sound_get_playing); api_register_method(g_duk, "Sound", "isSeekable", js_Sound_get_seekable); api_register_method(g_duk, "Sound", "getLength", js_Sound_get_length); api_register_method(g_duk, "Sound", "getPan", js_Sound_get_pan); api_register_method(g_duk, "Sound", "getPitch", js_Sound_get_pitch); api_register_method(g_duk, "Sound", "getPosition", js_Sound_get_position); api_register_method(g_duk, "Sound", "getRepeat", js_Sound_get_repeat); api_register_method(g_duk, "Sound", "getVolume", js_Sound_getVolume); api_register_method(g_duk, "Sound", "setPan", js_Sound_set_pan); api_register_method(g_duk, "Sound", "setPitch", js_Sound_set_pitch); api_register_method(g_duk, "Sound", "setPosition", js_Sound_set_position); api_register_method(g_duk, "Sound", "setRepeat", js_Sound_set_repeat); api_register_method(g_duk, "Sound", "setVolume", js_Sound_setVolume); api_register_method(g_duk, "Sound", "pause", js_Sound_pause); api_register_method(g_duk, "Sound", "play", js_Sound_play); api_register_method(g_duk, "Sound", "reset", js_Sound_reset); api_register_method(g_duk, "Sound", "stop", js_Sound_stop); } static duk_ret_t js_GetDefaultMixer(duk_context* ctx) { duk_push_sphere_obj(ctx, "Mixer", mixer_ref(s_def_mixer)); return 1; } static duk_ret_t js_new_Mixer(duk_context* ctx) { int n_args = duk_get_top(ctx); int freq = duk_require_int(ctx, 0); int bits = duk_require_int(ctx, 1); int channels = n_args >= 3 ? duk_require_int(ctx, 2) : 2; mixer_t* mixer; if (bits != 8 && bits != 16 && bits != 24 && bits != 32) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Mixer(): invalid bit depth for mixer (%i)", bits); if (channels < 1 || channels > 7) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Mixer(): invalid channel count for mixer (%i)", channels); if (!(mixer = mixer_new(freq, bits, channels))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Mixer(): unable to create %i-bit %ich voice", bits, channels); duk_push_sphere_obj(ctx, "Mixer", mixer); return 1; } static duk_ret_t js_Mixer_finalize(duk_context* ctx) { mixer_t* mixer; mixer = duk_require_sphere_obj(ctx, 0, "Mixer"); mixer_free(mixer); return 0; } static duk_ret_t js_Mixer_get_volume(duk_context* ctx) { mixer_t* mixer; duk_push_this(ctx); mixer = duk_require_sphere_obj(ctx, -1, "Mixer"); duk_pop(ctx); duk_push_number(ctx, mixer_get_gain(mixer)); return 1; } static duk_ret_t js_Mixer_set_volume(duk_context* ctx) { float volume = duk_require_number(ctx, 0); mixer_t* mixer; duk_push_this(ctx); mixer = duk_require_sphere_obj(ctx, -1, "Mixer"); duk_pop(ctx); mixer_set_gain(mixer, volume); return 0; } static duk_ret_t js_LoadSound(duk_context* ctx) { const char* filename; sound_t* sound; filename = duk_require_path(ctx, 0, "sounds", true); if (!(sound = sound_load(filename, get_default_mixer()))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "LoadSound(): unable to load sound file `%s`", filename); duk_push_sphere_obj(ctx, "Sound", sound); return 1; } static duk_ret_t js_new_Sound(duk_context* ctx) { duk_int_t n_args; const char* filename; mixer_t* mixer; sound_t* sound; n_args = duk_get_top(ctx); filename = duk_require_path(ctx, 0, NULL, false); mixer = n_args >= 2 && !duk_is_boolean(ctx, 1) ? duk_require_sphere_obj(ctx, 1, "Mixer") : get_default_mixer(); sound = sound_load(filename, mixer); if (sound == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Sound(): unable to load sound file `%s`", filename); duk_push_sphere_obj(ctx, "Sound", sound); return 1; } static duk_ret_t js_Sound_finalize(duk_context* ctx) { sound_t* sound; sound = duk_require_sphere_obj(ctx, 0, "Sound"); sound_free(sound); return 0; } static duk_ret_t js_Sound_toString(duk_context* ctx) { duk_push_string(ctx, "[object sound]"); return 1; } static duk_ret_t js_Sound_getVolume(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); duk_push_int(ctx, sound_get_gain(sound) * 255); return 1; } static duk_ret_t js_Sound_setVolume(duk_context* ctx) { int volume = duk_require_int(ctx, 0); sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); volume = volume < 0 ? 0 : volume > 255 ? 255 : volume; sound_set_gain(sound, (float)volume / 255); return 0; } static duk_ret_t js_Sound_get_length(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); duk_push_number(ctx, (long long)(sound_len(sound) * 1000000)); return 1; } static duk_ret_t js_Sound_get_mixer(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); duk_push_sphere_obj(ctx, "Mixer", mixer_ref(sound_get_mixer(sound))); return 1; } static duk_ret_t js_Sound_set_mixer(duk_context* ctx) { mixer_t* mixer = duk_require_sphere_obj(ctx, 0, "Mixer"); sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); sound_set_mixer(sound, mixer); return 1; } static duk_ret_t js_Sound_get_pan(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); duk_push_int(ctx, sound_get_pan(sound) * 255); return 1; } static duk_ret_t js_Sound_set_pan(duk_context* ctx) { int new_pan = duk_require_int(ctx, 0); sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); sound_set_pan(sound, (float)new_pan / 255); return 0; } static duk_ret_t js_Sound_get_pitch(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); duk_push_number(ctx, sound_get_pitch(sound)); return 1; } static duk_ret_t js_Sound_set_pitch(duk_context* ctx) { float new_pitch = duk_require_number(ctx, 0); sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); sound_set_pitch(sound, new_pitch); return 0; } static duk_ret_t js_Sound_get_playing(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); duk_push_boolean(ctx, sound_playing(sound)); return 1; } static duk_ret_t js_Sound_get_position(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); duk_push_number(ctx, (long long)(sound_tell(sound) * 1000000)); return 1; } static duk_ret_t js_Sound_set_position(duk_context* ctx) { long long new_pos = duk_require_number(ctx, 0); sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); sound_seek(sound, (double)new_pos / 1000000); return 0; } static duk_ret_t js_Sound_get_repeat(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); duk_push_boolean(ctx, sound_get_looping(sound)); return 1; } static duk_ret_t js_Sound_set_repeat(duk_context* ctx) { bool is_looped = duk_require_boolean(ctx, 0); sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); sound_set_looping(sound, is_looped); return 0; } static duk_ret_t js_Sound_get_seekable(duk_context* ctx) { duk_push_true(ctx); return 1; } static duk_ret_t js_Sound_get_volume(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); duk_push_number(ctx, sound_get_gain(sound)); return 1; } static duk_ret_t js_Sound_set_volume(duk_context* ctx) { float volume = duk_require_number(ctx, 0); sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); sound_set_gain(sound, volume); return 0; } static duk_ret_t js_Sound_pause(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); sound_stop(sound, false); return 0; } static duk_ret_t js_Sound_play(duk_context* ctx) { int n_args = duk_get_top(ctx); bool is_looping; sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); if (n_args >= 1) { sound_reload(sound); is_looping = duk_require_boolean(ctx, 0); sound_set_looping(sound, is_looping); } sound_play(sound); return 0; } static duk_ret_t js_Sound_reset(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); sound_seek(sound, 0.0); return 0; } static duk_ret_t js_Sound_stop(duk_context* ctx) { sound_t* sound; duk_push_this(ctx); sound = duk_require_sphere_obj(ctx, -1, "Sound"); duk_pop(ctx); sound_stop(sound, true); return 0; } static duk_ret_t js_new_SoundStream(duk_context* ctx) { // new SoundStream(frequency[, bits[, channels]]); // Arguments: // frequency: Audio frequency in Hz. (default: 22050) // bits: Bit depth. (default: 8) // channels: Number of independent channels. (default: 1) stream_t* stream; int argc; int frequency; int bits; int channels; argc = duk_get_top(ctx); frequency = argc >= 1 ? duk_require_int(ctx, 0) : 22050; bits = argc >= 2 ? duk_require_int(ctx, 1) : 8; channels = argc >= 3 ? duk_require_int(ctx, 1) : 1; if (bits != 8 && bits != 16 && bits != 24 && bits != 32) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SoundStream(): invalid bit depth (%i)", bits); if (!(stream = stream_new(frequency, bits, channels))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SoundStream(): stream creation failed"); duk_push_sphere_obj(ctx, "SoundStream", stream); return 1; } static duk_ret_t js_SoundStream_finalize(duk_context* ctx) { stream_t* stream; stream = duk_require_sphere_obj(ctx, 0, "SoundStream"); stream_free(stream); return 0; } static duk_ret_t js_SoundStream_get_bufferSize(duk_context* ctx) { stream_t* stream; duk_push_this(ctx); stream = duk_require_sphere_obj(ctx, -1, "SoundStream"); duk_pop(ctx); duk_push_number(ctx, stream->feed_size); return 1; } static duk_ret_t js_SoundStream_get_mixer(duk_context* ctx) { stream_t* stream; duk_push_this(ctx); stream = duk_require_sphere_obj(ctx, -1, "SoundStream"); duk_pop(ctx); duk_push_sphere_obj(ctx, "Mixer", mixer_ref(stream_get_mixer(stream))); return 1; } static duk_ret_t js_SoundStream_set_mixer(duk_context* ctx) { mixer_t* mixer = duk_require_sphere_obj(ctx, 0, "Mixer"); stream_t* stream; duk_push_this(ctx); stream = duk_require_sphere_obj(ctx, -1, "SoundStream"); duk_pop(ctx); stream_set_mixer(stream, mixer); return 1; } static duk_ret_t js_SoundStream_pause(duk_context* ctx) { stream_t* stream; duk_push_this(ctx); stream = duk_require_sphere_obj(ctx, -1, "SoundStream"); duk_pop(ctx); stream_pause(stream); return 0; } static duk_ret_t js_SoundStream_play(duk_context* ctx) { int n_args = duk_get_top(ctx); mixer_t* mixer = n_args >= 1 ? duk_require_sphere_obj(ctx, 0, "Mixer") : get_default_mixer(); stream_t* stream; duk_push_this(ctx); stream = duk_require_sphere_obj(ctx, -1, "SoundStream"); duk_pop(ctx); stream_set_mixer(stream, mixer); stream_play(stream); return 0; } static duk_ret_t js_SoundStream_stop(duk_context* ctx) { stream_t* stream; duk_push_this(ctx); stream = duk_require_sphere_obj(ctx, -1, "SoundStream"); duk_pop(ctx); stream_stop(stream); return 0; } static duk_ret_t js_SoundStream_write(duk_context* ctx) { // SoundStream:buffer(data); // Arguments: // data: An ArrayBuffer or TypedArray containing the audio data // to feed into the stream buffer. const void* data; duk_size_t size; stream_t* stream; duk_push_this(ctx); stream = duk_require_sphere_obj(ctx, -1, "SoundStream"); duk_pop(ctx); data = duk_require_buffer_data(ctx, 0, &size); stream_buffer(stream, data, size); return 0; } <file_sep>/src/compiler/cell.h #ifndef CELL__CELL_H__INCLUDED #define CELL__CELL_H__INCLUDED #include "posix.h" #include <zlib.h> #include "duktape.h" #include "lstring.h" #include "path.h" #include "utility.h" #include "vector.h" #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <time.h> #include <sys/stat.h> #include "version.h" #endif // CELL__CELL_H__INCLUDED <file_sep>/src/compiler/build.h #ifndef CELL__BUILD_H__INCLUDED #define CELL__BUILD_H__INCLUDED #include "assets.h" typedef struct build build_t; typedef struct target target_t; build_t* build_new (const path_t* in_path, const path_t* out_path, bool make_source_map); void build_free (build_t* build); bool build_is_ok (const build_t* build, int *out_num_errors, int *out_num_warnings); time_t build_timestamp (const build_t* build); target_t* build_add_asset (build_t* build, asset_t* asset, const path_t* subdir); vector_t* build_add_files (build_t* build, const path_t* pattern, bool recursive); void build_emit_error (build_t* build, const char* fmt, ...); void build_emit_warn (build_t* build, const char* fmt, ...); void build_install (build_t* build, const target_t* target, const path_t* path); bool build_prime (build_t* build, const char* rule_name); bool build_run (build_t* build); #endif // CELL__BUILD_H__INCLUDED <file_sep>/assets/system/modules/miniRT/prim.js /** * miniRT/prim CommonJS module * allows pre-rendering of expensive-to-draw primitives * (c) 2015-2016 <NAME> **/ if (typeof exports === 'undefined') { throw new TypeError("script must be loaded with require()"); } module.exports = { Circle: Circle, Text: Text, }; const cos = Math.cos; const sin = Math.sin; Circle.prototype = Object.create(Shape.prototype); Circle.prototype.constructor = Circle; function Circle(x, y, radius, color, color2) { if (arguments.length < 5) color2 = color; var numSegments = Math.min(radius, 126); var vertices = [ { x: x, y: y, u: 0.5, v: 0.5, color: color } ]; var pi2 = 2 * Math.PI; for (var i = 0; i < numSegments; ++i) { var phi = pi2 * i / numSegments; var c = cos(phi), s = sin(phi); vertices.push({ x: x + c * radius, y: y - s * radius, u: (c + 1.0) / 2.0, v: (s + 1.0) / 2.0, color: color2, }); } vertices.push({ x: x + radius, // cos(0) = 1.0 y: y, // sin(0) = 0.0 u: 1.0, v: 0.5, color: color2, }); var shape = new Shape(vertices, null, SHAPE_TRI_FAN); Object.setPrototypeOf(shape, Circle.prototype); return shape; } Text.prototype = Object.create(Shape.prototype); Text.prototype.constructor = Text; function Text(text, options) { options = options != null ? options : {}; var font = 'font' in options ? options.font : GetSystemFont(); var color = 'color' in options ? options.color : new Color(255, 255, 255, 255); var shadow = 'shadow' in options ? options.shadow : 0; var shadowColor = new Color(0, 0, 0, color.alpha); var width = font.getStringWidth(text) + Math.abs(shadow); var height = font.height + Math.abs(shadow); var surface = new Surface(width, height); var lastColorMask = font.getColorMask(); var offsetX = 0; var offsetY = 0; if (shadow > 0) { font.setColorMask(shadowColor); surface.drawText(font, shadow, shadow, text); font.setColorMask(color); surface.drawText(font, 0, 0, text); } else if (shadow < 0) { font.setColorMask(shadowColor); surface.drawText(font, 0, 0, text); font.setColorMask(color); surface.drawText(font, -shadow, -shadow, text); offsetX = shadow; offsetY = shadow; } else { font.setColorMask(color); surface.drawText(font, 0, 0, text); } font.setColorMask(lastColorMask); var image = surface.createImage(); width = image.width; height = image.height; var shape = new Shape([ { x: 0, y: 0, u: 0.0, v: 1.0 }, { x: width, y: 0, u: 1.0, v: 1.0 }, { x: 0, y: height + 1, u: 0.0, v: 0.0 }, { x: width, y: height, u: 1.0, v: 0.0 }, ], image); Object.setPrototypeOf(shape, Text.prototype); return shape; } <file_sep>/src/compiler/spk_writer.h #ifndef CELL__SPK_WRITER_H__INCLUDED #define CELL__SPK_WRITER_H__INCLUDED typedef struct spk_writer spk_writer_t; spk_writer_t* spk_create (const char* filename); void spk_close (spk_writer_t* writer); bool spk_add_file (spk_writer_t* writer, const char* filename, const char* spk_pathname); #endif // CELL__SPK_WRITER_H__INCLUDED <file_sep>/src/engine/matrix.h #ifndef MINISPHERE__MATRIX_H__INCLUDED #define MINISPHERE__MATRIX_H__INCLUDED typedef struct matrix matrix_t; matrix_t* matrix_new (void); matrix_t* matrix_clone (const matrix_t* matrix); matrix_t* matrix_ref (matrix_t* matrix); void matrix_free (matrix_t* matrix); const ALLEGRO_TRANSFORM* matrix_transform (const matrix_t* matrix); const float* matrix_items (const matrix_t* matrix); void matrix_compose (matrix_t* matrix, const matrix_t* other); void matrix_identity (matrix_t* matrix); void matrix_rotate (matrix_t* matrix, float theta, float vx, float vy, float vz); void matrix_scale (matrix_t* matrix, float sx, float sy, float sz); void matrix_translate (matrix_t* matrix, float dx, float dy, float dz); #endif // MINISPHERE__MATRIX_H__INCLUDED <file_sep>/src/debugger/message.h #ifndef SSJ__MESSAGE_H__INCLUDED #define SSJ__MESSAGE_H__INCLUDED #include "dvalue.h" typedef struct message message_t; typedef enum message_tag { MESSAGE_UNKNOWN, MESSAGE_REQ, MESSAGE_REP, MESSAGE_ERR, MESSAGE_NFY, } message_tag_t; enum req_command { REQ_BASICINFO = 0x10, REQ_SENDSTATUS = 0x11, REQ_PAUSE = 0x12, REQ_RESUME = 0x13, REQ_STEPINTO = 0x14, REQ_STEPOVER = 0x15, REQ_STEPOUT = 0x16, REQ_LISTBREAK = 0x17, REQ_ADDBREAK = 0x18, REQ_DELBREAK = 0x19, REQ_GETVAR = 0x1A, REQ_PUTVAR = 0x1B, REQ_GETCALLSTACK = 0x1C, REQ_GETLOCALS = 0x1D, REQ_EVAL = 0x1E, REQ_DETACH = 0x1F, REQ_DUMPHEAP = 0x20, REQ_GETBYTECODE = 0x21, REQ_APPREQUEST = 0x22, REQ_GETHEAPOBJINFO = 0x23, REQ_GETOBJPROPDESC = 0x24, REQ_GETOBJPROPDESCRANGE = 0x25, }; enum nfy_command { NFY_STATUS = 0x01, NFY_PRINT = 0x02, NFY_ALERT = 0x03, NFY_LOG = 0x04, NFY_THROW = 0x05, NFY_DETACHING = 0x06, NFY_APPNOTIFY = 0x07, }; enum err_command { ERR_UNKNOWN = 0x00, ERR_UNSUPPORTED = 0x01, ERR_TOO_MANY = 0x02, ERR_NOT_FOUND = 0x03, ERR_APP_ERROR = 0x04, }; enum appnotify { APPNFY_NOP, APPNFY_DEBUG_PRINT, }; enum apprequest { APPREQ_NOP, APPREQ_GAME_INFO, APPREQ_SOURCE, }; message_t* message_new (message_tag_t tag); void message_free (message_t* o); int message_len (const message_t* o); message_tag_t message_tag (const message_t* o); dvalue_tag_t message_get_atom_tag (const message_t* o, int index); const dvalue_t* message_get_dvalue (const message_t* o, int index); double message_get_float (const message_t* o, int index); int32_t message_get_int (const message_t* o, int index); const char* message_get_string (const message_t* o, int index); void message_add_dvalue (message_t* o, const dvalue_t* dvalue); void message_add_float (message_t* o, double value); void message_add_heapptr (message_t* o, remote_ptr_t value); void message_add_int (message_t* o, int value); void message_add_string (message_t* o, const char* value); message_t* message_recv (socket_t* socket); bool message_send (const message_t* o, socket_t* socket); #endif // SSJ__MESSAGE_H__INCLUDED <file_sep>/assets/system/modules/miniRT/threads.js /** * miniRT/threads CommonJS module * a threading engine for Sphere with an API similar to Pthreads * (c) 2015-2016 <NAME> **/ if (typeof exports === 'undefined') { throw new TypeError("script must be loaded with require()"); } const link = require('link'); // threads object // represents the threader. var threads = module.exports = (function() { var _SetFrameRate = SetFrameRate; var _SetMapEngineFrameRate = SetMapEngineFrameRate; var _SetRenderScript = SetRenderScript; var _SetUpdateScript = SetUpdateScript; var _MapEngine = MapEngine; var currentSelf = 0; var hasUpdated = false; var frameRate = 60; var manifest = GetGameManifest(); var nextThreadID = 1; var threads = []; if ('frameRate' in manifest && typeof manifest.frameRate === 'number') frameRate = manifest.frameRate; var threadSorter = function(a, b) { return a.priority != b.priority ? a.priority - b.priority : a.id - b.id; }; _SetUpdateScript(updateAll); _SetRenderScript(renderAll); _SetFrameRate(frameRate); _SetMapEngineFrameRate(frameRate); // the threading system commandeers several legacy APIs, making them unsafe // to use without messing with the operation of miniRT, so we disable them. // for MapEngine(), just override the framerate. MapEngine = function(mapName) { _MapEngine(mapName, frameRate); } SetUpdateScript = SetRenderScript = SetFrameRate = SetMapEngineFrameRate = function() { Abort("API incompatible with miniRT/threads", -1); } return { get frameRate() { return frameRate; }, set frameRate(value) { set_frameRate(value); }, create: create, createEx: createEx, isRunning: isRunning, join: join, kill: kill, renderAll: renderAll, self: self, updateAll: updateAll, }; function doFrame() { if (IsMapEngineRunning()) RenderMap(); else renderAll(); FlipScreen(); if (IsMapEngineRunning()) { hasUpdated = false; UpdateMapEngine(); if (!hasUpdated) updateAll(); } else { updateAll(); } }; // threads.frameRate (read/write) // gets or sets the miniRT frame rate. this should be used instead of // SetFrameRate(), which will throw an error if called. function set_frameRate(value) { frameRate = Math.floor(Math.max(value, 1)); _SetFrameRate(frameRate); _SetMapEngineFrameRate(frameRate); } // threads.create() // create an object thread. this is the recommended thread creation method. // arguments: // entity: the object for which to create the thread. this object's .update() method // will be called once per frame, along with .render() and .getInput() if they // exist, until .update() returns false. // priority: optional. the render priority for the new thread. higher-priority threads are rendered // later in a frame than lower-priority ones. ignored if no renderer is provided. (default: 0) function create(entity, priority) { Assert(entity instanceof Object || entity === null, "create() argument must be a valid object", -1); priority = priority !== undefined ? priority : 0; var update = entity.update; var render = (typeof entity.render === 'function') ? entity.render : undefined; var getInput = (typeof entity.getInput === 'function') ? entity.getInput : null; return createEx(entity, { priority: priority, update: entity.update, render: entity.render, getInput: entity.getInput, }); }; // threads.createEx() // create a thread with advanced options. // arguments: // that: the object to bind as 'this' to thread callbacks. may be null. // threadDesc: an object describing the thread. this should contain the following members: // update: the update function for the new thread. // render: optional. the render function for the new thread. // getInput: optional. the input handler for the new thread. // priority: optional. the render priority for the new thread. higher-priority threads // are rendered later in a frame than lower-priority ones. ignored if no // renderer is provided. (default: 0) // remarks: // this is for advanced thread creation. for typical use, it is recommended to use // threads.create() instead. function createEx(that, threadDesc) { Assert(arguments.length >= 2, "threads.createEx() expects 2 arguments", -1); var update = threadDesc.update.bind(that); var render = typeof threadDesc.render === 'function' ? threadDesc.render.bind(that) : undefined; var getInput = typeof threadDesc.getInput === 'function' ? threadDesc.getInput.bind(that) : undefined; var priority = 'priority' in threadDesc ? threadDesc.priority : 0; var newThread = { isValid: true, id: nextThreadID++, that: that, inputHandler: getInput, isBusy: false, priority: priority, renderer: render, updater: update, }; threads.push(newThread); return newThread.id; }; // threads.isRunning() // determine whether a thread is still running. // arguments: // threadID: the ID of the thread to check. function isRunning(threadID) { if (threadID == 0) return false; for (var i = 0; i < threads.length; ++i) { if (threads[i].id == threadID) { return true; } } return false; }; // threads.join() // Blocks the calling thread until one or more other threads have terminated. // arguments: // threadID: either a single thread ID or an array of them. any invalid thread // ID will cause an error to be thrown. function join(threadIDs) { threadIDs = threadIDs instanceof Array ? threadIDs : [ threadIDs ]; while (link(threads) .filterBy('id', threadIDs) .length() > 0) { doFrame(); } }; // threads.kill() // forcibly terminate a thread. // arguments: // threadID: the ID of the thread to terminate. function kill(threadID) { link(threads) .where(function(thread) { return thread.id == threadID }) .execute(function(thread) { thread.isValid = false; }) .remove(); }; // threads.renderAll() // Renders the current frame by calling all active threads' renderers. function renderAll() { if (IsSkippedFrame()) return; link(link(threads).sort(threadSorter)) .where(function(thread) { return thread.isValid; }) .where(function(thread) { return thread.renderer !== undefined; }) .each(function(thread) { thread.renderer(); }.bind(this)); }; // threads.self() // get the currently executing thread's thread ID. // Remarks: // if this function is used outside of a thread update, render or input // handling call, it will return 0 (the ID of the main thread). function self() { return currentSelf; }; // threads.updateAll() // update all active threads for the next frame. function updateAll(threadID) { var threadsEnding = []; link(link(threads).toArray()) .where(function(thread) { return thread.isValid; }) .where(function(thread) { return !thread.isBusy; }) .each(function(thread) { var lastSelf = currentSelf; thread.isBusy = true; currentSelf = thread.id; var isRunning = thread.updater(thread.id); if (thread.inputHandler !== undefined && isRunning) thread.inputHandler(); currentSelf = lastSelf; thread.isBusy = false; if (!isRunning) threadsEnding.push(thread.id); }.bind(this)); link(threadsEnding) .each(function(threadID) { kill(threadID); }); hasUpdated = true; } })(); <file_sep>/src/shared/lstring.h #ifndef MINISPHERE__LSTRING_H__INCLUDED #define MINISPHERE__LSTRING_H__INCLUDED #include <stdarg.h> #include <stddef.h> typedef struct lstring lstring_t; lstring_t* lstr_new (const char* cstr); lstring_t* lstr_newf (const char* fmt, ...); lstring_t* lstr_vnewf (const char* fmt, va_list args); lstring_t* lstr_from_buf (const char* buffer, size_t length); void lstr_free (lstring_t* string); const char* lstr_cstr (const lstring_t* string); int lstr_cmp (const lstring_t* string1, const lstring_t* string2); lstring_t* lstr_dup (const lstring_t* string); size_t lstr_len (const lstring_t* string); #endif // MINISPHERE__LSTRING_H__INCLUDED <file_sep>/src/engine/debugger.h #ifndef MINISPHERE__DEBUGGER_H__INCLUDED #define MINISPHERE__DEBUGGER_H__INCLUDED void initialize_debugger (bool want_attach, bool allow_remote); void shutdown_debugger (void); void update_debugger (void); bool is_debugger_attached (void); const char* get_compiled_name (const char* source_name); const char* get_source_name (const char* pathname); void cache_source (const char* name, const lstring_t* text); void debug_print (const char* text); #endif // MINISPHERE__DEBUGGER_H__INCLUDED <file_sep>/src/engine/script.c #include "minisphere.h" #include "script.h" #include "api.h" #include "debugger.h" #include "transpiler.h" #include "utility.h" struct script { unsigned int refcount; bool is_in_use; duk_uarridx_t id; }; static script_t* script_from_js_function (void* heapptr); static int s_next_script_id = 0; void initialize_scripts(void) { console_log(1, "initializing JS script manager"); duk_push_global_stash(g_duk); duk_push_array(g_duk); duk_put_prop_string(g_duk, -2, "scripts"); duk_pop(g_duk); initialize_transpiler(); } void shutdown_scripts(void) { console_log(1, "shutting down JS script manager"); shutdown_transpiler(); } bool evaluate_script(const char* filename) { sfs_file_t* file = NULL; path_t* path; const char* source_name; lstring_t* source_text = NULL; char* slurp; size_t size; path = make_sfs_path(filename, NULL, false); source_name = get_source_name(path_cstr(path)); if (!(slurp = sfs_fslurp(g_fs, filename, NULL, &size))) goto on_error; source_text = lstr_from_buf(slurp, size); free(slurp); // ensure non-JS scripts are transpiled to JS first. this is needed to support // TypeScript, CoffeeScript, etc. transparently. if (!transpile_to_js(&source_text, source_name)) goto on_error; // ready for launch in T-10...9...*munch* duk_push_lstring_t(g_duk, source_text); duk_push_string(g_duk, source_name); if (duk_pcompile(g_duk, DUK_COMPILE_EVAL) != DUK_EXEC_SUCCESS) goto on_error; if (duk_pcall(g_duk, 0) != DUK_EXEC_SUCCESS) goto on_error; lstr_free(source_text); path_free(path); return true; on_error: lstr_free(source_text); path_free(path); if (!duk_is_error(g_duk, -1)) duk_push_error_object(g_duk, DUK_ERR_ERROR, "script `%s` not found\n", filename); return false; } script_t* compile_script(const lstring_t* source, const char* fmt_name, ...) { va_list ap; lstring_t* name; script_t* script; va_start(ap, fmt_name); name = lstr_vnewf(fmt_name, ap); va_end(ap); script = calloc(1, sizeof(script_t)); console_log(3, "compiling script #%u as `%s`", s_next_script_id, lstr_cstr(name)); // this wouldn't be necessary if Duktape duk_get_heapptr() gave us a strong reference. // instead we get this ugliness where the compiled function is saved in the global stash // so it doesn't get eaten by the garbage collector. yummy! duk_push_global_stash(g_duk); duk_get_prop_string(g_duk, -1, "scripts"); duk_push_lstring_t(g_duk, source); duk_push_lstring_t(g_duk, name); duk_compile(g_duk, 0x0); duk_put_prop_index(g_duk, -2, s_next_script_id); duk_pop_2(g_duk); cache_source(lstr_cstr(name), source); lstr_free(name); script->id = s_next_script_id++; return ref_script(script); } script_t* ref_script(script_t* script) { ++script->refcount; return script; } void free_script(script_t* script) { if (script == NULL || --script->refcount > 0) return; console_log(3, "disposing script #%u no longer in use", script->id); // unstash the compiled function, it's now safe to GC duk_push_global_stash(g_duk); duk_get_prop_string(g_duk, -1, "scripts"); duk_del_prop_index(g_duk, -1, script->id); duk_pop_2(g_duk); free(script); } void run_script(script_t* script, bool allow_reentry) { bool was_in_use; if (script == NULL) // NULL is allowed, it's a no-op return; // check whether an instance of the script is already running. // if it is, but the script is reentrant, allow it. otherwise, return early // to prevent multiple invocation. if (script->is_in_use && !allow_reentry) { console_log(3, "skipping execution of script #%u, already in use", script->id); return; } was_in_use = script->is_in_use; console_log(4, "executing script #%u", script->id); // ref the script in case it gets freed during execution. the owner // may be destroyed in the process and we don't want to end up crashing. ref_script(script); // get the compiled script from the stash and run it. so dumb... script->is_in_use = true; duk_push_global_stash(g_duk); duk_get_prop_string(g_duk, -1, "scripts"); duk_get_prop_index(g_duk, -1, script->id); duk_call(g_duk, 0); duk_pop_3(g_duk); script->is_in_use = was_in_use; free_script(script); } script_t* duk_require_sphere_script(duk_context* ctx, duk_idx_t index, const char* name) { lstring_t* codestring; script_t* script; index = duk_require_normalize_index(ctx, index); if (duk_is_callable(ctx, index)) { // caller passed function directly script = script_from_js_function(duk_get_heapptr(ctx, index)); } else if (duk_is_string(ctx, index)) { // caller passed code string, compile it codestring = duk_require_lstring_t(ctx, index); script = compile_script(codestring, "%s", name); lstr_free(codestring); } else if (duk_is_null_or_undefined(ctx, index)) return NULL; else duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "script must be string, function, or null/undefined"); return script; } static script_t* script_from_js_function(void* heapptr) { script_t* script; if (!(script = calloc(1, sizeof(script_t)))) return NULL; duk_push_global_stash(g_duk); duk_get_prop_string(g_duk, -1, "scripts"); duk_push_heapptr(g_duk, heapptr); duk_put_prop_index(g_duk, -2, s_next_script_id); duk_pop_2(g_duk); script->id = s_next_script_id++; return ref_script(script); } <file_sep>/src/plugin/SettingsPages/SettingsPage.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Sphere.Plugins.Interfaces; using Sphere.Plugins; namespace minisphere.Gdk.SettingsPages { partial class SettingsPage : UserControl, ISettingsPage { private PluginMain _main; public SettingsPage(PluginMain main) { InitializeComponent(); _main = main; } public Control Control { get { return this; } } public bool Apply() { _main.Conf.GdkPath = GdkPathTextBox.Text; _main.Conf.MakeDebugPackages = MakeDebugPackageCheckBox.Checked; _main.Conf.AlwaysUseConsole = TestWithConsoleCheckBox.Checked; _main.Conf.TestInWindow = TestInWindowCheckBox.Checked; _main.Conf.Verbosity = VerbosityComboBox.SelectedIndex; return true; } protected override void OnLoad(EventArgs e) { GdkPathTextBox.Text = _main.Conf.GdkPath; MakeDebugPackageCheckBox.Checked = _main.Conf.MakeDebugPackages; TestWithConsoleCheckBox.Checked = _main.Conf.AlwaysUseConsole; TestInWindowCheckBox.Checked = _main.Conf.TestInWindow; VerbosityComboBox.SelectedIndex = _main.Conf.Verbosity; base.OnLoad(e); } private void BrowseButton_Click(object sender, EventArgs e) { FolderBrowserDialog fb = new FolderBrowserDialog(); fb.Description = "Select the folder where the minisphere GDK is installed. (minisphere 2.0+ required)"; fb.ShowNewFolderButton = false; if (fb.ShowDialog(this) == DialogResult.OK) { GdkPathTextBox.Text = fb.SelectedPath; } } } } <file_sep>/src/engine/map_engine.c #include "minisphere.h" #include "api.h" #include "audialis.h" #include "color.h" #include "image.h" #include "input.h" #include "obsmap.h" #include "persons.h" #include "script.h" #include "surface.h" #include "tileset.h" #include "vector.h" #include "map_engine.h" #define MAX_PLAYERS 4 enum map_script_type { MAP_SCRIPT_ON_ENTER, MAP_SCRIPT_ON_LEAVE, MAP_SCRIPT_ON_LEAVE_NORTH, MAP_SCRIPT_ON_LEAVE_EAST, MAP_SCRIPT_ON_LEAVE_SOUTH, MAP_SCRIPT_ON_LEAVE_WEST, MAP_SCRIPT_MAX }; static struct map* load_map (const char* path); static void free_map (struct map* map); static bool are_zones_at (int x, int y, int layer, int* out_count); static struct map_trigger* get_trigger_at (int x, int y, int layer, int* out_index); static struct map_zone* get_zone_at (int x, int y, int layer, int which, int* out_index); static bool change_map (const char* filename, bool preserve_persons); static int find_layer (const char* name); static void map_screen_to_layer (int layer, int camera_x, int camera_y, int* inout_x, int* inout_y); static void map_screen_to_map (int camera_x, int camera_y, int* inout_x, int* inout_y); static void process_map_input (void); static void render_map (void); static void update_map_engine (bool is_main_loop); static duk_ret_t js_MapEngine (duk_context* ctx); static duk_ret_t js_AreZonesAt (duk_context* ctx); static duk_ret_t js_IsCameraAttached (duk_context* ctx); static duk_ret_t js_IsInputAttached (duk_context* ctx); static duk_ret_t js_IsLayerReflective (duk_context* ctx); static duk_ret_t js_IsLayerVisible (duk_context* ctx); static duk_ret_t js_IsMapEngineRunning (duk_context* ctx); static duk_ret_t js_IsTriggerAt (duk_context* ctx); static duk_ret_t js_GetCameraPerson (duk_context* ctx); static duk_ret_t js_GetCameraX (duk_context* ctx); static duk_ret_t js_GetCameraY (duk_context* ctx); static duk_ret_t js_GetCurrentMap (duk_context* ctx); static duk_ret_t js_GetCurrentTrigger (duk_context* ctx); static duk_ret_t js_GetCurrentZone (duk_context* ctx); static duk_ret_t js_GetInputPerson (duk_context* ctx); static duk_ret_t js_GetLayerHeight (duk_context* ctx); static duk_ret_t js_GetLayerMask (duk_context* ctx); static duk_ret_t js_GetLayerWidth (duk_context* ctx); static duk_ret_t js_GetMapEngineFrameRate (duk_context* ctx); static duk_ret_t js_GetNextAnimatedTile (duk_context* ctx); static duk_ret_t js_GetNumLayers (duk_context* ctx); static duk_ret_t js_GetNumTiles (duk_context* ctx); static duk_ret_t js_GetNumTriggers (duk_context* ctx); static duk_ret_t js_GetNumZones (duk_context* ctx); static duk_ret_t js_GetTalkActivationButton (duk_context* ctx); static duk_ret_t js_GetTalkActivationKey (duk_context* ctx); static duk_ret_t js_GetTile (duk_context* ctx); static duk_ret_t js_GetTileDelay (duk_context* ctx); static duk_ret_t js_GetTileHeight (duk_context* ctx); static duk_ret_t js_GetTileImage (duk_context* ctx); static duk_ret_t js_GetTileName (duk_context* ctx); static duk_ret_t js_GetTileSurface (duk_context* ctx); static duk_ret_t js_GetTileWidth (duk_context* ctx); static duk_ret_t js_GetTriggerLayer (duk_context* ctx); static duk_ret_t js_GetTriggerX (duk_context* ctx); static duk_ret_t js_GetTriggerY (duk_context* ctx); static duk_ret_t js_GetZoneHeight (duk_context* ctx); static duk_ret_t js_GetZoneLayer (duk_context* ctx); static duk_ret_t js_GetZoneSteps (duk_context* ctx); static duk_ret_t js_GetZoneWidth (duk_context* ctx); static duk_ret_t js_GetZoneX (duk_context* ctx); static duk_ret_t js_GetZoneY (duk_context* ctx); static duk_ret_t js_SetCameraX (duk_context* ctx); static duk_ret_t js_SetCameraY (duk_context* ctx); static duk_ret_t js_SetColorMask (duk_context* ctx); static duk_ret_t js_SetDefaultMapScript (duk_context* ctx); static duk_ret_t js_SetLayerHeight (duk_context* ctx); static duk_ret_t js_SetLayerMask (duk_context* ctx); static duk_ret_t js_SetLayerReflective (duk_context* ctx); static duk_ret_t js_SetLayerRenderer (duk_context* ctx); static duk_ret_t js_SetLayerSize (duk_context* ctx); static duk_ret_t js_SetLayerVisible (duk_context* ctx); static duk_ret_t js_SetLayerWidth (duk_context* ctx); static duk_ret_t js_SetMapEngineFrameRate (duk_context* ctx); static duk_ret_t js_SetNextAnimatedTile (duk_context* ctx); static duk_ret_t js_SetRenderScript (duk_context* ctx); static duk_ret_t js_SetTalkActivationButton (duk_context* ctx); static duk_ret_t js_SetTalkActivationKey (duk_context* ctx); static duk_ret_t js_SetTile (duk_context* ctx); static duk_ret_t js_SetTileDelay (duk_context* ctx); static duk_ret_t js_SetTileImage (duk_context* ctx); static duk_ret_t js_SetTileName (duk_context* ctx); static duk_ret_t js_SetTileSurface (duk_context* ctx); static duk_ret_t js_SetTriggerLayer (duk_context* ctx); static duk_ret_t js_SetTriggerScript (duk_context* ctx); static duk_ret_t js_SetTriggerXY (duk_context* ctx); static duk_ret_t js_SetUpdateScript (duk_context* ctx); static duk_ret_t js_SetZoneLayer (duk_context* ctx); static duk_ret_t js_SetZoneMetrics (duk_context* ctx); static duk_ret_t js_SetZoneScript (duk_context* ctx); static duk_ret_t js_SetZoneSteps (duk_context* ctx); static duk_ret_t js_AddTrigger (duk_context* ctx); static duk_ret_t js_AddZone (duk_context* ctx); static duk_ret_t js_AttachCamera (duk_context* ctx); static duk_ret_t js_AttachInput (duk_context* ctx); static duk_ret_t js_AttachPlayerInput (duk_context* ctx); static duk_ret_t js_CallDefaultMapScript (duk_context* ctx); static duk_ret_t js_CallMapScript (duk_context* ctx); static duk_ret_t js_ChangeMap (duk_context* ctx); static duk_ret_t js_DetachCamera (duk_context* ctx); static duk_ret_t js_DetachInput (duk_context* ctx); static duk_ret_t js_DetachPlayerInput (duk_context* ctx); static duk_ret_t js_ExecuteTrigger (duk_context* ctx); static duk_ret_t js_ExecuteZones (duk_context* ctx); static duk_ret_t js_ExitMapEngine (duk_context* ctx); static duk_ret_t js_MapToScreenX (duk_context* ctx); static duk_ret_t js_MapToScreenY (duk_context* ctx); static duk_ret_t js_RemoveTrigger (duk_context* ctx); static duk_ret_t js_RemoveZone (duk_context* ctx); static duk_ret_t js_RenderMap (duk_context* ctx); static duk_ret_t js_ReplaceTilesOnLayer (duk_context* ctx); static duk_ret_t js_ScreenToMapX (duk_context* ctx); static duk_ret_t js_ScreenToMapY (duk_context* ctx); static duk_ret_t js_SetDelayScript (duk_context* ctx); static duk_ret_t js_UpdateMapEngine (duk_context* ctx); static person_t* s_camera_person = NULL; static int s_cam_x = 0; static int s_cam_y = 0; static color_t s_color_mask; static color_t s_fade_color_from; static color_t s_fade_color_to; static int s_fade_frames; static int s_fade_progress; static int s_map_corner_x; static int s_map_corner_y; static int s_current_trigger = -1; static int s_current_zone = -1; static script_t* s_def_scripts[MAP_SCRIPT_MAX]; static bool s_exiting = false; static int s_framerate = 0; static unsigned int s_frames = 0; static bool s_is_map_running = false; static lstring_t* s_last_bgm_file = NULL; static struct map* s_map = NULL; static sound_t* s_map_bgm_stream = NULL; static char* s_map_filename = NULL; static struct map_trigger* s_on_trigger = NULL; static struct player* s_players; static script_t* s_render_script = NULL; static int s_talk_button = 0; static script_t* s_update_script = NULL; static int s_num_delay_scripts = 0; static int s_max_delay_scripts = 0; static struct delay_script *s_delay_scripts = NULL; struct delay_script { script_t* script; int frames_left; }; struct map { int width, height; bool is_repeating; point3_t origin; lstring_t* bgm_file; script_t* scripts[MAP_SCRIPT_MAX]; tileset_t* tileset; vector_t* triggers; vector_t* zones; int num_layers; int num_persons; struct map_layer *layers; struct map_person *persons; }; struct map_layer { lstring_t* name; bool is_parallax; bool is_reflective; bool is_visible; float autoscroll_x; float autoscroll_y; color_t color_mask; int height; obsmap_t* obsmap; float parallax_x; float parallax_y; script_t* render_script; struct map_tile* tilemap; int width; }; struct map_person { lstring_t* name; lstring_t* spriteset; int x, y, z; lstring_t* create_script; lstring_t* destroy_script; lstring_t* command_script; lstring_t* talk_script; lstring_t* touch_script; }; struct map_tile { int tile_index; int frames_left; }; struct map_trigger { script_t* script; int x, y, z; }; struct map_zone { bool is_active; rect_t bounds; int interval; int steps_left; int layer; script_t* script; }; struct player { bool is_talk_allowed; person_t* person; int talk_key; }; #pragma pack(push, 1) struct rmp_header { char signature[4]; int16_t version; uint8_t type; int8_t num_layers; uint8_t reserved_1; int16_t num_entities; int16_t start_x; int16_t start_y; int8_t start_layer; int8_t start_direction; int16_t num_strings; int16_t num_zones; uint8_t repeat_map; uint8_t reserved[234]; }; struct rmp_entity_header { uint16_t x; uint16_t y; uint16_t z; uint16_t type; uint8_t reserved[8]; }; struct rmp_layer_header { int16_t width; int16_t height; uint16_t flags; float parallax_x; float parallax_y; float scrolling_x; float scrolling_y; int32_t num_segments; uint8_t is_reflective; uint8_t reserved[3]; }; struct rmp_zone_header { uint16_t x1; uint16_t y1; uint16_t x2; uint16_t y2; uint16_t layer; uint16_t interval; uint8_t reserved[4]; }; #pragma pack(pop) void initialize_map_engine(void) { int i; console_log(1, "initializing map engine"); initialize_persons_manager(); memset(s_def_scripts, 0, MAP_SCRIPT_MAX * sizeof(int)); s_map = NULL; s_map_filename = NULL; s_camera_person = NULL; s_players = calloc(MAX_PLAYERS, sizeof(struct player)); for (i = 0; i < MAX_PLAYERS; ++i) s_players[i].is_talk_allowed = true; s_current_trigger = -1; s_current_zone = -1; s_render_script = 0; s_update_script = 0; s_num_delay_scripts = s_max_delay_scripts = 0; s_delay_scripts = NULL; s_talk_button = 0; s_is_map_running = false; s_color_mask = color_new(0, 0, 0, 0); s_on_trigger = NULL; } void shutdown_map_engine(void) { int i; console_log(1, "shutting down map engine"); for (i = 0; i < s_num_delay_scripts; ++i) free_script(s_delay_scripts[i].script); free(s_delay_scripts); for (i = 0; i < MAP_SCRIPT_MAX; ++i) free_script(s_def_scripts[i]); free_script(s_update_script); free_script(s_render_script); free_map(s_map); free(s_players); shutdown_persons_manager(); } bool is_map_engine_running(void) { return s_is_map_running; } rect_t get_map_bounds(void) { rect_t bounds; int tile_w, tile_h; tileset_get_size(s_map->tileset, &tile_w, &tile_h); bounds.x1 = 0; bounds.y1 = 0; bounds.x2 = s_map->width * tile_w; bounds.y2 = s_map->height * tile_h; return bounds; } const char* get_map_name(void) { return s_map ? s_map_filename : NULL; } point3_t get_map_origin(void) { point3_t empty_point = { 0, 0, 0 }; return s_map ? s_map->origin : empty_point; } int get_map_tile(int x, int y, int layer) { int layer_h = s_map->layers[layer].height; int layer_w = s_map->layers[layer].width; if (s_map->is_repeating || s_map->layers[layer].is_parallax) { x = (x % layer_w + layer_w) % layer_w; y = (y % layer_h + layer_h) % layer_h; } if (x < 0 || y < 0 || x >= layer_w || y >= layer_h) return -1; return s_map->layers[layer].tilemap[x + y * layer_w].tile_index; } const tileset_t* get_map_tileset(void) { return s_map->tileset; } const obsmap_t* get_map_layer_obsmap(int layer) { return s_map->layers[layer].obsmap; } void get_trigger_xyz(int trigger_index, int* out_x, int* out_y, int* out_layer) { struct map_trigger* trigger; trigger = vector_get(s_map->triggers, trigger_index); if (out_x) *out_x = trigger->x; if (out_y) *out_y = trigger->y; if (out_layer) *out_layer = trigger->z; } rect_t get_zone_bounds(int zone_index) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); return zone->bounds; } int get_zone_layer(int zone_index) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); return zone->layer; } int get_zone_steps(int zone_index) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); return zone->interval; } void set_trigger_layer(int trigger_index, int layer) { struct map_trigger* trigger; trigger = vector_get(s_map->triggers, trigger_index); trigger->z = layer; } void set_trigger_script(int trigger_index, script_t* script) { script_t* old_script; struct map_trigger* trigger; trigger = vector_get(s_map->triggers, trigger_index); old_script = trigger->script; trigger->script = ref_script(script); free_script(old_script); } void set_trigger_xy(int trigger_index, int x, int y) { struct map_trigger* trigger; trigger = vector_get(s_map->triggers, trigger_index); trigger->x = x; trigger->y = y; } void set_zone_bounds(int zone_index, rect_t bounds) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); normalize_rect(&bounds); zone->bounds = bounds; } void set_zone_layer(int zone_index, int layer) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); zone->layer = layer; } void set_zone_script(int zone_index, script_t* script) { script_t* old_script; struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); old_script = zone->script; zone->script = ref_script(script); free_script(old_script); } void set_zone_steps(int zone_index, int interval) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); zone->interval = interval; zone->steps_left = 0; } bool add_trigger(int x, int y, int layer, script_t* script) { struct map_trigger trigger; console_log(2, "creating trigger #%d on map `%s`", vector_len(s_map->triggers), s_map_filename); console_log(3, " location: `%s` @ (%d,%d)", lstr_cstr(s_map->layers[layer].name), x, y); trigger.x = x; trigger.y = y; trigger.z = layer; trigger.script = ref_script(script); if (!vector_push(s_map->triggers, &trigger)) return false; return true; } bool add_zone(rect_t bounds, int layer, script_t* script, int steps) { struct map_zone zone; console_log(2, "creating %u-step zone #%d on map `%s`", steps, vector_len(s_map->zones), s_map_filename); console_log(3, " bounds: (%d,%d)-(%d,%d)", bounds.x1, bounds.y1, bounds.x2, bounds.y2); memset(&zone, 0, sizeof(struct map_zone)); zone.bounds = bounds; zone.layer = layer; zone.script = ref_script(script); zone.interval = steps; zone.steps_left = 0; if (!vector_push(s_map->zones, &zone)) return false; return true; } void detach_person(const person_t* person) { int i; if (s_camera_person == person) s_camera_person = NULL; for (i = 0; i < MAX_PLAYERS; ++i) if (s_players[i].person == person) s_players[i].person = NULL; } void normalize_map_entity_xy(double* inout_x, double* inout_y, int layer) { int tile_w, tile_h; int layer_w, layer_h; if (s_map == NULL) return; // can't normalize if no map loaded if (!s_map->is_repeating && !s_map->layers[layer].is_parallax) return; tileset_get_size(s_map->tileset, &tile_w, &tile_h); layer_w = s_map->layers[layer].width * tile_w; layer_h = s_map->layers[layer].height * tile_h; if (inout_x) *inout_x = fmod(fmod(*inout_x, layer_w) + layer_w, layer_w); if (inout_y) *inout_y = fmod(fmod(*inout_y, layer_h) + layer_h, layer_h); } void remove_trigger(int trigger_index) { vector_remove(s_map->triggers, trigger_index); } void remove_zone(int zone_index) { vector_remove(s_map->zones, zone_index); } bool resize_map_layer(int layer, int x_size, int y_size) { int old_height; int old_width; struct map_tile* tile; int tile_width; int tile_height; struct map_tile* tilemap; struct map_trigger* trigger; struct map_zone* zone; int x, y, i; old_width = s_map->layers[layer].width; old_height = s_map->layers[layer].height; // allocate a new tilemap and copy the old layer tiles into it. we can't simply realloc // because the tilemap is a 2D array. if (!(tilemap = malloc(x_size * y_size * sizeof(struct map_tile)))) return false; for (x = 0; x < x_size; ++x) { for (y = 0; y < y_size; ++y) { if (x < old_width && y < old_height) tilemap[x + y * x_size] = s_map->layers[layer].tilemap[x + y * old_width]; else { tile = &tilemap[x + y * x_size]; tile->frames_left = tileset_get_delay(s_map->tileset, 0); tile->tile_index = 0; } } } // free the old tilemap and substitute the new one free(s_map->layers[layer].tilemap); s_map->layers[layer].tilemap = tilemap; s_map->layers[layer].width = x_size; s_map->layers[layer].height = y_size; // if we resize the largest layer, the overall map size will change. // recalcuate it. tileset_get_size(s_map->tileset, &tile_width, &tile_height); s_map->width = 0; s_map->height = 0; for (i = 0; i < s_map->num_layers; ++i) { if (!s_map->layers[i].is_parallax) { s_map->width = fmax(s_map->width, s_map->layers[i].width * tile_width); s_map->height = fmax(s_map->height, s_map->layers[i].height * tile_height); } } // ensure zones and triggers remain in-bounds. if any are completely // out-of-bounds, delete them. for (i = (int)vector_len(s_map->zones) - 1; i >= 0; --i) { zone = vector_get(s_map->zones, i); if (zone->bounds.x1 >= s_map->width || zone->bounds.y1 >= s_map->height) vector_remove(s_map->zones, i); else { if (zone->bounds.x2 > s_map->width) zone->bounds.x2 = s_map->width; if (zone->bounds.y2 > s_map->height) zone->bounds.y2 = s_map->height; } } for (i = (int)vector_len(s_map->triggers) - 1; i >= 0; --i) { trigger = vector_get(s_map->triggers, i); if (trigger->x >= s_map->width || trigger->y >= s_map->height) vector_remove(s_map->triggers, i); } return true; } static struct map* load_map(const char* filename) { // strings: 0 - tileset filename // 1 - music filename // 2 - script filename (obsolete, not used) // 3 - entry script // 4 - exit script // 5 - exit north script // 6 - exit east script // 7 - exit south script // 8 - exit west script uint16_t count; struct rmp_entity_header entity_hdr; sfs_file_t* file = NULL; bool has_failed; struct map_layer* layer; struct rmp_layer_header layer_hdr; struct map* map = NULL; int num_tiles; struct map_person* person; struct rmp_header rmp; lstring_t* script; rect_t segment; int16_t* tile_data = NULL; path_t* tileset_path; tileset_t* tileset; struct map_trigger trigger; struct map_zone zone; struct rmp_zone_header zone_hdr; lstring_t* *strings = NULL; int i, j, x, y, z; console_log(2, "constructing new map from `%s`", filename); memset(&rmp, 0, sizeof(struct rmp_header)); if (!(file = sfs_fopen(g_fs, filename, NULL, "rb"))) goto on_error; map = calloc(1, sizeof(struct map)); if (sfs_fread(&rmp, sizeof(struct rmp_header), 1, file) != 1) goto on_error; if (memcmp(rmp.signature, ".rmp", 4) != 0) goto on_error; if (rmp.num_strings != 3 && rmp.num_strings != 5 && rmp.num_strings < 9) goto on_error; if (rmp.start_layer < 0 || rmp.start_layer >= rmp.num_layers) rmp.start_layer = 0; // being nice here, this really should fail outright switch (rmp.version) { case 1: // load strings (resource filenames, scripts, etc.) strings = calloc(rmp.num_strings, sizeof(lstring_t*)); has_failed = false; for (i = 0; i < rmp.num_strings; ++i) has_failed = has_failed || ((strings[i] = read_lstring(file, true)) == NULL); if (has_failed) goto on_error; // pre-allocate map structures map->layers = calloc(rmp.num_layers, sizeof(struct map_layer)); map->persons = calloc(rmp.num_entities, sizeof(struct map_person)); map->triggers = vector_new(sizeof(struct map_trigger)); map->zones = vector_new(sizeof(struct map_zone)); // load layers for (i = 0; i < rmp.num_layers; ++i) { if (sfs_fread(&layer_hdr, sizeof(struct rmp_layer_header), 1, file) != 1) goto on_error; layer = &map->layers[i]; layer->is_parallax = (layer_hdr.flags & 2) != 0x0; layer->is_reflective = layer_hdr.is_reflective; layer->is_visible = (layer_hdr.flags & 1) == 0x0; layer->color_mask = color_new(255, 255, 255, 255); layer->width = layer_hdr.width; layer->height = layer_hdr.height; layer->autoscroll_x = layer->is_parallax ? layer_hdr.scrolling_x : 0.0; layer->autoscroll_y = layer->is_parallax ? layer_hdr.scrolling_y : 0.0; layer->parallax_x = layer->is_parallax ? layer_hdr.parallax_x : 1.0; layer->parallax_y = layer->is_parallax ? layer_hdr.parallax_y : 1.0; if (!layer->is_parallax) { map->width = fmax(map->width, layer->width); map->height = fmax(map->height, layer->height); } if (!(layer->tilemap = malloc(layer_hdr.width * layer_hdr.height * sizeof(struct map_tile)))) goto on_error; layer->name = read_lstring(file, true); layer->obsmap = obsmap_new(); num_tiles = layer_hdr.width * layer_hdr.height; if ((tile_data = malloc(num_tiles * 2)) == NULL) goto on_error; if (sfs_fread(tile_data, 2, num_tiles, file) != num_tiles) goto on_error; for (j = 0; j < num_tiles; ++j) layer->tilemap[j].tile_index = tile_data[j]; for (j = 0; j < layer_hdr.num_segments; ++j) { if (!fread_rect_32(file, &segment)) goto on_error; obsmap_add_line(layer->obsmap, segment); } free(tile_data); tile_data = NULL; } // if either dimension is zero, the map has no non-parallax layers and is thus malformed if (map->width == 0 || map->height == 0) goto on_error; // load entities map->num_persons = 0; for (i = 0; i < rmp.num_entities; ++i) { if (sfs_fread(&entity_hdr, sizeof(struct rmp_entity_header), 1, file) != 1) goto on_error; if (entity_hdr.z < 0 || entity_hdr.z >= rmp.num_layers) entity_hdr.z = 0; switch (entity_hdr.type) { case 1: // person ++map->num_persons; person = &map->persons[map->num_persons - 1]; memset(person, 0, sizeof(struct map_person)); if (!(person->name = read_lstring(file, true))) goto on_error; if (!(person->spriteset = read_lstring(file, true))) goto on_error; person->x = entity_hdr.x; person->y = entity_hdr.y; person->z = entity_hdr.z; if (sfs_fread(&count, 2, 1, file) != 1 || count < 5) goto on_error; person->create_script = read_lstring(file, false); person->destroy_script = read_lstring(file, false); person->touch_script = read_lstring(file, false); person->talk_script = read_lstring(file, false); person->command_script = read_lstring(file, false); for (j = 5; j < count; ++j) lstr_free(read_lstring(file, true)); sfs_fseek(file, 16, SFS_SEEK_CUR); break; case 2: // trigger if ((script = read_lstring(file, false)) == NULL) goto on_error; memset(&trigger, 0, sizeof(struct map_trigger)); trigger.x = entity_hdr.x; trigger.y = entity_hdr.y; trigger.z = entity_hdr.z; trigger.script = compile_script(script, "%s/trig%d", filename, vector_len(map->triggers)); if (!vector_push(map->triggers, &trigger)) return false; lstr_free(script); break; default: goto on_error; } } // load zones for (i = 0; i < rmp.num_zones; ++i) { if (sfs_fread(&zone_hdr, sizeof(struct rmp_zone_header), 1, file) != 1) goto on_error; if ((script = read_lstring(file, false)) == NULL) goto on_error; if (zone_hdr.layer < 0 || zone_hdr.layer >= rmp.num_layers) zone_hdr.layer = 0; zone.layer = zone_hdr.layer; zone.bounds = new_rect(zone_hdr.x1, zone_hdr.y1, zone_hdr.x2, zone_hdr.y2); zone.interval = zone_hdr.interval; zone.steps_left = 0; zone.script = compile_script(script, "%s/zone%d", filename, vector_len(map->zones)); normalize_rect(&zone.bounds); if (!vector_push(map->zones, &zone)) return false; lstr_free(script); } // load tileset if (strcmp(lstr_cstr(strings[0]), "") != 0) { tileset_path = path_strip(path_new(filename)); path_append(tileset_path, lstr_cstr(strings[0])); tileset = tileset_new(path_cstr(tileset_path)); path_free(tileset_path); } else { tileset = tileset_read(file); } if (tileset == NULL) goto on_error; // initialize tile animation for (z = 0; z < rmp.num_layers; ++z) { layer = &map->layers[z]; for (x = 0; x < layer->width; ++x) for (y = 0; y < layer->height; ++y) { i = x + y * layer->width; map->layers[z].tilemap[i].frames_left = tileset_get_delay(tileset, map->layers[z].tilemap[i].tile_index); } } // wrap things up map->bgm_file = strcmp(lstr_cstr(strings[1]), "") != 0 ? lstr_dup(strings[1]) : NULL; map->num_layers = rmp.num_layers; map->is_repeating = rmp.repeat_map; map->origin.x = rmp.start_x; map->origin.y = rmp.start_y; map->origin.z = rmp.start_layer; map->tileset = tileset; if (rmp.num_strings >= 5) { map->scripts[MAP_SCRIPT_ON_ENTER] = compile_script(strings[3], "%s/onEnter", filename); map->scripts[MAP_SCRIPT_ON_LEAVE] = compile_script(strings[4], "%s/onLeave", filename); } if (rmp.num_strings >= 9) { map->scripts[MAP_SCRIPT_ON_LEAVE_NORTH] = compile_script(strings[5], "%s/onLeave", filename); map->scripts[MAP_SCRIPT_ON_LEAVE_EAST] = compile_script(strings[6], "%s/onLeaveEast", filename); map->scripts[MAP_SCRIPT_ON_LEAVE_SOUTH] = compile_script(strings[7], "%s/onLeaveSouth", filename); map->scripts[MAP_SCRIPT_ON_LEAVE_WEST] = compile_script(strings[8], "%s/onLeaveWest", filename); } for (i = 0; i < rmp.num_strings; ++i) lstr_free(strings[i]); free(strings); break; default: goto on_error; } sfs_fclose(file); return map; on_error: if (file != NULL) sfs_fclose(file); free(tile_data); if (strings != NULL) { for (i = 0; i < rmp.num_strings; ++i) lstr_free(strings[i]); free(strings); } if (map != NULL) { if (map->layers != NULL) { for (i = 0; i < rmp.num_layers; ++i) { lstr_free(map->layers[i].name); free(map->layers[i].tilemap); obsmap_free(map->layers[i].obsmap); } free(map->layers); } if (map->persons != NULL) { for (i = 0; i < map->num_persons; ++i) { lstr_free(map->persons[i].name); lstr_free(map->persons[i].spriteset); lstr_free(map->persons[i].create_script); lstr_free(map->persons[i].destroy_script); lstr_free(map->persons[i].command_script); lstr_free(map->persons[i].talk_script); lstr_free(map->persons[i].touch_script); } free(map->persons); } vector_free(map->triggers); vector_free(map->zones); free(map); } return NULL; } static void free_map(struct map* map) { struct map_trigger* trigger; struct map_zone* zone; iter_t iter; int i; if (map == NULL) return; for (i = 0; i < MAP_SCRIPT_MAX; ++i) free_script(map->scripts[i]); for (i = 0; i < map->num_layers; ++i) { free_script(map->layers[i].render_script); lstr_free(map->layers[i].name); free(map->layers[i].tilemap); obsmap_free(map->layers[i].obsmap); } for (i = 0; i < map->num_persons; ++i) { lstr_free(map->persons[i].name); lstr_free(map->persons[i].spriteset); lstr_free(map->persons[i].create_script); lstr_free(map->persons[i].destroy_script); lstr_free(map->persons[i].command_script); lstr_free(map->persons[i].talk_script); lstr_free(map->persons[i].touch_script); } iter = vector_enum(s_map->triggers); while (trigger = vector_next(&iter)) free_script(trigger->script); iter = vector_enum(s_map->zones); while (zone = vector_next(&iter)) free_script(zone->script); lstr_free(s_map->bgm_file); tileset_free(map->tileset); free(map->layers); free(map->persons); vector_free(map->triggers); vector_free(map->zones); free(map); } static bool are_zones_at(int x, int y, int layer, int* out_count) { int count = 0; struct map_zone* zone; bool zone_found; iter_t iter; zone_found = false; iter = vector_enum(s_map->zones); while (zone = vector_next(&iter)) { if (zone->layer != layer && false) // layer ignored for compatibility continue; if (is_point_in_rect(x, y, zone->bounds)) { zone_found = true; ++count; } } if (out_count) *out_count = count; return zone_found; } static struct map_trigger* get_trigger_at(int x, int y, int layer, int* out_index) { rect_t bounds; struct map_trigger* found_item = NULL; int tile_w, tile_h; struct map_trigger* trigger; iter_t iter; tileset_get_size(s_map->tileset, &tile_w, &tile_h); iter = vector_enum(s_map->triggers); while (trigger = vector_next(&iter)) { if (trigger->z != layer && false) // layer ignored for compatibility reasons continue; bounds.x1 = trigger->x - tile_w / 2; bounds.y1 = trigger->y - tile_h / 2; bounds.x2 = bounds.x1 + tile_w; bounds.y2 = bounds.y1 + tile_h; if (is_point_in_rect(x, y, bounds)) { found_item = trigger; if (out_index) *out_index = (int)iter.index; break; } } return found_item; } static struct map_zone* get_zone_at(int x, int y, int layer, int which, int* out_index) { struct map_zone* found_item = NULL; struct map_zone* zone; iter_t iter; int i; iter = vector_enum(s_map->zones); i = -1; while (zone = vector_next(&iter)) { if (zone->layer != layer && false) // layer ignored for compatibility continue; if (is_point_in_rect(x, y, zone->bounds) && which-- == 0) { found_item = zone; if (out_index) *out_index = (int)iter.index; break; } } return found_item; } static bool change_map(const char* filename, bool preserve_persons) { // note: if an error is detected during a map change, change_map() will return false, but // the map engine may be left in an inconsistent state. it is therefore probably wise // to consider such a situation unrecoverable. struct map* map; person_t* person; struct map_person* person_info; path_t* path; spriteset_t* spriteset = NULL; int i; console_log(2, "changing current map to `%s`", filename); map = load_map(filename); if (map == NULL) return false; if (s_map != NULL) { // run map exit scripts first, before loading new map run_script(s_def_scripts[MAP_SCRIPT_ON_LEAVE], false); run_script(s_map->scripts[MAP_SCRIPT_ON_LEAVE], false); } // close out old map and prep for new one free_map(s_map); free(s_map_filename); for (i = 0; i < s_num_delay_scripts; ++i) free_script(s_delay_scripts[i].script); s_num_delay_scripts = 0; s_map = map; s_map_filename = strdup(filename); reset_persons(preserve_persons); // populate persons for (i = 0; i < s_map->num_persons; ++i) { person_info = &s_map->persons[i]; path = make_sfs_path(lstr_cstr(person_info->spriteset), "spritesets", true); spriteset = load_spriteset(path_cstr(path)); path_free(path); if (spriteset == NULL) goto on_error; if (!(person = create_person(lstr_cstr(person_info->name), spriteset, false, NULL))) goto on_error; free_spriteset(spriteset); set_person_xyz(person, person_info->x, person_info->y, person_info->z); compile_person_script(person, PERSON_SCRIPT_ON_CREATE, person_info->create_script); compile_person_script(person, PERSON_SCRIPT_ON_DESTROY, person_info->destroy_script); compile_person_script(person, PERSON_SCRIPT_ON_TOUCH, person_info->touch_script); compile_person_script(person, PERSON_SCRIPT_ON_TALK, person_info->talk_script); compile_person_script(person, PERSON_SCRIPT_GENERATOR, person_info->command_script); // normally this is handled by create_person(), but since in this case the // person-specific create script isn't compiled until after the person is created, // the map engine gets the responsibility. call_person_script(person, PERSON_SCRIPT_ON_CREATE, false); } // set camera over starting position s_cam_x = s_map->origin.x; s_cam_y = s_map->origin.y; // start up map BGM (if same as previous, leave alone) if (s_map->bgm_file == NULL && s_map_bgm_stream != NULL) { sound_free(s_map_bgm_stream); lstr_free(s_last_bgm_file); s_map_bgm_stream = NULL; s_last_bgm_file = NULL; } else if (s_map->bgm_file != NULL && (s_last_bgm_file == NULL || lstr_cmp(s_map->bgm_file, s_last_bgm_file) != 0)) { sound_free(s_map_bgm_stream); lstr_free(s_last_bgm_file); s_last_bgm_file = lstr_dup(s_map->bgm_file); path = make_sfs_path(lstr_cstr(s_map->bgm_file), "sounds", true); if (s_map_bgm_stream = sound_load(path_cstr(path), get_default_mixer())) { sound_set_looping(s_map_bgm_stream, true); sound_play(s_map_bgm_stream); } path_free(path); } // run map entry scripts run_script(s_def_scripts[MAP_SCRIPT_ON_ENTER], false); run_script(s_map->scripts[MAP_SCRIPT_ON_ENTER], false); s_frames = 0; return true; on_error: free_spriteset(spriteset); free_map(s_map); return false; } static int find_layer(const char* name) { int i; for (i = 0; i < s_map->num_layers; ++i) { if (strcmp(name, lstr_cstr(s_map->layers[0].name)) == 0) return i; } return -1; } static void map_screen_to_layer(int layer, int camera_x, int camera_y, int* inout_x, int* inout_y) { rect_t bounds; int center_x, center_y; int layer_w, layer_h; float plx_offset_x = 0.0, plx_offset_y = 0.0; int tile_w, tile_h; int x_offset, y_offset; // get layer and screen metrics tileset_get_size(s_map->tileset, &tile_w, &tile_h); layer_w = s_map->layers[layer].width * tile_w; layer_h = s_map->layers[layer].height * tile_h; center_x = g_res_x / 2; center_y = g_res_y / 2; // initial camera correction if (!s_map->is_repeating) { bounds = get_map_bounds(); camera_x = fmin(fmax(camera_x, bounds.x1 + center_x), bounds.x2 - center_x); camera_y = fmin(fmax(camera_y, bounds.y1 + center_y), bounds.y2 - center_y); } // remap screen coordinates to layer coordinates plx_offset_x = s_frames * s_map->layers[layer].autoscroll_x - camera_x * (s_map->layers[layer].parallax_x - 1.0); plx_offset_y = s_frames * s_map->layers[layer].autoscroll_y - camera_y * (s_map->layers[layer].parallax_y - 1.0); x_offset = camera_x - center_x - plx_offset_x; y_offset = camera_y - center_y - plx_offset_y; if (!s_map->is_repeating && !s_map->layers[layer].is_parallax) { // if the map is smaller than the screen, windowbox it if (layer_w < g_res_x) x_offset = -(g_res_x - layer_w) / 2; if (layer_h < g_res_y) y_offset = -(g_res_y - layer_h) / 2; } if (inout_x) *inout_x += x_offset; if (inout_y) *inout_y += y_offset; // normalize coordinates. this simplifies rendering calculations. if (s_map->is_repeating || s_map->layers[layer].is_parallax) { if (inout_x) *inout_x = (*inout_x % layer_w + layer_w) % layer_w; if (inout_y) *inout_y = (*inout_y % layer_h + layer_h) % layer_h; } } static void map_screen_to_map(int camera_x, int camera_y, int* inout_x, int* inout_y) { rect_t bounds; int center_x, center_y; int map_w, map_h; int tile_w, tile_h; int x_offset, y_offset; // get layer and screen metrics tileset_get_size(s_map->tileset, &tile_w, &tile_h); map_w = s_map->width * tile_w; map_h = s_map->height * tile_h; center_x = g_res_x / 2; center_y = g_res_y / 2; // initial camera correction if (!s_map->is_repeating) { bounds = get_map_bounds(); camera_x = fmin(fmax(camera_x, bounds.x1 + center_x), bounds.x2 - center_x); camera_y = fmin(fmax(camera_y, bounds.y1 + center_y), bounds.y2 - center_y); } // remap screen coordinates to map coordinates x_offset = camera_x - center_x; y_offset = camera_y - center_y; if (!s_map->is_repeating) { // if the map is smaller than the screen, windowbox it if (map_w < g_res_x) x_offset = -(g_res_x - map_w) / 2; if (map_h < g_res_y) y_offset = -(g_res_y - map_h) / 2; } if (inout_x) *inout_x += x_offset; if (inout_y) *inout_y += y_offset; // normalize coordinates if (s_map->is_repeating) { if (inout_x) *inout_x = (*inout_x % map_w + map_w) % map_w; if (inout_y) *inout_y = (*inout_y % map_h + map_h) % map_h; } } static void process_map_input(void) { int mv_x, mv_y; person_t* person; int i; // clear out excess keys from key queue clear_key_queue(); // check for player control of input persons, if there are any for (i = 0; i < MAX_PLAYERS; ++i) { person = s_players[i].person; if (person != NULL) { if (is_key_down(get_player_key(i, PLAYER_KEY_A)) || is_key_down(s_players[i].talk_key) || is_joy_button_down(i, s_talk_button)) { if (s_players[i].is_talk_allowed) talk_person(person); s_players[i].is_talk_allowed = false; } else // allow talking again only after key is released s_players[i].is_talk_allowed = true; mv_x = 0; mv_y = 0; if (!is_person_busy(person)) { // allow player control only if input person is idle if (is_key_down(get_player_key(i, PLAYER_KEY_UP))) mv_y = -1; if (is_key_down(get_player_key(i, PLAYER_KEY_RIGHT))) mv_x = 1; if (is_key_down(get_player_key(i, PLAYER_KEY_DOWN))) mv_y = 1; if (is_key_down(get_player_key(i, PLAYER_KEY_LEFT))) mv_x = -1; } switch (mv_x + mv_y * 3) { case -3: // north queue_person_command(person, COMMAND_MOVE_NORTH, true); queue_person_command(person, COMMAND_FACE_NORTH, true); queue_person_command(person, COMMAND_ANIMATE, false); break; case -2: // northeast queue_person_command(person, COMMAND_MOVE_NORTHEAST, true); queue_person_command(person, COMMAND_FACE_NORTHEAST, true); queue_person_command(person, COMMAND_ANIMATE, false); break; case 1: // east queue_person_command(person, COMMAND_MOVE_EAST, true); queue_person_command(person, COMMAND_FACE_EAST, true); queue_person_command(person, COMMAND_ANIMATE, false); break; case 4: // southeast queue_person_command(person, COMMAND_MOVE_SOUTHEAST, true); queue_person_command(person, COMMAND_FACE_SOUTHEAST, true); queue_person_command(person, COMMAND_ANIMATE, false); break; case 3: // south queue_person_command(person, COMMAND_MOVE_SOUTH, true); queue_person_command(person, COMMAND_FACE_SOUTH, true); queue_person_command(person, COMMAND_ANIMATE, false); break; case 2: // southwest queue_person_command(person, COMMAND_MOVE_SOUTHWEST, true); queue_person_command(person, COMMAND_FACE_SOUTHWEST, true); queue_person_command(person, COMMAND_ANIMATE, false); break; case -1: // west queue_person_command(person, COMMAND_MOVE_WEST, true); queue_person_command(person, COMMAND_FACE_WEST, true); queue_person_command(person, COMMAND_ANIMATE, false); break; case -4: // northwest queue_person_command(person, COMMAND_MOVE_NORTHWEST, true); queue_person_command(person, COMMAND_FACE_NORTHWEST, true); queue_person_command(person, COMMAND_ANIMATE, false); break; } } } update_bound_keys(true); } static void render_map(void) { bool is_repeating; int cell_x; int cell_y; int first_cell_x; int first_cell_y; struct map_layer* layer; int layer_height; int layer_width; ALLEGRO_COLOR overlay_color; int tile_height; int tile_index; int tile_width; int off_x, off_y; int x, y, z; if (screen_is_skipframe(g_screen)) return; // render map layers from bottom to top (+Z = up) tileset_get_size(s_map->tileset, &tile_width, &tile_height); for (z = 0; z < s_map->num_layers; ++z) { layer = &s_map->layers[z]; is_repeating = s_map->is_repeating || layer->is_parallax; layer_width = layer->width * tile_width; layer_height = layer->height * tile_height; off_x = 0; off_y = 0; map_screen_to_layer(z, s_cam_x, s_cam_y, &off_x, &off_y); // render person reflections if layer is reflective al_hold_bitmap_drawing(true); if (layer->is_reflective) { if (is_repeating) { // for small repeating maps, persons need to be repeated as well for (y = 0; y < g_res_y / layer_height + 2; ++y) for (x = 0; x < g_res_x / layer_width + 2; ++x) render_persons(z, true, off_x - x * layer_width, off_y - y * layer_height); } else { render_persons(z, true, off_x, off_y); } } // render tiles, but only if the layer is visible if (layer->is_visible) { first_cell_x = off_x / tile_width; first_cell_y = off_y / tile_height; for (y = 0; y < g_res_y / tile_height + 2; ++y) for (x = 0; x < g_res_x / tile_width + 2; ++x) { cell_x = is_repeating ? (x + first_cell_x) % layer->width : x + first_cell_x; cell_y = is_repeating ? (y + first_cell_y) % layer->height : y + first_cell_y; if (cell_x < 0 || cell_x >= layer->width || cell_y < 0 || cell_y >= layer->height) continue; tile_index = layer->tilemap[cell_x + cell_y * layer->width].tile_index; tileset_draw(s_map->tileset, layer->color_mask, x * tile_width - off_x % tile_width, y * tile_height - off_y % tile_height, tile_index); } } // render persons if (is_repeating) { // for small repeating maps, persons need to be repeated as well for (y = 0; y < g_res_y / layer_height + 2; ++y) for (x = 0; x < g_res_x / layer_width + 2; ++x) render_persons(z, false, off_x - x * layer_width, off_y - y * layer_height); } else { render_persons(z, false, off_x, off_y); } al_hold_bitmap_drawing(false); run_script(layer->render_script, false); } overlay_color = al_map_rgba(s_color_mask.r, s_color_mask.g, s_color_mask.b, s_color_mask.alpha); al_draw_filled_rectangle(0, 0, g_res_x, g_res_y, overlay_color); run_script(s_render_script, false); } static void update_map_engine(bool is_main_loop) { int index; int last_trigger; int last_zone; int layer; int map_w, map_h; int num_zone_steps; script_t* script_to_run; int script_type; double start_x[MAX_PLAYERS]; double start_y[MAX_PLAYERS]; int tile_w, tile_h; struct map_trigger* trigger; double x, y, px, py; struct map_zone* zone; int i, j, k; ++s_frames; tileset_get_size(s_map->tileset, &tile_w, &tile_h); map_w = s_map->width * tile_w; map_h = s_map->height * tile_h; tileset_update(s_map->tileset); for (i = 0; i < MAX_PLAYERS; ++i) if (s_players[i].person != NULL) get_person_xy(s_players[i].person, &start_x[i], &start_y[i], false); update_persons(); // update color mask fade level if (s_fade_progress < s_fade_frames) { ++s_fade_progress; s_color_mask = color_lerp(s_fade_color_to, s_fade_color_from, s_fade_progress, s_fade_frames - s_fade_progress); } // update camera if (s_camera_person != NULL) { get_person_xy(s_camera_person, &x, &y, true); s_cam_x = x; s_cam_y = y; } // run edge script if the camera has moved past the edge of the map // note: only applies for non-repeating maps if (is_main_loop && !s_map->is_repeating) { script_type = s_cam_y < 0 ? MAP_SCRIPT_ON_LEAVE_NORTH : s_cam_x >= map_w ? MAP_SCRIPT_ON_LEAVE_EAST : s_cam_y >= map_h ? MAP_SCRIPT_ON_LEAVE_SOUTH : s_cam_x < 0 ? MAP_SCRIPT_ON_LEAVE_WEST : MAP_SCRIPT_MAX; if (script_type < MAP_SCRIPT_MAX) { run_script(s_def_scripts[script_type], false); run_script(s_map->scripts[script_type], false); } } // if there are any input persons, check for trigger activation for (i = 0; i < MAX_PLAYERS; ++i) if (s_players[i].person != NULL) { // did we step on a trigger or move to a new one? get_person_xyz(s_players[i].person, &x, &y, &layer, true); trigger = get_trigger_at(x, y, layer, &index); if (trigger != s_on_trigger) { last_trigger = s_current_trigger; s_current_trigger = index; s_on_trigger = trigger; if (trigger) run_script(trigger->script, false); s_current_trigger = last_trigger; } } // update any zones occupied by the input person // note: a zone's step count is in reality a pixel count, so a zone // may be updated multiple times in a single frame. for (k = 0; k < MAX_PLAYERS; ++k) if (s_players[k].person != NULL) { get_person_xy(s_players[k].person, &x, &y, false); px = abs(x - start_x[k]); py = abs(y - start_y[k]); num_zone_steps = px > py ? px : py; for (i = 0; i < num_zone_steps; ++i) { j = 0; while (zone = get_zone_at(x, y, layer, j++, &index)) { if (zone->steps_left-- <= 0) { last_zone = s_current_zone; s_current_zone = index; zone->steps_left = zone->interval; run_script(zone->script, true); s_current_zone = last_zone; } } } } // check if there are any delay scripts due to run this frame // and run the ones that are for (i = 0; i < s_num_delay_scripts; ++i) { if (s_delay_scripts[i].frames_left-- <= 0) { script_to_run = s_delay_scripts[i].script; for (j = i; j < s_num_delay_scripts - 1; ++j) s_delay_scripts[j] = s_delay_scripts[j + 1]; --s_num_delay_scripts; --i; run_script(script_to_run, false); free_script(script_to_run); } } // now that everything else is in order, we can run the // update script! run_script(s_update_script, false); } void init_map_engine_api(duk_context* ctx) { api_register_method(ctx, NULL, "MapEngine", js_MapEngine); api_register_method(ctx, NULL, "AreZonesAt", js_AreZonesAt); api_register_method(ctx, NULL, "IsCameraAttached", js_IsCameraAttached); api_register_method(ctx, NULL, "IsInputAttached", js_IsInputAttached); api_register_method(ctx, NULL, "IsLayerReflective", js_IsLayerReflective); api_register_method(ctx, NULL, "IsLayerVisible", js_IsLayerVisible); api_register_method(ctx, NULL, "IsMapEngineRunning", js_IsMapEngineRunning); api_register_method(ctx, NULL, "IsTriggerAt", js_IsTriggerAt); api_register_method(ctx, NULL, "GetCameraPerson", js_GetCameraPerson); api_register_method(ctx, NULL, "GetCameraX", js_GetCameraX); api_register_method(ctx, NULL, "GetCameraY", js_GetCameraY); api_register_method(ctx, NULL, "GetCurrentMap", js_GetCurrentMap); api_register_method(ctx, NULL, "GetCurrentTrigger", js_GetCurrentTrigger); api_register_method(ctx, NULL, "GetCurrentZone", js_GetCurrentZone); api_register_method(ctx, NULL, "GetInputPerson", js_GetInputPerson); api_register_method(ctx, NULL, "GetLayerHeight", js_GetLayerHeight); api_register_method(ctx, NULL, "GetLayerMask", js_GetLayerMask); api_register_method(ctx, NULL, "GetLayerWidth", js_GetLayerWidth); api_register_method(ctx, NULL, "GetMapEngineFrameRate", js_GetMapEngineFrameRate); api_register_method(ctx, NULL, "GetNextAnimatedTile", js_GetNextAnimatedTile); api_register_method(ctx, NULL, "GetNumLayers", js_GetNumLayers); api_register_method(ctx, NULL, "GetNumTiles", js_GetNumTiles); api_register_method(ctx, NULL, "GetNumTriggers", js_GetNumTriggers); api_register_method(ctx, NULL, "GetNumZones", js_GetNumZones); api_register_method(ctx, NULL, "GetTalkActivationButton", js_GetTalkActivationButton); api_register_method(ctx, NULL, "GetTalkActivationKey", js_GetTalkActivationKey); api_register_method(ctx, NULL, "GetTile", js_GetTile); api_register_method(ctx, NULL, "GetTileDelay", js_GetTileDelay); api_register_method(ctx, NULL, "GetTileImage", js_GetTileImage); api_register_method(ctx, NULL, "GetTileHeight", js_GetTileHeight); api_register_method(ctx, NULL, "GetTileName", js_GetTileName); api_register_method(ctx, NULL, "GetTileSurface", js_GetTileSurface); api_register_method(ctx, NULL, "GetTileWidth", js_GetTileWidth); api_register_method(ctx, NULL, "GetTriggerLayer", js_GetTriggerLayer); api_register_method(ctx, NULL, "GetTriggerX", js_GetTriggerX); api_register_method(ctx, NULL, "GetTriggerY", js_GetTriggerY); api_register_method(ctx, NULL, "GetZoneHeight", js_GetZoneHeight); api_register_method(ctx, NULL, "GetZoneLayer", js_GetZoneLayer); api_register_method(ctx, NULL, "GetZoneSteps", js_GetZoneSteps); api_register_method(ctx, NULL, "GetZoneWidth", js_GetZoneWidth); api_register_method(ctx, NULL, "GetZoneX", js_GetZoneX); api_register_method(ctx, NULL, "GetZoneY", js_GetZoneY); api_register_method(ctx, NULL, "SetCameraX", js_SetCameraX); api_register_method(ctx, NULL, "SetCameraY", js_SetCameraY); api_register_method(ctx, NULL, "SetColorMask", js_SetColorMask); api_register_method(ctx, NULL, "SetDefaultMapScript", js_SetDefaultMapScript); api_register_method(ctx, NULL, "SetLayerHeight", js_SetLayerHeight); api_register_method(ctx, NULL, "SetLayerMask", js_SetLayerMask); api_register_method(ctx, NULL, "SetLayerReflective", js_SetLayerReflective); api_register_method(ctx, NULL, "SetLayerRenderer", js_SetLayerRenderer); api_register_method(ctx, NULL, "SetLayerSize", js_SetLayerSize); api_register_method(ctx, NULL, "SetLayerVisible", js_SetLayerVisible); api_register_method(ctx, NULL, "SetLayerWidth", js_SetLayerWidth); api_register_method(ctx, NULL, "SetMapEngineFrameRate", js_SetMapEngineFrameRate); api_register_method(ctx, NULL, "SetNextAnimatedTile", js_SetNextAnimatedTile); api_register_method(ctx, NULL, "SetRenderScript", js_SetRenderScript); api_register_method(ctx, NULL, "SetTalkActivationButton", js_SetTalkActivationButton); api_register_method(ctx, NULL, "SetTalkActivationKey", js_SetTalkActivationKey); api_register_method(ctx, NULL, "SetTile", js_SetTile); api_register_method(ctx, NULL, "SetTileDelay", js_SetTileDelay); api_register_method(ctx, NULL, "SetTileImage", js_SetTileImage); api_register_method(ctx, NULL, "SetTileName", js_SetTileName); api_register_method(ctx, NULL, "SetTileSurface", js_SetTileSurface); api_register_method(ctx, NULL, "SetTriggerLayer", js_SetTriggerLayer); api_register_method(ctx, NULL, "SetTriggerScript", js_SetTriggerScript); api_register_method(ctx, NULL, "SetTriggerXY", js_SetTriggerXY); api_register_method(ctx, NULL, "SetUpdateScript", js_SetUpdateScript); api_register_method(ctx, NULL, "SetZoneLayer", js_SetZoneLayer); api_register_method(ctx, NULL, "SetZoneMetrics", js_SetZoneMetrics); api_register_method(ctx, NULL, "SetZoneScript", js_SetZoneScript); api_register_method(ctx, NULL, "SetZoneSteps", js_SetZoneSteps); api_register_method(ctx, NULL, "AddTrigger", js_AddTrigger); api_register_method(ctx, NULL, "AddZone", js_AddZone); api_register_method(ctx, NULL, "AttachCamera", js_AttachCamera); api_register_method(ctx, NULL, "AttachInput", js_AttachInput); api_register_method(ctx, NULL, "AttachPlayerInput", js_AttachPlayerInput); api_register_method(ctx, NULL, "CallDefaultMapScript", js_CallDefaultMapScript); api_register_method(ctx, NULL, "CallMapScript", js_CallMapScript); api_register_method(ctx, NULL, "ChangeMap", js_ChangeMap); api_register_method(ctx, NULL, "DetachCamera", js_DetachCamera); api_register_method(ctx, NULL, "DetachInput", js_DetachInput); api_register_method(ctx, NULL, "DetachPlayerInput", js_DetachPlayerInput); api_register_method(ctx, NULL, "ExecuteTrigger", js_ExecuteTrigger); api_register_method(ctx, NULL, "ExecuteZones", js_ExecuteZones); api_register_method(ctx, NULL, "ExitMapEngine", js_ExitMapEngine); api_register_method(ctx, NULL, "MapToScreenX", js_MapToScreenX); api_register_method(ctx, NULL, "MapToScreenY", js_MapToScreenY); api_register_method(ctx, NULL, "RemoveTrigger", js_RemoveTrigger); api_register_method(ctx, NULL, "RemoveZone", js_RemoveZone); api_register_method(ctx, NULL, "RenderMap", js_RenderMap); api_register_method(ctx, NULL, "ReplaceTilesOnLayer", js_ReplaceTilesOnLayer); api_register_method(ctx, NULL, "ScreenToMapX", js_ScreenToMapX); api_register_method(ctx, NULL, "ScreenToMapY", js_ScreenToMapY); api_register_method(ctx, NULL, "SetDelayScript", js_SetDelayScript); api_register_method(ctx, NULL, "UpdateMapEngine", js_UpdateMapEngine); // Map script types api_register_const(ctx, "SCRIPT_ON_ENTER_MAP", MAP_SCRIPT_ON_ENTER); api_register_const(ctx, "SCRIPT_ON_LEAVE_MAP", MAP_SCRIPT_ON_LEAVE); api_register_const(ctx, "SCRIPT_ON_LEAVE_MAP_NORTH", MAP_SCRIPT_ON_LEAVE_NORTH); api_register_const(ctx, "SCRIPT_ON_LEAVE_MAP_EAST", MAP_SCRIPT_ON_LEAVE_EAST); api_register_const(ctx, "SCRIPT_ON_LEAVE_MAP_SOUTH", MAP_SCRIPT_ON_LEAVE_SOUTH); api_register_const(ctx, "SCRIPT_ON_LEAVE_MAP_WEST", MAP_SCRIPT_ON_LEAVE_WEST); // initialize subcomponent APIs (persons, etc.) init_persons_api(); } int duk_require_map_layer(duk_context* ctx, duk_idx_t index) { int layer; const char* name; duk_require_type_mask(ctx, index, DUK_TYPE_MASK_STRING | DUK_TYPE_MASK_NUMBER); if (duk_is_number(ctx, index)) { layer = duk_get_int(ctx, index); if (layer < 0 || layer >= s_map->num_layers) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "layer index out of range (%d)", layer); } else { name = duk_get_string(ctx, index); if ((layer = find_layer(name)) == -1) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "no layer exists with name `%s`", name); } return layer; } static duk_ret_t js_MapEngine(duk_context* ctx) { const char* filename; int framerate; int num_args; num_args = duk_get_top(ctx); filename = duk_require_path(ctx, 0, "maps", true); framerate = num_args >= 2 ? duk_require_int(ctx, 1) : g_framerate; s_is_map_running = true; s_exiting = false; s_color_mask = color_new(0, 0, 0, 0); s_fade_color_to = s_fade_color_from = s_color_mask; s_fade_progress = s_fade_frames = 0; al_clear_to_color(al_map_rgba(0, 0, 0, 255)); s_framerate = framerate; if (!change_map(filename, true)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "MapEngine(): unable to load map file `%s` into map engine", filename); while (!s_exiting) { render_map(); screen_flip(g_screen, s_framerate); update_map_engine(true); process_map_input(); } reset_persons(false); s_is_map_running = false; return 0; } static duk_ret_t js_AreZonesAt(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int layer = duk_require_map_layer(ctx, 2); duk_push_boolean(ctx, are_zones_at(x, y, layer, NULL)); return 1; } static duk_ret_t js_IsCameraAttached(duk_context* ctx) { duk_push_boolean(ctx, s_camera_person != NULL); return 1; } static duk_ret_t js_IsInputAttached(duk_context* ctx) { const char* name; person_t* person; int player; int i; if (duk_get_top(ctx) < 1) player = 0; else if (duk_is_string(ctx, 0)) { name = duk_get_string(ctx, 0); if (!(person = find_person(name))) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "IsInputAttached(): person `%s` doesn't exist", name); player = -1; for (i = MAX_PLAYERS - 1; i >= 0; --i) // ensures Sphere semantics player = s_players[i].person == person ? i : player; if (player == -1) return duk_push_false(ctx), 1; } else if (duk_is_number(ctx, 0)) player = duk_get_int(ctx, 0); else duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "IsInputAttached(): player number or string expected"); if (player < 0 || player >= MAX_PLAYERS) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "IsInputAttached(): player number out of range (%d)", player); duk_push_boolean(ctx, s_players[player].person != NULL); return 1; } static duk_ret_t js_IsLayerReflective(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IsLayerReflective(): map engine not running"); duk_push_boolean(ctx, s_map->layers[layer].is_reflective); return 1; } static duk_ret_t js_IsLayerVisible(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IsLayerVisible(): map engine not running"); duk_push_boolean(ctx, s_map->layers[layer].is_visible); return 1; } static duk_ret_t js_IsMapEngineRunning(duk_context* ctx) { duk_push_boolean(ctx, s_is_map_running); return 1; } static duk_ret_t js_IsTriggerAt(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int layer = duk_require_map_layer(ctx, 2); duk_push_boolean(ctx, get_trigger_at(x, y, layer, NULL) != NULL); return 1; } static duk_ret_t js_GetCameraPerson(duk_context* ctx) { if (s_camera_person == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetCameraPerson(): invalid operation, camera not attached"); duk_push_string(ctx, get_person_name(s_camera_person)); return 1; } static duk_ret_t js_GetCameraX(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetCameraX(): map engine not running"); duk_push_int(ctx, s_cam_x); return 1; } static duk_ret_t js_GetCameraY(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetCameraX(): map engine not running"); duk_push_int(ctx, s_cam_y); return 1; } static duk_ret_t js_GetCurrentMap(duk_context* ctx) { path_t* map_name; path_t* origin; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetCurrentMap(): map engine not running"); // GetCurrentMap() in Sphere 1.x returns the map path // relative to the 'maps' directory. map_name = path_new(s_map_filename); if (!path_is_rooted(map_name)) { origin = path_new("maps/"); path_relativize(map_name, origin); path_free(origin); } duk_push_string(ctx, path_cstr(map_name)); path_free(map_name); return 1; } static duk_ret_t js_GetCurrentTrigger(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetCurrentTrigger(): map engine not running"); if (s_current_trigger == -1) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetCurrentTrigger(): cannot call outside of a trigger script"); duk_push_int(ctx, s_current_trigger); return 1; } static duk_ret_t js_GetCurrentZone(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetCurrentZone(): map engine not running"); if (s_current_zone == -1) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetCurrentZone(): cannot call outside of a zone script"); duk_push_int(ctx, s_current_zone); return 1; } static duk_ret_t js_GetInputPerson(duk_context* ctx) { int n_args = duk_get_top(ctx); int player = n_args >= 1 ? duk_require_int(ctx, 0) : 0; if (player < 0 || player >= MAX_PLAYERS) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetInputPerson(): player number out of range (%d)", player); if (s_players[player].person == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetInputPerson(): input not attached for player %d", player + 1); duk_push_string(ctx, get_person_name(s_players[player].person)); return 1; } static duk_ret_t js_GetLayerHeight(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetLayerHeight(): map engine not running"); duk_push_int(ctx, s_map->layers[layer].height); return 1; } static duk_ret_t js_GetLayerMask(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetLayerMask(): map engine not running"); duk_push_sphere_color(ctx, s_map->layers[layer].color_mask); return 1; } static duk_ret_t js_GetLayerName(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetLayerName(): map engine not running"); duk_push_lstring_t(ctx, s_map->layers[layer].name); return 1; } static duk_ret_t js_GetLayerWidth(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetLayerWidth(): map engine not running"); duk_push_int(ctx, s_map->layers[layer].width); return 1; } static duk_ret_t js_GetMapEngineFrameRate(duk_context* ctx) { duk_push_int(ctx, s_framerate); return 1; } static duk_ret_t js_GetNextAnimatedTile(duk_context* ctx) { int tile_index = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetNextAnimatedTile(): map engine not running"); if (tile_index < 0 || tile_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetNextAnimatedTile(): invalid tile index (%d)", tile_index); duk_push_int(ctx, tileset_get_next(s_map->tileset, tile_index)); return 1; } static duk_ret_t js_GetNumLayers(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetNumLayers(): map engine not running"); duk_push_int(ctx, s_map->num_layers); return 1; } static duk_ret_t js_GetNumTiles(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetNumTiles(): map engine not running"); duk_push_int(ctx, tileset_len(s_map->tileset)); return 1; } static duk_ret_t js_GetNumTriggers(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetNumTriggers(): map engine not running"); duk_push_number(ctx, vector_len(s_map->triggers)); return 1; } static duk_ret_t js_GetNumZones(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetNumZones(): map engine not running"); duk_push_number(ctx, vector_len(s_map->zones)); return 1; } static duk_ret_t js_GetTalkActivationButton(duk_context* ctx) { duk_push_int(ctx, s_talk_button); return 1; } static duk_ret_t js_GetTalkActivationKey(duk_context* ctx) { int n_args = duk_get_top(ctx); int player = n_args >= 1 ? duk_require_int(ctx, 0) : 0; if (player < 0 || player >= MAX_PLAYERS) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetTalkActivationKey(): player number out of range (%d)", player); duk_push_int(ctx, s_players[player].talk_key); return 1; } static duk_ret_t js_GetTile(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int layer = duk_require_map_layer(ctx, 2); int layer_w, layer_h; struct map_tile* tilemap; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTile(): map engine not running"); layer_w = s_map->layers[layer].width; layer_h = s_map->layers[layer].height; tilemap = s_map->layers[layer].tilemap; duk_push_int(ctx, tilemap[x + y * layer_w].tile_index); return 1; } static duk_ret_t js_GetTileDelay(duk_context* ctx) { int tile_index = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTileDelay(): map engine not running"); if (tile_index < 0 || tile_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetTileDelay(): invalid tile index (%d)", tile_index); duk_push_int(ctx, tileset_get_delay(s_map->tileset, tile_index)); return 1; } static duk_ret_t js_GetTileHeight(duk_context* ctx) { int w, h; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTileHeight(): map engine not running"); tileset_get_size(s_map->tileset, &w, &h); duk_push_int(ctx, h); return 1; } static duk_ret_t js_GetTileImage(duk_context* ctx) { int tile_index = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTileImage(): map engine not running"); if (tile_index < 0 || tile_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetTileImage(): invalid tile index (%d)", tile_index); duk_push_sphere_image(ctx, tileset_get_image(s_map->tileset, tile_index)); return 1; } static duk_ret_t js_GetTileName(duk_context* ctx) { int tile_index = duk_require_int(ctx, 0); const lstring_t* tile_name; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTileName(): map engine not running"); if (tile_index < 0 || tile_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetTileName(): invalid tile index (%d)", tile_index); tile_name = tileset_get_name(s_map->tileset, tile_index); duk_push_lstring_t(ctx, tile_name); return 1; } static duk_ret_t js_GetTileSurface(duk_context* ctx) { int tile_index = duk_require_int(ctx, 0); image_t* image; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTileSurface(): map engine not running"); if (tile_index < 0 || tile_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetTileSurface(): invalid tile index (%d)", tile_index); if ((image = clone_image(tileset_get_image(s_map->tileset, tile_index))) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTileSurface(): unable to create new surface image"); duk_push_sphere_obj(ctx, "Surface", image); return 1; } static duk_ret_t js_GetTileWidth(duk_context* ctx) { int w, h; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTileWidth(): map engine not running"); tileset_get_size(s_map->tileset, &w, &h); duk_push_int(ctx, w); return 1; } static duk_ret_t js_GetTriggerLayer(duk_context* ctx) { int trigger_index = duk_require_int(ctx, 0); int layer; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTriggerLayer(): map engine not running"); if (trigger_index < 0 || trigger_index >= (int)vector_len(s_map->triggers)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetTriggerLayer(): invalid trigger index (%d)", trigger_index); get_trigger_xyz(trigger_index, NULL, NULL, &layer); duk_push_int(ctx, layer); return 1; } static duk_ret_t js_GetTriggerX(duk_context* ctx) { int trigger_index = duk_require_int(ctx, 0); int x; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTriggerX(): map engine not running"); if (trigger_index < 0 || trigger_index >= (int)vector_len(s_map->triggers)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetTriggerX(): invalid trigger index (%d)", trigger_index); get_trigger_xyz(trigger_index, &x, NULL, NULL); duk_push_int(ctx, x); return 1; } static duk_ret_t js_GetTriggerY(duk_context* ctx) { int trigger_index = duk_require_int(ctx, 0); int y; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetTriggerX(): map engine not running"); if (trigger_index < 0 || trigger_index >= (int)vector_len(s_map->triggers)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetTriggerX(): invalid trigger index (%d)", trigger_index); get_trigger_xyz(trigger_index, NULL, &y, NULL); duk_push_int(ctx, y); return 1; } static duk_ret_t js_GetZoneHeight(duk_context* ctx) { int zone_index = duk_require_int(ctx, 0); rect_t bounds; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetZoneHeight(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetZoneHeight(): invalid zone index (%d)", zone_index); bounds = get_zone_bounds(zone_index); duk_push_int(ctx, bounds.y2 - bounds.y1); return 1; } static duk_ret_t js_GetZoneLayer(duk_context* ctx) { int zone_index = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetZoneLayer(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetZoneLayer(): invalid zone index (%d)", zone_index); duk_push_int(ctx, get_zone_layer(zone_index)); return 1; } static duk_ret_t js_GetZoneSteps(duk_context* ctx) { int zone_index = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetZoneLayer(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetZoneLayer(): invalid zone index (%d)", zone_index); duk_push_int(ctx, get_zone_steps(zone_index)); return 1; } static duk_ret_t js_GetZoneWidth(duk_context* ctx) { int zone_index = duk_require_int(ctx, 0); rect_t bounds; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetZoneWidth(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetZoneWidth(): invalid zone index (%d)", zone_index); bounds = get_zone_bounds(zone_index); duk_push_int(ctx, bounds.x2 - bounds.x1); return 1; } static duk_ret_t js_GetZoneX(duk_context* ctx) { int zone_index = duk_require_int(ctx, 0); rect_t bounds; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetZoneX(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetZoneX(): invalid zone index (%d)", zone_index); bounds = get_zone_bounds(zone_index); duk_push_int(ctx, bounds.x1); return 1; } static duk_ret_t js_GetZoneY(duk_context* ctx) { int zone_index = duk_require_int(ctx, 0); rect_t bounds; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetZoneY(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetZoneY(): invalid zone index (%d)", zone_index); bounds = get_zone_bounds(zone_index); duk_push_int(ctx, bounds.y1); return 1; } static duk_ret_t js_SetCameraX(duk_context* ctx) { int new_x = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetCameraX(): map engine not running"); s_cam_x = new_x; return 0; } static duk_ret_t js_SetCameraY(duk_context* ctx) { int new_y = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetCameraY(): map engine not running"); s_cam_y = new_y; return 0; } static duk_ret_t js_SetColorMask(duk_context* ctx) { int n_args = duk_get_top(ctx); color_t new_mask = duk_require_sphere_color(ctx, 0); int frames = n_args >= 2 ? duk_require_int(ctx, 1) : 0; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetColorMask(): map engine not running"); if (frames < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetColorMask(): frames must be positive (got: %d)", frames); if (frames > 0) { s_fade_color_to = new_mask; s_fade_color_from = s_color_mask; s_fade_frames = frames; s_fade_progress = 0; } else { s_color_mask = new_mask; s_fade_color_to = s_fade_color_from = new_mask; s_fade_progress = s_fade_frames = 0; } return 0; } static duk_ret_t js_SetDefaultMapScript(duk_context* ctx) { int script_type = duk_require_int(ctx, 0); const char* script_name = (script_type == MAP_SCRIPT_ON_ENTER) ? "synth:onLoadMap.js" : (script_type == MAP_SCRIPT_ON_LEAVE) ? "synth:onUnloadMap.js" : (script_type == MAP_SCRIPT_ON_LEAVE_NORTH) ? "synth:onLeaveMapNorth.js" : (script_type == MAP_SCRIPT_ON_LEAVE_EAST) ? "synth:onLeaveMapEast.js" : (script_type == MAP_SCRIPT_ON_LEAVE_SOUTH) ? "synth:onLeaveMapSouth.js" : (script_type == MAP_SCRIPT_ON_LEAVE_WEST) ? "synth:onLeaveMapWest.js" : NULL; script_t* script = duk_require_sphere_script(ctx, 1, script_name); if (script_type < 0 || script_type >= MAP_SCRIPT_MAX) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetDefaultMapScript(): invalid map script constant"); free_script(s_def_scripts[script_type]); s_def_scripts[script_type] = script; return 0; } static duk_ret_t js_SetDelayScript(duk_context* ctx) { int frames = duk_require_int(ctx, 0); script_t* script = duk_require_sphere_script(ctx, 1, "[delay script]"); struct delay_script* delay; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetDelayScript(): map engine not running"); if (frames < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetDelayScript(): frames must be positive"); if (++s_num_delay_scripts > s_max_delay_scripts) { s_max_delay_scripts = s_num_delay_scripts * 2; if (!(s_delay_scripts = realloc(s_delay_scripts, s_max_delay_scripts * sizeof(struct delay_script)))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetDelayScript(): unable to enlarge delay script queue"); } delay = &s_delay_scripts[s_num_delay_scripts - 1]; delay->script = script; delay->frames_left = frames; return 0; } static duk_ret_t js_SetLayerHeight(duk_context* ctx) { int layer; int new_height; layer = duk_require_map_layer(ctx, 0); new_height = duk_require_int(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerHeight(): map engine not running"); if (new_height <= 0) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerHeight(): height must be positive and nonzero (got: %d)", new_height); if (!resize_map_layer(layer, s_map->layers[layer].width, new_height)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerHeight(): unable to resize layer %d", layer); return 0; } static duk_ret_t js_SetLayerMask(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); color_t mask = duk_require_sphere_color(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerMask(): map engine not running"); s_map->layers[layer].color_mask = mask; return 0; } static duk_ret_t js_SetLayerReflective(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); bool is_reflective = duk_require_boolean(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerReflective(): map engine not running"); s_map->layers[layer].is_reflective = is_reflective; return 0; } static duk_ret_t js_SetLayerRenderer(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); char script_name[50]; script_t* script; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerRenderer(): map engine not running"); sprintf(script_name, "[layer %d render script]", layer); script = duk_require_sphere_script(ctx, 1, script_name); free_script(s_map->layers[layer].render_script); s_map->layers[layer].render_script = script; return 0; } static duk_ret_t js_SetLayerSize(duk_context* ctx) { int layer; int new_height; int new_width; layer = duk_require_map_layer(ctx, 0); new_width = duk_require_int(ctx, 1); new_height = duk_require_int(ctx, 2); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerHeight(): map engine not running"); if (new_width <= 0 || new_height <= 0) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerHeight(): dimensions must be positive and nonzero (got W: %d, H: %d)", new_width, new_height); if (!resize_map_layer(layer, new_width, new_height)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerHeight(): unable to resize layer %d", layer); return 0; } static duk_ret_t js_SetLayerVisible(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); bool is_visible = duk_require_boolean(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerVisible(): map engine not running"); s_map->layers[layer].is_visible = is_visible; return 0; } static duk_ret_t js_SetLayerWidth(duk_context* ctx) { int layer; int new_width; layer = duk_require_map_layer(ctx, 0); new_width = duk_require_int(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerWidth(): map engine not running"); if (new_width <= 0) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerWidth(): width must be positive and nonzero (got: %d)", new_width); if (!resize_map_layer(layer, new_width, s_map->layers[layer].height)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetLayerWidth(): unable to resize layer %d", layer); return 0; } static duk_ret_t js_SetMapEngineFrameRate(duk_context* ctx) { s_framerate = duk_to_int(ctx, 0); return 0; } static duk_ret_t js_SetNextAnimatedTile(duk_context* ctx) { int tile_index = duk_require_int(ctx, 0); int next_index = duk_require_int(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetNextAnimatedTile(): map engine not running"); if (tile_index < 0 || tile_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetNextAnimatedTile(): invalid tile index (%d)", tile_index); if (next_index < 0 || next_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetNextAnimatedTile(): invalid tile index for next tile (%d)", tile_index); tileset_set_next(s_map->tileset, tile_index, next_index); return 0; } static duk_ret_t js_SetRenderScript(duk_context* ctx) { script_t* script = duk_require_sphere_script(ctx, 0, "default/renderScript"); free_script(s_render_script); s_render_script = script; return 0; } static duk_ret_t js_SetTalkActivationButton(duk_context* ctx) { int button = duk_require_int(ctx, 0); s_talk_button = button; return 0; } static duk_ret_t js_SetTalkActivationKey(duk_context* ctx) { int n_args = duk_get_top(ctx); int key = duk_require_int(ctx, 0); int player = n_args >= 2 ? duk_require_int(ctx, 1) : 0; if (player < 0 || player >= MAX_PLAYERS) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetTalkActivationKey(): player number out of range (%d)", player); s_players[player].talk_key = key; return 0; } static duk_ret_t js_SetTile(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int layer = duk_require_map_layer(ctx, 2); int tile_index = duk_require_int(ctx, 3); int layer_w, layer_h; struct map_tile* tilemap; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetTile(): map engine not running"); layer_w = s_map->layers[layer].width; layer_h = s_map->layers[layer].height; tilemap = s_map->layers[layer].tilemap; tilemap[x + y * layer_w].tile_index = tile_index; tilemap[x + y * layer_w].frames_left = tileset_get_delay(s_map->tileset, tile_index); return 0; } static duk_ret_t js_SetTileDelay(duk_context* ctx) { int tile_index = duk_require_int(ctx, 0); int delay = duk_require_int(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetTileDelay(): map engine not running"); if (tile_index < 0 || tile_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetTileDelay(): invalid tile index (%d)", tile_index); if (delay < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetTileDelay(): delay must be positive (got: %d)", delay); tileset_set_delay(s_map->tileset, tile_index, delay); return 0; } static duk_ret_t js_SetTileImage(duk_context* ctx) { int tile_index = duk_require_int(ctx, 0); image_t* image = duk_require_sphere_image(ctx, 1); int c_tiles; int image_w, image_h; int tile_w, tile_h; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetTileImage(): map engine not running"); c_tiles = tileset_len(s_map->tileset); if (tile_index < 0 || tile_index >= c_tiles) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetTileImage(): invalid tile index (%d)", tile_index); tileset_get_size(s_map->tileset, &tile_w, &tile_h); image_w = get_image_width(image); image_h = get_image_height(image); if (image_w != tile_w || image_h != tile_h) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "SetTileImage(): image dimensions (%dx%d) don't match tile dimensions (%dx%d)", image_w, image_h, tile_w, tile_h); tileset_set_image(s_map->tileset, tile_index, image); return 0; } static duk_ret_t js_SetTileName(duk_context* ctx) { int tile_index = duk_require_int(ctx, 0); lstring_t* name = duk_require_lstring_t(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetTileName(): map engine not running"); if (tile_index < 0 || tile_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetTileName(): invalid tile index (%d)", tile_index); if (!tileset_set_name(s_map->tileset, tile_index, name)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetTileName(): unable to set tile name"); lstr_free(name); return 0; } static duk_ret_t js_SetTileSurface(duk_context* ctx) { int tile_index = duk_require_int(ctx, 0); image_t* image = duk_require_sphere_obj(ctx, 1, "Surface"); int image_w, image_h; int num_tiles; int tile_w, tile_h; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetTileSurface(): map engine not running"); num_tiles = tileset_len(s_map->tileset); if (tile_index < 0 || tile_index >= num_tiles) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetTileSurface(): invalid tile index (%d)", tile_index); tileset_get_size(s_map->tileset, &tile_w, &tile_h); image_w = get_image_width(image); image_h = get_image_height(image); if (image_w != tile_w || image_h != tile_h) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "SetTileSurface(): surface dimensions (%dx%d) don't match tile dimensions (%dx%d)", image_w, image_h, tile_w, tile_h); tileset_set_image(s_map->tileset, tile_index, image); return 0; } static duk_ret_t js_SetTriggerLayer(duk_context* ctx) { int trigger_index = duk_require_int(ctx, 0); int layer = duk_require_int(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetTriggerLayer(): map engine not running"); if (trigger_index < 0 || trigger_index >= (int)vector_len(s_map->triggers)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetTriggerLayer(): invalid trigger index (%d)", trigger_index); set_trigger_layer(trigger_index, layer); return 0; } static duk_ret_t js_SetTriggerScript(duk_context* ctx) { int trigger_index = duk_require_int(ctx, 0); script_t* script; lstring_t* script_name; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetTriggerScript(): map engine not running"); if (trigger_index < 0 || trigger_index >= (int)vector_len(s_map->triggers)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetTriggerScript(): invalid trigger index (%d)", trigger_index); if (!(script_name = lstr_newf("%s/trigger~%d/onStep", get_map_name(), trigger_index))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetTriggerScript(): unable to compile trigger script"); script = duk_require_sphere_script(ctx, 1, lstr_cstr(script_name)); lstr_free(script_name); set_trigger_script(trigger_index, script); free_script(script); return 0; } static duk_ret_t js_SetTriggerXY(duk_context* ctx) { int trigger_index = duk_require_int(ctx, 0); int x = duk_require_int(ctx, 1); int y = duk_require_int(ctx, 2); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetTriggerXY(): map engine not running"); if (trigger_index < 0 || trigger_index >= (int)vector_len(s_map->triggers)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetTriggerXY(): invalid trigger index (%d)", trigger_index); set_trigger_xy(trigger_index, x, y); return 0; } static duk_ret_t js_SetUpdateScript(duk_context* ctx) { script_t* script = duk_require_sphere_script(ctx, 0, "default/updateScript"); free_script(s_update_script); s_update_script = script; return 0; } static duk_ret_t js_SetZoneLayer(duk_context* ctx) { int zone_index = duk_require_int(ctx, 0); int layer = duk_require_map_layer(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetZoneLayer(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetZoneLayer(): invalid zone index (%d)", zone_index); set_zone_layer(zone_index, layer); return 0; } static duk_ret_t js_SetZoneMetrics(duk_context* ctx) { int n_args = duk_get_top(ctx); int zone_index = duk_require_int(ctx, 0); int x = duk_require_int(ctx, 1); int y = duk_require_int(ctx, 2); int width = duk_require_int(ctx, 3); int height = duk_require_int(ctx, 4); int layer = n_args >= 6 ? duk_require_map_layer(ctx, 5) : -1; rect_t map_bounds; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetZoneDimensions(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetZoneDimensions(): invalid zone index (%d)", zone_index); map_bounds = get_map_bounds(); if (width <= 0 || height <= 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetZoneDimensions(): width and height must be greater than zero"); if (x < map_bounds.x1 || y < map_bounds.y1 || x + width > map_bounds.x2 || y + height > map_bounds.y2) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetZoneDimensions(): zone cannot extend outside map (%d,%d,%d,%d)", x, y, width, height); set_zone_bounds(zone_index, new_rect(x, y, x + width, y + height)); if (layer >= 0) set_zone_layer(zone_index, layer); return 0; } static duk_ret_t js_SetZoneScript(duk_context* ctx) { int zone_index = duk_require_int(ctx, 0); script_t* script; lstring_t* script_name; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetZoneScript(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetZoneScript(): invalid zone index `%d`", zone_index); if (!(script_name = lstr_newf("%s/zone%d", get_map_name(), zone_index))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetZoneScript(): error compiling zone script"); script = duk_require_sphere_script(ctx, 1, lstr_cstr(script_name)); lstr_free(script_name); set_zone_script(zone_index, script); free_script(script); return 0; } static duk_ret_t js_SetZoneSteps(duk_context* ctx) { int zone_index = duk_require_int(ctx, 0); int steps = duk_require_int(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetZoneLayer(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetZoneLayer(): invalid zone index `%d`", zone_index); if (steps <= 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetZoneSteps(): steps must be positive (got: %d)", steps); set_zone_steps(zone_index, steps); return 0; } static duk_ret_t js_AddTrigger(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int layer = duk_require_map_layer(ctx, 2); lstring_t* script_name; rect_t bounds; script_t* script; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "AddTrigger(): map engine not running"); bounds = get_map_bounds(); if (x < bounds.x1 || y < bounds.y1 || x >= bounds.x2 || y >= bounds.y2) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "AddTrigger(): trigger must be inside map (got X: %d, Y: %d)", x, y); if (!(script_name = lstr_newf("%s/trig%d", get_map_name(), vector_len(s_map->triggers)))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "AddTrigger(): unable to compile trigger script"); script = duk_require_sphere_script(ctx, 3, lstr_cstr(script_name)); lstr_free(script_name); if (!add_trigger(x, y, layer, script)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "AddTrigger(): unable to add trigger to map"); duk_push_number(ctx, vector_len(s_map->triggers) - 1); return 1; } static duk_ret_t js_AddZone(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int width = duk_require_int(ctx, 2); int height = duk_require_int(ctx, 3); int layer = duk_require_map_layer(ctx, 4); lstring_t* script_name; rect_t bounds; script_t* script; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "AddZone(): map engine not running"); bounds = get_map_bounds(); if (width <= 0 || height <= 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "AddZone(): width and height must be greater than zero"); if (x < bounds.x1 || y < bounds.y1 || x + width > bounds.x2 || y + height > bounds.y2) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "AddZone(): zone must be inside map (got X: %d, Y: %d, W: %d,H: %d)", x, y, width, height); if (!(script_name = lstr_newf("%s/zone%d", get_map_name(), vector_len(s_map->zones)))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "AddZone(): unable to compile zone script"); script = duk_require_sphere_script(ctx, 5, lstr_cstr(script_name)); lstr_free(script_name); if (!add_zone(new_rect(x, y, width, height), layer, script, 8)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "AddZone(): unable to add zone to map"); duk_push_number(ctx, vector_len(s_map->zones) - 1); return 1; } static duk_ret_t js_AttachCamera(duk_context* ctx) { const char* name; person_t* person; name = duk_to_string(ctx, 0); if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "AttachCamera(): person `%s` doesn't exist", name); s_camera_person = person; return 0; } static duk_ret_t js_AttachInput(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; int i; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "AttachInput(): person `%s` doesn't exist", name); for (i = 0; i < MAX_PLAYERS; ++i) // detach person from other players if (s_players[i].person == person) s_players[i].person = NULL; s_players[0].person = person; return 0; } static duk_ret_t js_AttachPlayerInput(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int player = duk_require_int(ctx, 1); person_t* person; int i; if (player < 0 || player >= MAX_PLAYERS) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "AttachPlayerInput(): player number out of range (%d)", player); if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "AttachInput(): person `%s` doesn't exist", name); for (i = 0; i < MAX_PLAYERS; ++i) // detach person from other players if (s_players[i].person == person) s_players[i].person = NULL; s_players[player].person = person; return 0; } static duk_ret_t js_CallDefaultMapScript(duk_context* ctx) { int type = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "CallDefaultMapScript(): map engine not running"); if (type < 0 || type >= MAP_SCRIPT_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "CallDefaultMapScript(): invalid script type constant"); run_script(s_def_scripts[type], false); return 0; } static duk_ret_t js_CallMapScript(duk_context* ctx) { int type = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "CallMapScript(): map engine not running"); if (type < 0 || type >= MAP_SCRIPT_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "CallMapScript(): invalid script type constant"); run_script(s_map->scripts[type], false); return 0; } static duk_ret_t js_ChangeMap(duk_context* ctx) { const char* filename; filename = duk_require_path(ctx, 0, "maps", true); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ChangeMap(): map engine not running"); if (!change_map(filename, false)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ChangeMap(): unable to load map file `%s`", filename); return 0; } static duk_ret_t js_RemoveTrigger(duk_context* ctx) { int trigger_index = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RemoveTrigger(): map engine not running"); if (trigger_index < 0 || trigger_index >= (int)vector_len(s_map->triggers)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "RemoveTrigger(): invalid trigger index (%d)", trigger_index); remove_trigger(trigger_index); return 0; } static duk_ret_t js_RemoveZone(duk_context* ctx) { int zone_index = duk_require_int(ctx, 0); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RemoveZone(): map engine not running"); if (zone_index < 0 || zone_index >= (int)vector_len(s_map->zones)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "RemoveZone(): invalid zone index (%d)", zone_index); remove_zone(zone_index); return 0; } static duk_ret_t js_DetachCamera(duk_context* ctx) { s_camera_person = NULL; return 0; } static duk_ret_t js_DetachInput(duk_context* ctx) { s_players[0].person = NULL; return 0; } static duk_ret_t js_DetachPlayerInput(duk_context* ctx) { const char* name; person_t* person; int player; int i; if (duk_get_top(ctx) < 1) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "DetachPlayerInput(): player number or string expected as argument"); else if (duk_is_string(ctx, 0)) { name = duk_get_string(ctx, 0); if (!(person = find_person(name))) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "DetachPlayerInput(): person `%s` doesn't exist", name); player = -1; for (i = MAX_PLAYERS - 1; i >= 0; --i) // ensures Sphere semantics player = s_players[i].person == person ? i : player; if (player == -1) return 0; } else if (duk_is_number(ctx, 0)) player = duk_get_int(ctx, 0); else duk_error_ni(ctx, -1, DUK_ERR_ERROR, "DetachPlayerInput(): player number or string expected as argument"); if (player < 0 || player >= MAX_PLAYERS) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "DetachPlayerInput(): player number out of range (%d)", player); s_players[player].person = NULL; return 0; } static duk_ret_t js_ExecuteTrigger(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int layer = duk_require_map_layer(ctx, 2); int index; int last_trigger; struct map_trigger* trigger; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ExecuteTrigger(): map engine not running"); if (trigger = get_trigger_at(x, y, layer, &index)) { last_trigger = s_current_trigger; s_current_trigger = index; run_script(trigger->script, true); s_current_trigger = last_trigger; } return 0; } static duk_ret_t js_ExecuteZones(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int layer = duk_require_map_layer(ctx, 2); int index; int last_zone; struct map_zone* zone; int i; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ExecuteZones(): map engine not running"); i = 0; while (zone = get_zone_at(x, y, layer, i++, &index)) { last_zone = s_current_zone; s_current_zone = index; run_script(zone->script, true); s_current_zone = last_zone; } return 0; } static duk_ret_t js_ExitMapEngine(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ExitMapEngine(): map engine not running"); s_exiting = true; return 0; } static duk_ret_t js_MapToScreenX(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); double x = duk_require_int(ctx, 1); int offset_x; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "MapToScreenX(): map engine not running"); offset_x = 0; map_screen_to_map(s_cam_x, s_cam_y, &offset_x, NULL); duk_push_int(ctx, x - offset_x); return 1; } static duk_ret_t js_MapToScreenY(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); double y = duk_require_int(ctx, 1); int offset_y; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "MapToScreenY(): map engine not running"); offset_y = 0; map_screen_to_map(s_cam_x, s_cam_y, NULL, &offset_y); duk_push_int(ctx, y - offset_y); return 1; } static duk_ret_t js_RenderMap(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RenderMap(): map engine not running"); render_map(); return 0; } static duk_ret_t js_ReplaceTilesOnLayer(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); int old_index = duk_require_int(ctx, 1); int new_index = duk_require_int(ctx, 2); int layer_w, layer_h; struct map_tile* p_tile; int i_x, i_y; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ReplaceTilesOnLayer(): map engine not running"); if (old_index < 0 || old_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ReplaceTilesOnLayer(): old invalid tile index (%d)", old_index); if (new_index < 0 || new_index >= tileset_len(s_map->tileset)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "ReplaceTilesOnLayer(): new invalid tile index (%d)", new_index); layer_w = s_map->layers[layer].width; layer_h = s_map->layers[layer].height; for (i_x = 0; i_x < layer_w; ++i_x) for (i_y = 0; i_y < layer_h; ++i_y) { p_tile = &s_map->layers[layer].tilemap[i_x + i_y * layer_w]; if (p_tile->tile_index == old_index) p_tile->tile_index = new_index; } return 0; } static duk_ret_t js_ScreenToMapX(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); int x = duk_require_int(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ScreenToMapX(): map engine not running"); map_screen_to_map(s_cam_x, s_cam_y, &x, NULL); duk_push_int(ctx, x); return 1; } static duk_ret_t js_ScreenToMapY(duk_context* ctx) { int layer = duk_require_map_layer(ctx, 0); int y = duk_require_int(ctx, 1); if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "ScreenToMapY(): map engine not running"); map_screen_to_map(s_cam_x, s_cam_y, NULL, &y); duk_push_int(ctx, y); return 1; } static duk_ret_t js_UpdateMapEngine(duk_context* ctx) { if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "UpdateMapEngine(): map engine not running"); update_map_engine(false); return 0; } <file_sep>/src/debugger/help.h #ifndef SSJ__HELP_H__INCLUDED #define SSJ__HELP_H__INCLUDED void help_print (const char* command_name); #endif // SSJ__HELP_H__INCLUDED <file_sep>/src/engine/tileset.c #include "minisphere.h" #include "atlas.h" #include "image.h" #include "obsmap.h" #include "tileset.h" struct tileset { unsigned int id; atlas_t* atlas; int atlas_pitch; int height; image_t* texture; int num_tiles; struct tile* tiles; int width; }; struct tile { int delay; int frames_left; image_t* image; int image_index; lstring_t* name; int next_index; int num_obs_lines; obsmap_t* obsmap; }; #pragma pack(push, 1) struct rts_header { uint8_t signature[4]; uint16_t version; uint16_t num_tiles; uint16_t tile_width; uint16_t tile_height; uint16_t tile_bpp; uint8_t compression; uint8_t has_obstructions; uint8_t reserved[240]; }; struct rts_tile_header { uint8_t unknown_1; uint8_t animated; int16_t next_tile; int16_t delay; uint8_t unknown_2; uint8_t obsmap_type; uint16_t num_segments; uint16_t name_length; uint8_t terraformed; uint8_t reserved[19]; }; #pragma pack(pop) static unsigned int s_next_tileset_id = 0; tileset_t* tileset_new(const char* filename) { sfs_file_t* file; tileset_t* tileset; console_log(2, "loading tileset #%u as `%s`", s_next_tileset_id, filename); if ((file = sfs_fopen(g_fs, filename, NULL, "rb")) == NULL) goto on_error; tileset = tileset_read(file); sfs_fclose(file); return tileset; on_error: console_log(2, "failed to load tileset #%u", s_next_tileset_id++); return NULL; } tileset_t* tileset_read(sfs_file_t* file) { atlas_t* atlas = NULL; long file_pos; struct rts_header rts; rect_t segment; struct rts_tile_header tilehdr; struct tile* tiles = NULL; tileset_t* tileset = NULL; int i, j; memset(&rts, 0, sizeof(struct rts_header)); console_log(2, "reading tileset #%u from open file", s_next_tileset_id); if (file == NULL) goto on_error; file_pos = sfs_ftell(file); if ((tileset = calloc(1, sizeof(tileset_t))) == NULL) goto on_error; if (sfs_fread(&rts, sizeof(struct rts_header), 1, file) != 1) goto on_error; if (memcmp(rts.signature, ".rts", 4) != 0 || rts.version < 1 || rts.version > 1) goto on_error; if (rts.tile_bpp != 32) goto on_error; if (!(tiles = calloc(rts.num_tiles, sizeof(struct tile)))) goto on_error; // read in all the tile bitmaps (use atlasing) if (!(atlas = atlas_new(rts.num_tiles, rts.tile_width, rts.tile_height))) goto on_error; atlas_lock(atlas); for (i = 0; i < rts.num_tiles; ++i) if (!(tiles[i].image = atlas_load(atlas, file, i, rts.tile_width, rts.tile_height))) goto on_error; atlas_unlock(atlas); tileset->atlas = atlas; // read in tile headers and obstruction maps for (i = 0; i < rts.num_tiles; ++i) { if (sfs_fread(&tilehdr, sizeof(struct rts_tile_header), 1, file) != 1) goto on_error; tiles[i].name = read_lstring_raw(file, tilehdr.name_length, true); tiles[i].next_index = tilehdr.animated ? tilehdr.next_tile : i; tiles[i].delay = tilehdr.animated ? tilehdr.delay : 0; tiles[i].image_index = i; tiles[i].frames_left = tiles[i].delay; if (rts.has_obstructions) { switch (tilehdr.obsmap_type) { case 1: // pixel-perfect obstruction (no longer supported) sfs_fseek(file, rts.tile_width * rts.tile_height, SFS_SEEK_CUR); break; case 2: // line segment-based obstruction tiles[i].num_obs_lines = tilehdr.num_segments; if ((tiles[i].obsmap = obsmap_new()) == NULL) goto on_error; for (j = 0; j < tilehdr.num_segments; ++j) { if (!fread_rect_16(file, &segment)) goto on_error; obsmap_add_line(tiles[i].obsmap, segment); } break; default: goto on_error; } } } // wrap things up tileset->id = s_next_tileset_id++; tileset->width = rts.tile_width; tileset->height = rts.tile_height; tileset->num_tiles = rts.num_tiles; tileset->tiles = tiles; return tileset; on_error: // oh no! console_log(2, "failed to read tileset #%u", s_next_tileset_id); if (file != NULL) sfs_fseek(file, file_pos, SFS_SEEK_SET); if (tiles != NULL) { for (i = 0; i < rts.num_tiles; ++i) { lstr_free(tiles[i].name); obsmap_free(tiles[i].obsmap); free_image(tiles[i].image); } free(tileset->tiles); } atlas_free(atlas); free(tileset); return NULL; } void tileset_free(tileset_t* tileset) { int i; console_log(3, "disposing tileset #%u as it is no longer in use", tileset->id); for (i = 0; i < tileset->num_tiles; ++i) { lstr_free(tileset->tiles[i].name); free_image(tileset->tiles[i].image); obsmap_free(tileset->tiles[i].obsmap); } atlas_free(tileset->atlas); free(tileset->tiles); free(tileset); } int tileset_get_next(const tileset_t* tileset, int tile_index) { int next_index; next_index = tileset->tiles[tile_index].next_index; return next_index >= 0 && next_index < tileset->num_tiles ? next_index : tile_index; } int tileset_len(const tileset_t* tileset) { return tileset->num_tiles; } int tileset_get_delay(const tileset_t* tileset, int tile_index) { return tileset->tiles[tile_index].delay; } image_t* tileset_get_image(const tileset_t* tileset, int tile_index) { return tileset->tiles[tile_index].image; } const lstring_t* tileset_get_name(const tileset_t* tileset, int tile_index) { return tileset->tiles[tile_index].name; } const obsmap_t* tileset_obsmap(const tileset_t* tileset, int tile_index) { if (tile_index >= 0) return tileset->tiles[tile_index].obsmap; else return NULL; } void tileset_get_size(const tileset_t* tileset, int* out_w, int* out_h) { *out_w = tileset->width; *out_h = tileset->height; } void tileset_set_next(tileset_t* tileset, int tile_index, int next_index) { tileset->tiles[tile_index].next_index = next_index; } void tileset_set_delay(tileset_t* tileset, int tile_index, int delay) { tileset->tiles[tile_index].delay = delay; } void tileset_set_image(tileset_t* tileset, int tile_index, image_t* image) { // CAUTION: the new tile image is assumed to be the same same size as the tile it // replaces. if it's not, the engine won't crash, but it may cause graphical // glitches. rect_t xy; xy = atlas_xy(tileset->atlas, tile_index); blit_image(image, tileset->texture, xy.x1, xy.y1); } bool tileset_set_name(tileset_t* tileset, int tile_index, const lstring_t* name) { lstring_t* new_name; if (!(new_name = lstr_dup(name))) return false; lstr_free(tileset->tiles[tile_index].name); tileset->tiles[tile_index].name = new_name; return true; } void tileset_update(tileset_t* tileset) { struct tile* tile; int i; for (i = 0; i < tileset->num_tiles; ++i) { tile = &tileset->tiles[i]; if (tile->frames_left > 0 && --tile->frames_left == 0) { tile->image_index = tileset_get_next(tileset, tile->image_index); tile->frames_left = tileset_get_delay(tileset, tile->image_index); } } } void tileset_draw(const tileset_t* tileset, color_t mask, float x, float y, int tile_index) { if (tile_index < 0) return; tile_index = tileset->tiles[tile_index].image_index; al_draw_tinted_bitmap(get_image_bitmap(tileset->tiles[tile_index].image), al_map_rgba(mask.r, mask.g, mask.b, mask.alpha), x, y, 0x0); } <file_sep>/src/engine/galileo.h #ifndef MINISPHERE__GALILEO_H__INCLUDED #define MINISPHERE__GALILEO_H__INCLUDED #include "shader.h" typedef struct shape shape_t; typedef struct group group_t; typedef enum shape_type { SHAPE_AUTO, SHAPE_POINTS, SHAPE_LINES, SHAPE_LINE_LOOP, SHAPE_LINE_STRIP, SHAPE_TRIANGLES, SHAPE_TRI_FAN, SHAPE_TRI_STRIP, SHAPE_MAX } shape_type_t; typedef struct vertex { float x, y, z; float u, v; color_t color; } vertex_t; void initialize_galileo (void); void shutdown_galileo (void); shader_t* get_default_shader (void); vertex_t vertex (float x, float y, float z, float u, float v, color_t color); group_t* group_new (shader_t* shader); group_t* group_ref (group_t* group); void group_free (group_t* group); shader_t* group_get_shader (const group_t* group); matrix_t* group_get_transform (const group_t* group); void group_set_shader (group_t* group, shader_t* shader); void group_set_transform (group_t* group, matrix_t* transform); bool group_add_shape (group_t* group, shape_t* shape); void group_draw (const group_t* group, image_t* surface); void group_put_float (group_t* group, const char* name, float value); void group_put_int (group_t* group, const char* name, int value); void group_put_matrix (group_t* group, const char* name, const matrix_t* matrix); shape_t* shape_new (shape_type_t type, image_t* texture); shape_t* shape_ref (shape_t* shape); void shape_free (shape_t* shape); float_rect_t shape_bounds (const shape_t* shape); image_t* shape_texture (const shape_t* shape); void shape_set_texture (shape_t* shape, image_t* texture); bool shape_add_vertex (shape_t* shape, vertex_t vertex); void shape_draw (shape_t* shape, matrix_t* matrix, image_t* surface); void shape_upload (shape_t* shape); void init_galileo_api (void); #endif // MINISPHERE__GALILEO_H__INCLUDED <file_sep>/src/debugger/sockets.h #ifndef SSJ__SOCKET_H__INCLUDED #define SSJ__SOCKET_H__INCLUDED typedef struct socket socket_t; void sockets_init (void); void sockets_deinit (void); socket_t* socket_connect (const char* hostname, int port, double timeout); void socket_close (socket_t* obj); bool socket_is_live (socket_t* obj); int socket_recv (socket_t* obj, void* buffer, int num_bytes); int socket_send (socket_t* obj, const void* data, int num_bytes); #endif // SSJ__SOCKET_H__INCLUDED <file_sep>/src/engine/persons.h // the declaration below has been deliberately hoisted outside of the // include guard; as there is a mutual dependency between the map engine // and persons manager, the engine won't compile otherwise. typedef struct person person_t; #ifndef MINISPHERE__PERSONS_H__INCLUDED #define MINISPHERE__PERSONS_H__INCLUDED #include "map_engine.h" #include "spriteset.h" typedef enum command_op { COMMAND_WAIT, COMMAND_ANIMATE, COMMAND_FACE_NORTH, COMMAND_FACE_NORTHEAST, COMMAND_FACE_EAST, COMMAND_FACE_SOUTHEAST, COMMAND_FACE_SOUTH, COMMAND_FACE_SOUTHWEST, COMMAND_FACE_WEST, COMMAND_FACE_NORTHWEST, COMMAND_MOVE_NORTH, COMMAND_MOVE_NORTHEAST, COMMAND_MOVE_EAST, COMMAND_MOVE_SOUTHEAST, COMMAND_MOVE_SOUTH, COMMAND_MOVE_SOUTHWEST, COMMAND_MOVE_WEST, COMMAND_MOVE_NORTHWEST, COMMAND_RUN_SCRIPT } command_op_t; typedef enum person_script { PERSON_SCRIPT_ON_CREATE, PERSON_SCRIPT_ON_DESTROY, PERSON_SCRIPT_ON_TOUCH, PERSON_SCRIPT_ON_TALK, PERSON_SCRIPT_GENERATOR, PERSON_SCRIPT_MAX } person_script_t; void initialize_persons_manager (void); void shutdown_persons_manager (void); person_t* create_person (const char* name, spriteset_t* spriteset, bool is_persistent, script_t* create_script); void destroy_person (person_t* person); bool has_person_moved (const person_t* person); bool is_person_busy (const person_t* person); bool is_person_following (const person_t* person, const person_t* leader); bool is_person_ignored (const person_t* person, const person_t* by_person); bool is_person_obstructed_at (const person_t* person, double x, double y, person_t** out_obstructing_person, int* out_tile_index); double get_person_angle (const person_t* person); rect_t get_person_base (const person_t* person); color_t get_person_mask (const person_t* person); const char* get_person_name (const person_t* person); void get_person_scale (const person_t*, double* out_scale_x, double* out_scale_y); void get_person_speed (const person_t* person, double* out_x_speed, double* out_y_speed); spriteset_t* get_person_spriteset (person_t* person); void get_person_xy (const person_t* person, double* out_x, double* out_y, bool normalize); void get_person_xyz (const person_t* person, double* out_x, double* out_y, int* out_layer, bool want_normalize); void set_person_angle (person_t* person, double theta); void set_person_mask (person_t* person, color_t mask); void set_person_scale (person_t*, double scale_x, double scale_y); void set_person_script (person_t* person, int type, script_t* script); void set_person_speed (person_t* person, double x_speed, double y_speed); void set_person_spriteset (person_t* person, spriteset_t* spriteset); void set_person_xyz (person_t* person, double x, double y, int layer); bool call_person_script (const person_t* person, int type, bool use_default); bool compile_person_script (person_t* person, int type, const lstring_t* codestring); person_t* find_person (const char* name); bool queue_person_command (person_t* person, int command, bool is_immediate); bool queue_person_script (person_t* person, script_t* script, bool is_immediate); void reset_persons (bool keep_existing); void render_persons (int layer, bool is_flipped, int cam_x, int cam_y); void talk_person (const person_t* person); void update_persons (void); void init_persons_api (void); #endif // MINISPHERE__PERSONS_H__INCLUDED <file_sep>/src/engine/script.h #ifndef MINISPHERE__SCRIPT_H__INCLUDED #define MINISPHERE__SCRIPT_H__INCLUDED typedef struct script script_t; void initialize_scripts (void); void shutdown_scripts (void); bool evaluate_script (const char* filename); script_t* compile_script (const lstring_t* script, const char* fmt_name, ...); script_t* ref_script (script_t* script); void free_script (script_t* script); void run_script (script_t* script, bool allow_reentry); script_t* duk_require_sphere_script (duk_context* ctx, duk_idx_t index, const char* name); #endif // MINISPHERE__SCRIPT_H__INCLUDED <file_sep>/src/compiler/build.c #include "cell.h" #include "build.h" #include "assets.h" #include "spk_writer.h" #include "tinydir.h" struct build { duk_context* duktape; path_t* in_path; vector_t* installs; path_t* out_path; int last_warn_count; bool make_source_map; int num_errors; int num_warnings; char* rule_name; spk_writer_t* spk; path_t* staging_path; vector_t* targets; time_t timestamp; }; struct install { const target_t* target; path_t* path; }; struct target { unsigned int num_refs; asset_t* asset; path_t* subpath; }; static duk_ret_t js_api_install (duk_context* ctx); static duk_ret_t js_api_files (duk_context* ctx); static duk_ret_t js_api_s2gm (duk_context* ctx); static duk_ret_t js_api_sgm (duk_context* ctx); static int compare_asset_names (const void* in_a, const void* in_b); static void do_add_files (build_t* build, const char* wildcard, const path_t* path, const path_t* subpath, bool recursive, vector_t* *inout_targets); static bool do_build_target (build_t* build, const target_t* target, bool *out_is_new); static bool do_install_target (build_t* build, struct install* inst, bool *out_is_new); static void emit_op_begin (build_t* build, const char* fmt, ...); static void emit_op_end (build_t* build, const char* fmt, ...); static void validate_targets (build_t* build); build_t* build_new(const path_t* in_path, const path_t* out_path, bool make_source_map) { build_t* build = NULL; path_t* script_path; struct stat stat_buf; build = calloc(1, sizeof(build_t)); // check for Cellscript.js in input directory script_path = path_rebase(path_new("Cellscript.js"), in_path); if (stat(path_cstr(script_path), &stat_buf) != 0 || !(stat_buf.st_mode & S_IFREG)) { fprintf(stderr, "error: unable to stat Cellscript.js\n"); return NULL; } build->timestamp = stat_buf.st_mtime; path_free(script_path); // initialize JavaScript environment build->duktape = duk_create_heap_default(); duk_push_global_stash(build->duktape); duk_push_pointer(build->duktape, build); duk_put_prop_string(build->duktape, -2, "\xFF""environ"); duk_pop(build->duktape); // wire up JavaScript API duk_push_c_function(build->duktape, js_api_install, DUK_VARARGS); duk_put_global_string(build->duktape, "install"); duk_push_c_function(build->duktape, js_api_files, DUK_VARARGS); duk_put_global_string(build->duktape, "files"); duk_push_c_function(build->duktape, js_api_s2gm, DUK_VARARGS); duk_put_global_string(build->duktape, "s2gm"); duk_push_c_function(build->duktape, js_api_sgm, DUK_VARARGS); duk_put_global_string(build->duktape, "sgm"); // set up build environment (ensure directory exists, etc.) path_mkdir(out_path); if (path_filename_cstr(out_path)) { build->spk = spk_create(path_cstr(out_path)); if (build->spk == NULL) { fprintf(stderr, "error: unable to create package `%s`\n", path_cstr(out_path)); goto on_error; } } build->make_source_map = make_source_map; build->targets = vector_new(sizeof(target_t*)); build->installs = vector_new(sizeof(struct install)); build->in_path = path_resolve(path_dup(in_path), NULL); build->out_path = path_resolve(path_dup(out_path), NULL); build->staging_path = path_rebase(path_new(".cell/"), build->in_path); if (build->out_path == NULL) { fprintf(stderr, "error: unable to create `%s`\n", path_cstr(out_path)); goto on_error; } return build; on_error: duk_destroy_heap(build->duktape); free(build); return NULL; } void build_free(build_t* build) { struct install *p_inst; target_t* *p_target; iter_t iter; if (build == NULL) return; duk_destroy_heap(build->duktape); iter = vector_enum(build->targets); while (p_target = vector_next(&iter)) { asset_free((*p_target)->asset); path_free((*p_target)->subpath); free(*p_target); } vector_free(build->targets); iter = vector_enum(build->installs); while (p_inst = vector_next(&iter)) { path_free(p_inst->path); } vector_free(build->installs); path_free(build->staging_path); path_free(build->in_path); path_free(build->out_path); spk_close(build->spk); free(build->rule_name); free(build); } bool build_is_ok(const build_t* build, int *out_n_errors, int *out_n_warnings) { if (out_n_errors) *out_n_errors = build->num_errors; if (out_n_warnings) *out_n_warnings = build->num_warnings; return build->num_errors == 0; } target_t* build_add_asset(build_t* build, asset_t* asset, const path_t* subpath) { target_t* target; target = calloc(1, sizeof(target_t)); target->asset = asset; target->subpath = subpath != NULL ? path_dup(subpath) : path_new("./"); vector_push(build->targets, &target); return target; } vector_t* build_add_files(build_t* build, const path_t* pattern, bool recursive) { path_t* path; vector_t* targets; char* wildcard; targets = vector_new(sizeof(target_t*)); path = path_rebase(path_strip(path_dup(pattern)), build->in_path); wildcard = strdup(path_filename_cstr(pattern)); do_add_files(build, wildcard, path, NULL, recursive, &targets); path_free(path); free(wildcard); return targets; } void build_emit_error(build_t* build, const char* fmt, ...) { va_list ap; ++build->num_errors; va_start(ap, fmt); printf("\n error: "); vprintf(fmt, ap); va_end(ap); } void build_emit_warn(build_t* build, const char* fmt, ...) { va_list ap; ++build->num_warnings; va_start(ap, fmt); printf("\n warning: "); vprintf(fmt, ap); va_end(ap); } void build_install(build_t* build, const target_t* target, const path_t* path) { struct install inst; inst.target = target; inst.path = path != NULL ? path_dup(path) : path_new("./"); vector_push(build->installs, &inst); } bool build_prime(build_t* build, const char* rule_name) { char func_name[255]; path_t* script_path; build->rule_name = strdup(rule_name); // process build script emit_op_begin(build, "processing Cellscript.js rule `%s`", rule_name); sprintf(func_name, "$%s", rule_name); script_path = path_rebase(path_new("Cellscript.js"), build->in_path); if (duk_peval_file(build->duktape, path_cstr(script_path)) != 0) { path_free(script_path); build_emit_error(build, "JS: %s", duk_safe_to_string(build->duktape, -1)); goto on_error; } path_free(script_path); if (duk_get_global_string(build->duktape, func_name) && duk_is_callable(build->duktape, -1)) { if (duk_pcall(build->duktape, 0) != 0) { build_emit_error(build, "JS: %s", duk_safe_to_string(build->duktape, -1)); goto on_error; } } else { build_emit_error(build, "no Cellscript rule named `%s`", rule_name); goto on_error; } validate_targets(build); if (build->num_errors) goto on_error; path_append_dir(build->staging_path, rule_name); emit_op_end(build, "OK."); return true; on_error: printf("\n"); return false; } bool build_run(build_t* build) { bool has_changed = false; bool is_new; const char* json; duk_size_t json_size; int num_assets; path_t* path; struct install *p_inst; target_t* *p_target; iter_t iter; if (vector_len(build->installs) == 0) { build_emit_error(build, "no assets staged for install"); return false; } // build and install assets printf("compiling assets... "); path_mkdir(build->staging_path); num_assets = 0; iter = vector_enum(build->targets); while (p_target = vector_next(&iter)) { if (!do_build_target(build, *p_target, &is_new)) return false; if (is_new) { if (num_assets == 0) printf("\n"); printf(" %s\n", path_cstr(asset_object_path((*p_target)->asset))); ++num_assets; has_changed = true; } } if (num_assets > 0) printf(" %d asset(s) compiled\n", num_assets); else printf("up-to-date.\n"); printf("installing assets... "); num_assets = 0; iter = vector_enum(build->installs); while (p_inst = vector_next(&iter)) { if (!do_install_target(build, p_inst, &is_new)) return false; if (is_new) { if (num_assets == 0) printf("\n"); printf(" %s\n", path_cstr(p_inst->path)); ++num_assets; has_changed = true; } } if (num_assets > 0) printf(" %d asset(s) installed\n", num_assets); else printf("up-to-date.\n"); // generate source map if (build->make_source_map) { printf("generating source map... "); duk_push_object(build->duktape); duk_push_string(build->duktape, path_cstr(build->in_path)); duk_put_prop_string(build->duktape, -2, "origin"); duk_push_object(build->duktape); iter = vector_enum(build->installs); while (p_inst = vector_next(&iter)) { path = path_resolve(path_dup(asset_object_path(p_inst->target->asset)), build->in_path); duk_push_string(build->duktape, path_cstr(path)); duk_put_prop_string(build->duktape, -2, path_cstr(p_inst->path)); path_free(path); } duk_put_prop_string(build->duktape, -2, "fileMap"); duk_json_encode(build->duktape, -1); json = duk_get_lstring(build->duktape, -1, &json_size); path = path_rebase(path_new("sourcemap.json"), build->spk != NULL ? build->staging_path : build->out_path); path_mkdir(build->out_path); if (!fspew(json, json_size, path_cstr(path))) { path_free(path); fprintf(stderr, "\nerror: failed to write source map\n"); return false; } if (build->spk != NULL) spk_add_file(build->spk, path_cstr(path), path_filename_cstr(path)); path_free(path); printf("OK.\n"); } else if (build->spk == NULL) { // non-debug build, remove any existing source map path = path_rebase(path_new("sourcemap.json"), build->out_path); unlink(path_cstr(path)); path_free(path); } printf("%s -> %s\n", build->rule_name, path_cstr(build->out_path)); printf(" %d errors, %d warnings\n", build->num_errors, build->num_warnings); return true; } static int compare_asset_names(const void* in_a, const void* in_b) { const path_t* path_a; const path_t* path_b; path_a = asset_name((*(target_t**)in_a)->asset); path_b = asset_name((*(target_t**)in_b)->asset); return path_a == path_b ? 0 : path_a == NULL ? 1 : path_b == NULL ? -1 : strcmp(path_cstr(path_a), path_cstr(path_b)); } static void do_add_files(build_t* build, const char* wildcard, const path_t* path, const path_t* subpath, bool recursive, vector_t* *inout_targets) { tinydir_dir dir; tinydir_file file_info; path_t* file_path = NULL; path_t* full_path; path_t* new_subpath; target_t* target; full_path = subpath != NULL ? path_cat(path_dup(path), subpath) : path_dup(path); tinydir_open(&dir, path_cstr(full_path)); path_free(full_path); dir.n_files; while (dir.has_next) { tinydir_readfile(&dir, &file_info); tinydir_next(&dir); path_free(file_path); file_path = file_info.is_dir ? path_new_dir(file_info.path) : path_new(file_info.path); if (!path_resolve(file_path, NULL)) continue; if (strcmp(file_info.name, ".") == 0 || strcmp(file_info.name, "..") == 0) continue; if (!wildcmp(file_info.name, wildcard) && file_info.is_reg) continue; if (path_cmp(file_path, build->staging_path)) continue; if (file_info.is_reg) { target = build_add_asset(build, asset_new_file(file_path), subpath); vector_push(*inout_targets, &target); } else if (file_info.is_dir && recursive) { new_subpath = subpath != NULL ? path_append_dir(path_dup(subpath), file_info.name) : path_new_dir(file_info.name); do_add_files(build, wildcard, path, new_subpath, recursive, inout_targets); path_free(new_subpath); } } path_free(file_path); tinydir_close(&dir); } static bool do_build_target(build_t* build, const target_t* target, bool *out_is_new) { return target->num_refs == 0 || asset_build(target->asset, build->staging_path, out_is_new); } static bool do_install_target(build_t* build, struct install* inst, bool *out_is_new) { void* file_data = NULL; size_t file_size; const char* fn_dest; const char* fn_src; path_t* out_path; struct stat sb_src, sb_dest; const path_t* src_path; *out_is_new = false; if (!(src_path = asset_object_path(inst->target->asset))) return false; if (build->spk == NULL) { out_path = path_cat(path_dup(build->out_path), inst->path); path_cat(out_path, inst->target->subpath); path_append(out_path, path_filename_cstr(src_path)); path_mkdir(out_path); fn_src = path_cstr(src_path); fn_dest = path_cstr(out_path); if (stat(fn_src, &sb_src) != 0) { build_emit_error(build, "unable to access `%s`", fn_src); return false; } if (stat(fn_dest, &sb_dest) != 0 || difftime(sb_src.st_mtime, sb_dest.st_mtime) > 0.0) { path_mkdir(out_path); if (!(file_data = fslurp(fn_src, &file_size)) || !fspew(file_data, file_size, fn_dest)) { free(file_data); build_emit_error(build, "unable to copy `%s` to `%s`", path_cstr(src_path), path_cstr(out_path)); return false; } free(file_data); *out_is_new = true; } path_free(inst->path); inst->path = path_resolve(out_path, build->out_path); } else { out_path = path_cat(path_dup(inst->path), inst->target->subpath); path_collapse(out_path, true); path_append(out_path, path_filename_cstr(src_path)); spk_add_file(build->spk, path_cstr(src_path), path_cstr(out_path)); path_free(inst->path); inst->path = out_path; *out_is_new = true; } return true; } static void emit_op_begin(build_t* build, const char* fmt, ...) { va_list ap; build->last_warn_count = build->num_warnings; va_start(ap, fmt); vprintf(fmt, ap); printf("... "); va_end(ap); } static void emit_op_end(build_t* build, const char* fmt, ...) { va_list ap; if (build->num_warnings > build->last_warn_count) printf("\n"); else { va_start(ap, fmt); vprintf(fmt, ap); printf("\n"); va_end(ap); } } static void validate_targets(build_t* build) { const path_t* name; int num_dups = 0; const path_t* prev_name = NULL; vector_t* targets; iter_t iter; target_t* *p_target; // check for asset name conflicts targets = vector_sort(vector_dup(build->targets), compare_asset_names); iter = vector_enum(build->targets); while (p_target = vector_next(&iter)) { if (!(name = asset_name((*p_target)->asset))) continue; if (!(*p_target)->num_refs == 0) continue; if (prev_name != NULL && path_cmp(name, prev_name)) ++num_dups; else { if (num_dups > 0) build_emit_error(build, "`%s` %d-way asset conflict", path_cstr(name), num_dups + 1); num_dups = 0; } prev_name = name; } if (num_dups > 0) build_emit_error(build, "`%s` %d-way asset conflict", path_cstr(prev_name), num_dups + 1); vector_free(targets); } static duk_ret_t js_api_install(duk_context* ctx) { build_t* build; int n_args; duk_size_t n_targets; path_t* path = NULL; target_t* target; size_t i; n_args = duk_get_top(ctx); if (n_args >= 2) path = path_new_dir(duk_require_string(ctx, 1)); duk_push_global_stash(ctx); build = (duk_get_prop_string(ctx, -1, "\xFF""environ"), duk_get_pointer(ctx, -1)); duk_pop_2(ctx); if (!duk_is_array(ctx, 0)) { target = duk_require_pointer(ctx, 0); ++target->num_refs; build_install(build, target, path); } else { n_targets = duk_get_length(ctx, 0); for (i = 0; i < n_targets; ++i) { duk_get_prop_index(ctx, 0, (duk_uarridx_t)i); target = duk_require_pointer(ctx, -1); ++target->num_refs; build_install(build, target, path); duk_pop(ctx); } } path_free(path); return 0; } static duk_ret_t js_api_files(duk_context* ctx) { int n_args; build_t* build; duk_uarridx_t idx = 0; bool is_recursive; path_t* pattern; vector_t* targets; target_t** p_target; iter_t iter; n_args = duk_get_top(ctx); pattern = path_new(duk_require_string(ctx, 0)); if (path_filename_cstr(pattern) == NULL) path_append(pattern, "*"); is_recursive = n_args >= 2 ? duk_require_boolean(ctx, 1) : false; duk_push_global_stash(ctx); build = (duk_get_prop_string(ctx, -1, "\xFF""environ"), duk_get_pointer(ctx, -1)); duk_pop_2(ctx); targets = build_add_files(build, pattern, is_recursive); if (vector_len(targets) == 0) build_emit_warn(build, "files(): no files match `%s`", path_cstr(pattern)); duk_push_array(ctx); iter = vector_enum(targets); while (p_target = vector_next(&iter)) { duk_push_pointer(ctx, *p_target); duk_put_prop_index(ctx, -2, idx++); } vector_free(targets); path_free(pattern); return 1; } static duk_ret_t js_api_sgm(duk_context* ctx) { build_t* build; sgm_info_t manifest; char* token; char* next_token; char* res_string; target_t* target; duk_require_object_coercible(ctx, 0); duk_push_global_stash(ctx); build = (duk_get_prop_string(ctx, -1, "\xFF""environ"), duk_get_pointer(ctx, -1)); duk_pop_2(ctx); duk_get_prop_string(ctx, 0, "name"); duk_get_prop_string(ctx, 0, "author"); duk_get_prop_string(ctx, 0, "summary"); duk_get_prop_string(ctx, 0, "resolution"); duk_get_prop_string(ctx, 0, "script"); strcpy(manifest.name, duk_require_string(ctx, -5)); strcpy(manifest.author, duk_require_string(ctx, -4)); strcpy(manifest.description, duk_require_string(ctx, -3)); strcpy(manifest.script, duk_require_string(ctx, -1)); // parse the screen resolution string res_string = strdup(duk_require_string(ctx, -2)); token = strtok_r(res_string, "x", &next_token); manifest.width = atoi(token); if (!(token = strtok_r(NULL, "x", &next_token))) duk_error(ctx, DUK_ERR_TYPE_ERROR, "sgm(): malformed resolution `%s`", duk_require_string(ctx, -2)); manifest.height = atoi(token); if (strtok_r(NULL, "x", &next_token) || manifest.width <= 0 || manifest.height <= 0) duk_error(ctx, DUK_ERR_TYPE_ERROR, "sgm(): malformed resolution `%s`", duk_require_string(ctx, -2)); free(res_string); target = build_add_asset(build, asset_new_sgm(manifest, build->timestamp), NULL); duk_push_pointer(ctx, target); return 1; } static duk_ret_t js_api_s2gm(duk_context* ctx) { build_t* build; const char* json; path_t* name; target_t* target; duk_require_object_coercible(ctx, 0); duk_push_global_stash(ctx); build = (duk_get_prop_string(ctx, -1, "\xFF""environ"), duk_get_pointer(ctx, -1)); duk_pop_2(ctx); if (!duk_get_prop_string(ctx, 0, "author")) build_emit_warn(build, "s2gm(): 'author' field is missing"); if (!duk_get_prop_string(ctx, 0, "summary")) build_emit_warn(build, "s2gm(): 'summary' field is missing"); duk_pop_2(ctx); json = duk_json_encode(ctx, 0); name = path_new("game.s2gm"); target = build_add_asset(build, asset_new_raw(name, json, strlen(json), build->timestamp), NULL); path_free(name); duk_push_pointer(ctx, target); return 1; } <file_sep>/src/shared/version.h #ifndef MINISPHERE__VERSION_H__INCLUDED #define MINISPHERE__VERSION_H__INCLUDED #define PRODUCT_NAME "minisphere" #define VERSION_NAME "3.1.0" #endif // MINISPHERE__VERSION_H__INCLUDED <file_sep>/src/debugger/session.h #ifndef SSJ__SESSION_H__INCLUDED #define SSJ__SESSION_H__INCLUDED #include "inferior.h" #include "parser.h" typedef struct session session_t; session_t* session_new (inferior_t* inferior); void session_free (session_t* ses); void session_run (session_t* ses, bool run_now); #endif // SSJ__SESSION_H__INCLUDED <file_sep>/src/engine/api.c #include "minisphere.h" #include "animation.h" #include "async.h" #include "audialis.h" #include "bytearray.h" #include "color.h" #include "debugger.h" #include "file.h" #include "font.h" #include "galileo.h" #include "image.h" #include "input.h" #include "logger.h" #include "map_engine.h" #include "rng.h" #include "shader.h" #include "sockets.h" #include "spriteset.h" #include "surface.h" #include "transpiler.h" #include "windowstyle.h" #include "api.h" #define SPHERE_API_VERSION 2.0 #define SPHERE_API_LEVEL 1 static const char* const SPHERE_EXTENSIONS[] = { "sphere-legacy-api", "sphere-obj-constructors", "sphere-obj-props", "sphere-async-api", "sphere-audialis", "sphere-coffeescript", "sphere-commonjs", "sphere-frameskip-api", "sphere-galileo", "sphere-galileo-shaders", "sphere-map-engine", "sphere-new-sockets", "sphere-rng-object", "sphere-s2gm", "sphere-spherefs", "sphere-typescript", }; static duk_ret_t js_GetVersion (duk_context* ctx); static duk_ret_t js_GetVersionString (duk_context* ctx); static duk_ret_t js_GetExtensions (duk_context* ctx); static duk_ret_t js_RequireSystemScript (duk_context* ctx); static duk_ret_t js_RequireScript (duk_context* ctx); static duk_ret_t js_EvaluateSystemScript (duk_context* ctx); static duk_ret_t js_EvaluateScript (duk_context* ctx); static duk_ret_t js_IsSkippedFrame (duk_context* ctx); static duk_ret_t js_GetFrameRate (duk_context* ctx); static duk_ret_t js_GetGameManifest (duk_context* ctx); static duk_ret_t js_GetGameList (duk_context* ctx); static duk_ret_t js_GetMaxFrameSkips (duk_context* ctx); static duk_ret_t js_GetScreenHeight (duk_context* ctx); static duk_ret_t js_GetScreenWidth (duk_context* ctx); static duk_ret_t js_GetSeconds (duk_context* ctx); static duk_ret_t js_GetTime (duk_context* ctx); static duk_ret_t js_SetFrameRate (duk_context* ctx); static duk_ret_t js_SetMaxFrameSkips (duk_context* ctx); static duk_ret_t js_SetScreenSize (duk_context* ctx); static duk_ret_t js_Abort (duk_context* ctx); static duk_ret_t js_Alert (duk_context* ctx); static duk_ret_t js_Assert (duk_context* ctx); static duk_ret_t js_CreateStringFromCode (duk_context* ctx); static duk_ret_t js_DebugPrint (duk_context* ctx); static duk_ret_t js_Delay (duk_context* ctx); static duk_ret_t js_DoEvents (duk_context* ctx); static duk_ret_t js_ExecuteGame (duk_context* ctx); static duk_ret_t js_Exit (duk_context* ctx); static duk_ret_t js_FlipScreen (duk_context* ctx); static duk_ret_t js_GarbageCollect (duk_context* ctx); static duk_ret_t js_Print (duk_context* ctx); static duk_ret_t js_RestartGame (duk_context* ctx); static duk_ret_t js_UnskipFrame (duk_context* ctx); static duk_ret_t duk_mod_search (duk_context* ctx); static vector_t* s_extensions; static void* s_print_ptr; static lstring_t* s_user_agent; void initialize_api(duk_context* ctx) { int num_extensions; int i; console_log(1, "initializing Sphere API"); s_user_agent = lstr_newf("v%.1f (%s %s)", SPHERE_API_VERSION, PRODUCT_NAME, VERSION_NAME); console_log(1, " API %s", lstr_cstr(s_user_agent)); // register API extensions s_extensions = vector_new(sizeof(char*)); num_extensions = sizeof SPHERE_EXTENSIONS / sizeof SPHERE_EXTENSIONS[0]; for (i = 0; i < num_extensions; ++i) { console_log(1, " %s", SPHERE_EXTENSIONS[i]); api_register_extension(SPHERE_EXTENSIONS[i]); } // register the 'global' global object alias (like Node.js!). // this provides direct access to the global object from any scope. duk_push_global_object(ctx); duk_push_string(ctx, "global"); duk_push_global_object(ctx); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE); // inject __defineGetter__/__defineSetter__ polyfills duk_eval_string(ctx, "Object.defineProperty(Object.prototype, '__defineGetter__', { value: function(name, func) {" "Object.defineProperty(this, name, { get: func, configurable: true }); } });"); duk_eval_string(ctx, "Object.defineProperty(Object.prototype, '__defineSetter__', { value: function(name, func) {" "Object.defineProperty(this, name, { set: func, configurable: true }); } });"); // save built-in print() in case a script overwrites it duk_get_global_string(ctx, "print"); s_print_ptr = duk_get_heapptr(ctx, -1); duk_pop(ctx); // set up RequireScript() inclusion tracking table duk_push_global_stash(ctx); duk_push_object(ctx); duk_put_prop_string(ctx, -2, "RequireScript"); duk_pop(ctx); // stash an object to hold prototypes for built-in objects duk_push_global_stash(ctx); duk_push_object(ctx); duk_put_prop_string(ctx, -2, "prototypes"); duk_pop(ctx); // register module search callback duk_get_global_string(ctx, "Duktape"); duk_push_c_function(ctx, duk_mod_search, DUK_VARARGS); duk_put_prop_string(ctx, -2, "modSearch"); duk_pop(ctx); // register core API functions api_register_method(ctx, NULL, "GetVersion", js_GetVersion); api_register_method(ctx, NULL, "GetVersionString", js_GetVersionString); api_register_method(ctx, NULL, "GetExtensions", js_GetExtensions); api_register_method(ctx, NULL, "EvaluateScript", js_EvaluateScript); api_register_method(ctx, NULL, "EvaluateSystemScript", js_EvaluateSystemScript); api_register_method(ctx, NULL, "RequireScript", js_RequireScript); api_register_method(ctx, NULL, "RequireSystemScript", js_RequireSystemScript); api_register_method(ctx, NULL, "IsSkippedFrame", js_IsSkippedFrame); api_register_method(ctx, NULL, "GetFrameRate", js_GetFrameRate); api_register_method(ctx, NULL, "GetGameManifest", js_GetGameManifest); api_register_method(ctx, NULL, "GetGameList", js_GetGameList); api_register_method(ctx, NULL, "GetMaxFrameSkips", js_GetMaxFrameSkips); api_register_method(ctx, NULL, "GetScreenHeight", js_GetScreenHeight); api_register_method(ctx, NULL, "GetScreenWidth", js_GetScreenWidth); api_register_method(ctx, NULL, "GetSeconds", js_GetSeconds); api_register_method(ctx, NULL, "GetTime", js_GetTime); api_register_method(ctx, NULL, "SetFrameRate", js_SetFrameRate); api_register_method(ctx, NULL, "SetMaxFrameSkips", js_SetMaxFrameSkips); api_register_method(ctx, NULL, "SetScreenSize", js_SetScreenSize); api_register_method(ctx, NULL, "Abort", js_Abort); api_register_method(ctx, NULL, "Alert", js_Alert); api_register_method(ctx, NULL, "Assert", js_Assert); api_register_method(ctx, NULL, "CreateStringFromCode", js_CreateStringFromCode); api_register_method(ctx, NULL, "DebugPrint", js_DebugPrint); api_register_method(ctx, NULL, "Delay", js_Delay); api_register_method(ctx, NULL, "DoEvents", js_DoEvents); api_register_method(ctx, NULL, "Exit", js_Exit); api_register_method(ctx, NULL, "ExecuteGame", js_ExecuteGame); api_register_method(ctx, NULL, "FlipScreen", js_FlipScreen); api_register_method(ctx, NULL, "GarbageCollect", js_GarbageCollect); api_register_method(ctx, NULL, "Print", js_Print); api_register_method(ctx, NULL, "RestartGame", js_RestartGame); api_register_method(ctx, NULL, "UnskipFrame", js_UnskipFrame); // initialize subsystem APIs init_animation_api(); init_async_api(); init_audialis_api(); init_bytearray_api(); init_color_api(); init_file_api(); init_font_api(g_duk); init_galileo_api(); init_image_api(g_duk); init_input_api(); init_logging_api(); init_map_engine_api(g_duk); init_rng_api(); init_screen_api(); init_shader_api(); init_sockets_api(); init_spriteset_api(g_duk); init_surface_api(); init_windowstyle_api(); } void shutdown_api(void) { console_log(1, "shutting down Sphere API"); lstr_free(s_user_agent); } bool api_have_extension(const char* name) { iter_t iter; char* *i_name; iter = vector_enum(s_extensions); while (i_name = vector_next(&iter)) if (strcmp(*i_name, name) == 0) return true; return false; } int api_level(void) { return SPHERE_API_LEVEL; } void api_register_const(duk_context* ctx, const char* name, double value) { duk_push_global_object(ctx); duk_push_string(ctx, name); duk_push_number(ctx, value); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_SET_CONFIGURABLE); duk_pop(ctx); } void api_register_ctor(duk_context* ctx, const char* name, duk_c_function fn, duk_c_function finalizer) { duk_push_global_object(ctx); duk_push_c_function(ctx, fn, DUK_VARARGS); duk_push_string(ctx, "name"); duk_push_string(ctx, name); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE); // create a prototype. Duktape won't assign one for us. duk_push_object(ctx); duk_push_string(ctx, name); duk_put_prop_string(ctx, -2, "\xFF" "ctor"); if (finalizer != NULL) { duk_push_c_function(ctx, finalizer, DUK_VARARGS); duk_put_prop_string(ctx, -2, "\xFF" "dtor"); } // save the prototype in the prototype stash. for full compatibility with // Sphere 1.5, we have to allow native objects to be created through the // legacy APIs even if the corresponding constructor is overwritten or shadowed. // for that to work, the prototype must remain accessible. duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "prototypes"); duk_dup(ctx, -3); duk_put_prop_string(ctx, -2, name); duk_pop_2(ctx); // attach prototype to constructor duk_push_string(ctx, "prototype"); duk_insert(ctx, -2); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_SET_WRITABLE); duk_push_string(ctx, name); duk_insert(ctx, -2); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_SET_WRITABLE | DUK_DEFPROP_SET_CONFIGURABLE); duk_pop(ctx); } bool api_register_extension(const char* designation) { char* string; if (!(string = strdup(designation))) return false; if (!vector_push(s_extensions, &string)) return false; return true; } void api_register_function(duk_context* ctx, const char* namespace_name, const char* name, duk_c_function fn) { duk_push_global_object(ctx); // ensure the namespace object exists if (namespace_name != NULL) { if (!duk_get_prop_string(ctx, -1, namespace_name)) { duk_pop(ctx); duk_push_string(ctx, namespace_name); duk_push_object(ctx); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_SET_WRITABLE | DUK_DEFPROP_SET_CONFIGURABLE); duk_get_prop_string(ctx, -1, namespace_name); } } duk_push_string(ctx, name); duk_push_c_function(ctx, fn, DUK_VARARGS); duk_push_string(ctx, "name"); duk_push_string(ctx, name); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_SET_WRITABLE | DUK_DEFPROP_SET_CONFIGURABLE); if (namespace_name != NULL) duk_pop(ctx); duk_pop(ctx); } void api_register_method(duk_context* ctx, const char* ctor_name, const char* name, duk_c_function fn) { duk_push_global_object(ctx); if (ctor_name != NULL) { // load the prototype from the prototype stash duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "prototypes"); duk_get_prop_string(ctx, -1, ctor_name); } duk_push_c_function(ctx, fn, DUK_VARARGS); duk_push_string(ctx, "name"); duk_push_string(ctx, name); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE); // for a defprop, Duktape expects the key to be pushed first, then the value; however, since // we have the value (the function being registered) on the stack already by this point, we // need to shuffle things around to make everything work. duk_push_string(ctx, name); duk_insert(ctx, -2); duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_SET_WRITABLE | DUK_DEFPROP_SET_CONFIGURABLE); if (ctor_name != NULL) duk_pop_3(ctx); duk_pop(ctx); } void api_register_prop(duk_context* ctx, const char* ctor_name, const char* name, duk_c_function getter, duk_c_function setter) { duk_uint_t flags; int obj_index; duk_push_global_object(ctx); if (ctor_name != NULL) { duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "prototypes"); duk_get_prop_string(ctx, -1, ctor_name); } obj_index = duk_normalize_index(ctx, -1); duk_push_string(ctx, name); flags = DUK_DEFPROP_SET_CONFIGURABLE; if (getter != NULL) { duk_push_c_function(ctx, getter, DUK_VARARGS); flags |= DUK_DEFPROP_HAVE_GETTER; } if (setter != NULL) { duk_push_c_function(ctx, setter, DUK_VARARGS); flags |= DUK_DEFPROP_HAVE_SETTER; } duk_def_prop(g_duk, obj_index, flags); if (ctor_name != NULL) duk_pop_3(ctx); duk_pop(ctx); } noreturn duk_error_ni(duk_context* ctx, int blame_offset, duk_errcode_t err_code, const char* fmt, ...) { va_list ap; char* filename; int line_number; // get filename and line number from Duktape call stack duk_get_global_string(g_duk, "Duktape"); duk_get_prop_string(g_duk, -1, "act"); duk_push_int(g_duk, -2 + blame_offset); duk_call(g_duk, 1); if (!duk_is_object(g_duk, -1)) { duk_pop(g_duk); duk_get_prop_string(g_duk, -1, "act"); duk_push_int(g_duk, -2); duk_call(g_duk, 1); } duk_get_prop_string(g_duk, -1, "lineNumber"); duk_get_prop_string(g_duk, -2, "function"); duk_get_prop_string(g_duk, -1, "fileName"); filename = strdup(duk_safe_to_string(g_duk, -1)); line_number = duk_to_int(g_duk, -3); duk_pop_n(g_duk, 5); // construct an Error object va_start(ap, fmt); duk_push_error_object_va(ctx, err_code, fmt, ap); va_end(ap); duk_push_string(ctx, filename); duk_put_prop_string(ctx, -2, "fileName"); duk_push_int(ctx, line_number); duk_put_prop_string(ctx, -2, "lineNumber"); free(filename); duk_throw(ctx); } duk_bool_t duk_is_sphere_obj(duk_context* ctx, duk_idx_t index, const char* ctor_name) { const char* obj_ctor_name; duk_bool_t result; index = duk_require_normalize_index(ctx, index); if (!duk_is_object_coercible(ctx, index)) return 0; duk_get_prop_string(ctx, index, "\xFF" "ctor"); obj_ctor_name = duk_safe_to_string(ctx, -1); result = strcmp(obj_ctor_name, ctor_name) == 0; duk_pop(ctx); return result; } void duk_push_sphere_obj(duk_context* ctx, const char* ctor_name, void* udata) { duk_idx_t obj_index; duk_push_object(ctx); obj_index = duk_normalize_index(ctx, -1); duk_push_pointer(ctx, udata); duk_put_prop_string(ctx, -2, "\xFF" "udata"); duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "prototypes"); duk_get_prop_string(ctx, -1, ctor_name); if (duk_get_prop_string(ctx, -1, "\xFF" "dtor")) { duk_set_finalizer(ctx, obj_index); } else duk_pop(ctx); duk_set_prototype(ctx, obj_index); duk_pop_2(ctx); } void* duk_require_sphere_obj(duk_context* ctx, duk_idx_t index, const char* ctor_name) { void* udata; index = duk_require_normalize_index(ctx, index); if (!duk_is_sphere_obj(ctx, index, ctor_name)) duk_error(ctx, DUK_ERR_TYPE_ERROR, "expected a %s object", ctor_name); duk_get_prop_string(ctx, index, "\xFF" "udata"); udata = duk_get_pointer(ctx, -1); duk_pop(ctx); return udata; } static duk_ret_t duk_mod_search(duk_context* ctx) { vector_t* filenames; lstring_t* filename; size_t len; const char* name; char* slurp; lstring_t* source_text; iter_t iter; lstring_t* *p; name = duk_get_string(ctx, 0); if (name[0] == '~') duk_error_ni(ctx, -2, DUK_ERR_TYPE_ERROR, "SphereFS prefix not allowed in module ID"); filenames = vector_new(sizeof(lstring_t*)); filename = lstr_newf("lib/%s.js", name); vector_push(filenames, &filename); filename = lstr_newf("lib/%s.ts", name); vector_push(filenames, &filename); filename = lstr_newf("lib/%s.coffee", name); vector_push(filenames, &filename); filename = lstr_newf("#/modules/%s.js", name); vector_push(filenames, &filename); filename = lstr_newf("#/modules/%s.ts", name); vector_push(filenames, &filename); filename = lstr_newf("#/modules/%s.coffee", name); vector_push(filenames, &filename); filename = NULL; iter = vector_enum(filenames); while (p = vector_next(&iter)) { if (filename == NULL && sfs_fexist(g_fs, lstr_cstr(*p), NULL)) filename = lstr_dup(*p); lstr_free(*p); } vector_free(filenames); if (filename == NULL) duk_error_ni(ctx, -2, DUK_ERR_REFERENCE_ERROR, "CommonJS module `%s` not found", name); console_log(2, "initializing JS module `%s` as `%s`", name, lstr_cstr(filename)); if (!(slurp = sfs_fslurp(g_fs, lstr_cstr(filename), NULL, &len))) duk_error_ni(ctx, -2, DUK_ERR_ERROR, "unable to read script `%s`", lstr_cstr(filename)); source_text = lstr_from_buf(slurp, len); free(slurp); if (!transpile_to_js(&source_text, lstr_cstr(filename))) { lstr_free(source_text); duk_throw(ctx); } duk_push_lstring_t(ctx, filename); duk_put_prop_string(ctx, 3, "filename"); duk_push_lstring_t(ctx, source_text); lstr_free(source_text); lstr_free(filename); return 1; } static duk_ret_t js_GetVersion(duk_context* ctx) { duk_push_number(ctx, SPHERE_API_VERSION); return 1; } static duk_ret_t js_GetVersionString(duk_context* ctx) { duk_push_string(ctx, lstr_cstr(s_user_agent)); return 1; } static duk_ret_t js_GetExtensions(duk_context* ctx) { char** i_string; iter_t iter; int i; duk_push_array(ctx); iter = vector_enum(s_extensions); i = 0; while (i_string = vector_next(&iter)) { duk_push_string(ctx, *i_string); duk_put_prop_index(ctx, -2, i++); } return 1; } static duk_ret_t js_EvaluateScript(duk_context* ctx) { const char* filename; filename = duk_require_path(ctx, 0, "scripts", true); if (!sfs_fexist(g_fs, filename, NULL)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "EvaluateScript(): file `%s` not found", filename); if (!evaluate_script(filename)) duk_throw(ctx); return 1; } static duk_ret_t js_EvaluateSystemScript(duk_context* ctx) { const char* filename = duk_require_string(ctx, 0); char path[SPHERE_PATH_MAX]; sprintf(path, "scripts/lib/%s", filename); if (!sfs_fexist(g_fs, path, NULL)) sprintf(path, "#/scripts/%s", filename); if (!sfs_fexist(g_fs, path, NULL)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "EvaluateSystemScript(): system script `%s` not found", filename); if (!evaluate_script(path)) duk_throw(ctx); return 1; } static duk_ret_t js_RequireScript(duk_context* ctx) { const char* filename; bool is_required; filename = duk_require_path(ctx, 0, "scripts", true); if (!sfs_fexist(g_fs, filename, NULL)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RequireScript(): file `%s` not found", filename); duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "RequireScript"); duk_get_prop_string(ctx, -1, filename); is_required = duk_get_boolean(ctx, -1); duk_pop(ctx); if (!is_required) { duk_push_true(ctx); duk_put_prop_string(ctx, -2, filename); if (!evaluate_script(filename)) duk_throw(ctx); } duk_pop_3(ctx); return 0; } static duk_ret_t js_RequireSystemScript(duk_context* ctx) { const char* filename = duk_require_string(ctx, 0); bool is_required; char path[SPHERE_PATH_MAX]; sprintf(path, "scripts/lib/%s", filename); if (!sfs_fexist(g_fs, path, NULL)) sprintf(path, "#/scripts/%s", filename); if (!sfs_fexist(g_fs, path, NULL)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RequireSystemScript(): system script `%s` not found", filename); duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "RequireScript"); duk_get_prop_string(ctx, -1, path); is_required = duk_get_boolean(ctx, -1); duk_pop(ctx); if (!is_required) { duk_push_true(ctx); duk_put_prop_string(ctx, -2, path); if (!evaluate_script(path)) duk_throw(ctx); } duk_pop_2(ctx); return 0; } static duk_ret_t js_IsSkippedFrame(duk_context* ctx) { duk_push_boolean(ctx, screen_is_skipframe(g_screen)); return 1; } static duk_ret_t js_GetFrameRate(duk_context* ctx) { duk_push_int(ctx, g_framerate); return 1; } static duk_ret_t js_GetGameManifest(duk_context* ctx) { duk_push_lstring_t(ctx, get_game_manifest(g_fs)); duk_json_decode(ctx, -1); duk_push_string(ctx, path_cstr(get_game_path(g_fs))); duk_put_prop_string(ctx, -2, "directory"); return 1; } static duk_ret_t js_GetGameList(duk_context* ctx) { ALLEGRO_FS_ENTRY* file_info; ALLEGRO_FS_ENTRY* fse; path_t* path = NULL; path_t* paths[2]; sandbox_t* sandbox; int i, j = 0; // build search paths paths[0] = path_rebase(path_new("games/"), enginepath()); paths[1] = path_rebase(path_new("minisphere/games/"), homepath()); // search for supported games duk_push_array(ctx); for (i = sizeof paths / sizeof(path_t*) - 1; i >= 0; --i) { fse = al_create_fs_entry(path_cstr(paths[i])); if (al_get_fs_entry_mode(fse) & ALLEGRO_FILEMODE_ISDIR && al_open_directory(fse)) { while (file_info = al_read_directory(fse)) { path = path_new(al_get_fs_entry_name(file_info)); if (sandbox = new_sandbox(path_cstr(path))) { duk_push_lstring_t(ctx, get_game_manifest(sandbox)); duk_json_decode(ctx, -1); duk_push_string(ctx, path_cstr(path)); duk_put_prop_string(ctx, -2, "directory"); duk_put_prop_index(ctx, -2, j++); free_sandbox(sandbox); } path_free(path); } } al_destroy_fs_entry(fse); path_free(paths[i]); } return 1; } static duk_ret_t js_GetMaxFrameSkips(duk_context* ctx) { duk_push_int(ctx, screen_get_frameskip(g_screen)); return 1; } static duk_ret_t js_GetScreenHeight(duk_context* ctx) { duk_push_int(ctx, g_res_y); return 1; } static duk_ret_t js_GetScreenWidth(duk_context* ctx) { duk_push_int(ctx, g_res_x); return 1; } static duk_ret_t js_GetSeconds(duk_context* ctx) { duk_push_number(ctx, al_get_time()); return 1; } static duk_ret_t js_GetTime(duk_context* ctx) { duk_push_number(ctx, floor(al_get_time() * 1000)); return 1; } static duk_ret_t js_SetFrameRate(duk_context* ctx) { int framerate = duk_require_int(ctx, 0); if (framerate < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetFrameRate(): framerate must be positive (got: %d)", framerate); g_framerate = framerate; return 0; } static duk_ret_t js_SetMaxFrameSkips(duk_context* ctx) { int max_skips = duk_require_int(ctx, 0); if (max_skips < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetMaxFrameSkips(): value cannot be negative (%d)", max_skips); screen_set_frameskip(g_screen, max_skips); return 0; } static duk_ret_t js_SetScreenSize(duk_context* ctx) { int res_width; int res_height; res_width = duk_require_int(ctx, 0); res_height = duk_require_int(ctx, 1); if (res_width < 0 || res_height < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetScreenSize(): dimensions cannot be negative (got X: %d, Y: %d)", res_width, res_height); screen_resize(g_screen, res_width, res_height); return 0; } static duk_ret_t js_Alert(duk_context* ctx) { int n_args = duk_get_top(ctx); const char* text = n_args >= 1 && !duk_is_null_or_undefined(ctx, 0) ? duk_to_string(ctx, 0) : "It's 8:12... do you know where the pig is?\n\nIt's...\n\n\n\n\n\n\nBEHIND YOU! *MUNCH*"; int stack_offset = n_args >= 2 ? duk_require_int(ctx, 1) : 0; const char* caller_info; const char* filename; int line_number; if (stack_offset > 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Alert(): stack offset must be negative"); // get filename and line number of Alert() call duk_push_global_object(ctx); duk_get_prop_string(ctx, -1, "Duktape"); duk_get_prop_string(ctx, -1, "act"); duk_push_int(ctx, -3 + stack_offset); duk_call(ctx, 1); if (!duk_is_object(ctx, -1)) { duk_pop(ctx); duk_get_prop_string(ctx, -1, "act"); duk_push_int(ctx, -3); duk_call(ctx, 1); } duk_remove(ctx, -2); duk_get_prop_string(ctx, -1, "lineNumber"); line_number = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, -1, "function"); duk_get_prop_string(ctx, -1, "fileName"); filename = duk_get_string(ctx, -1); duk_pop(ctx); duk_pop_2(ctx); // show the message screen_show_mouse(g_screen, true); caller_info = duk_push_sprintf(ctx, "%s (line %i)", filename, line_number), duk_get_string(ctx, -1); al_show_native_message_box(screen_display(g_screen), "Alert from Sphere game", caller_info, text, NULL, 0x0); screen_show_mouse(g_screen, false); return 0; } static duk_ret_t js_Abort(duk_context* ctx) { int n_args = duk_get_top(ctx); const char* message = n_args >= 1 ? duk_to_string(ctx, 0) : "Some type of weird pig just ate your game!\n\n\n\n\n\n\n\n...and you*munch*"; int stack_offset = n_args >= 2 ? duk_require_int(ctx, 1) : 0; if (stack_offset > 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Abort(): stack offset must be negative"); duk_error_ni(ctx, -1 + stack_offset, DUK_ERR_ERROR, "%s", message); } static duk_ret_t js_Assert(duk_context* ctx) { const char* filename; int line_number; const char* message; int num_args; bool result; int stack_offset; lstring_t* text; num_args = duk_get_top(ctx); result = duk_to_boolean(ctx, 0); message = duk_require_string(ctx, 1); stack_offset = num_args >= 3 ? duk_require_int(ctx, 2) : 0; if (stack_offset > 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Assert(): stack offset must be negative"); if (!result) { // get the offending script and line number from the call stack duk_push_global_object(ctx); duk_get_prop_string(ctx, -1, "Duktape"); duk_get_prop_string(ctx, -1, "act"); duk_push_int(ctx, -3 + stack_offset); duk_call(ctx, 1); if (!duk_is_object(ctx, -1)) { duk_pop(ctx); duk_get_prop_string(ctx, -1, "act"); duk_push_int(ctx, -3); duk_call(ctx, 1); } duk_remove(ctx, -2); duk_get_prop_string(ctx, -1, "lineNumber"); line_number = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, -1, "function"); duk_get_prop_string(ctx, -1, "fileName"); filename = duk_get_string(ctx, -1); duk_pop(ctx); duk_pop_2(ctx); fprintf(stderr, "ASSERT: `%s:%i` : %s\n", filename, line_number, message); // if an assertion fails in a game being debugged: // - the user may choose to ignore it, in which case execution continues. this is useful // in some debugging scenarios. // - if the user chooses not to continue, a prompt breakpoint will be triggered, turning // over control to the attached debugger. if (is_debugger_attached()) { text = lstr_newf("%s (line: %i)\n%s\n\nYou can ignore the error, or pause execution, turning over control to the attached debugger. If you choose to debug, execution will pause at the statement following the failed Assert().\n\nIgnore the error and continue?", filename, line_number, message); if (!al_show_native_message_box(screen_display(g_screen), "Script Error", "Assertion failed!", lstr_cstr(text), NULL, ALLEGRO_MESSAGEBOX_WARN | ALLEGRO_MESSAGEBOX_YES_NO)) { duk_debugger_pause(ctx); } lstr_free(text); } } duk_dup(ctx, 0); return 1; } static duk_ret_t js_CreateStringFromCode(duk_context* ctx) { int code = duk_require_int(ctx, 0); char cstr[2]; if (code < 0 || code > 255) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "CreateStringFromCode(): character code is out of ASCII range (%i)", code); cstr[0] = (char)code; cstr[1] = '\0'; duk_push_string(ctx, cstr); return 1; } static duk_ret_t js_DebugPrint(duk_context* ctx) { int num_items; num_items = duk_get_top(ctx); // separate printed values with a space duk_push_string(ctx, " "); duk_insert(ctx, 0); // tack on a newline and concatenate the values duk_push_string(ctx, "\n"); duk_join(ctx, num_items + 1); debug_print(duk_get_string(ctx, -1)); return 0; } static duk_ret_t js_Delay(duk_context* ctx) { double millisecs = floor(duk_require_number(ctx, 0)); if (millisecs < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Delay(): delay must be positive (got: %.0f)", millisecs); delay(millisecs / 1000); return 0; } static duk_ret_t js_DoEvents(duk_context* ctx) { do_events(); duk_push_boolean(ctx, true); return 1; } static duk_ret_t js_ExecuteGame(duk_context* ctx) { path_t* games_path; const char* filename; filename = duk_require_string(ctx, 0); // store the old game path so we can relaunch when the chained game exits g_last_game_path = path_dup(get_game_path(g_fs)); // if the passed-in path is relative, resolve it relative to <engine>/games. // this is done for compatibility with Sphere 1.x. g_game_path = path_new(filename); games_path = path_rebase(path_new("games/"), enginepath()); path_rebase(g_game_path, games_path); path_free(games_path); restart_engine(); } static duk_ret_t js_Exit(duk_context* ctx) { exit_game(false); } static duk_ret_t js_FlipScreen(duk_context* ctx) { screen_flip(g_screen, g_framerate); return 0; } static duk_ret_t js_GarbageCollect(duk_context* ctx) { duk_gc(ctx, 0x0); duk_gc(ctx, 0x0); return 0; } static duk_ret_t js_Print(duk_context* ctx) { int num_items; num_items = duk_get_top(ctx); duk_push_heapptr(ctx, s_print_ptr); duk_insert(ctx, 0); duk_call(ctx, num_items); return 0; } static duk_ret_t js_RestartGame(duk_context* ctx) { restart_engine(); } static duk_ret_t js_UnskipFrame(duk_context* ctx) { screen_unskip_frame(g_screen); return 0; } <file_sep>/src/compiler/tileset.c #include "tileset.h" #include "image.h" #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <string.h> #pragma pack(push, 1) struct rts_header { uint8_t signature[4]; uint16_t version; uint16_t num_tiles; uint16_t tile_width; uint16_t tile_height; uint16_t tile_bpp; uint8_t compression; uint8_t has_obstructions; uint8_t reserved[240]; }; struct rts_tile_header { uint8_t unknown_1; uint8_t animated; int16_t next_tile; int16_t delay; uint8_t unknown_2; uint8_t obsmap_type; uint16_t num_segments; uint16_t name_length; uint8_t terraformed; uint8_t reserved[19]; }; #pragma pack(pop) void build_tileset(const path_t* path, const image_t* image, int tile_width, int tile_height) { FILE* file; ptrdiff_t pitch; const uint32_t* pixelbuf; struct rts_header rts; struct rts_tile_header tile; int x, y; int i_y; uint16_t i; memset(&rts, 0, sizeof(struct rts_header)); memcpy(&rts.signature, ".rts", 4); rts.version = 1; rts.num_tiles = (image_get_width(image) / tile_width) * (image_get_height(image) / tile_height); rts.has_obstructions = 0; rts.tile_width = (uint16_t)tile_width; rts.tile_height = (uint16_t)tile_height; rts.tile_bpp = 32; file = fopen(path_cstr(path), "wb"); fwrite(&rts, sizeof(struct rts_header), 1, file); pitch = image_get_pitch(image); x = 0; y = 0; for (i = 0; i < rts.num_tiles; ++i) { for (i_y = 0; i_y < tile_height; ++i_y) { pixelbuf = image_get_pixelbuf(image) + x + (y + i_y) * pitch; fwrite(pixelbuf, tile_width * 4, 1, file); } if ((x += tile_width) + tile_width > image_get_width(image)) { x = 0; y += tile_height; } } memset(&tile, 0, sizeof(struct rts_tile_header)); for (i = 0; i < rts.num_tiles; ++i) fwrite(&tile, sizeof(struct rts_tile_header), 1, file); fclose(file); } <file_sep>/src/debugger/main.c #include "ssj.h" #include <dyad.h> #include "inferior.h" #include "session.h" struct cmdline { path_t* path; bool run_now; }; static struct cmdline* parse_cmdline (int argc, char* argv[], int *out_retval); static void free_cmdline (struct cmdline* obj); static void print_cell_quote (void); static void print_banner (bool want_copyright, bool want_deps); static void print_usage (void); int main(int argc, char* argv[]) { struct cmdline* cmdline; inferior_t* inferior; int retval; session_t* session; if (!(cmdline = parse_cmdline(argc, argv, &retval))) return retval; print_banner(true, false); printf("\n"); if (cmdline->path != NULL && !launch_minisphere(cmdline->path)) return EXIT_FAILURE; inferiors_init(); if (!(inferior = inferior_new("127.0.0.1", 1208))) return EXIT_FAILURE; printf("\n"); session = session_new(inferior); session_run(session, cmdline->run_now); session_free(session); inferior_free(inferior); inferiors_deinit(); free_cmdline(cmdline); return EXIT_SUCCESS; } bool launch_minisphere(path_t* game_path) { #if defined(_WIN32) char* command_line; HMODULE h_module; TCHAR pathname[MAX_PATH]; printf("starting %s... ", path_cstr(game_path)); fflush(stdout); h_module = GetModuleHandle(NULL); GetModuleFileName(h_module, pathname, MAX_PATH); PathRemoveFileSpec(pathname); SetCurrentDirectory(pathname); if (!PathFileExists(TEXT(".\\spherun.exe"))) goto on_error; else { STARTUPINFOA si; PROCESS_INFORMATION pi; memset(&si, 0, sizeof(STARTUPINFOA)); si.cb = sizeof(STARTUPINFOA); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError = GetStdHandle(STD_ERROR_HANDLE); si.wShowWindow = SW_HIDE; command_line = strnewf("./spherun.exe --debug \"%s\"", path_cstr(game_path)); CreateProcessA(NULL, command_line, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi); free(command_line); printf("OK.\n"); return true; } #else path_t* path; char pathname[PATH_MAX]; ssize_t pathname_len; struct stat stat_buf; printf("starting %s... ", path_cstr(game_path)); fflush(stdout); memset(pathname, 0, sizeof pathname); pathname_len = readlink("/proc/self/exe", pathname, PATH_MAX); if (pathname_len == -1 || pathname_len == PATH_MAX) goto on_error; path = path_strip(path_new(pathname)); if (chdir(path_cstr(path)) != 0) goto on_error; path_append(path, "spherun"); if (stat(path_cstr(path), &stat_buf) != 0) goto on_error; else { if (fork() != 0) path_free(path); else { // suppress minisphere's stdout. this is kind of a hack for now; eventually // I'd like to intermingle the engine's output with SSJ's, like in native // debuggers e.g. GDB. dup2(open("/dev/null", O_WRONLY), STDOUT_FILENO); dup2(open("/dev/null", O_WRONLY), STDERR_FILENO); execlp("./spherun", "./spherun", "--debug", path_cstr(game_path), NULL); } printf("OK.\n"); return true; } #endif on_error: printf("error!\n"); return false; } char* strnewf(const char* fmt, ...) { va_list ap, apc; char* buffer; int buf_size; va_start(ap, fmt); va_copy(apc, ap); buf_size = vsnprintf(NULL, 0, fmt, apc) + 1; va_end(apc); buffer = malloc(buf_size); va_copy(apc, ap); vsnprintf(buffer, buf_size, fmt, apc); va_end(apc); va_end(ap); return buffer; } static void free_cmdline(struct cmdline* obj) { path_free(obj->path); free(obj); } static struct cmdline* parse_cmdline(int argc, char* argv[], int *out_retval) { struct cmdline* cmdline; bool have_target = false; const char* short_args; int i; size_t i_arg; // parse the command line cmdline = calloc(1, sizeof(struct cmdline)); *out_retval = EXIT_SUCCESS; for (i = 1; i < argc; ++i) { if (strstr(argv[i], "--") == argv[i]) { if (strcmp(argv[i], "--help") == 0) { print_usage(); goto on_output_only; } else if (strcmp(argv[i], "--version") == 0) { print_banner(true, true); goto on_output_only; } else if (strcmp(argv[i], "--explode") == 0) { print_cell_quote(); goto on_output_only; } else if (strcmp(argv[i], "--connect") == 0) have_target = true; else if (strcmp(argv[i], "--run") == 0) cmdline->run_now = true; else { printf("ssj: error: unknown option `%s`\n", argv[i]); goto on_output_only; } } else if (argv[i][0] == '-') { short_args = argv[i]; for (i_arg = strlen(short_args) - 1; i_arg >= 1; --i_arg) { switch (short_args[i_arg]) { case 'c': have_target = true; break; case 'r': cmdline->run_now = true; break; default: printf("ssj: error: unknown option '-%c'\n", short_args[i_arg]); *out_retval = EXIT_FAILURE; goto on_output_only; } } } else { path_free(cmdline->path); cmdline->path = path_resolve(path_new(argv[i]), NULL); if (cmdline->path == NULL) { printf("ssj: error: cannot resolve pathname `%s`\n", argv[i]); *out_retval = EXIT_FAILURE; goto on_output_only; } have_target = true; } } // sanity-check command line parameters if (!have_target) { print_usage(); goto on_output_only; } // we're good! return cmdline; on_output_only: free(cmdline); return NULL; } static void print_cell_quote(void) { static const char* const MESSAGES[] = { "I am the universe's END!!", "I expected the end to be a little more dramatic...", "Chanting a little prayer before you die?", "Don't you realize yet you're up against the perfect weapon?!", "YES! I can feel you slipping...!", "These are your last minutes, boy. So try to make them COUNT!" "Would you stop interfering!?", "You're all so anxious to die, aren't you? Well all you had to do WAS ASK!", "Why can't you people JUST STAY DOWN!!", "They just keep lining up to die!", "No chance! YOU HAVE NO CHANCE!!", "SAY GOODBYE!", "I WAS PERFECT...!", }; srand((unsigned int)time(NULL)); printf("Release it, Gohan--release everything! Remember all the pain he's caused, the\n"); printf("people he's hurt--now MAKE THAT YOUR POWER!!\n\n"); printf(" Cell says:\n \"%s\"\n", MESSAGES[rand() % (sizeof MESSAGES / sizeof(const char*))]); } static void print_banner(bool want_copyright, bool want_deps) { printf("SSJ %s Sphere JavaScript Debugger (%s)\n", VERSION_NAME, sizeof(void*) == 8 ? "x64" : "x86"); if (want_copyright) { printf("easy-to-use JavaScript debugger for minisphere\n"); printf("(c) 2015-2016 <NAME>\n"); } if (want_deps) { printf("\n"); printf(" Dyad.c: v%s\n", dyad_getVersion()); } } static void print_usage(void) { print_banner(true, false); printf("\n"); printf("USAGE:\n"); printf(" ssj [--run] <game-path>\n"); printf(" ssj -c [--run]\n"); printf("\n"); printf("OPTIONS:\n"); printf(" -c, --connect Connect to a target which has already been started. If no \n"); printf(" connection can be made within 30 seconds, SSJ will exit. \n"); printf(" -r, --run Prevent SSJ from pausing execution on attach. When starting\n"); printf(" a new instance, begin execution immediately. \n"); printf(" --version Print the version number of SSJ and its dependencies. \n"); printf(" --help Print this help text. \n"); } <file_sep>/src/engine/spherefs.c #include "minisphere.h" #include "spherefs.h" #include "file.h" #include "spk.h" enum fs_type { SPHEREFS_UNKNOWN, SPHEREFS_LOCAL, SPHEREFS_SPK, }; struct sandbox { unsigned int id; unsigned int refcount; path_t* root_path; lstring_t* manifest; lstring_t* name; lstring_t* author; lstring_t* summary; int res_x; int res_y; path_t* script_path; lstring_t* sourcemap; spk_t* spk; int type; }; struct sfs_file { enum fs_type fs_type; ALLEGRO_FILE* handle; spk_file_t* spk_file; }; static duk_ret_t duk_load_s2gm (duk_context* ctx); static bool resolve_path (sandbox_t* fs, const char* filename, const char* base_dir, path_t* *out_path, enum fs_type *out_fs_type); static unsigned int s_next_sandbox_id = 0; sandbox_t* new_sandbox(const char* game_path) { sandbox_t* fs; path_t* path; int res_x; int res_y; size_t sgm_size; kevfile_t* sgm_file; char* sgm_text = NULL; spk_t* spk; void* sourcemap_data; size_t sourcemap_size; console_log(1, "opening `%s` in sandbox #%u", game_path, s_next_sandbox_id); fs = ref_sandbox(calloc(1, sizeof(sandbox_t))); fs->id = s_next_sandbox_id; path = path_new(game_path); if (!path_resolve(path, NULL)) goto on_error; if (spk = open_spk(path_cstr(path))) { // Sphere Package (.spk) fs->type = SPHEREFS_SPK; fs->root_path = path_dup(path); fs->spk = spk; } else if (path_has_extension(path, ".sgm") || path_has_extension(path, ".s2gm")) { // game manifest fs->type = SPHEREFS_LOCAL; fs->root_path = path_strip(path_dup(path)); } else if (path_is_file(path)) { // non-SPK file, assume JS script fs->type = SPHEREFS_LOCAL; fs->root_path = path_strip(path_dup(path)); // synthesize a game manifest for the script. this way we make this trick // transparent to the rest of the engine, keeping things simple. console_log(1, "synthesizing manifest for `%s` in sandbox #%u", path_cstr(path), s_next_sandbox_id); fs->name = lstr_new(path_filename_cstr(path)); fs->author = lstr_new("Author Unknown"); fs->summary = lstr_new(path_cstr(path)); fs->res_x = 320; fs->res_y = 240; fs->script_path = path_new(path_filename_cstr(path)); duk_push_object(g_duk); duk_push_lstring_t(g_duk, fs->name); duk_put_prop_string(g_duk, -2, "name"); duk_push_lstring_t(g_duk, fs->author); duk_put_prop_string(g_duk, -2, "author"); duk_push_lstring_t(g_duk, fs->summary); duk_put_prop_string(g_duk, -2, "summary"); duk_push_sprintf(g_duk, "%dx%d", fs->res_x, fs->res_y); duk_put_prop_string(g_duk, -2, "resolution"); duk_push_string(g_duk, path_cstr(fs->script_path)); duk_put_prop_string(g_duk, -2, "script"); fs->manifest = lstr_new(duk_json_encode(g_duk, -1)); duk_pop(g_duk); } else { // default case, unpacked game folder fs->type = SPHEREFS_LOCAL; fs->root_path = path_strip(path_dup(path)); } path_free(path); path = NULL; // try to load the game manifest if one hasn't been synthesized already if (fs->name == NULL) { if (sgm_text = sfs_fslurp(fs, "game.s2gm", NULL, &sgm_size)) { console_log(1, "parsing Spherical manifest in sandbox #%u", s_next_sandbox_id); fs->manifest = lstr_from_buf(sgm_text, sgm_size); duk_push_pointer(g_duk, fs); duk_push_lstring_t(g_duk, fs->manifest); if (duk_safe_call(g_duk, duk_load_s2gm, 2, 1) != 0) { console_log(0, "error parsing JSON manifest `game.s2gm`\n %s", duk_to_string(g_duk, -1)); duk_pop(g_duk); goto on_error; } duk_pop(g_duk); free(sgm_text); sgm_text = NULL; } else if (sgm_file = kev_open(fs, "game.sgm", false)) { console_log(1, "parsing legacy manifest in sandbox #%u", s_next_sandbox_id); fs->name = lstr_new(kev_read_string(sgm_file, "name", "Untitled")); fs->author = lstr_new(kev_read_string(sgm_file, "author", "Author Unknown")); fs->summary = lstr_new(kev_read_string(sgm_file, "description", "No information available.")); fs->res_x = kev_read_float(sgm_file, "screen_width", 320); fs->res_y = kev_read_float(sgm_file, "screen_height", 240); fs->script_path = make_sfs_path(kev_read_string(sgm_file, "script", "main.js"), "scripts", true); kev_close(sgm_file); // generate a JSON manifest (used by, e.g. GetGameManifest()) duk_push_object(g_duk); duk_push_lstring_t(g_duk, fs->name); duk_put_prop_string(g_duk, -2, "name"); duk_push_lstring_t(g_duk, fs->author); duk_put_prop_string(g_duk, -2, "author"); duk_push_lstring_t(g_duk, fs->summary); duk_put_prop_string(g_duk, -2, "summary"); duk_push_sprintf(g_duk, "%dx%d", fs->res_x, fs->res_y); duk_put_prop_string(g_duk, -2, "resolution"); duk_push_string(g_duk, path_cstr(fs->script_path)); duk_put_prop_string(g_duk, -2, "script"); fs->manifest = lstr_new(duk_json_encode(g_duk, -1)); duk_pop(g_duk); } else goto on_error; } get_sgm_resolution(fs, &res_x, &res_y); console_log(1, " title: %s", get_sgm_name(fs)); console_log(1, " author: %s", get_sgm_author(fs)); console_log(1, " resolution: %ix%i", res_x, res_y); // load the source map if (sourcemap_data = sfs_fslurp(fs, "sourcemap.json", NULL, &sourcemap_size)) fs->sourcemap = lstr_from_buf(sourcemap_data, sourcemap_size); free(sourcemap_data); s_next_sandbox_id++; return fs; on_error: console_log(1, "unable to create sandbox #%u ", s_next_sandbox_id++); path_free(path); free(sgm_text); if (fs != NULL) { free_spk(fs->spk); free(fs); } return NULL; } sandbox_t* ref_sandbox(sandbox_t* fs) { if (fs == NULL) return NULL; ++fs->refcount; return fs; } void free_sandbox(sandbox_t* fs) { if (fs == NULL || --fs->refcount > 0) return; console_log(3, "disposing sandbox #%u no longer in use", fs->id); if (fs->type == SPHEREFS_SPK) free_spk(fs->spk); lstr_free(fs->sourcemap); path_free(fs->script_path); path_free(fs->root_path); lstr_free(fs->manifest); free(fs); } const lstring_t* get_game_manifest(const sandbox_t* fs) { return fs->manifest; } const path_t* get_game_path(const sandbox_t* fs) { return fs->root_path; } void get_sgm_resolution(sandbox_t* fs, int *out_width, int *out_height) { *out_width = fs->res_x; *out_height = fs->res_y; } const char* get_sgm_name(sandbox_t* fs) { return lstr_cstr(fs->name); } const char* get_sgm_author(sandbox_t* fs) { return lstr_cstr(fs->author); } const char* get_sgm_summary(sandbox_t* fs) { return lstr_cstr(fs->summary); } const path_t* get_sgm_script_path(sandbox_t* fs) { return fs->script_path; } path_t* make_sfs_path(const char* filename, const char* base_dir_name, bool legacy) { // note: make_sfs_path() collapses '../' path hops unconditionally, as per // SphereFS spec. this ensures an unpackaged game can't subvert the // sandbox by navigating outside of its directory via a symbolic link. path_t* base_path = NULL; path_t* path; char* prefix; path = path_new(filename); if (path_is_rooted(path)) // absolute path? return path; if (legacy && path_num_hops(path) >= 1 && path_hop_cmp(path, 0, "~")) { path_remove_hop(path, 0); path_insert_hop(path, 0, "@"); } base_path = path_new_dir(base_dir_name != NULL ? base_dir_name : "./"); if (path_num_hops(path) == 0) path_rebase(path, base_path); else if (path_hop_cmp(path, 0, "@")) { path_remove_hop(path, 0); path_collapse(path, true); } else if (path_hop_cmp(path, 0, "#") || path_hop_cmp(path, 0, "~")) { prefix = strdup(path_hop_cstr(path, 0)); path_remove_hop(path, 0); path_collapse(path, true); path_insert_hop(path, 0, prefix); free(prefix); } else path_rebase(path, base_path); path_collapse(path, true); path_free(base_path); return path; } vector_t* list_filenames(sandbox_t* fs, const char* dirname, const char* base_dir, bool want_dirs) { path_t* dir_path; ALLEGRO_FS_ENTRY* file_info; path_t* file_path; lstring_t* filename; enum fs_type fs_type; ALLEGRO_FS_ENTRY* fse = NULL; vector_t* list = NULL; int type_flag; if (!resolve_path(fs, dirname, base_dir, &dir_path, &fs_type)) goto on_error; if (!(list = vector_new(sizeof(lstring_t*)))) goto on_error; switch (fs_type) { case SPHEREFS_LOCAL: type_flag = want_dirs ? ALLEGRO_FILEMODE_ISDIR : ALLEGRO_FILEMODE_ISFILE; fse = al_create_fs_entry(path_cstr(dir_path)); if (al_get_fs_entry_mode(fse) & ALLEGRO_FILEMODE_ISDIR && al_open_directory(fse)) { while (file_info = al_read_directory(fse)) { file_path = path_new(al_get_fs_entry_name(file_info)); filename = lstr_new(path_filename_cstr(file_path)); if (al_get_fs_entry_mode(file_info) & type_flag) vector_push(list, &filename); path_free(file_path); al_destroy_fs_entry(file_info); } } al_destroy_fs_entry(fse); break; case SPHEREFS_SPK: list = list_spk_filenames(fs->spk, path_cstr(dir_path), want_dirs); break; } path_free(dir_path); return list; on_error: al_destroy_fs_entry(fse); path_free(dir_path); vector_free(list); return NULL; } sfs_file_t* sfs_fopen(sandbox_t* fs, const char* filename, const char* base_dir, const char* mode) { path_t* dir_path; sfs_file_t* file; path_t* file_path = NULL; file = calloc(1, sizeof(sfs_file_t)); if (!resolve_path(fs, filename, base_dir, &file_path, &file->fs_type)) goto on_error; switch (file->fs_type) { case SPHEREFS_LOCAL: if (strchr(mode, 'w') || strchr(mode, '+') || strchr(mode, 'a')) { // write access requested, ensure directory exists dir_path = path_strip(path_dup(file_path)); path_mkdir(dir_path); path_free(dir_path); } if (!(file->handle = al_fopen(path_cstr(file_path), mode))) goto on_error; break; case SPHEREFS_SPK: if (!(file->spk_file = spk_fopen(fs->spk, path_cstr(file_path), mode))) goto on_error; break; } path_free(file_path); return file; on_error: path_free(file_path); free(file); return NULL; } void sfs_fclose(sfs_file_t* file) { if (file == NULL) return; switch (file->fs_type) { case SPHEREFS_LOCAL: al_fclose(file->handle); break; case SPHEREFS_SPK: spk_fclose(file->spk_file); break; } free(file); } bool sfs_fexist(sandbox_t* fs, const char* filename, const char* base_dir) { sfs_file_t* file; if (!(file = sfs_fopen(fs, filename, base_dir, "rb"))) return false; sfs_fclose(file); return true; } int sfs_fputc(int ch, sfs_file_t* file) { switch (file->fs_type) { case SPHEREFS_LOCAL: return al_fputc(file->handle, ch); case SPHEREFS_SPK: return spk_fputc(ch, file->spk_file); default: return EOF; } } int sfs_fputs(const char* string, sfs_file_t* file) { switch (file->fs_type) { case SPHEREFS_LOCAL: return al_fputs(file->handle, string); case SPHEREFS_SPK: return spk_fputs(string, file->spk_file); default: return false; } } size_t sfs_fread(void* buf, size_t size, size_t count, sfs_file_t* file) { switch (file->fs_type) { case SPHEREFS_LOCAL: return al_fread(file->handle, buf, size * count) / size; case SPHEREFS_SPK: return spk_fread(buf, size, count, file->spk_file); default: return 0; } } void* sfs_fslurp(sandbox_t* fs, const char* filename, const char* base_dir, size_t *out_size) { sfs_file_t* file = NULL; size_t data_size; void* slurp; if (!(file = sfs_fopen(fs, filename, base_dir, "rb"))) goto on_error; sfs_fseek(file, 0, SFS_SEEK_END); data_size = sfs_ftell(file); if (!(slurp = malloc(data_size + 1))) goto on_error; sfs_fseek(file, 0, SFS_SEEK_SET); sfs_fread(slurp, data_size, 1, file); sfs_fclose(file); *((char*)slurp + data_size) = '\0'; // nifty NUL terminator if (out_size) *out_size = data_size; return slurp; on_error: sfs_fclose(file); return NULL; } bool sfs_fspew(sandbox_t* fs, const char* filename, const char* base_dir, void* buf, size_t size) { sfs_file_t* file = NULL; if (!(file = sfs_fopen(fs, filename, base_dir, "wb"))) return false; sfs_fwrite(buf, size, 1, file); sfs_fclose(file); return true; } bool sfs_fseek(sfs_file_t* file, long long offset, sfs_whence_t whence) { switch (file->fs_type) { case SPHEREFS_LOCAL: return al_fseek(file->handle, offset, whence) == 0; case SPHEREFS_SPK: return spk_fseek(file->spk_file, offset, whence); } return false; } long long sfs_ftell(sfs_file_t* file) { switch (file->fs_type) { case SPHEREFS_LOCAL: return al_ftell(file->handle); case SPHEREFS_SPK: return spk_ftell(file->spk_file); } return -1; } size_t sfs_fwrite(const void* buf, size_t size, size_t count, sfs_file_t* file) { switch (file->fs_type) { case SPHEREFS_LOCAL: return al_fwrite(file->handle, buf, size * count) / size; case SPHEREFS_SPK: return spk_fwrite(buf, size, count, file->spk_file); default: return 0; } } bool sfs_mkdir(sandbox_t* fs, const char* dirname, const char* base_dir) { enum fs_type fs_type; path_t* path; if (!resolve_path(fs, dirname, base_dir, &path, &fs_type)) return false; switch (fs_type) { case SPHEREFS_LOCAL: return path_mkdir(path); case SPHEREFS_SPK: return false; default: return false; } } bool sfs_rmdir(sandbox_t* fs, const char* dirname, const char* base_dir) { enum fs_type fs_type; path_t* path; if (!resolve_path(fs, dirname, base_dir, &path, &fs_type)) return false; switch (fs_type) { case SPHEREFS_LOCAL: return rmdir(path_cstr(path)) == 0; case SPHEREFS_SPK: return false; default: return false; } } bool sfs_rename(sandbox_t* fs, const char* name1, const char* name2, const char* base_dir) { enum fs_type fs_type; path_t* path1; path_t* path2; if (!resolve_path(fs, name1, base_dir, &path1, &fs_type)) return false; if (!resolve_path(fs, name2, base_dir, &path2, &fs_type)) return false; switch (fs_type) { case SPHEREFS_LOCAL: return rename(path_cstr(path1), path_cstr(path2)) == 0; case SPHEREFS_SPK: return false; default: return false; } } bool sfs_unlink(sandbox_t* fs, const char* filename, const char* base_dir) { enum fs_type fs_type; path_t* path; if (!resolve_path(fs, filename, base_dir, &path, &fs_type)) return false; switch (fs_type) { case SPHEREFS_LOCAL: return unlink(path_cstr(path)) == 0; case SPHEREFS_SPK: return false; default: return false; } } static duk_ret_t duk_load_s2gm(duk_context* ctx) { // arguments: -2 = sandbox_t* fs (pointer) // -1 = .s2gm JSON text (string) sandbox_t* fs; duk_idx_t json_idx; fs = duk_get_pointer(ctx, -2); json_idx = duk_normalize_index(ctx, -1); // load required entries duk_dup(ctx, json_idx); duk_json_decode(ctx, -1); if (!duk_get_prop_string(g_duk, -1, "name") || !duk_is_string(g_duk, -1)) goto on_error; fs->name = lstr_new(duk_get_string(g_duk, -1)); if (!duk_get_prop_string(g_duk, -2, "resolution") || !duk_is_string(g_duk, -1)) goto on_error; sscanf(duk_get_string(g_duk, -1), "%dx%d", &fs->res_x, &fs->res_y); if (!duk_get_prop_string(g_duk, -3, "script") || !duk_is_string(g_duk, -1)) goto on_error; fs->script_path = path_new(duk_get_string(g_duk, -1)); // game summary is optional, use a default summary if one is not provided. if (duk_get_prop_string(g_duk, -4, "author") && duk_is_string(g_duk, -1)) fs->author = lstr_new(duk_get_string(g_duk, -1)); else fs->author = lstr_new("Author Unknown"); if (duk_get_prop_string(g_duk, -5, "summary") && duk_is_string(g_duk, -1)) fs->summary = lstr_new(duk_get_string(g_duk, -1)); else fs->summary = lstr_new("No information available."); return 0; on_error: return -1; } static bool resolve_path(sandbox_t* fs, const char* filename, const char* base_dir, path_t* *out_path, enum fs_type *out_fs_type) { // the path resolver is the core of SphereFS. it handles all canonization of paths // so that the game doesn't have to care whether it's running from a local directory, // Sphere SPK package, etc. path_t* origin; *out_path = path_new(filename); if (path_is_rooted(*out_path)) { // absolute path *out_fs_type = SPHEREFS_LOCAL; return true; } path_free(*out_path); *out_path = NULL; // process SphereFS path if (strlen(filename) >= 2 && memcmp(filename, "@/", 2) == 0) { // the @/ prefix is an alias for the game directory. it is used in contexts // where a bare SphereFS filename may be ambiguous, e.g. in a require() call. if (fs == NULL) goto on_error; *out_path = path_new(filename + 2); if (fs->type == SPHEREFS_LOCAL) path_rebase(*out_path, fs->root_path); *out_fs_type = fs->type; } else if (strlen(filename) >= 2 && memcmp(filename, "~/", 2) == 0) { // the ~/ prefix refers to the user's home directory, specificially a Sphere Data subfolder // of it. this is where saved game data should be placed. *out_path = path_new(filename + 2); origin = path_rebase(path_new("minisphere/save/"), homepath()); path_rebase(*out_path, origin); path_free(origin); *out_fs_type = SPHEREFS_LOCAL; } else if (strlen(filename) >= 2 && memcmp(filename, "#/", 2) == 0) { // the #/ prefix refers to the engine's "system" directory. *out_path = path_new(filename + 2); origin = path_rebase(path_new("system/"), enginepath()); if (!path_resolve(origin, NULL)) { path_free(origin); origin = path_rebase(path_new("../share/minisphere/system/"), enginepath()); } path_rebase(*out_path, origin); path_free(origin); *out_fs_type = SPHEREFS_LOCAL; } else { // default case: assume relative path if (fs == NULL) goto on_error; *out_path = make_sfs_path(filename, base_dir, false); if (fs->type == SPHEREFS_LOCAL) // convert to absolute path path_rebase(*out_path, fs->root_path); *out_fs_type = fs->type; } return true; on_error: path_free(*out_path); *out_path = NULL; *out_fs_type = SPHEREFS_UNKNOWN; return false; } <file_sep>/src/engine/animation.h #ifndef MINISPHERE__ANIMATION_H__INCLUDED #define MINISPHERE__ANIMATION_H__INCLUDED typedef struct animation animation_t; animation_t* animation_new (const char* path); animation_t* animation_ref (animation_t* anim); void animation_free (animation_t* anim); bool animation_update (animation_t* anim); void init_animation_api (void); #endif // MINISPHERE__ANIMATION_H__INCLUDED <file_sep>/Makefile version=$(shell cat VERSION) pkgname=minisphere-$(version) ifndef prefix prefix=/usr endif installdir=$(DESTDIR)$(prefix) ifndef CC CC=cc endif ifndef CFLAGS CFLAGS=-O3 endif engine_sources=src/engine/main.c \ src/shared/duktape.c src/shared/dyad.c src/shared/mt19937ar.c \ src/shared/lstring.c src/shared/path.c src/shared/unicode.c \ src/shared/vector.c \ src/engine/animation.c src/engine/api.c src/engine/async.c \ src/engine/atlas.c src/engine/audialis.c src/engine/bytearray.c \ src/engine/color.c src/engine/console.c src/engine/debugger.c \ src/engine/file.c src/engine/font.c src/engine/galileo.c \ src/engine/geometry.c src/engine/image.c src/engine/input.c \ src/engine/logger.c src/engine/map_engine.c src/engine/matrix.c \ src/engine/obsmap.c src/engine/persons.c src/engine/rng.c \ src/engine/screen.c src/engine/script.c src/engine/shader.c \ src/engine/sockets.c src/engine/spherefs.c src/engine/spk.c \ src/engine/spriteset.c src/engine/surface.c src/engine/tileset.c \ src/engine/transpiler.c src/engine/utility.c src/engine/windowstyle.c engine_libs= \ -lallegro_acodec -lallegro_audio -lallegro_color -lallegro_dialog \ -lallegro_image -lallegro_memfile -lallegro_primitives -lallegro \ -lmng -lz -lm cell_sources=src/compiler/main.c \ src/shared/duktape.c src/shared/path.c src/shared/vector.c \ src/compiler/assets.c src/compiler/build.c src/compiler/spk_writer.c \ src/compiler/utility.c cell_libs= \ -lz -lm ssj_sources=src/debugger/main.c \ src/shared/dyad.c src/shared/path.c src/shared/vector.c \ src/debugger/backtrace.c src/debugger/dvalue.c src/debugger/help.c \ src/debugger/inferior.c src/debugger/message.c src/debugger/objview.c \ src/debugger/parser.c src/debugger/session.c src/debugger/sockets.c \ src/debugger/source.c .PHONY: all all: minisphere spherun cell ssj .PHONY: minisphere minisphere: bin/minisphere .PHONY: spherun spherun: bin/minisphere bin/spherun .PHONY: cell cell: bin/cell .PHONY: ssj ssj: bin/ssj .PHONY: deb deb: dist cp dist/minisphere-$(version).tar.gz dist/minisphere_$(version).orig.tar.gz cd dist && tar xf minisphere_$(version).orig.tar.gz cp -r src/debian dist/minisphere-$(version) cd dist/minisphere-$(version) && debuild -S -sa .PHONY: dist dist: mkdir -p dist/$(pkgname) cp -r assets desktop docs manpages src dist/$(pkgname) cp Makefile VERSION dist/$(pkgname) cp CHANGELOG.md LICENSE.txt README.md dist/$(pkgname) cd dist && tar cfz $(pkgname).tar.gz $(pkgname) && rm -rf dist/$(pkgname) .PHONY: install install: all mkdir -p $(installdir)/bin mkdir -p $(installdir)/share/minisphere mkdir -p $(installdir)/share/applications mkdir -p $(installdir)/share/doc/minisphere mkdir -p $(installdir)/share/icons/hicolor/scalable/mimetypes mkdir -p $(installdir)/share/mime/packages mkdir -p $(installdir)/share/man/man1 mkdir -p $(installdir)/share/pixmaps cp bin/minisphere bin/spherun bin/cell bin/ssj $(installdir)/bin cp -r bin/system $(installdir)/share/minisphere gzip docs/spherical-api.txt -c > $(installdir)/share/doc/minisphere/spherical-api.gz gzip docs/cellscript-api.txt -c > $(installdir)/share/doc/minisphere/cellscript-api.gz gzip docs/miniRT-api.txt -c > $(installdir)/share/doc/minisphere/miniRT-api.gz gzip manpages/minisphere.1 -c > $(installdir)/share/man/man1/minisphere.1.gz gzip manpages/spherun.1 -c > $(installdir)/share/man/man1/spherun.1.gz gzip manpages/cell.1 -c > $(installdir)/share/man/man1/cell.1.gz gzip manpages/ssj.1 -c > $(installdir)/share/man/man1/ssj.1.gz cp desktop/minisphere.desktop $(installdir)/share/applications cp desktop/sphere-icon.svg $(installdir)/share/pixmaps cp desktop/mimetypes/minisphere.xml $(installdir)/share/mime/packages cp desktop/mimetypes/*.svg $(installdir)/share/icons/hicolor/scalable/mimetypes .PHONY: clean clean: rm -rf bin rm -rf dist bin/minisphere: mkdir -p bin $(CC) -o bin/minisphere $(CFLAGS) -Isrc/shared -Isrc/engine \ -DDUK_OPT_HAVE_CUSTOM_H \ $(engine_sources) $(engine_libs) cp -r assets/system bin bin/spherun: mkdir -p bin $(CC) -o bin/spherun $(CFLAGS) -Isrc/shared -Isrc/engine \ -DDUK_OPT_HAVE_CUSTOM_H -DMINISPHERE_SPHERUN \ $(engine_sources) $(engine_libs) bin/cell: mkdir -p bin $(CC) -o bin/cell $(CFLAGS) -Isrc/shared $(cell_sources) $(cell_libs) bin/ssj: mkdir -p bin $(CC) -o bin/ssj $(CFLAGS) -Isrc/shared $(ssj_sources) <file_sep>/src/engine/duk_custom.h #include "version.h" #define DUK_USE_FASTINT #if defined(MINISPHERE_SPHERUN) #undef DUK_USE_TARGET_INFO #define DUK_USE_TARGET_INFO PRODUCT_NAME VERSION_NAME #define DUK_USE_DEBUGGER_SUPPORT #define DUK_USE_DEBUGGER_FWD_PRINTALERT #define DUK_USE_DEBUGGER_PAUSE_UNCAUGHT #define DUK_USE_DEBUGGER_INSPECT #define DUK_USE_INTERRUPT_COUNTER #endif <file_sep>/src/debugger/objview.c #include "ssj.h" #include "objview.h" #include "dvalue.h" struct entry { char* key; prop_tag_t tag; unsigned int flags; dvalue_t* getter; dvalue_t* setter; dvalue_t* value; }; struct objview { int num_props; int array_size; struct entry* props; }; objview_t* objview_new(void) { struct entry* array; int array_size = 16; objview_t* obj; array = malloc(array_size * sizeof(struct entry)); obj = calloc(1, sizeof(objview_t)); obj->props = array; obj->array_size = array_size; return obj; } void objview_free(objview_t* obj) { int i; if (obj == NULL) return; for (i = 0; i < obj->num_props; ++i) { free(obj->props[i].key); dvalue_free(obj->props[i].value); dvalue_free(obj->props[i].getter); dvalue_free(obj->props[i].setter); } free(obj); } unsigned int objview_get_flags(const objview_t* obj, int index) { return obj->props[index].flags; } int objview_len(const objview_t* obj) { return obj->num_props; } prop_tag_t objview_get_tag(const objview_t* obj, int index) { return obj->props[index].tag; } const char* objview_get_key(const objview_t* obj, int index) { return obj->props[index].key; } const dvalue_t* objview_get_getter(const objview_t* obj, int index) { return obj->props[index].tag == PROP_ACCESSOR ? obj->props[index].getter : NULL; } const dvalue_t* objview_get_setter(const objview_t* obj, int index) { return obj->props[index].tag == PROP_ACCESSOR ? obj->props[index].setter : NULL; } const dvalue_t* objview_get_value(const objview_t* obj, int index) { return obj->props[index].tag == PROP_VALUE ? obj->props[index].value : NULL; } void objview_add_accessor(objview_t* obj, const char* key, const dvalue_t* getter, const dvalue_t* setter, unsigned int flags) { int idx; idx = obj->num_props++; if (obj->num_props > obj->array_size) { obj->array_size *= 2; obj->props = realloc(obj->props, obj->array_size * sizeof(struct entry)); } obj->props[idx].tag = PROP_ACCESSOR; obj->props[idx].key = strdup(key); obj->props[idx].value = NULL; obj->props[idx].getter = dvalue_dup(getter); obj->props[idx].setter = dvalue_dup(setter); obj->props[idx].flags = flags; } void objview_add_value(objview_t* obj, const char* key, const dvalue_t* value, unsigned int flags) { int idx; idx = obj->num_props++; if (obj->num_props > obj->array_size) { obj->array_size *= 2; obj->props = realloc(obj->props, obj->array_size * sizeof(struct entry)); } obj->props[idx].tag = PROP_VALUE; obj->props[idx].key = strdup(key); obj->props[idx].value = dvalue_dup(value); obj->props[idx].getter = NULL; obj->props[idx].setter = NULL; obj->props[idx].flags = flags; } <file_sep>/src/debugger/dvalue.c #include "ssj.h" #include "dvalue.h" #include "sockets.h" const char* const CLASS_NAMES[] = { "unknown", "arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", "String", "global", "ObjEnv", "DecEnv", "Buffer", "Pointer", "Thread", "ArrayBuffer", "DataView", "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array", }; struct dvalue { enum dvalue_tag tag; union { double float_value; int int_value; struct { remote_ptr_t value; uint8_t class; } ptr; struct { void* data; size_t size; } buffer; }; }; static void print_duktape_ptr(remote_ptr_t ptr) { if (ptr.size == 8) // x64 pointer printf("%016"PRIx64"h", (uint64_t)ptr.addr); else if (ptr.size == 4) // x86 pointer printf("%08"PRIx32"h", (uint32_t)ptr.addr); } dvalue_t* dvalue_new(dvalue_tag_t tag) { dvalue_t* obj; obj = calloc(1, sizeof(dvalue_t)); obj->tag = tag; return obj; } dvalue_t* dvalue_new_float(double value) { dvalue_t* obj; obj = calloc(1, sizeof(dvalue_t)); obj->tag = DVALUE_FLOAT; obj->float_value = value; return obj; } dvalue_t* dvalue_new_heapptr(remote_ptr_t value) { dvalue_t* obj; obj = calloc(1, sizeof(dvalue_t)); obj->tag = DVALUE_HEAPPTR; obj->ptr.value.addr = value.addr; obj->ptr.value.size = value.size; return obj; } dvalue_t* dvalue_new_int(int value) { dvalue_t* obj; obj = calloc(1, sizeof(dvalue_t)); obj->tag = DVALUE_INT; obj->int_value = value; return obj; } dvalue_t* dvalue_new_string(const char* value) { dvalue_t* obj; obj = calloc(1, sizeof(dvalue_t)); obj->tag = DVALUE_STRING; obj->buffer.data = strdup(value); obj->buffer.size = strlen(value); return obj; } dvalue_t* dvalue_dup(const dvalue_t* src) { dvalue_t* obj; obj = calloc(1, sizeof(dvalue_t)); memcpy(obj, src, sizeof(dvalue_t)); if (obj->tag == DVALUE_STRING || obj->tag == DVALUE_BUFFER) { obj->buffer.data = malloc(src->buffer.size + 1); memcpy(obj->buffer.data, src->buffer.data, src->buffer.size + 1); } return obj; } void dvalue_free(dvalue_t* obj) { if (obj == NULL) return; if (obj->tag == DVALUE_STRING || obj->tag == DVALUE_BUFFER) free(obj->buffer.data); free(obj); } dvalue_tag_t dvalue_tag(const dvalue_t* obj) { return obj->tag; } const char* dvalue_as_cstr(const dvalue_t* obj) { return obj->tag == DVALUE_STRING ? obj->buffer.data : NULL; } double dvalue_as_float(const dvalue_t* obj) { return obj->tag == DVALUE_FLOAT ? obj->float_value : obj->tag == DVALUE_INT ? (double)obj->int_value : 0.0; } remote_ptr_t dvalue_as_ptr(const dvalue_t* obj) { remote_ptr_t retval; memset(&retval, 0, sizeof(remote_ptr_t)); if (obj->tag == DVALUE_PTR || obj->tag == DVALUE_HEAPPTR || obj->tag == DVALUE_OBJ || obj->tag == DVALUE_LIGHTFUNC) { retval.addr = obj->ptr.value.addr; retval.size = obj->ptr.value.size; } return retval; } int dvalue_as_int(const dvalue_t* obj) { return obj->tag == DVALUE_INT ? obj->int_value : obj->tag == DVALUE_FLOAT ? (int)obj->float_value : 0; } void dvalue_print(const dvalue_t* obj, bool is_verbose) { switch (dvalue_tag(obj)) { case DVALUE_UNDEF: printf("undefined"); break; case DVALUE_UNUSED: printf("unused"); break; case DVALUE_NULL: printf("null"); break; case DVALUE_TRUE: printf("true"); break; case DVALUE_FALSE: printf("false"); break; case DVALUE_FLOAT: printf("%g", obj->float_value); break; case DVALUE_INT: printf("%d", obj->int_value); break; case DVALUE_STRING: printf("\"%s\"", (char*)obj->buffer.data); break; case DVALUE_BUFFER: printf("{buf:\"%zd bytes\"}", obj->buffer.size); break; case DVALUE_HEAPPTR: printf("{heap:\""); print_duktape_ptr(dvalue_as_ptr(obj)); printf("\"}"); break; case DVALUE_LIGHTFUNC: printf("{lightfunc:\""); print_duktape_ptr(dvalue_as_ptr(obj)); printf("\"}"); break; case DVALUE_OBJ: if (!is_verbose) printf("{...}"); else { printf("{ obj:`%s` }", CLASS_NAMES[obj->ptr.class]); } break; case DVALUE_PTR: printf("{ptr:\""); print_duktape_ptr(dvalue_as_ptr(obj)); printf("\"}"); break; default: printf("*munch*"); } } dvalue_t* dvalue_recv(socket_t* socket) { dvalue_t* obj; uint8_t data[32]; uint8_t ib; int read_size; ptrdiff_t i, j; obj = calloc(1, sizeof(dvalue_t)); if (socket_recv(socket, &ib, 1) == 0) goto lost_connection; obj->tag = (enum dvalue_tag)ib; switch (ib) { case DVALUE_INT: if (socket_recv(socket, data, 4) == 0) goto lost_connection; obj->tag = DVALUE_INT; obj->int_value = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]; break; case DVALUE_STRING: if (socket_recv(socket, data, 4) == 0) goto lost_connection; obj->buffer.size = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]; obj->buffer.data = calloc(1, obj->buffer.size + 1); read_size = (int)obj->buffer.size; if (socket_recv(socket, obj->buffer.data, read_size) != read_size) goto lost_connection; obj->tag = DVALUE_STRING; break; case DVALUE_STRING16: if (socket_recv(socket, data, 2) == 0) goto lost_connection; obj->buffer.size = (data[0] << 8) + data[1]; obj->buffer.data = calloc(1, obj->buffer.size + 1); read_size = (int)obj->buffer.size; if (socket_recv(socket, obj->buffer.data, read_size) != read_size) goto lost_connection; obj->tag = DVALUE_STRING; break; case DVALUE_BUFFER: if (socket_recv(socket, data, 4) == 0) goto lost_connection; obj->buffer.size = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]; obj->buffer.data = calloc(1, obj->buffer.size + 1); read_size = (int)obj->buffer.size; if (socket_recv(socket, obj->buffer.data, read_size) != read_size) goto lost_connection; obj->tag = DVALUE_BUFFER; break; case DVALUE_BUF16: if (socket_recv(socket, data, 2) == 0) goto lost_connection; obj->buffer.size = (data[0] << 8) + data[1]; obj->buffer.data = calloc(1, obj->buffer.size + 1); read_size = (int)obj->buffer.size; if (socket_recv(socket, obj->buffer.data, read_size) != read_size) goto lost_connection; obj->tag = DVALUE_BUFFER; break; case DVALUE_FLOAT: if (socket_recv(socket, data, 8) == 0) goto lost_connection; ((uint8_t*)&obj->float_value)[0] = data[7]; ((uint8_t*)&obj->float_value)[1] = data[6]; ((uint8_t*)&obj->float_value)[2] = data[5]; ((uint8_t*)&obj->float_value)[3] = data[4]; ((uint8_t*)&obj->float_value)[4] = data[3]; ((uint8_t*)&obj->float_value)[5] = data[2]; ((uint8_t*)&obj->float_value)[6] = data[1]; ((uint8_t*)&obj->float_value)[7] = data[0]; obj->tag = DVALUE_FLOAT; break; case DVALUE_OBJ: if (socket_recv(socket, &obj->ptr.class, 1) == 0) goto lost_connection; if (socket_recv(socket, &obj->ptr.value.size, 1) == 0) goto lost_connection; if (socket_recv(socket, data, obj->ptr.value.size) == 0) goto lost_connection; obj->tag = DVALUE_OBJ; for (i = 0, j = obj->ptr.value.size - 1; j >= 0; ++i, --j) ((uint8_t*)&obj->ptr.value.addr)[i] = data[j]; break; case DVALUE_PTR: if (socket_recv(socket, &obj->ptr.value.size, 1) == 0) goto lost_connection; if (socket_recv(socket, data, obj->ptr.value.size) == 0) goto lost_connection; obj->tag = DVALUE_PTR; for (i = 0, j = obj->ptr.value.size - 1; j >= 0; ++i, --j) ((uint8_t*)&obj->ptr.value.addr)[i] = data[j]; break; case DVALUE_LIGHTFUNC: if (socket_recv(socket, data, 2) == 0) goto lost_connection; if (socket_recv(socket, &obj->ptr.value.size, 1) == 0) goto lost_connection; if (socket_recv(socket, data, obj->ptr.value.size) == 0) goto lost_connection; obj->tag = DVALUE_LIGHTFUNC; for (i = 0, j = obj->ptr.value.size - 1; j >= 0; ++i, --j) ((uint8_t*)&obj->ptr.value.addr)[i] = data[j]; break; case DVALUE_HEAPPTR: if (socket_recv(socket, &obj->ptr.value.size, 1) == 0) goto lost_connection; if (socket_recv(socket, data, obj->ptr.value.size) == 0) goto lost_connection; obj->tag = DVALUE_HEAPPTR; for (i = 0, j = obj->ptr.value.size - 1; j >= 0; ++i, --j) ((uint8_t*)&obj->ptr.value.addr)[i] = data[j]; break; default: if (ib >= 0x60 && ib <= 0x7F) { obj->tag = DVALUE_STRING; obj->buffer.size = ib - 0x60; obj->buffer.data = calloc(1, obj->buffer.size + 1); read_size = (int)obj->buffer.size; if (socket_recv(socket, obj->buffer.data, read_size) != read_size) goto lost_connection; } else if (ib >= 0x80 && ib <= 0xBF) { obj->tag = DVALUE_INT; obj->int_value = ib - 0x80; } else if (ib >= 0xC0) { if (socket_recv(socket, data, 1) == 0) goto lost_connection; obj->tag = DVALUE_INT; obj->int_value = ((ib - 0xC0) << 8) + data[0]; } } return obj; lost_connection: free(obj); return NULL; } bool dvalue_send(const dvalue_t* obj, socket_t* socket) { uint8_t data[32]; uint32_t str_length; ptrdiff_t i, j; data[0] = (uint8_t)obj->tag; socket_send(socket, data, 1); switch (obj->tag) { case DVALUE_INT: data[0] = (uint8_t)(obj->int_value >> 24 & 0xFF); data[1] = (uint8_t)(obj->int_value >> 16 & 0xFF); data[2] = (uint8_t)(obj->int_value >> 8 & 0xFF); data[3] = (uint8_t)(obj->int_value & 0xFF); socket_send(socket, data, 4); break; case DVALUE_STRING: str_length = (uint32_t)strlen(obj->buffer.data); data[0] = (uint8_t)(str_length >> 24 & 0xFF); data[1] = (uint8_t)(str_length >> 16 & 0xFF); data[2] = (uint8_t)(str_length >> 8 & 0xFF); data[3] = (uint8_t)(str_length & 0xFF); socket_send(socket, data, 4); socket_send(socket, obj->buffer.data, (int)str_length); break; case DVALUE_FLOAT: data[0] = ((uint8_t*)&obj->float_value)[7]; data[1] = ((uint8_t*)&obj->float_value)[6]; data[2] = ((uint8_t*)&obj->float_value)[5]; data[3] = ((uint8_t*)&obj->float_value)[4]; data[4] = ((uint8_t*)&obj->float_value)[3]; data[5] = ((uint8_t*)&obj->float_value)[2]; data[6] = ((uint8_t*)&obj->float_value)[1]; data[7] = ((uint8_t*)&obj->float_value)[0]; socket_send(socket, data, 8); break; case DVALUE_HEAPPTR: for (i = 0, j = obj->ptr.value.size - 1; j >= 0; ++i, --j) data[i] = ((uint8_t*)&obj->ptr.value.addr)[j]; socket_send(socket, &obj->ptr.value.size, 1); socket_send(socket, data, obj->ptr.value.size); break; } return socket_is_live(socket); } <file_sep>/src/engine/async.h #ifndef MINISPHERE__ASYNC_H__INCLUDED #define MINISPHERE__ASYNC_H__INCLUDED #include "script.h" bool initialize_async (void); void shutdown_async (void); void update_async (void); bool queue_async_script (script_t* script); void init_async_api (void); #endif // MINISPHERE__ASYNC_H__INCLUDED <file_sep>/RELEASES.md Release Notes ============= minisphere 3.1 -------------- * SphereFS prefixes have changed. Single-character prefixes are now used for SphereFS paths instead of the `~usr`, `~sgm`, and `~sys` aliases used in previous versions. Any code depending on the old prefixes will need to be updated. * The user data folder has been renamed to "minisphere". This was done to be more friendly to Linux users, for whom filenames with spaces are often inconvenient. If you need to keep your save data from minisphere 3.0, move it into `<documents>/minisphere/save`. * The Galileo API has been updated with new features. These improvements bring some minor breaking changes with them as well. Refer to the API reference for details. * The search path for CommonJS modules has changed since 3.0. Modules are now searched for in `@/lib/` instead of `@/commonjs/`. * `ListeningSocket` has been renamed to `Server`. Networking code will need to be updated. minisphere 3.0 -------------- * SphereFS sandboxing is more comprehensive. API calls taking filenames no longer accept absolute paths, and will throw a sandbox violation error if one is given. As this behavior matches Sphere 1.x, few if any games should be affected by the change. * minisphere 3.0 stores user data in a different location than past versions. Any save data stored in `<documents>/minisphere` will need to be moved into `<documents>/Sphere 2.0/saveData` to be picked up by the new version. * miniRT has been overhauled for the 3.0 release and is now provided in the form of CommonJS modules. Games will no longer be able to pull in miniRT globally using `RequireSystemScript()` and should instead use `require()` to get at the individual modules making up of the library. Games relying on the older miniRT bits will need to be updated. * When using the SSJ command-line debugger, source code is downloaded directly from minisphere without accessing the original source tree (which need not be present). When CoffeeScript or TypeScript are used, the JavaScript code generated by the transpiler, not the original source, will be provided to the debugger. * CommonJS module resolution has changed. Previously the engine searched for modules in `~sgm/modules`. minisphere 3.0 changes this to `~sgm/commonjs`. * `Assert()` behavior differs from past releases. Failing asserts will no longer throw, and minisphere completely ignores the error if no debugger is attached. This was done for consistency with assert semantics in other programming languages. * When a debugger is attached, minisphere 3.0 co-opts the `F12` key, normally used to take screenshots, for the purpose of triggering a prompt breakpoint. This may be surprising for those who arenít expecting it. * TypeScript support in minisphere 3.0 is mostly provisional. In order to maintain normal Sphere script semantics, the TypeScript compiler API `ts.transpile()` is used to convert TypeScript to JavaScript before running the code. While this allows all valid TypeScript syntax, some features such as compiler-enforced typing and module import will likely not be available. * Official Windows builds of minisphere are compiled against Allegro 5.1. Linux builds are compiled against Allegro 5.0 instead, which disables several features. Notably, Galileo shader support is lost. If a game attempts to construct a `ShaderProgram` object in a minisphere build compiled against Allegro 5.0, the constructor will throw an error. Games using shaders should be prepared to handle the error. * If SSJ terminates prematurely during a debugging session, either because of a crash or due to accidentally pressing `Ctrl+C`, minisphere will wait up to 30 seconds for the debugger to reconnect. During this time, you may enter `ssj -c` on the command line to connect to the running engine instance and pick up where you left off. <file_sep>/src/engine/rng.c #include "minisphere.h" #include "api.h" #include "mt19937ar.h" #include "rng.h" static duk_ret_t js_RNG_seed (duk_context* ctx); static duk_ret_t js_RNG_chance (duk_context* ctx); static duk_ret_t js_RNG_normal (duk_context* ctx); static duk_ret_t js_RNG_random (duk_context* ctx); static duk_ret_t js_RNG_range (duk_context* ctx); static duk_ret_t js_RNG_sample (duk_context* ctx); static duk_ret_t js_RNG_string (duk_context* ctx); static duk_ret_t js_RNG_uniform (duk_context* ctx); static const char* const RNG_STRING_CORPUS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static long s_corpus_size; void initialize_rng(void) { unsigned long seed; console_log(1, "initializing random number generator"); seed = (unsigned long)time(NULL); console_log(2, " initial seed: %lu", seed); init_genrand(seed); s_corpus_size = (long)strlen(RNG_STRING_CORPUS); } void seed_rng(unsigned long seed) { console_log(2, "seeding random number generator"); console_log(2, " seed value: %lu", seed); init_genrand(seed); } bool rng_chance(double odds) { return odds > genrand_real2(); } double rng_normal(double mean, double sigma) { static bool s_have_y = false; static double s_y; double u, v, w; double x; if (!s_have_y) { do { u = 2.0 * genrand_res53() - 1.0; v = 2.0 * genrand_res53() - 1.0; w = u * u + v * v; } while (w >= 1.0); w = sqrt(-2 * log(w) / w); x = u * w; s_y = v * w; s_have_y = true; } else { x = s_y; s_have_y = false; } return mean + x * sigma; } double rng_random(void) { return genrand_res53(); } long rng_ranged(long lower, long upper) { long range = abs(upper - lower) + 1; return (lower < upper ? lower : upper) + genrand_int31() % range; } const char* rng_string(int length) { static char s_name[256]; long index; int i; for (i = 0; i < length; ++i) { index = rng_ranged(0, s_corpus_size - 1); s_name[i] = RNG_STRING_CORPUS[index]; } s_name[length - 1] = '\0'; return s_name; } double rng_uniform(double mean, double variance) { double error; error = variance * 2 * (0.5 - genrand_real2()); return mean + error; } void init_rng_api(void) { api_register_function(g_duk, "RNG", "seed", js_RNG_seed); api_register_function(g_duk, "RNG", "chance", js_RNG_chance); api_register_function(g_duk, "RNG", "normal", js_RNG_normal); api_register_function(g_duk, "RNG", "random", js_RNG_random); api_register_function(g_duk, "RNG", "range", js_RNG_range); api_register_function(g_duk, "RNG", "sample", js_RNG_sample); api_register_function(g_duk, "RNG", "string", js_RNG_string); api_register_function(g_duk, "RNG", "uniform", js_RNG_uniform); } static duk_ret_t js_RNG_seed(duk_context* ctx) { unsigned long new_seed; new_seed = duk_require_number(ctx, 0); seed_rng(new_seed); return 0; } static duk_ret_t js_RNG_chance(duk_context* ctx) { double odds; odds = duk_require_number(ctx, 0); duk_push_boolean(ctx, rng_chance(odds)); return 1; } static duk_ret_t js_RNG_normal(duk_context* ctx) { double mean; double sigma; mean = duk_require_number(ctx, 0); sigma = duk_require_number(ctx, 1); duk_push_number(ctx, rng_normal(mean, sigma)); return 1; } static duk_ret_t js_RNG_random(duk_context* ctx) { duk_push_number(ctx, rng_random()); return 1; } static duk_ret_t js_RNG_range(duk_context* ctx) { long lower; long upper; lower = duk_require_number(ctx, 0); upper = duk_require_number(ctx, 1); duk_push_number(ctx, rng_ranged(lower, upper)); return 1; } static duk_ret_t js_RNG_sample(duk_context* ctx) { duk_uarridx_t index; long length; duk_require_object_coercible(ctx, 0); length = (long)duk_get_length(ctx, 0); index = rng_ranged(0, length - 1); duk_get_prop_index(ctx, 0, index); return 1; } static duk_ret_t js_RNG_string(duk_context* ctx) { int num_args; int length; num_args = duk_get_top(ctx); length = num_args >= 1 ? duk_require_number(ctx, 0) : 10; if (length < 1 || length > 255) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "RNG.string(): length must be [1-255] (got: %d)", length); duk_push_string(ctx, rng_string(length)); return 1; } static duk_ret_t js_RNG_uniform(duk_context* ctx) { double mean; double variance; mean = duk_require_number(ctx, 0); variance = duk_require_number(ctx, 1); duk_push_number(ctx, rng_uniform(mean, variance)); return 1; } <file_sep>/src/engine/obsmap.c #include "minisphere.h" #include "obsmap.h" struct obsmap { unsigned int id; int num_lines; int max_lines; rect_t *lines; }; static unsigned int s_next_obsmap_id = 0; obsmap_t* obsmap_new(void) { obsmap_t* obsmap = NULL; console_log(4, "creating new obstruction map #%u", s_next_obsmap_id); obsmap = calloc(1, sizeof(obsmap_t)); obsmap->max_lines = 0; obsmap->num_lines = 0; obsmap->id = s_next_obsmap_id++; return obsmap; } void obsmap_free(obsmap_t* obsmap) { if (obsmap == NULL) return; console_log(4, "disposing obstruction map #%u no longer in use", obsmap->id); free(obsmap->lines); free(obsmap); } bool obsmap_add_line(obsmap_t* obsmap, rect_t line) { int new_size; rect_t *line_list; console_log(4, "adding line segment (%i,%i)-(%i,%i) to obstruction map #%u", line.x1, line.y1, line.x2, line.y2, obsmap->id); if (obsmap->num_lines + 1 > obsmap->max_lines) { new_size = (obsmap->num_lines + 1) * 2; if ((line_list = realloc(obsmap->lines, new_size * sizeof(rect_t))) == NULL) return false; obsmap->max_lines = new_size; obsmap->lines = line_list; } obsmap->lines[obsmap->num_lines] = line; ++obsmap->num_lines; return true; } bool obsmap_test_line(const obsmap_t* obsmap, rect_t line) { int i; for (i = 0; i < obsmap->num_lines; ++i) { if (do_lines_intersect(line, obsmap->lines[i])) return true; } return false; } bool obsmap_test_rect(const obsmap_t* obsmap, rect_t rect) { return obsmap_test_line(obsmap, new_rect(rect.x1, rect.y1, rect.x2, rect.y1)) || obsmap_test_line(obsmap, new_rect(rect.x2, rect.y1, rect.x2, rect.y2)) || obsmap_test_line(obsmap, new_rect(rect.x1, rect.y2, rect.x2, rect.y2)) || obsmap_test_line(obsmap, new_rect(rect.x1, rect.y1, rect.x1, rect.y2)); } <file_sep>/src/compiler/assets.h #ifndef CELL__ASSETS_H__INCLUDED #define CELL__ASSETS_H__INCLUDED #include <time.h> typedef struct asset asset_t; typedef struct sgm_info { char name[256]; char author[256]; char description[256]; int width; int height; char script[256]; } sgm_info_t; extern asset_t* asset_new_file (const path_t* path); extern asset_t* asset_new_raw (const path_t* name, const void* buffer, size_t size, time_t src_mtime); extern asset_t* asset_new_sgm (sgm_info_t sgm, time_t src_mtime); extern void asset_free (asset_t* asset); extern const path_t* asset_name (const asset_t* asset); extern const path_t* asset_object_path (const asset_t* asset); extern bool asset_build (asset_t* asset, const path_t* int_path, bool *out_is_new); #endif // CELL__ASSETS_H__INCLUDED <file_sep>/src/shared/vector.c // WARNING: be careful when using this! // to cut down on the number of casts needed when using this generic vector implementation, // void pointers are thrown around with abandon. as a result, it is not type safe at all // and WILL blow up in your face if you're careless with it. you have been warned! #include "vector.h" #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <string.h> static bool vector_resize (vector_t* vector, size_t min_items); struct vector { size_t pitch; uint8_t* buffer; size_t num_items; size_t max_items; }; vector_t* vector_new(size_t pitch) { vector_t* vector; if (!(vector = calloc(1, sizeof(vector_t)))) return NULL; vector->pitch = pitch; vector_resize(vector, 8); return vector; } vector_t* vector_dup(const vector_t* vector) { vector_t* copy; copy = vector_new(vector->pitch); vector_resize(copy, vector->num_items); memcpy(copy->buffer, vector->buffer, vector->pitch * vector->num_items); return copy; } void vector_free(vector_t* vector) { if (vector == NULL) return; free(vector->buffer); free(vector); } void* vector_get(const vector_t* vector, size_t index) { return vector->buffer + index * vector->pitch; } void vector_set(vector_t* vector, size_t index, const void* in_object) { uint8_t* p_item; p_item = vector->buffer + index * vector->pitch; memcpy(p_item, in_object, vector->pitch); } size_t vector_len(const vector_t* vector) { return vector->num_items; } void vector_clear(vector_t* vector) { vector->num_items = 0; vector_resize(vector, 8); } bool vector_push(vector_t* vector, const void* in_object) { if (!vector_resize(vector, vector->num_items + 1)) return false; memcpy(vector->buffer + vector->num_items * vector->pitch, in_object, vector->pitch); ++vector->num_items; return true; } void vector_remove(vector_t* vector, size_t index) { size_t move_size; uint8_t* p_item; --vector->num_items; move_size = (vector->num_items - index) * vector->pitch; p_item = vector->buffer + index * vector->pitch; memmove(p_item, p_item + vector->pitch, move_size); vector_resize(vector, vector->num_items); } vector_t* vector_sort(vector_t* vector, int (*comparer)(const void* in_a, const void* in_b)) { qsort(vector->buffer, vector->num_items, vector->pitch, comparer); return vector; } iter_t vector_enum(vector_t* vector) { iter_t iter; iter.vector = vector; iter.ptr = NULL; iter.index = -1; return iter; } void* vector_next(iter_t* iter) { const vector_t* vector; void* p_tail; vector = iter->vector; iter->ptr = iter->ptr != NULL ? (uint8_t*)iter->ptr + vector->pitch : vector->buffer; ++iter->index; p_tail = vector->buffer + vector->num_items * vector->pitch; return (iter->ptr < p_tail) ? iter->ptr : NULL; } void iter_remove(iter_t* iter) { vector_t* vector; vector = iter->vector; vector_remove(vector, iter->index); --iter->index; iter->ptr = iter->index >= 0 ? vector->buffer + iter->index * vector->pitch : NULL; } static bool vector_resize(vector_t* vector, size_t min_items) { uint8_t* new_buffer; size_t new_max; new_max = vector->max_items; if (min_items > vector->max_items) // is the buffer too small? new_max = min_items * 2; else if (min_items < vector->max_items / 4) // if item count drops below 1/4 of peak size, shrink the buffer new_max = min_items * 2; if (new_max != vector->max_items) { if (!(new_buffer = realloc(vector->buffer, new_max * vector->pitch)) && new_max > 0) return false; vector->buffer = new_buffer; vector->max_items = new_max; } return true; } <file_sep>/src/compiler/spk_writer.c #include "cell.h" #include "spk_writer.h" #include "vector.h" #pragma pack(push, 1) struct spk_header { char magic[4]; uint16_t version; uint32_t num_files; uint32_t idx_offset; uint8_t reserved[2]; }; #pragma pack(pop) struct spk_entry { char* pathname; uint32_t offset; uint32_t file_size; uint32_t pack_size; }; struct spk_writer { FILE* file; vector_t* index; }; spk_writer_t* spk_create(const char* filename) { const uint16_t VERSION = 1; spk_writer_t* writer; writer = calloc(1, sizeof(spk_writer_t)); if (!(writer->file = fopen(filename, "wb"))) return NULL; fseek(writer->file, sizeof(struct spk_header), SEEK_SET); writer->index = vector_new(sizeof(struct spk_entry)); return writer; } void spk_close(spk_writer_t* writer) { const uint16_t VERSION = 1; struct spk_header hdr; uint32_t idx_offset; uint16_t path_size; struct spk_entry *p_entry; iter_t iter; if (writer == NULL) return; // write package index idx_offset = ftell(writer->file); iter = vector_enum(writer->index); while (p_entry = vector_next(&iter)) { // for compatibility with Sphere 1.5, we have to include the NUL terminator // in the filename. this, despite the fact that there is an explicit length // field in the header... path_size = (uint16_t)strlen(p_entry->pathname) + 1; fwrite(&VERSION, sizeof(uint16_t), 1, writer->file); fwrite(&path_size, sizeof(uint16_t), 1, writer->file); fwrite(&p_entry->offset, sizeof(uint32_t), 1, writer->file); fwrite(&p_entry->file_size, sizeof(uint32_t), 1, writer->file); fwrite(&p_entry->pack_size, sizeof(uint32_t), 1, writer->file); fwrite(p_entry->pathname, 1, path_size, writer->file); // free the pathname buffer now, we no longer need it and // it saves us a few lines of code later. free(p_entry->pathname); } // write the SPK header fseek(writer->file, 0, SEEK_SET); memset(&hdr, 0, sizeof(struct spk_header)); memcpy(hdr.magic, ".spk", 4); hdr.version = 1; hdr.num_files = (uint32_t)vector_len(writer->index); hdr.idx_offset = idx_offset; fwrite(&hdr, sizeof(struct spk_header), 1, writer->file); // finally, close the file fclose(writer->file); vector_free(writer->index); free(writer); } bool spk_add_file(spk_writer_t* writer, const char* filename, const char* spk_pathname) { uLong bufsize; struct spk_entry idx_entry; FILE* file; void* file_data = NULL; long file_size; long offset; void* packdata; if (!(file = fopen(filename, "rb"))) goto on_error; fseek(file, 0, SEEK_END); file_size = ftell(file); fseek(file, 0, SEEK_SET); file_data = malloc(file_size); if (fread(file_data, 1, file_size, file) != file_size) goto on_error; fclose(file); packdata = malloc(bufsize = compressBound(file_size)); compress(packdata, &bufsize, file_data, file_size); offset = ftell(writer->file); fwrite(packdata, bufsize, 1, writer->file); free(file_data); free(packdata); idx_entry.pathname = strdup(spk_pathname); idx_entry.file_size = file_size; idx_entry.pack_size = bufsize; idx_entry.offset = offset; vector_push(writer->index, &idx_entry); return true; on_error: free(file_data); return false; } <file_sep>/src/shared/unicode.c // utf8decode function (c) 2008-2010 <NAME> <<EMAIL>> // See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. #include "unicode.h" #include <stddef.h> #include <stdint.h> static const uint8_t utf8d[] = { // The first part of the table maps bytes to character classes that // to reduce the size of the transition table and create bitmasks. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, // The second part is a transition table that maps a combination // of a state of the automaton and a character class to a state. 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12, 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,12,12,12,12,12, }; uint32_t utf8decode(uint32_t* state, uint32_t* codep, uint8_t byte) { uint32_t type = utf8d[byte]; *codep = (*state != UTF8_ACCEPT) ? (byte & 0x3fu) | (*codep << 6) : (0xff >> type) & (byte); *state = utf8d[256 + *state + type]; return *state; } size_t utf8len(const char* string) { uint8_t byte; uint32_t cp; size_t length = 0; uint32_t utf8state; while ((byte = *string++) != '\0') { utf8state = UTF8_ACCEPT; while (utf8decode(&utf8state, &cp, byte) > UTF8_REJECT); ++length; } return length; } <file_sep>/INSTALL.md minisphere Installation Instructions ==================================== minisphere compiles on all three major platforms (Windows, Linux, and OS X). This file contains instructions for how to compile and install the engine on each platform. Windows ------- You can build a complete 32- or 64-bit distribution of minisphere using the included Visual Studio solution `minisphere.sln` located in `msvs/`. Visual Studio 2015 or later is required; as of this writing, Visual Studio Community 2015 can be downloaded free of charge from here: [Download Visual Studio Community 2015] (https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx) Allegro is provided through NuGet, and static libraries and/or source are included for all other dependencies, so no additional software is required to build for Windows. Linux ----- minisphere depends on Allegro 5 (5.1 or later is recommended), libmng, and zlib. libmng and zlib are usually available through your distribution's package manager, but Allegro 5.1 is considered "unstable" and likely won't be available through that channel. You can build against Allegro 5.0, but this version has some fairly major bugs and is not recommended except as a last resort. If you're running Ubuntu, there are PPA packages available for Allegro 5.1 here: <https://launchpad.net/~allegro/+archive/ubuntu/5.1> Otherwise, you can compile and install Allegro yourself. Clone the Allegro repository from GitHub and follow the installation instructions found in `README_make.txt` to get Allegro set up on your system. [Allegro 5 GitHub Repository] (https://github.com/liballeg/allegro5) Once you have Allegro and other necessary dependencies installed, simply switch to the directory where you checked out minisphere and run `make` on the command-line. This will build minisphere and all GDK tools in `bin/`. To install minisphere on your system, follow this up with `sudo make install`. Mac OS X -------- Building minisphere for OS X is very similar to Linux and uses Make as well. The dependencies are the same; however, it's not necessary to build Allegro 5.1 yourself if you have Homebrew. To get Allegro installed, simply run `brew install --devel allegro` from the command line. Then switch to the directory where you checked out minisphere and run `make`. <file_sep>/src/engine/surface.h #ifndef MINISPHERE__SURFACE_H__INCLUDED #define MINISPHERE__SURFACE_H__INCLUDED #include "image.h" void init_surface_api (void); typedef enum blend_mode { BLEND_BLEND, BLEND_REPLACE, BLEND_RGB_ONLY, BLEND_ALPHA_ONLY, BLEND_ADD, BLEND_SUBTRACT, BLEND_MULTIPLY, BLEND_AVERAGE, BLEND_INVERT, BLEND_MAX } blend_mode_t; #endif // MINISPHERE__SURFACE_H__INCLUDED <file_sep>/src/engine/surface.c #include "minisphere.h" #include "api.h" #include "color.h" #include "image.h" #include "surface.h" static uint8_t* duk_require_rgba_lut (duk_context* ctx, duk_idx_t index); static void apply_blend_mode (int blend_mode); static void reset_blender (void); static duk_ret_t js_GrabSurface (duk_context* ctx); static duk_ret_t js_CreateSurface (duk_context* ctx); static duk_ret_t js_LoadSurface (duk_context* ctx); static duk_ret_t js_new_Surface (duk_context* ctx); static duk_ret_t js_Surface_finalize (duk_context* ctx); static duk_ret_t js_Surface_get_height (duk_context* ctx); static duk_ret_t js_Surface_get_width (duk_context* ctx); static duk_ret_t js_Surface_toString (duk_context* ctx); static duk_ret_t js_Surface_getPixel (duk_context* ctx); static duk_ret_t js_Surface_setAlpha (duk_context* ctx); static duk_ret_t js_Surface_setBlendMode (duk_context* ctx); static duk_ret_t js_Surface_setPixel (duk_context* ctx); static duk_ret_t js_Surface_applyColorFX (duk_context* ctx); static duk_ret_t js_Surface_applyColorFX4 (duk_context* ctx); static duk_ret_t js_Surface_applyLookup (duk_context* ctx); static duk_ret_t js_Surface_blit (duk_context* ctx); static duk_ret_t js_Surface_blitMaskSurface (duk_context* ctx); static duk_ret_t js_Surface_blitSurface (duk_context* ctx); static duk_ret_t js_Surface_clone (duk_context* ctx); static duk_ret_t js_Surface_cloneSection (duk_context* ctx); static duk_ret_t js_Surface_createImage (duk_context* ctx); static duk_ret_t js_Surface_drawText (duk_context* ctx); static duk_ret_t js_Surface_filledCircle (duk_context* ctx); static duk_ret_t js_Surface_flipHorizontally (duk_context* ctx); static duk_ret_t js_Surface_flipVertically (duk_context* ctx); static duk_ret_t js_Surface_gradientCircle (duk_context* ctx); static duk_ret_t js_Surface_gradientRectangle (duk_context* ctx); static duk_ret_t js_Surface_line (duk_context* ctx); static duk_ret_t js_Surface_outlinedCircle (duk_context* ctx); static duk_ret_t js_Surface_outlinedRectangle (duk_context* ctx); static duk_ret_t js_Surface_pointSeries (duk_context* ctx); static duk_ret_t js_Surface_rotate (duk_context* ctx); static duk_ret_t js_Surface_rectangle (duk_context* ctx); static duk_ret_t js_Surface_replaceColor (duk_context* ctx); static duk_ret_t js_Surface_rescale (duk_context* ctx); static duk_ret_t js_Surface_save (duk_context* ctx); void init_surface_api(void) { // register Surface API functions api_register_method(g_duk, NULL, "GrabSurface", js_GrabSurface); // register Surface API constants api_register_const(g_duk, "BLEND", BLEND_BLEND); api_register_const(g_duk, "REPLACE", BLEND_REPLACE); api_register_const(g_duk, "RGB_ONLY", BLEND_RGB_ONLY); api_register_const(g_duk, "ALPHA_ONLY", BLEND_ALPHA_ONLY); api_register_const(g_duk, "ADD", BLEND_ADD); api_register_const(g_duk, "SUBTRACT", BLEND_SUBTRACT); api_register_const(g_duk, "MULTIPLY", BLEND_MULTIPLY); api_register_const(g_duk, "AVERAGE", BLEND_AVERAGE); api_register_const(g_duk, "INVERT", BLEND_INVERT); // register Surface methods and properties api_register_method(g_duk, NULL, "CreateSurface", js_CreateSurface); api_register_method(g_duk, NULL, "LoadSurface", js_LoadSurface); api_register_ctor(g_duk, "Surface", js_new_Surface, js_Surface_finalize); api_register_method(g_duk, "Surface", "toString", js_Surface_toString); api_register_prop(g_duk, "Surface", "height", js_Surface_get_height, NULL); api_register_prop(g_duk, "Surface", "width", js_Surface_get_width, NULL); api_register_method(g_duk, "Surface", "getPixel", js_Surface_getPixel); api_register_method(g_duk, "Surface", "setAlpha", js_Surface_setAlpha); api_register_method(g_duk, "Surface", "setBlendMode", js_Surface_setBlendMode); api_register_method(g_duk, "Surface", "setPixel", js_Surface_setPixel); api_register_method(g_duk, "Surface", "applyColorFX", js_Surface_applyColorFX); api_register_method(g_duk, "Surface", "applyColorFX4", js_Surface_applyColorFX4); api_register_method(g_duk, "Surface", "applyLookup", js_Surface_applyLookup); api_register_method(g_duk, "Surface", "blit", js_Surface_blit); api_register_method(g_duk, "Surface", "blitMaskSurface", js_Surface_blitMaskSurface); api_register_method(g_duk, "Surface", "blitSurface", js_Surface_blitSurface); api_register_method(g_duk, "Surface", "clone", js_Surface_clone); api_register_method(g_duk, "Surface", "cloneSection", js_Surface_cloneSection); api_register_method(g_duk, "Surface", "createImage", js_Surface_createImage); api_register_method(g_duk, "Surface", "drawText", js_Surface_drawText); api_register_method(g_duk, "Surface", "filledCircle", js_Surface_filledCircle); api_register_method(g_duk, "Surface", "flipHorizontally", js_Surface_flipHorizontally); api_register_method(g_duk, "Surface", "flipVertically", js_Surface_flipVertically); api_register_method(g_duk, "Surface", "gradientCircle", js_Surface_gradientCircle); api_register_method(g_duk, "Surface", "gradientRectangle", js_Surface_gradientRectangle); api_register_method(g_duk, "Surface", "line", js_Surface_line); api_register_method(g_duk, "Surface", "outlinedCircle", js_Surface_outlinedCircle); api_register_method(g_duk, "Surface", "outlinedRectangle", js_Surface_outlinedRectangle); api_register_method(g_duk, "Surface", "pointSeries", js_Surface_pointSeries); api_register_method(g_duk, "Surface", "rotate", js_Surface_rotate); api_register_method(g_duk, "Surface", "rectangle", js_Surface_rectangle); api_register_method(g_duk, "Surface", "replaceColor", js_Surface_replaceColor); api_register_method(g_duk, "Surface", "rescale", js_Surface_rescale); api_register_method(g_duk, "Surface", "save", js_Surface_save); } static uint8_t* duk_require_rgba_lut(duk_context* ctx, duk_idx_t index) { uint8_t* lut; int length; int i; index = duk_require_normalize_index(ctx, index); duk_require_object_coercible(ctx, index); lut = malloc(sizeof(uint8_t) * 256); length = fmin(duk_get_length(ctx, index), 256); for (i = length; i < 256; ++i) lut[i] = i; for (i = 0; i < length; ++i) { duk_get_prop_index(ctx, index, i); lut[i] = fmin(fmax(duk_require_int(ctx, -1), 0), 255); duk_pop(ctx); } return lut; } static void apply_blend_mode(int blend_mode) { switch (blend_mode) { case BLEND_BLEND: al_set_separate_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, ALLEGRO_ADD, ALLEGRO_INVERSE_DEST_COLOR, ALLEGRO_ONE); break; case BLEND_REPLACE: al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO); break; case BLEND_ADD: al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ONE); break; case BLEND_SUBTRACT: al_set_blender(ALLEGRO_DEST_MINUS_SRC, ALLEGRO_ONE, ALLEGRO_ONE); break; case BLEND_MULTIPLY: al_set_separate_blender(ALLEGRO_ADD, ALLEGRO_DEST_COLOR, ALLEGRO_ZERO, ALLEGRO_ADD, ALLEGRO_ZERO, ALLEGRO_ONE); break; case BLEND_INVERT: al_set_separate_blender(ALLEGRO_ADD, ALLEGRO_ZERO, ALLEGRO_INVERSE_SRC_COLOR, ALLEGRO_ADD, ALLEGRO_ZERO, ALLEGRO_ONE); break; } } static void reset_blender(void) { al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA); } static duk_ret_t js_GrabSurface(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int w = duk_require_int(ctx, 2); int h = duk_require_int(ctx, 3); image_t* image; if (!(image = screen_grab(g_screen, x, y, w, h))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GrabSurface(): unable to grab backbuffer image"); duk_push_sphere_obj(ctx, "Surface", image); return 1; } static duk_ret_t js_CreateSurface(duk_context* ctx) { return js_new_Surface(ctx); } static duk_ret_t js_LoadSurface(duk_context* ctx) { // LoadSurface(filename); (legacy) // Constructs a new Surface object from an image file. // Arguments: // filename: The name of the image file, relative to @/images. const char* filename; image_t* image; filename = duk_require_path(ctx, 0, "images", true); if (!(image = load_image(filename))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "LoadSurface(): unable to load image file `%s`", filename); duk_push_sphere_obj(ctx, "Surface", image); return 1; } static duk_ret_t js_new_Surface(duk_context* ctx) { int n_args; const char* filename; color_t fill_color; image_t* image; image_t* src_image; int width, height; n_args = duk_get_top(ctx); if (n_args >= 2) { width = duk_require_int(ctx, 0); height = duk_require_int(ctx, 1); fill_color = n_args >= 3 ? duk_require_sphere_color(ctx, 2) : color_new(0, 0, 0, 0); if (!(image = create_image(width, height))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface(): unable to create new surface"); fill_image(image, fill_color); } else if (duk_is_sphere_obj(ctx, 0, "Image")) { src_image = duk_require_sphere_image(ctx, 0); if (!(image = clone_image(src_image))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface(): unable to create surface from image"); } else { filename = duk_require_path(ctx, 0, NULL, false); image = load_image(filename); if (image == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface(): unable to load image file `%s`", filename); } duk_push_sphere_obj(ctx, "Surface", image); return 1; } static duk_ret_t js_Surface_finalize(duk_context* ctx) { image_t* image; image = duk_require_sphere_obj(ctx, 0, "Surface"); free_image(image); return 0; } static duk_ret_t js_Surface_get_height(duk_context* ctx) { image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_push_int(ctx, get_image_height(image)); return 1; } static duk_ret_t js_Surface_get_width(duk_context* ctx) { image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_push_int(ctx, get_image_width(image)); return 1; } static duk_ret_t js_Surface_toString(duk_context* ctx) { duk_push_string(ctx, "[object surface]"); return 1; } static duk_ret_t js_Surface_setPixel(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); color_t color = duk_require_sphere_color(ctx, 2); image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); set_image_pixel(image, x, y, color); return 0; } static duk_ret_t js_Surface_getPixel(duk_context* ctx) { int height; image_t* image; color_t pixel; int width; int x; int y; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); x = duk_require_int(ctx, 0); y = duk_require_int(ctx, 1); width = get_image_width(image); height = get_image_height(image); if (x < 0 || x >= width || y < 0 || y >= height) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Surface:getPixel(): X/Y out of range (%i,%i) for %ix%i surface", x, y, width, height); pixel = get_image_pixel(image, x, y); duk_push_sphere_color(ctx, pixel); return 1; } static duk_ret_t js_Surface_applyColorFX(duk_context* ctx) { colormatrix_t matrix; int height; int width; int x; int y; image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); x = duk_require_int(ctx, 0); y = duk_require_int(ctx, 1); width = duk_require_int(ctx, 2); height = duk_require_int(ctx, 3); matrix = duk_require_sphere_colormatrix(ctx, 4); if (x < 0 || y < 0 || x + width > get_image_width(image) || y + height > get_image_height(image)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Surface:applyColorFX(): area of effect extends past image (%i,%i,%i,%i)", x, y, width, height); if (!apply_color_matrix(image, matrix, x, y, width, height)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:applyColorFX(): unable to apply transformation"); return 0; } static duk_ret_t js_Surface_applyColorFX4(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int w = duk_require_int(ctx, 2); int h = duk_require_int(ctx, 3); colormatrix_t ul_mat = duk_require_sphere_colormatrix(ctx, 4); colormatrix_t ur_mat = duk_require_sphere_colormatrix(ctx, 5); colormatrix_t ll_mat = duk_require_sphere_colormatrix(ctx, 6); colormatrix_t lr_mat = duk_require_sphere_colormatrix(ctx, 7); image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); if (x < 0 || y < 0 || x + w > get_image_width(image) || y + h > get_image_height(image)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Surface:applyColorFX4(): area of effect extends past image (%i,%i,%i,%i)", x, y, w, h); if (!apply_color_matrix_4(image, ul_mat, ur_mat, ll_mat, lr_mat, x, y, w, h)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:applyColorFX4(): unable to apply transformation"); return 0; } static duk_ret_t js_Surface_applyLookup(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int w = duk_require_int(ctx, 2); int h = duk_require_int(ctx, 3); uint8_t* red_lu = duk_require_rgba_lut(ctx, 4); uint8_t* green_lu = duk_require_rgba_lut(ctx, 5); uint8_t* blue_lu = duk_require_rgba_lut(ctx, 6); uint8_t* alpha_lu = duk_require_rgba_lut(ctx, 7); image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); if (x < 0 || y < 0 || x + w > get_image_width(image) || y + h > get_image_height(image)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Surface:applyColorFX(): area of effect extends past image (%i,%i,%i,%i)", x, y, w, h); if (!apply_image_lookup(image, x, y, w, h, red_lu, green_lu, blue_lu, alpha_lu)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:applyLookup(): unable to apply lookup transformation"); free(red_lu); free(green_lu); free(blue_lu); free(alpha_lu); return 0; } static duk_ret_t js_Surface_blit(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); if (!screen_is_skipframe(g_screen)) al_draw_bitmap(get_image_bitmap(image), x, y, 0x0); return 0; } static duk_ret_t js_Surface_blitMaskSurface(duk_context* ctx) { image_t* src_image = duk_require_sphere_obj(ctx, 0, "Surface"); int x = duk_require_int(ctx, 1); int y = duk_require_int(ctx, 2); color_t mask = duk_require_sphere_color(ctx, 3); int blend_mode; image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); al_draw_tinted_bitmap(get_image_bitmap(src_image), nativecolor(mask), x, y, 0x0); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); return 0; } static duk_ret_t js_Surface_blitSurface(duk_context* ctx) { image_t* src_image = duk_require_sphere_obj(ctx, 0, "Surface"); int x = duk_require_int(ctx, 1); int y = duk_require_int(ctx, 2); int blend_mode; image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); al_draw_bitmap(get_image_bitmap(src_image), x, y, 0x0); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); return 0; } static duk_ret_t js_Surface_clone(duk_context* ctx) { image_t* image; image_t* new_image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); if ((new_image = clone_image(image)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:clone() - Unable to create new surface image"); duk_push_sphere_obj(ctx, "Surface", new_image); return 1; } static duk_ret_t js_Surface_cloneSection(duk_context* ctx) { int height; image_t* image; image_t* new_image; int width; int x; int y; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); x = duk_require_int(ctx, 0); y = duk_require_int(ctx, 1); width = duk_require_int(ctx, 2); height = duk_require_int(ctx, 3); if ((new_image = create_image(width, height)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:cloneSection(): unable to create surface"); al_set_target_bitmap(get_image_bitmap(new_image)); al_draw_bitmap_region(get_image_bitmap(image), x, y, width, height, 0, 0, 0x0); al_set_target_backbuffer(screen_display(g_screen)); duk_push_sphere_obj(ctx, "Surface", new_image); return 1; } static duk_ret_t js_Surface_createImage(duk_context* ctx) { image_t* image; image_t* new_image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); if ((new_image = clone_image(image)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:createImage(): unable to create image"); duk_push_sphere_image(ctx, new_image); free_image(new_image); return 1; } static duk_ret_t js_Surface_drawText(duk_context* ctx) { font_t* font = duk_require_sphere_obj(ctx, 0, "Font"); int x = duk_require_int(ctx, 1); int y = duk_require_int(ctx, 2); const char* text = duk_to_string(ctx, 3); int blend_mode; color_t color; image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, 0, "\xFF" "color_mask"); color = duk_require_sphere_color(ctx, -1); duk_pop(ctx); apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); draw_text(font, color, x, y, TEXT_ALIGN_LEFT, text); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); return 0; } static duk_ret_t js_Surface_filledCircle(duk_context* ctx) { int x = duk_require_number(ctx, 0); int y = duk_require_number(ctx, 1); int radius = duk_require_number(ctx, 2); color_t color = duk_require_sphere_color(ctx, 3); int blend_mode; image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); al_draw_filled_circle(x, y, radius, nativecolor(color)); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); return 0; } static duk_ret_t js_Surface_flipHorizontally(duk_context* ctx) { image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_pop(ctx); flip_image(image, true, false); return 0; } static duk_ret_t js_Surface_flipVertically(duk_context* ctx) { image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_pop(ctx); flip_image(image, false, true); return 0; } static duk_ret_t js_Surface_gradientCircle(duk_context* ctx) { static ALLEGRO_VERTEX s_vbuf[128]; int x = duk_require_number(ctx, 0); int y = duk_require_number(ctx, 1); int radius = duk_require_number(ctx, 2); color_t in_color = duk_require_sphere_color(ctx, 3); color_t out_color = duk_require_sphere_color(ctx, 4); int blend_mode; image_t* image; double phi; int vcount; int i; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); vcount = fmin(radius, 126); s_vbuf[0].x = x; s_vbuf[0].y = y; s_vbuf[0].z = 0; s_vbuf[0].color = nativecolor(in_color); for (i = 0; i < vcount; ++i) { phi = 2 * M_PI * i / vcount; s_vbuf[i + 1].x = x + cos(phi) * radius; s_vbuf[i + 1].y = y - sin(phi) * radius; s_vbuf[i + 1].z = 0; s_vbuf[i + 1].color = nativecolor(out_color); } s_vbuf[i + 1].x = x + cos(0) * radius; s_vbuf[i + 1].y = y - sin(0) * radius; s_vbuf[i + 1].z = 0; s_vbuf[i + 1].color = nativecolor(out_color); al_draw_prim(s_vbuf, NULL, NULL, 0, vcount + 2, ALLEGRO_PRIM_TRIANGLE_FAN); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); return 0; } static duk_ret_t js_Surface_gradientRectangle(duk_context* ctx) { int x1 = duk_require_int(ctx, 0); int y1 = duk_require_int(ctx, 1); int x2 = x1 + duk_require_int(ctx, 2); int y2 = y1 + duk_require_int(ctx, 3); color_t color_ul = duk_require_sphere_color(ctx, 4); color_t color_ur = duk_require_sphere_color(ctx, 5); color_t color_lr = duk_require_sphere_color(ctx, 6); color_t color_ll = duk_require_sphere_color(ctx, 7); int blend_mode; image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); ALLEGRO_VERTEX verts[] = { { x1, y1, 0, 0, 0, nativecolor(color_ul) }, { x2, y1, 0, 0, 0, nativecolor(color_ur) }, { x1, y2, 0, 0, 0, nativecolor(color_ll) }, { x2, y2, 0, 0, 0, nativecolor(color_lr) } }; al_draw_prim(verts, NULL, NULL, 0, 4, ALLEGRO_PRIM_TRIANGLE_STRIP); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); return 0; } static duk_ret_t js_Surface_line(duk_context* ctx) { float x1 = duk_require_int(ctx, 0) + 0.5; float y1 = duk_require_int(ctx, 1) + 0.5; float x2 = duk_require_int(ctx, 2) + 0.5; float y2 = duk_require_int(ctx, 3) + 0.5; color_t color = duk_require_sphere_color(ctx, 4); int blend_mode; image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); al_draw_line(x1, y1, x2, y2, nativecolor(color), 1); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); return 0; } static duk_ret_t js_Surface_outlinedCircle(duk_context* ctx) { int x = duk_require_number(ctx, 0); int y = duk_require_number(ctx, 1); int radius = duk_require_number(ctx, 2); color_t color = duk_require_sphere_color(ctx, 3); int blend_mode; image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); al_draw_circle(x, y, radius, nativecolor(color), 1); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); return 0; } static duk_ret_t js_Surface_pointSeries(duk_context* ctx) { color_t color = duk_require_sphere_color(ctx, 1); int blend_mode; image_t* image; size_t num_points; int x, y; ALLEGRO_VERTEX* vertices; ALLEGRO_COLOR vtx_color; unsigned int i; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); if (!duk_is_array(ctx, 0)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:pointSeries(): first argument must be an array"); duk_get_prop_string(ctx, 0, "length"); num_points = duk_get_uint(ctx, 0); duk_pop(ctx); if (num_points > INT_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Surface:pointSeries(): too many vertices (%u)", num_points); vertices = calloc(num_points, sizeof(ALLEGRO_VERTEX)); vtx_color = nativecolor(color); for (i = 0; i < num_points; ++i) { duk_get_prop_index(ctx, 0, i); duk_get_prop_string(ctx, 0, "x"); x = duk_require_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, 0, "y"); y = duk_require_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); vertices[i].x = x + 0.5; vertices[i].y = y + 0.5; vertices[i].color = vtx_color; } apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); al_draw_prim(vertices, NULL, NULL, 0, (int)num_points, ALLEGRO_PRIM_POINT_LIST); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); free(vertices); return 0; } static duk_ret_t js_Surface_outlinedRectangle(duk_context* ctx) { int n_args = duk_get_top(ctx); float x1 = duk_require_int(ctx, 0) + 0.5; float y1 = duk_require_int(ctx, 1) + 0.5; float x2 = x1 + duk_require_int(ctx, 2) - 1; float y2 = y1 + duk_require_int(ctx, 3) - 1; color_t color = duk_require_sphere_color(ctx, 4); int thickness = n_args >= 6 ? duk_require_int(ctx, 5) : 1; int blend_mode; image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); al_draw_rectangle(x1, y1, x2, y2, nativecolor(color), thickness); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); return 0; } static duk_ret_t js_Surface_replaceColor(duk_context* ctx) { color_t color = duk_require_sphere_color(ctx, 0); color_t new_color = duk_require_sphere_color(ctx, 1); image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_pop(ctx); if (!replace_image_color(image, color, new_color)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:replaceColor() - Failed to perform replacement"); return 0; } static duk_ret_t js_Surface_rescale(duk_context* ctx) { int width = duk_require_int(ctx, 0); int height = duk_require_int(ctx, 1); image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_pop(ctx); if (!rescale_image(image, width, height)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:rescale() - Failed to rescale image"); duk_push_this(ctx); return 1; } static duk_ret_t js_Surface_rotate(duk_context* ctx) { int n_args = duk_get_top(ctx); float angle = duk_require_number(ctx, 0); bool want_resize = n_args >= 2 ? duk_require_boolean(ctx, 1) : true; image_t* image; image_t* new_image; int new_w, new_h; int w, h; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_pop(ctx); w = new_w = get_image_width(image); h = new_h = get_image_height(image); if (want_resize) { // TODO: implement in-place resizing for Surface:rotate() } if ((new_image = create_image(new_w, new_h)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:rotate() - Failed to create new surface bitmap"); al_set_target_bitmap(get_image_bitmap(new_image)); al_draw_rotated_bitmap(get_image_bitmap(image), (float)w / 2, (float)h / 2, (float)new_w / 2, (float)new_h / 2, angle, 0x0); al_set_target_backbuffer(screen_display(g_screen)); // free old image and replace internal image pointer // at one time this was an acceptable thing to do; now it's just a hack free_image(image); duk_push_this(ctx); duk_push_pointer(ctx, new_image); duk_put_prop_string(ctx, -2, "\xFF" "udata"); return 1; } static duk_ret_t js_Surface_rectangle(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int w = duk_require_int(ctx, 2); int h = duk_require_int(ctx, 3); color_t color = duk_require_sphere_color(ctx, 4); image_t* image; int blend_mode; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_get_prop_string(ctx, -1, "\xFF" "blend_mode"); blend_mode = duk_get_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); apply_blend_mode(blend_mode); al_set_target_bitmap(get_image_bitmap(image)); al_draw_filled_rectangle(x, y, x + w, y + h, nativecolor(color)); al_set_target_backbuffer(screen_display(g_screen)); reset_blender(); return 0; } static duk_ret_t js_Surface_save(duk_context* ctx) { const char* filename; image_t* image; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_pop(ctx); filename = duk_require_path(ctx, 0, "images", true); save_image(image, filename); return 1; } static duk_ret_t js_Surface_setAlpha(duk_context* ctx) { int n_args = duk_get_top(ctx); int alpha = duk_require_int(ctx, 0); bool want_all = n_args >= 2 ? duk_require_boolean(ctx, 1) : true; image_t* image; image_lock_t* lock; color_t* pixel; int w, h; int i_x, i_y; duk_push_this(ctx); image = duk_require_sphere_obj(ctx, -1, "Surface"); duk_pop(ctx); if (!(lock = lock_image(image))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Surface:setAlpha(): unable to lock surface"); w = get_image_width(image); h = get_image_height(image); alpha = alpha < 0 ? 0 : alpha > 255 ? 255 : alpha; for (i_y = h - 1; i_y >= 0; --i_y) for (i_x = w - 1; i_x >= 0; --i_x) { pixel = &lock->pixels[i_x + i_y * lock->pitch]; pixel->alpha = want_all || pixel->alpha != 0 ? alpha : pixel->alpha; } unlock_image(image, lock); return 0; } static duk_ret_t js_Surface_setBlendMode(duk_context* ctx) { duk_push_this(ctx); duk_dup(ctx, 0); duk_put_prop_string(ctx, -2, "\xFF" "blend_mode"); duk_pop(ctx); return 0; } <file_sep>/src/engine/logger.c #include "minisphere.h" #include "api.h" #include "lstring.h" #include "logger.h" struct logger { unsigned int refcount; unsigned int id; sfs_file_t* file; int num_blocks; int max_blocks; struct log_block* blocks; }; struct log_block { lstring_t* name; }; static duk_ret_t js_OpenLog (duk_context* ctx); static duk_ret_t js_new_Logger (duk_context* ctx); static duk_ret_t js_Logger_finalize (duk_context* ctx); static duk_ret_t js_Logger_toString (duk_context* ctx); static duk_ret_t js_Logger_beginBlock (duk_context* ctx); static duk_ret_t js_Logger_endBlock (duk_context* ctx); static duk_ret_t js_Logger_write (duk_context* ctx); static unsigned int s_next_logger_id = 0; logger_t* log_open(const char* filename) { lstring_t* log_entry; logger_t* logger = NULL; time_t now; char timestamp[100]; console_log(2, "creating logger #%u for `%s`", s_next_logger_id, filename); logger = calloc(1, sizeof(logger_t)); if (!(logger->file = sfs_fopen(g_fs, filename, NULL, "a"))) goto on_error; time(&now); strftime(timestamp, 100, "%a %Y %b %d %H:%M:%S", localtime(&now)); log_entry = lstr_newf("LOG OPENED: %s\n", timestamp); sfs_fputs(lstr_cstr(log_entry), logger->file); lstr_free(log_entry); logger->id = s_next_logger_id++; return log_ref(logger); on_error: // oh no! console_log(2, "failed to open file for logger #%u", s_next_logger_id++); free(logger); return NULL; } logger_t* log_ref(logger_t* logger) { ++logger->refcount; return logger; } void log_close(logger_t* logger) { lstring_t* log_entry; time_t now; char timestamp[100]; if (logger == NULL || --logger->refcount > 0) return; console_log(3, "disposing logger #%u no longer in use", logger->id); time(&now); strftime(timestamp, 100, "%a %Y %b %d %H:%M:%S", localtime(&now)); log_entry = lstr_newf("LOG CLOSED: %s\n\n", timestamp); sfs_fputs(lstr_cstr(log_entry), logger->file); lstr_free(log_entry); sfs_fclose(logger->file); free(logger); } bool log_begin_block(logger_t* logger, const char* title) { lstring_t* block_name; struct log_block* blocks; int new_count; new_count = logger->num_blocks + 1; if (new_count > logger->max_blocks) { if (!(blocks = realloc(logger->blocks, new_count * 2))) return false; logger->blocks = blocks; logger->max_blocks = new_count * 2; } if (!(block_name = lstr_newf("%s", title))) return false; log_write(logger, "BEGIN", lstr_cstr(block_name)); logger->blocks[logger->num_blocks].name = block_name; ++logger->num_blocks; return true; } void log_end_block(logger_t* logger) { lstring_t* block_name; --logger->num_blocks; block_name = logger->blocks[logger->num_blocks].name; log_write(logger, "END", lstr_cstr(block_name)); lstr_free(block_name); } void log_write(logger_t* logger, const char* prefix, const char* text) { time_t now; char timestamp[100]; int i; time(&now); strftime(timestamp, 100, "%a %Y %b %d %H:%M:%S -- ", localtime(&now)); sfs_fputs(timestamp, logger->file); for (i = 0; i < logger->num_blocks; ++i) sfs_fputc('\t', logger->file); if (prefix != NULL) { sfs_fputs(prefix, logger->file); sfs_fputc(' ', logger->file); } sfs_fputs(text, logger->file); sfs_fputc('\n', logger->file); } void init_logging_api(void) { // Logger object api_register_method(g_duk, NULL, "OpenLog", js_OpenLog); api_register_ctor(g_duk, "Logger", js_new_Logger, js_Logger_finalize); api_register_method(g_duk, "Logger", "toString", js_Logger_toString); api_register_method(g_duk, "Logger", "beginBlock", js_Logger_beginBlock); api_register_method(g_duk, "Logger", "endBlock", js_Logger_endBlock); api_register_method(g_duk, "Logger", "write", js_Logger_write); } static duk_ret_t js_OpenLog(duk_context* ctx) { const char* filename; logger_t* logger; filename = duk_require_path(ctx, 0, "logs", true); if (!(logger = log_open(filename))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "OpenLog(): unable to open file for logging `%s`", filename); duk_push_sphere_obj(ctx, "Logger", logger); return 1; } static duk_ret_t js_new_Logger(duk_context* ctx) { const char* filename; logger_t* logger; filename = duk_require_path(ctx, 0, NULL, false); if (!(logger = log_open(filename))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Logger(): unable to open file for logging `%s`", filename); duk_push_sphere_obj(ctx, "Logger", logger); return 1; } static duk_ret_t js_Logger_finalize(duk_context* ctx) { logger_t* logger; logger = duk_require_sphere_obj(ctx, 0, "Logger"); log_close(logger); return 0; } static duk_ret_t js_Logger_toString(duk_context* ctx) { duk_push_string(ctx, "[object log]"); return 1; } static duk_ret_t js_Logger_beginBlock(duk_context* ctx) { const char* title = duk_to_string(ctx, 0); logger_t* logger; duk_push_this(ctx); logger = duk_require_sphere_obj(ctx, -1, "Logger"); if (!log_begin_block(logger, title)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Log:beginBlock(): unable to create new log block"); return 0; } static duk_ret_t js_Logger_endBlock(duk_context* ctx) { logger_t* logger; duk_push_this(ctx); logger = duk_require_sphere_obj(ctx, -1, "Logger"); log_end_block(logger); return 0; } static duk_ret_t js_Logger_write(duk_context* ctx) { const char* text = duk_to_string(ctx, 0); logger_t* logger; duk_push_this(ctx); logger = duk_require_sphere_obj(ctx, -1, "Logger"); log_write(logger, NULL, text); return 0; } <file_sep>/src/plugin/Debugger/DValue.cs using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace minisphere.Gdk.Debugger { enum DValueTag { EOM = 0x00, REQ = 0x01, REP = 0x02, ERR = 0x03, NFY = 0x04, Integer = 0x10, String = 0x11, SmallString = 0x12, Buffer = 0x13, SmallBuffer = 0x14, Unused = 0x15, Undefined = 0x16, Null = 0x17, True = 0x18, False = 0x19, Float = 0x1A, Object = 0x1B, Pointer = 0x1C, LightFunc = 0x1D, HeapPtr = 0x1E, } enum HeapClass { Unknown, Arguments, Array, Boolean, Date, Error, Function, JSON, Math, Number, Object, RegExp, String, Global, ObjEnv, DecEnv, Buffer, Pointer, Thread, ArrayBuffer, DataView, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, } struct HeapPtr { public HeapClass Class; public byte[] Data; public byte Size; } class DValue { private DValueTag _tag; private dynamic _value; public DValue(DValueTag value) { _tag = value; } public DValue(byte[] buffer) { _tag = DValueTag.Buffer; _value = buffer; } public DValue(double value) { _tag = DValueTag.Float; _value = value; } public DValue(int value) { _tag = DValueTag.Integer; _value = value; } public DValue(string value) { _tag = DValueTag.String; _value = value; } public DValue(HeapPtr ptr) { _tag = DValueTag.HeapPtr; _value = ptr; } public static explicit operator double(DValue dvalue) { return dvalue._tag == DValueTag.Float ? dvalue._value : dvalue._tag == DValueTag.Integer ? (double)dvalue._value : 0.0; } public static explicit operator int(DValue dvalue) { return dvalue._tag == DValueTag.Integer ? dvalue._value : dvalue._tag == DValueTag.Float ? (int)dvalue._value : 0; } public static explicit operator string(DValue dvalue) { return dvalue._tag == DValueTag.String ? dvalue._value : 0; } public static explicit operator HeapPtr(DValue dvalue) { return dvalue._tag == DValueTag.HeapPtr ? dvalue._value : null; } public DValueTag Tag { get { return _tag; } } public static DValue Receive(Socket socket) { byte initialByte; byte[] bytes; int length = -1; Encoding utf8 = new UTF8Encoding(false); if (!socket.ReceiveAll(bytes = new byte[1])) return null; initialByte = bytes[0]; if (initialByte >= 0x60 && initialByte < 0x80) { length = initialByte - 0x60; if (!socket.ReceiveAll(bytes = new byte[length])) return null; return new DValue(utf8.GetString(bytes)); } else if (initialByte >= 0x80 && initialByte < 0xC0) { return new DValue(initialByte - 0x80); } else if (initialByte >= 0xC0) { Array.Resize(ref bytes, 2); if (socket.Receive(bytes, 1, 1, SocketFlags.None) == 0) return null; return new DValue(((initialByte - 0xC0) << 8) + bytes[1]); } else { HeapPtr heapPtr = new HeapPtr(); switch ((DValueTag)initialByte) { case DValueTag.EOM: case DValueTag.REQ: case DValueTag.REP: case DValueTag.ERR: case DValueTag.NFY: case DValueTag.Unused: case DValueTag.Undefined: case DValueTag.Null: case DValueTag.True: case DValueTag.False: return new DValue((DValueTag)initialByte); case DValueTag.Integer: // 32-bit integer if (!socket.ReceiveAll(bytes = new byte[4])) return null; return new DValue((bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3]); case DValueTag.String: if (!socket.ReceiveAll(bytes = new byte[4])) return null; length = (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3]; if (!socket.ReceiveAll(bytes = new byte[length])) return null; return new DValue(utf8.GetString(bytes)); case DValueTag.SmallString: if (!socket.ReceiveAll(bytes = new byte[2])) return null; length = (bytes[0] << 8) + bytes[1]; if (!socket.ReceiveAll(bytes = new byte[length])) return null; return new DValue(utf8.GetString(bytes)); case DValueTag.Buffer: if (!socket.ReceiveAll(bytes = new byte[4])) return null; length = (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3]; if (!socket.ReceiveAll(bytes = new byte[length])) return null; return new DValue(bytes); case DValueTag.SmallBuffer: if (!socket.ReceiveAll(bytes = new byte[2])) return null; length = (bytes[0] << 8) + bytes[1]; if (!socket.ReceiveAll(bytes = new byte[length])) return null; return new DValue(bytes); case DValueTag.Float: if (!socket.ReceiveAll(bytes = new byte[8])) return null; if (BitConverter.IsLittleEndian) Array.Reverse(bytes); return new DValue(BitConverter.ToDouble(bytes, 0)); case DValueTag.Object: socket.ReceiveAll(bytes = new byte[1]); heapPtr.Class = (HeapClass)bytes[0]; socket.ReceiveAll(bytes = new byte[1]); heapPtr.Size = bytes[0]; socket.ReceiveAll(heapPtr.Data = new byte[heapPtr.Size]); return new DValue(heapPtr); case DValueTag.Pointer: socket.ReceiveAll(bytes = new byte[1]); socket.ReceiveAll(new byte[bytes[0]]); return new DValue(DValueTag.Pointer); case DValueTag.LightFunc: socket.ReceiveAll(bytes = new byte[3]); socket.ReceiveAll(new byte[bytes[2]]); return new DValue(DValueTag.LightFunc); case DValueTag.HeapPtr: heapPtr.Class = HeapClass.Unknown; socket.ReceiveAll(bytes = new byte[1]); heapPtr.Size = bytes[0]; socket.ReceiveAll(heapPtr.Data = new byte[heapPtr.Size]); return new DValue(heapPtr); default: return null; } } } public bool Send(Socket socket) { try { socket.Send(new byte[] { (byte)_tag }); switch (_tag) { case DValueTag.Float: byte[] floatBytes = BitConverter.GetBytes(_value); if (BitConverter.IsLittleEndian) Array.Reverse(floatBytes); socket.Send(floatBytes); break; case DValueTag.Integer: socket.Send(new byte[] { (byte)(_value >> 24 & 0xFF), (byte)(_value >> 16 & 0xFF), (byte)(_value >> 8 & 0xFF), (byte)(_value & 0xFF) }); break; case DValueTag.String: var utf8 = new UTF8Encoding(false); byte[] stringBytes = utf8.GetBytes(_value); socket.Send(new byte[] { (byte)(stringBytes.Length >> 24 & 0xFF), (byte)(stringBytes.Length >> 16 & 0xFF), (byte)(stringBytes.Length >> 8 & 0xFF), (byte)(stringBytes.Length & 0xFF) }); socket.Send(stringBytes); break; case DValueTag.HeapPtr: socket.Send(new byte[] { _value.Size }); socket.Send(_value.Data); break; } return true; } catch (SocketException) { return false; } } public override string ToString() { return _tag == DValueTag.HeapPtr && _value.Class == HeapClass.Array ? "[ ... ]" : _tag == DValueTag.HeapPtr ? string.Format(@"{{ obj: '{0}' }}", _value.Class.ToString()) : _tag == DValueTag.Undefined ? "undefined" : _tag == DValueTag.Null ? "null" : _tag == DValueTag.True ? "true" : _tag == DValueTag.False ? "false" : _tag == DValueTag.Integer ? _value.ToString() : _tag == DValueTag.Float ? _value.ToString() : _tag == DValueTag.String ? string.Format("\"{0}\"", _value.Replace(@"""", @"\""").Replace("\r", @"\r").Replace("\n", @"\n")) : "*munch*"; } } } <file_sep>/src/engine/logger.h typedef struct logger logger_t; logger_t* log_open (const char* filename); logger_t* log_ref (logger_t* logger); void log_close (logger_t* logger); bool log_begin_block (logger_t* logger, const char* title); void log_end_block (logger_t* logger); void log_write (logger_t* logger, const char* prefix, const char* text); void init_logging_api (void); <file_sep>/src/plugin/Plugins/Ssj2Debugger.cs using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Sphere.Plugins; using Sphere.Plugins.Interfaces; using Sphere.Plugins.Views; using minisphere.Gdk.Forms; using minisphere.Gdk.Debugger; namespace minisphere.Gdk.Plugins { class Ssj2Debugger : IDebugger, IDisposable { private string sgmPath; private Process engineProcess; private string engineDir; private bool haveError = false; private ConcurrentQueue<dynamic[]> replies = new ConcurrentQueue<dynamic[]>(); private Timer focusTimer; private string sourcePath; private Timer updateTimer; private bool expectDetach = false; private PluginMain plugin; public Ssj2Debugger(PluginMain main, string gamePath, string enginePath, Process engine, IProject project) { plugin = main; sgmPath = gamePath; sourcePath = project.RootPath; engineProcess = engine; engineDir = Path.GetDirectoryName(enginePath); focusTimer = new Timer(HandleFocusSwitch, this, Timeout.Infinite, Timeout.Infinite); updateTimer = new Timer(UpdateDebugViews, this, Timeout.Infinite, Timeout.Infinite); } public void Dispose() { Inferior.Dispose(); focusTimer.Dispose(); updateTimer.Dispose(); } public Inferior Inferior { get; private set; } public string FileName { get; private set; } public int LineNumber { get; private set; } public bool Running { get; private set; } public event EventHandler Attached; public event EventHandler Detached; public event EventHandler<PausedEventArgs> Paused; public event EventHandler Resumed; public async Task<bool> Attach() { try { await Connect("localhost", 1208); ++plugin.Sessions; return true; } catch (TimeoutException) { return false; } } public async Task Detach() { expectDetach = true; await Inferior.Detach(); Dispose(); } private async Task Connect(string hostname, int port, uint timeout = 5000) { long endTime = DateTime.Now.Ticks + timeout * 10000; while (DateTime.Now.Ticks < endTime) { try { Inferior = new Inferior(); Inferior.Attached += duktape_Attached; Inferior.Detached += duktape_Detached; Inferior.Throw += duktape_ErrorThrown; Inferior.Alert += duktape_Print; Inferior.Print += duktape_Print; Inferior.Status += duktape_Status; await Inferior.Connect(hostname, port); return; } catch (SocketException) { // a SocketException in this situation just means we failed to connect, // likely due to nobody listening. we can safely ignore it; just keep trying // until the timeout expires. } } throw new TimeoutException(); } private void duktape_Attached(object sender, EventArgs e) { PluginManager.Core.Invoke(new Action(() => { Attached?.Invoke(this, EventArgs.Empty); Panes.Inspector.Ssj = this; Panes.Errors.Ssj = this; Panes.Inspector.Enabled = false; Panes.Console.Clear(); Panes.Errors.Clear(); Panes.Inspector.Clear(); Panes.Console.Print(string.Format("SSJ2 " + plugin.Version + " minisphere GUI Debugger")); Panes.Console.Print(string.Format("a graphical JS debugger for Sphere Studio")); Panes.Console.Print(string.Format("(c) 2015-2016 <NAME>")); Panes.Console.Print(""); }), null); } private void duktape_Detached(object sender, EventArgs e) { PluginManager.Core.Invoke(new Action(async () => { if (!expectDetach) { await Task.Delay(1000); if (!engineProcess.HasExited) { try { await Connect("localhost", 1208); return; // we're reconnected, don't detach. } catch (TimeoutException) { // if we time out on the reconnection attempt, go on and signal a // detach to Sphere Studio. } } } focusTimer.Change(Timeout.Infinite, Timeout.Infinite); Detached?.Invoke(this, EventArgs.Empty); --plugin.Sessions; PluginManager.Core.Docking.Hide(Panes.Inspector); PluginManager.Core.Docking.Activate(Panes.Console); Panes.Console.Print("SSJ session has ended."); }), null); } private void duktape_ErrorThrown(object sender, ThrowEventArgs e) { PluginManager.Core.Invoke(new Action(() => { Panes.Errors.Add(e.Message, e.IsFatal, e.FileName, e.LineNumber); PluginManager.Core.Docking.Show(Panes.Errors); PluginManager.Core.Docking.Activate(Panes.Errors); if (e.IsFatal) haveError = true; }), null); } private void duktape_Print(object sender, TraceEventArgs e) { PluginManager.Core.Invoke(new Action(() => { Panes.Console.Print(e.Text); }), null); } private void duktape_Status(object sender, EventArgs e) { PluginManager.Core.Invoke(new Action(async () => { bool wantPause = !Inferior.Running; bool wantResume = !Running && Inferior.Running; Running = Inferior.Running; if (wantPause) { focusTimer.Change(Timeout.Infinite, Timeout.Infinite); FileName = ResolvePath(Inferior.FileName); LineNumber = Inferior.LineNumber; if (!File.Exists(FileName)) { // filename reported by Duktape doesn't exist; walk callstack for a // JavaScript call as a fallback var callStack = await Inferior.GetCallStack(); var topCall = callStack.First(entry => entry.Item3 != 0); var callIndex = Array.IndexOf(callStack, topCall); FileName = ResolvePath(topCall.Item2); LineNumber = topCall.Item3; await Panes.Inspector.SetCallStack(callStack, callIndex); Panes.Inspector.Enabled = true; } else { updateTimer.Change(500, Timeout.Infinite); } } if (wantResume && Inferior.Running) { focusTimer.Change(250, Timeout.Infinite); updateTimer.Change(Timeout.Infinite, Timeout.Infinite); Panes.Errors.ClearHighlight(); } if (wantPause && Paused != null) { PauseReason reason = haveError ? PauseReason.Exception : PauseReason.Breakpoint; haveError = false; Paused(this, new PausedEventArgs(reason)); } if (wantResume && Resumed != null) Resumed(this, EventArgs.Empty); }), null); } public async Task SetBreakpoint(string fileName, int lineNumber) { fileName = UnresolvePath(fileName); await Inferior.AddBreak(fileName, lineNumber); } public async Task ClearBreakpoint(string fileName, int lineNumber) { fileName = UnresolvePath(fileName); // clear all matching breakpoints var breaks = await Inferior.ListBreak(); for (int i = breaks.Length - 1; i >= 0; --i) { string fn = breaks[i].Item1; int line = breaks[i].Item2; if (fileName == fn && lineNumber == line) await Inferior.DelBreak(i); } } public async Task Resume() { await Inferior.Resume(); } public async Task Pause() { await Inferior.Pause(); } public async Task StepInto() { await Inferior.StepInto(); } public async Task StepOut() { await Inferior.StepOut(); } public async Task StepOver() { await Inferior.StepOver(); } private static void HandleFocusSwitch(object state) { PluginManager.Core.Invoke(new Action(() => { Ssj2Debugger me = (Ssj2Debugger)state; try { NativeMethods.SetForegroundWindow(me.engineProcess.MainWindowHandle); Panes.Inspector.Enabled = false; Panes.Inspector.Clear(); } catch (InvalidOperationException) { // this will be thrown by Process.MainWindowHandle if the process // is no longer running; we can safely ignore it. } }), null); } private static void UpdateDebugViews(object state) { PluginManager.Core.Invoke(new Action(async () => { Ssj2Debugger me = (Ssj2Debugger)state; var callStack = await me.Inferior.GetCallStack(); if (!me.Running) { await Panes.Inspector.SetCallStack(callStack); Panes.Inspector.Enabled = true; PluginManager.Core.Docking.Activate(Panes.Inspector); } }), null); } /// <summary> /// Resolves a SphereFS path into an absolute one. /// </summary> /// <param name="path">The SphereFS path to resolve.</param> internal string ResolvePath(string path) { if (Path.IsPathRooted(path)) return path.Replace('/', Path.DirectorySeparatorChar); if (path.StartsWith("@/")) path = Path.Combine(sourcePath, path.Substring(2)); else if (path.StartsWith("#/")) path = Path.Combine(engineDir, "system", path.Substring(2)); else if (path.StartsWith("~/")) path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "minisphere", path.Substring(2)); else path = Path.Combine(sourcePath, path); return path.Replace('/', Path.DirectorySeparatorChar); } /// <summary> /// Converts an absolute path into a SphereFS path. If this is /// not possible, leaves the path as-is. /// </summary> /// <param name="path">The absolute path to unresolve.</param> private string UnresolvePath(string path) { var pathSep = Path.DirectorySeparatorChar.ToString(); string sourceRoot = sourcePath.EndsWith(pathSep) ? sourcePath : sourcePath + pathSep; string sysRoot = Path.Combine(engineDir, @"system") + pathSep; if (path.StartsWith(sysRoot)) path = string.Format("#/{0}", path.Substring(sysRoot.Length).Replace(pathSep, "/")); else if (path.StartsWith(sourceRoot)) path = path.Substring(sourceRoot.Length).Replace(pathSep, "/"); return path; } private void UpdateStatus() { FileName = ResolvePath(Inferior.FileName); LineNumber = Inferior.LineNumber; Running = Inferior.Running; } } } <file_sep>/src/debugger/inferior.c #include "ssj.h" #include "inferior.h" #include "backtrace.h" #include "help.h" #include "message.h" #include "objview.h" #include "parser.h" #include "session.h" #include "sockets.h" #include "source.h" struct source { char* filename; source_t* source; }; struct inferior { unsigned int id_no; int num_sources; bool is_detached; bool is_paused; char* title; char* author; backtrace_t* calls; int frame_index; bool have_debug_info; int line_no; uint8_t ptr_size; socket_t* socket; struct source* sources; }; static void clear_pause_cache (inferior_t* obj); static bool do_handshake (socket_t* socket); static bool handle_notify (inferior_t* obj, const message_t* msg); static unsigned int s_next_id_no = 1; void inferiors_init(void) { sockets_init(); } void inferiors_deinit(void) { sockets_deinit(); } inferior_t* inferior_new(const char* hostname, int port) { inferior_t* obj; message_t* req; message_t* rep; obj = calloc(1, sizeof(inferior_t)); printf("connecting to %s:%d... ", hostname, port); fflush(stdout); if (!(obj->socket = socket_connect(hostname, port, 30.0))) goto on_error; printf("OK.\n"); if (!do_handshake(obj->socket)) goto on_error; printf("querying target... "); req = message_new(MESSAGE_REQ); message_add_int(req, REQ_APPREQUEST); message_add_int(req, APPREQ_GAME_INFO); rep = inferior_request(obj, req); obj->title = strdup(message_get_string(rep, 0)); obj->author = strdup(message_get_string(rep, 1)); message_free(rep); printf("OK.\n"); printf(" game: %s\n", obj->title); printf(" author: %s\n", obj->author); obj->id_no = s_next_id_no++; return obj; on_error: free(obj); return NULL; } void inferior_free(inferior_t* obj) { int i; clear_pause_cache(obj); for (i = 0; i < obj->num_sources; ++i) { source_free(obj->sources[i].source); free(obj->sources[i].filename); } socket_close(obj->socket); free(obj->title); free(obj->author); free(obj); } bool inferior_update(inferior_t* obj) { bool is_active = true; message_t* msg = NULL; if (obj->is_detached) return false; if (!(msg = message_recv(obj->socket))) goto detached; if (!handle_notify(obj, msg)) goto detached; message_free(msg); return true; detached: message_free(msg); obj->is_detached = true; return false; } bool inferior_attached(const inferior_t* obj) { return !obj->is_detached; } bool inferior_running(const inferior_t* obj) { return !obj->is_paused && inferior_attached(obj); } const char* inferior_author(const inferior_t* obj) { return obj->author; } const char* inferior_title(const inferior_t* obj) { return obj->title; } const backtrace_t* inferior_get_calls(inferior_t* obj) { char* call_name; const char* filename; const char* function_name; int line_no; message_t* msg; int num_frames; int i; if (obj->calls == NULL) { msg = message_new(MESSAGE_REQ); message_add_int(msg, REQ_GETCALLSTACK); if (!(msg = inferior_request(obj, msg))) return NULL; num_frames = message_len(msg) / 4; obj->calls = backtrace_new(); for (i = 0; i < num_frames; ++i) { function_name = message_get_string(msg, i * 4 + 1); if (strcmp(function_name, "") == 0) call_name = strdup("[anon]"); else call_name = strnewf("%s()", function_name); filename = message_get_string(msg, i * 4); line_no = message_get_int(msg, i * 4 + 2); backtrace_add(obj->calls, call_name, filename, line_no); } message_free(msg); } return obj->calls; } objview_t* inferior_get_object(inferior_t* obj, remote_ptr_t heapptr, bool get_all) { unsigned int flags; const dvalue_t* getter; bool is_accessor; int index = 0; char* key_string; int prop_flags; const dvalue_t* prop_key; message_t* msg; const dvalue_t* setter; const dvalue_t* value; objview_t* view; msg = message_new(MESSAGE_REQ); message_add_int(msg, REQ_GETOBJPROPDESCRANGE); message_add_heapptr(msg, heapptr); message_add_int(msg, 0); message_add_int(msg, INT_MAX); if (!(msg = inferior_request(obj, msg))) return NULL; view = objview_new(); while (index < message_len(msg)) { prop_flags = message_get_int(msg, index++); prop_key = message_get_dvalue(msg, index++); if (dvalue_tag(prop_key) == DVALUE_STRING) key_string = strdup(dvalue_as_cstr(prop_key)); else key_string = strnewf("%d", dvalue_as_int(prop_key)); is_accessor = (prop_flags & 0x008) != 0; if (prop_flags & 0x100) { index += is_accessor ? 2 : 1; continue; } flags = 0x0; if (prop_flags & 0x01) flags |= PROP_WRITABLE; if (prop_flags & 0x02) flags |= PROP_ENUMERABLE; if (prop_flags & 0x04) flags |= PROP_CONFIGURABLE; if (is_accessor) { getter = message_get_dvalue(msg, index++); setter = message_get_dvalue(msg, index++); objview_add_accessor(view, key_string, getter, setter, flags); } else { value = message_get_dvalue(msg, index++); if (dvalue_tag(value) != DVALUE_UNUSED) objview_add_value(view, key_string, value, flags); } free(key_string); } message_free(msg); return view; } const source_t* inferior_get_source(inferior_t* obj, const char* filename) { int cache_id; message_t* msg; source_t* source; const char* text; int i; for (i = 0; i < obj->num_sources; ++i) { if (strcmp(filename, obj->sources[i].filename) == 0) return obj->sources[i].source; } msg = message_new(MESSAGE_REQ); message_add_int(msg, REQ_APPREQUEST); message_add_int(msg, APPREQ_SOURCE); message_add_string(msg, filename); if (!(msg = inferior_request(obj, msg))) goto on_error; if (message_tag(msg) == MESSAGE_ERR) goto on_error; text = message_get_string(msg, 0); source = source_new(text); cache_id = obj->num_sources++; obj->sources = realloc(obj->sources, obj->num_sources * sizeof(struct source)); obj->sources[cache_id].filename = strdup(filename); obj->sources[cache_id].source = source; return source; on_error: message_free(msg); return NULL; } objview_t* inferior_get_vars(inferior_t* obj, int frame) { const char* name; message_t* msg; int num_vars; const dvalue_t* value; objview_t* vars; int i; msg = message_new(MESSAGE_REQ); message_add_int(msg, REQ_GETLOCALS); message_add_int(msg, -frame - 1); if (!(msg = inferior_request(obj, msg))) return NULL; vars = objview_new(); num_vars = message_len(msg) / 2; for (i = 0; i < num_vars; ++i) { name = message_get_string(msg, i * 2 + 0); value = message_get_dvalue(msg, i * 2 + 1); objview_add_value(vars, name, value, 0x0); } return vars; } int inferior_add_breakpoint(inferior_t* obj, const char* filename, int linenum) { int handle; message_t* msg; msg = message_new(MESSAGE_REQ); message_add_int(msg, REQ_ADDBREAK); message_add_string(msg, filename); message_add_int(msg, linenum); if (!(msg = inferior_request(obj, msg))) goto on_error; if (message_tag(msg) == MESSAGE_ERR) goto on_error; handle = message_get_int(msg, 0); message_free(msg); return handle; on_error: message_free(msg); return -1; } bool inferior_clear_breakpoint(inferior_t* obj, int handle) { message_t* msg; msg = message_new(MESSAGE_REQ); message_add_int(msg, REQ_DELBREAK); message_add_int(msg, handle); if (!(msg = inferior_request(obj, msg))) goto on_error; if (message_tag(msg) == MESSAGE_ERR) goto on_error; message_free(msg); return true; on_error: message_free(msg); return false; } void inferior_detach(inferior_t* obj) { message_t* msg; msg = message_new(MESSAGE_REQ); message_add_int(msg, REQ_DETACH); if (!(msg = inferior_request(obj, msg))) return; message_free(msg); while (inferior_attached(obj)) inferior_update(obj); } dvalue_t* inferior_eval(inferior_t* obj, const char* expr, int frame, bool* out_is_error) { dvalue_t* dvalue = NULL; message_t* msg; msg = message_new(MESSAGE_REQ); message_add_int(msg, REQ_EVAL); message_add_string(msg, expr); message_add_int(msg, -(1 + frame)); msg = inferior_request(obj, msg); dvalue = dvalue_dup(message_get_dvalue(msg, 1)); *out_is_error = message_get_int(msg, 0) != 0; message_free(msg); return dvalue; } bool inferior_pause(inferior_t* obj) { message_t* msg; msg = message_new(MESSAGE_REQ); message_add_int(msg, REQ_PAUSE); if (!(msg = inferior_request(obj, msg))) return false; return true; } message_t* inferior_request(inferior_t* obj, message_t* msg) { message_t* response = NULL; if (!(message_send(msg, obj->socket))) goto lost_connection; do { message_free(response); if (!(response = message_recv(obj->socket))) goto lost_connection; if (message_tag(response) == MESSAGE_NFY) handle_notify(obj, response); } while (message_tag(response) == MESSAGE_NFY); message_free(msg); return response; lost_connection: printf("inferior lost connection with the target.\n"); message_free(msg); obj->is_detached = true; return NULL; } bool inferior_resume(inferior_t* obj, resume_op_t op) { message_t* msg; msg = message_new(MESSAGE_REQ); message_add_int(msg, op == OP_STEP_OVER ? REQ_STEPOVER : op == OP_STEP_IN ? REQ_STEPINTO : op == OP_STEP_OUT ? REQ_STEPOUT : REQ_RESUME); if (!(msg = inferior_request(obj, msg))) return false; obj->frame_index = 0; obj->is_paused = false; while (inferior_running(obj)) inferior_update(obj); return true; } static void clear_pause_cache(inferior_t* obj) { backtrace_free(obj->calls); obj->calls = NULL; } static bool do_handshake(socket_t* socket) { static char handshake[128]; ptrdiff_t idx; char* next_token; char* token; printf("verifying... "); idx = 0; do { if (idx >= 127) // probably not a Duktape handshake goto on_error; socket_recv(socket, &handshake[idx], 1); } while (handshake[idx++] != '\n'); handshake[idx - 1] = '\0'; // remove the newline // parse handshake line if (!(token = strtok_r(handshake, " ", &next_token))) goto on_error; if (atoi(token) != 1) goto on_error; if (!(token = strtok_r(NULL, " ", &next_token))) goto on_error; if (!(token = strtok_r(NULL, " ", &next_token))) goto on_error; printf("OK.\n"); return true; on_error: printf("\33[31;1merror!\33[m\n"); return false; } static bool handle_notify(inferior_t* obj, const message_t* msg) { int status_type; switch (message_tag(msg)) { case MESSAGE_NFY: switch (message_get_int(msg, 0)) { case NFY_APPNOTIFY: switch (message_get_int(msg, 1)) { case APPNFY_DEBUG_PRINT: printf("t: %s", message_get_string(msg, 2)); break; } break; case NFY_STATUS: status_type = message_get_int(msg, 1); obj->is_paused = status_type != 0; if (!obj->is_paused) clear_pause_cache(obj); break; case NFY_PRINT: printf("p: %s", message_get_string(msg, 1)); break; case NFY_ALERT: printf("a: %s", message_get_string(msg, 1)); break; case NFY_LOG: printf("l: %s", message_get_string(msg, 1)); break; case NFY_THROW: if ((status_type = message_get_int(msg, 1)) == 0) break; printf("**************************************************\n"); printf("uncaught exception! - at %s:%d\n", message_get_string(msg, 3), message_get_int(msg, 4)); printf(" value: "); dvalue_print(message_get_dvalue(msg, 2), true); printf("\n**************************************************\n\n"); break; case NFY_DETACHING: status_type = message_get_int(msg, 1); if (status_type == 0) printf("inferior disconnected normally.\n"); else printf("inferior disconnected due to an error.\n"); obj->is_detached = true; return false; } break; } return true; } <file_sep>/src/engine/input.c #include "minisphere.h" #include "api.h" #include "debugger.h" #include "file.h" #include "input.h" #include "vector.h" #define MAX_JOYSTICKS 4 #define MAX_JOY_BUTTONS 32 struct key_queue { int num_keys; int keys[255]; }; enum mouse_button { MOUSE_BUTTON_LEFT, MOUSE_BUTTON_RIGHT, MOUSE_BUTTON_MIDDLE }; enum mouse_wheel_event { MOUSE_WHEEL_UP, MOUSE_WHEEL_DOWN }; static duk_ret_t js_AreKeysLeft (duk_context* ctx); static duk_ret_t js_IsAnyKeyPressed (duk_context* ctx); static duk_ret_t js_IsJoystickButtonPressed (duk_context* ctx); static duk_ret_t js_IsKeyPressed (duk_context* ctx); static duk_ret_t js_IsMouseButtonPressed (duk_context* ctx); static duk_ret_t js_GetJoystickAxis (duk_context* ctx); static duk_ret_t js_GetKey (duk_context* ctx); static duk_ret_t js_GetKeyString (duk_context* ctx); static duk_ret_t js_GetNumMouseWheelEvents (duk_context* ctx); static duk_ret_t js_GetMouseWheelEvent (duk_context* ctx); static duk_ret_t js_GetMouseX (duk_context* ctx); static duk_ret_t js_GetMouseY (duk_context* ctx); static duk_ret_t js_GetNumJoysticks (duk_context* ctx); static duk_ret_t js_GetNumJoystickAxes (duk_context* ctx); static duk_ret_t js_GetNumJoystickButtons (duk_context* ctx); static duk_ret_t js_GetNumMouseWheelEvents (duk_context* ctx); static duk_ret_t js_GetPlayerKey (duk_context* ctx); static duk_ret_t js_GetToggleState (duk_context* ctx); static duk_ret_t js_SetMousePosition (duk_context* ctx); static duk_ret_t js_SetPlayerKey (duk_context* ctx); static duk_ret_t js_BindKey (duk_context* ctx); static duk_ret_t js_BindJoystickButton (duk_context* ctx); static duk_ret_t js_ClearKeyQueue (duk_context* ctx); static duk_ret_t js_UnbindKey (duk_context* ctx); static duk_ret_t js_UnbindJoystickButton (duk_context* ctx); static void bind_button (vector_t* bindings, int joy_index, int button, script_t* on_down_script, script_t* on_up_script); static void bind_key (vector_t* bindings, int keycode, script_t* on_down_script, script_t* on_up_script); static void queue_key (int keycode); static void queue_wheel_event (int event); static vector_t* s_bound_buttons; static vector_t* s_bound_keys; static vector_t* s_bound_map_keys; static int s_default_key_map[4][PLAYER_KEY_MAX]; static ALLEGRO_EVENT_QUEUE* s_events; static bool s_have_joystick; static bool s_have_mouse; static ALLEGRO_JOYSTICK* s_joy_handles[MAX_JOYSTICKS]; static int s_key_map[4][PLAYER_KEY_MAX]; static struct key_queue s_key_queue; static bool s_key_state[ALLEGRO_KEY_MAX]; static int s_keymod_state; static int s_last_wheel_pos = 0; static int s_num_joysticks = 0; static int s_num_wheel_events = 0; static bool s_has_keymap_changed = false; static int s_wheel_queue[255]; struct bound_button { int joystick_id; int button; bool is_pressed; script_t* on_down_script; script_t* on_up_script; }; struct bound_key { int keycode; bool is_pressed; script_t* on_down_script; script_t* on_up_script; }; void initialize_input(void) { int i; console_log(1, "initializing input"); al_install_keyboard(); if (!(s_have_mouse = al_install_mouse())) console_log(1, " mouse initialization failed"); if (!(s_have_joystick = al_install_joystick())) console_log(1, " joystick initialization failed"); s_events = al_create_event_queue(); al_register_event_source(s_events, al_get_keyboard_event_source()); if (s_have_mouse) al_register_event_source(s_events, al_get_mouse_event_source()); if (s_have_joystick) al_register_event_source(s_events, al_get_joystick_event_source()); // look for active joysticks if (s_have_joystick) { s_num_joysticks = fmin(MAX_JOYSTICKS, al_get_num_joysticks()); for (i = 0; i < MAX_JOYSTICKS; ++i) s_joy_handles[i] = i < s_num_joysticks ? al_get_joystick(i) : NULL; } // create bound key vectors s_bound_buttons = vector_new(sizeof(struct bound_button)); s_bound_keys = vector_new(sizeof(struct bound_key)); s_bound_map_keys = vector_new(sizeof(struct bound_key)); // fill in default player key map memset(s_key_map, 0, sizeof(s_key_map)); s_default_key_map[0][PLAYER_KEY_UP] = ALLEGRO_KEY_UP; s_default_key_map[0][PLAYER_KEY_DOWN] = ALLEGRO_KEY_DOWN; s_default_key_map[0][PLAYER_KEY_LEFT] = ALLEGRO_KEY_LEFT; s_default_key_map[0][PLAYER_KEY_RIGHT] = ALLEGRO_KEY_RIGHT; s_default_key_map[0][PLAYER_KEY_A] = ALLEGRO_KEY_Z; s_default_key_map[0][PLAYER_KEY_B] = ALLEGRO_KEY_X; s_default_key_map[0][PLAYER_KEY_X] = ALLEGRO_KEY_C; s_default_key_map[0][PLAYER_KEY_Y] = ALLEGRO_KEY_V; s_default_key_map[0][PLAYER_KEY_MENU] = ALLEGRO_KEY_TAB; s_default_key_map[1][PLAYER_KEY_UP] = ALLEGRO_KEY_W; s_default_key_map[1][PLAYER_KEY_DOWN] = ALLEGRO_KEY_S; s_default_key_map[1][PLAYER_KEY_LEFT] = ALLEGRO_KEY_A; s_default_key_map[1][PLAYER_KEY_RIGHT] = ALLEGRO_KEY_D; s_default_key_map[1][PLAYER_KEY_A] = ALLEGRO_KEY_1; s_default_key_map[1][PLAYER_KEY_B] = ALLEGRO_KEY_2; s_default_key_map[1][PLAYER_KEY_X] = ALLEGRO_KEY_3; s_default_key_map[1][PLAYER_KEY_Y] = ALLEGRO_KEY_4; s_default_key_map[1][PLAYER_KEY_MENU] = ALLEGRO_KEY_TAB; s_default_key_map[2][PLAYER_KEY_UP] = ALLEGRO_KEY_PAD_8; s_default_key_map[2][PLAYER_KEY_DOWN] = ALLEGRO_KEY_PAD_2; s_default_key_map[2][PLAYER_KEY_LEFT] = ALLEGRO_KEY_PAD_4; s_default_key_map[2][PLAYER_KEY_RIGHT] = ALLEGRO_KEY_PAD_6; s_default_key_map[2][PLAYER_KEY_A] = ALLEGRO_KEY_PAD_PLUS; s_default_key_map[2][PLAYER_KEY_B] = ALLEGRO_KEY_PAD_MINUS; s_default_key_map[2][PLAYER_KEY_X] = ALLEGRO_KEY_PAD_0; s_default_key_map[2][PLAYER_KEY_Y] = ALLEGRO_KEY_PAD_DELETE; s_default_key_map[2][PLAYER_KEY_MENU] = ALLEGRO_KEY_TAB; s_default_key_map[3][PLAYER_KEY_UP] = ALLEGRO_KEY_I; s_default_key_map[3][PLAYER_KEY_DOWN] = ALLEGRO_KEY_K; s_default_key_map[3][PLAYER_KEY_LEFT] = ALLEGRO_KEY_J; s_default_key_map[3][PLAYER_KEY_RIGHT] = ALLEGRO_KEY_L; s_default_key_map[3][PLAYER_KEY_A] = ALLEGRO_KEY_7; s_default_key_map[3][PLAYER_KEY_B] = ALLEGRO_KEY_8; s_default_key_map[3][PLAYER_KEY_X] = ALLEGRO_KEY_9; s_default_key_map[3][PLAYER_KEY_Y] = ALLEGRO_KEY_0; s_default_key_map[3][PLAYER_KEY_MENU] = ALLEGRO_KEY_TAB; // load global key mappings load_key_map(); } void shutdown_input(void) { struct bound_button* pbutton; struct bound_key* pkey; iter_t iter; // save player key mappings console_log(1, "shutting down input"); // free bound key scripts iter = vector_enum(s_bound_buttons); while (pbutton = vector_next(&iter)) { free_script(pbutton->on_down_script); free_script(pbutton->on_up_script); } iter = vector_enum(s_bound_keys); while (pkey = vector_next(&iter)) { free_script(pkey->on_down_script); free_script(pkey->on_up_script); } iter = vector_enum(s_bound_map_keys); while (pkey = vector_next(&iter)) { free_script(pkey->on_down_script); free_script(pkey->on_up_script); } vector_free(s_bound_buttons); vector_free(s_bound_keys); vector_free(s_bound_map_keys); // shut down Allegro input al_destroy_event_queue(s_events); al_uninstall_joystick(); al_uninstall_mouse(); al_uninstall_keyboard(); } bool is_any_key_down(void) { int i_key; update_input(); for (i_key = 0; i_key < ALLEGRO_KEY_MAX; ++i_key) if (s_key_state[i_key]) return true; return false; } bool is_joy_button_down(int joy_index, int button) { ALLEGRO_JOYSTICK_STATE joy_state; ALLEGRO_JOYSTICK* joystick; if (!s_have_joystick) return false; if (!(joystick = s_joy_handles[joy_index])) return 0.0; al_get_joystick_state(joystick, &joy_state); return joy_state.button[button] > 0; } bool is_key_down(int keycode) { bool is_pressed; update_input(); switch (keycode) { case ALLEGRO_KEY_LSHIFT: is_pressed = s_key_state[ALLEGRO_KEY_LSHIFT] || s_key_state[ALLEGRO_KEY_RSHIFT]; break; case ALLEGRO_KEY_LCTRL: is_pressed = s_key_state[ALLEGRO_KEY_LCTRL] || s_key_state[ALLEGRO_KEY_RCTRL]; break; case ALLEGRO_KEY_ALT: is_pressed = s_key_state[ALLEGRO_KEY_ALT] || s_key_state[ALLEGRO_KEY_ALTGR]; break; default: is_pressed = s_key_state[keycode]; } return is_pressed; } float get_joy_axis(int joy_index, int axis_index) { ALLEGRO_JOYSTICK_STATE joy_state; ALLEGRO_JOYSTICK* joystick; int n_stick_axes; int n_sticks; int i; if (!s_have_joystick || !(joystick = s_joy_handles[joy_index])) return 0.0; al_get_joystick_state(joystick, &joy_state); n_sticks = al_get_joystick_num_sticks(joystick); for (i = 0; i < n_sticks; ++i) { n_stick_axes = al_get_joystick_num_axes(joystick, i); if (axis_index < n_stick_axes) return joy_state.stick[i].axis[axis_index]; axis_index -= n_stick_axes; } return 0.0; } int get_joy_axis_count(int joy_index) { ALLEGRO_JOYSTICK* joystick; int n_axes; int n_sticks; int i; if (!s_have_joystick || !(joystick = s_joy_handles[joy_index])) return 0; n_sticks = al_get_joystick_num_sticks(joystick); n_axes = 0; for (i = 0; i < n_sticks; ++i) n_axes += al_get_joystick_num_axes(joystick, i); return n_axes; } int get_joy_button_count(int joy_index) { ALLEGRO_JOYSTICK* joystick; if (!s_have_joystick || !(joystick = s_joy_handles[joy_index])) return 0; return al_get_joystick_num_buttons(joystick); } int get_player_key(int player, player_key_t vkey) { return s_key_map[player][vkey]; } void attach_input_display(void) { al_register_event_source(s_events, al_get_display_event_source(screen_display(g_screen))); } void set_player_key(int player, player_key_t vkey, int keycode) { s_key_map[player][vkey] = keycode; s_has_keymap_changed = g_game_path != NULL; } void clear_key_queue(void) { s_key_queue.num_keys = 0; } void load_key_map(void) { kevfile_t* file; const char* key_name; char* filename; lstring_t* setting; int i, j; filename = g_fs != NULL ? "keymap.kev" : "#/minisphere.conf"; if (!(file = kev_open(g_fs, filename, true))) return; for (i = 0; i < 4; ++i) for (j = 0; j < PLAYER_KEY_MAX; ++j) { key_name = j == PLAYER_KEY_UP ? "UP" : j == PLAYER_KEY_DOWN ? "DOWN" : j == PLAYER_KEY_LEFT ? "LEFT" : j == PLAYER_KEY_RIGHT ? "RIGHT" : j == PLAYER_KEY_A ? "A" : j == PLAYER_KEY_B ? "B" : j == PLAYER_KEY_X ? "X" : j == PLAYER_KEY_Y ? "Y" : j == PLAYER_KEY_MENU ? "MENU" : "8:12"; setting = lstr_newf("keymap_Player%i_%s", i + 1, key_name); s_key_map[i][j] = kev_read_float(file, lstr_cstr(setting), s_default_key_map[i][j]); lstr_free(setting); } kev_close(file); } void save_key_map(void) { kevfile_t* file; const char* key_name; lstring_t* setting; int i, j; if (!s_has_keymap_changed || g_game_path == NULL) return; console_log(1, "saving player key mappings"); file = kev_open(g_fs, "keymap.kev", true); for (i = 0; i < 4; ++i) for (j = 0; j < PLAYER_KEY_MAX; ++j) { key_name = j == PLAYER_KEY_UP ? "UP" : j == PLAYER_KEY_DOWN ? "DOWN" : j == PLAYER_KEY_LEFT ? "LEFT" : j == PLAYER_KEY_RIGHT ? "RIGHT" : j == PLAYER_KEY_A ? "A" : j == PLAYER_KEY_B ? "B" : j == PLAYER_KEY_X ? "X" : j == PLAYER_KEY_Y ? "Y" : j == PLAYER_KEY_MENU ? "MENU" : "8:12"; setting = lstr_newf("keymap_Player%i_%s", i + 1, key_name); kev_write_float(file, lstr_cstr(setting), s_key_map[i][j]); lstr_free(setting); } kev_close(file); } void update_bound_keys(bool use_map_keys) { struct bound_button* button; struct bound_key* key; bool is_down; iter_t iter; // check bound keyboard keys if (use_map_keys) { iter = vector_enum(s_bound_map_keys); while (key = vector_next(&iter)) { is_down = s_key_state[key->keycode]; if (is_down && !key->is_pressed) run_script(key->on_down_script, false); if (!is_down && key->is_pressed) run_script(key->on_up_script, false); key->is_pressed = is_down; } } iter = vector_enum(s_bound_keys); while (key = vector_next(&iter)) { is_down = s_key_state[key->keycode]; if (is_down && !key->is_pressed) run_script(key->on_down_script, false); if (!is_down && key->is_pressed) run_script(key->on_up_script, false); key->is_pressed = is_down; } // check bound joystick buttons iter = vector_enum(s_bound_buttons); while (button = vector_next(&iter)) { is_down = is_joy_button_down(button->joystick_id, button->button); if (is_down && !button->is_pressed) run_script(button->on_down_script, false); if (!is_down && button->is_pressed) run_script(button->on_up_script, false); button->is_pressed = is_down; } } void update_input(void) { ALLEGRO_EVENT event; int keycode; ALLEGRO_MOUSE_STATE mouse_state; // process Allegro input events while (al_get_next_event(s_events, &event)) { switch (event.type) { case ALLEGRO_EVENT_DISPLAY_SWITCH_OUT: // Alt+Tabbing out can cause keys to get "stuck", this works around it // by clearing the states when switching away. memset(s_key_state, 0, ALLEGRO_KEY_MAX * sizeof(bool)); break; case ALLEGRO_EVENT_KEY_DOWN: keycode = event.keyboard.keycode; s_key_state[keycode] = true; // queue Ctrl/Alt/Shift keys (Sphere compatibility hack) if (keycode == ALLEGRO_KEY_LCTRL || keycode == ALLEGRO_KEY_RCTRL || keycode == ALLEGRO_KEY_ALT || keycode == ALLEGRO_KEY_ALTGR || keycode == ALLEGRO_KEY_LSHIFT || keycode == ALLEGRO_KEY_RSHIFT) { if (keycode == ALLEGRO_KEY_LCTRL || keycode == ALLEGRO_KEY_RCTRL) queue_key(ALLEGRO_KEY_LCTRL); if (keycode == ALLEGRO_KEY_ALT || keycode == ALLEGRO_KEY_ALTGR) queue_key(ALLEGRO_KEY_ALT); if (keycode == ALLEGRO_KEY_LSHIFT || keycode == ALLEGRO_KEY_RSHIFT) queue_key(ALLEGRO_KEY_LSHIFT); } break; case ALLEGRO_EVENT_KEY_UP: s_key_state[event.keyboard.keycode] = false; break; case ALLEGRO_EVENT_KEY_CHAR: s_keymod_state = event.keyboard.modifiers; switch (event.keyboard.keycode) { case ALLEGRO_KEY_ENTER: if (event.keyboard.modifiers & ALLEGRO_KEYMOD_ALT || event.keyboard.modifiers & ALLEGRO_KEYMOD_ALTGR) { screen_toggle_fullscreen(g_screen); } else { queue_key(event.keyboard.keycode); } break; case ALLEGRO_KEY_F10: screen_toggle_fullscreen(g_screen); break; case ALLEGRO_KEY_F11: screen_toggle_fps(g_screen); break; case ALLEGRO_KEY_F12: if (is_debugger_attached()) duk_debugger_pause(g_duk); else screen_queue_screenshot(g_screen); break; default: queue_key(event.keyboard.keycode); break; } } } // check whether mouse wheel moved since last update if (s_have_mouse) { al_get_mouse_state(&mouse_state); if (mouse_state.z > s_last_wheel_pos) queue_wheel_event(MOUSE_WHEEL_UP); if (mouse_state.z < s_last_wheel_pos) queue_wheel_event(MOUSE_WHEEL_DOWN); s_last_wheel_pos = mouse_state.z; } } static void bind_button(vector_t* bindings, int joy_index, int button, script_t* on_down_script, script_t* on_up_script) { bool is_new_entry = true; struct bound_button* bound; struct bound_button new_binding; script_t* old_down_script; script_t* old_up_script; iter_t iter; new_binding.joystick_id = joy_index; new_binding.button = button; new_binding.is_pressed = false; new_binding.on_down_script = on_down_script; new_binding.on_up_script = on_up_script; iter = vector_enum(bindings); while (bound = vector_next(&iter)) { if (bound->joystick_id == joy_index && bound->button == button) { bound->is_pressed = false; old_down_script = bound->on_down_script; old_up_script = bound->on_up_script; memcpy(bound, &new_binding, sizeof(struct bound_button)); if (old_down_script != bound->on_down_script) free_script(old_down_script); if (old_up_script != bound->on_up_script) free_script(old_up_script); is_new_entry = false; } } if (is_new_entry) vector_push(bindings, &new_binding); } static void bind_key(vector_t* bindings, int keycode, script_t* on_down_script, script_t* on_up_script) { bool is_new_key = true; struct bound_key* key; struct bound_key new_binding; script_t* old_down_script; script_t* old_up_script; iter_t iter; new_binding.keycode = keycode; new_binding.is_pressed = false; new_binding.on_down_script = on_down_script; new_binding.on_up_script = on_up_script; iter = vector_enum(bindings); while (key = vector_next(&iter)) { if (key->keycode == keycode) { key->is_pressed = false; old_down_script = key->on_down_script; old_up_script = key->on_up_script; memcpy(key, &new_binding, sizeof(struct bound_key)); if (old_down_script != key->on_down_script) free_script(old_down_script); if (old_up_script != key->on_up_script) free_script(old_up_script); is_new_key = false; } } if (is_new_key) vector_push(bindings, &new_binding); } void init_input_api(void) { api_register_const(g_duk, "PLAYER_1", 0); api_register_const(g_duk, "PLAYER_2", 1); api_register_const(g_duk, "PLAYER_3", 2); api_register_const(g_duk, "PLAYER_4", 3); api_register_const(g_duk, "PLAYER_KEY_MENU", PLAYER_KEY_MENU); api_register_const(g_duk, "PLAYER_KEY_UP", PLAYER_KEY_UP); api_register_const(g_duk, "PLAYER_KEY_DOWN", PLAYER_KEY_DOWN); api_register_const(g_duk, "PLAYER_KEY_LEFT", PLAYER_KEY_LEFT); api_register_const(g_duk, "PLAYER_KEY_RIGHT", PLAYER_KEY_RIGHT); api_register_const(g_duk, "PLAYER_KEY_A", PLAYER_KEY_A); api_register_const(g_duk, "PLAYER_KEY_B", PLAYER_KEY_B); api_register_const(g_duk, "PLAYER_KEY_X", PLAYER_KEY_X); api_register_const(g_duk, "PLAYER_KEY_Y", PLAYER_KEY_Y); api_register_const(g_duk, "KEY_NONE", 0); api_register_const(g_duk, "KEY_SHIFT", ALLEGRO_KEY_LSHIFT); api_register_const(g_duk, "KEY_CTRL", ALLEGRO_KEY_LCTRL); api_register_const(g_duk, "KEY_ALT", ALLEGRO_KEY_ALT); api_register_const(g_duk, "KEY_UP", ALLEGRO_KEY_UP); api_register_const(g_duk, "KEY_DOWN", ALLEGRO_KEY_DOWN); api_register_const(g_duk, "KEY_LEFT", ALLEGRO_KEY_LEFT); api_register_const(g_duk, "KEY_RIGHT", ALLEGRO_KEY_RIGHT); api_register_const(g_duk, "KEY_APOSTROPHE", ALLEGRO_KEY_QUOTE); api_register_const(g_duk, "KEY_BACKSLASH", ALLEGRO_KEY_BACKSLASH); api_register_const(g_duk, "KEY_BACKSPACE", ALLEGRO_KEY_BACKSPACE); api_register_const(g_duk, "KEY_CLOSEBRACE", ALLEGRO_KEY_CLOSEBRACE); api_register_const(g_duk, "KEY_CAPSLOCK", ALLEGRO_KEY_CAPSLOCK); api_register_const(g_duk, "KEY_COMMA", ALLEGRO_KEY_COMMA); api_register_const(g_duk, "KEY_DELETE", ALLEGRO_KEY_DELETE); api_register_const(g_duk, "KEY_END", ALLEGRO_KEY_END); api_register_const(g_duk, "KEY_ENTER", ALLEGRO_KEY_ENTER); api_register_const(g_duk, "KEY_EQUALS", ALLEGRO_KEY_EQUALS); api_register_const(g_duk, "KEY_ESCAPE", ALLEGRO_KEY_ESCAPE); api_register_const(g_duk, "KEY_HOME", ALLEGRO_KEY_HOME); api_register_const(g_duk, "KEY_INSERT", ALLEGRO_KEY_INSERT); api_register_const(g_duk, "KEY_MINUS", ALLEGRO_KEY_MINUS); api_register_const(g_duk, "KEY_NUMLOCK", ALLEGRO_KEY_NUMLOCK); api_register_const(g_duk, "KEY_OPENBRACE", ALLEGRO_KEY_OPENBRACE); api_register_const(g_duk, "KEY_PAGEDOWN", ALLEGRO_KEY_PGDN); api_register_const(g_duk, "KEY_PAGEUP", ALLEGRO_KEY_PGUP); api_register_const(g_duk, "KEY_PERIOD", ALLEGRO_KEY_FULLSTOP); api_register_const(g_duk, "KEY_SCROLLOCK", ALLEGRO_KEY_SCROLLLOCK); api_register_const(g_duk, "KEY_SCROLLLOCK", ALLEGRO_KEY_SCROLLLOCK); api_register_const(g_duk, "KEY_SEMICOLON", ALLEGRO_KEY_SEMICOLON); api_register_const(g_duk, "KEY_SPACE", ALLEGRO_KEY_SPACE); api_register_const(g_duk, "KEY_SLASH", ALLEGRO_KEY_SLASH); api_register_const(g_duk, "KEY_TAB", ALLEGRO_KEY_TAB); api_register_const(g_duk, "KEY_TILDE", ALLEGRO_KEY_TILDE); api_register_const(g_duk, "KEY_F1", ALLEGRO_KEY_F1); api_register_const(g_duk, "KEY_F2", ALLEGRO_KEY_F2); api_register_const(g_duk, "KEY_F3", ALLEGRO_KEY_F3); api_register_const(g_duk, "KEY_F4", ALLEGRO_KEY_F4); api_register_const(g_duk, "KEY_F5", ALLEGRO_KEY_F5); api_register_const(g_duk, "KEY_F6", ALLEGRO_KEY_F6); api_register_const(g_duk, "KEY_F7", ALLEGRO_KEY_F7); api_register_const(g_duk, "KEY_F8", ALLEGRO_KEY_F8); api_register_const(g_duk, "KEY_F9", ALLEGRO_KEY_F9); api_register_const(g_duk, "KEY_F10", ALLEGRO_KEY_F10); api_register_const(g_duk, "KEY_F11", ALLEGRO_KEY_F11); api_register_const(g_duk, "KEY_F12", ALLEGRO_KEY_F12); api_register_const(g_duk, "KEY_A", ALLEGRO_KEY_A); api_register_const(g_duk, "KEY_B", ALLEGRO_KEY_B); api_register_const(g_duk, "KEY_C", ALLEGRO_KEY_C); api_register_const(g_duk, "KEY_D", ALLEGRO_KEY_D); api_register_const(g_duk, "KEY_E", ALLEGRO_KEY_E); api_register_const(g_duk, "KEY_F", ALLEGRO_KEY_F); api_register_const(g_duk, "KEY_G", ALLEGRO_KEY_G); api_register_const(g_duk, "KEY_H", ALLEGRO_KEY_H); api_register_const(g_duk, "KEY_I", ALLEGRO_KEY_I); api_register_const(g_duk, "KEY_J", ALLEGRO_KEY_J); api_register_const(g_duk, "KEY_K", ALLEGRO_KEY_K); api_register_const(g_duk, "KEY_L", ALLEGRO_KEY_L); api_register_const(g_duk, "KEY_M", ALLEGRO_KEY_M); api_register_const(g_duk, "KEY_N", ALLEGRO_KEY_N); api_register_const(g_duk, "KEY_O", ALLEGRO_KEY_O); api_register_const(g_duk, "KEY_P", ALLEGRO_KEY_P); api_register_const(g_duk, "KEY_Q", ALLEGRO_KEY_Q); api_register_const(g_duk, "KEY_R", ALLEGRO_KEY_R); api_register_const(g_duk, "KEY_S", ALLEGRO_KEY_S); api_register_const(g_duk, "KEY_T", ALLEGRO_KEY_T); api_register_const(g_duk, "KEY_U", ALLEGRO_KEY_U); api_register_const(g_duk, "KEY_V", ALLEGRO_KEY_V); api_register_const(g_duk, "KEY_W", ALLEGRO_KEY_W); api_register_const(g_duk, "KEY_X", ALLEGRO_KEY_X); api_register_const(g_duk, "KEY_Y", ALLEGRO_KEY_Y); api_register_const(g_duk, "KEY_Z", ALLEGRO_KEY_Z); api_register_const(g_duk, "KEY_1", ALLEGRO_KEY_1); api_register_const(g_duk, "KEY_2", ALLEGRO_KEY_2); api_register_const(g_duk, "KEY_3", ALLEGRO_KEY_3); api_register_const(g_duk, "KEY_4", ALLEGRO_KEY_4); api_register_const(g_duk, "KEY_5", ALLEGRO_KEY_5); api_register_const(g_duk, "KEY_6", ALLEGRO_KEY_6); api_register_const(g_duk, "KEY_7", ALLEGRO_KEY_7); api_register_const(g_duk, "KEY_8", ALLEGRO_KEY_8); api_register_const(g_duk, "KEY_9", ALLEGRO_KEY_9); api_register_const(g_duk, "KEY_0", ALLEGRO_KEY_0); api_register_const(g_duk, "KEY_NUM_1", ALLEGRO_KEY_PAD_1); api_register_const(g_duk, "KEY_NUM_2", ALLEGRO_KEY_PAD_2); api_register_const(g_duk, "KEY_NUM_3", ALLEGRO_KEY_PAD_3); api_register_const(g_duk, "KEY_NUM_4", ALLEGRO_KEY_PAD_4); api_register_const(g_duk, "KEY_NUM_5", ALLEGRO_KEY_PAD_5); api_register_const(g_duk, "KEY_NUM_6", ALLEGRO_KEY_PAD_6); api_register_const(g_duk, "KEY_NUM_7", ALLEGRO_KEY_PAD_7); api_register_const(g_duk, "KEY_NUM_8", ALLEGRO_KEY_PAD_8); api_register_const(g_duk, "KEY_NUM_9", ALLEGRO_KEY_PAD_9); api_register_const(g_duk, "KEY_NUM_0", ALLEGRO_KEY_PAD_0); api_register_const(g_duk, "MOUSE_LEFT", MOUSE_BUTTON_LEFT); api_register_const(g_duk, "MOUSE_MIDDLE", MOUSE_BUTTON_MIDDLE); api_register_const(g_duk, "MOUSE_RIGHT", MOUSE_BUTTON_RIGHT); api_register_const(g_duk, "MOUSE_WHEEL_UP", MOUSE_WHEEL_UP); api_register_const(g_duk, "MOUSE_WHEEL_DOWN", MOUSE_WHEEL_DOWN); api_register_const(g_duk, "JOYSTICK_AXIS_X", 0); api_register_const(g_duk, "JOYSTICK_AXIS_Y", 1); api_register_const(g_duk, "JOYSTICK_AXIS_Z", 2); api_register_const(g_duk, "JOYSTICK_AXIS_R", 3); api_register_const(g_duk, "JOYSTICK_AXIS_U", 4); api_register_const(g_duk, "JOYSTICK_AXIS_V", 5); api_register_method(g_duk, NULL, "AreKeysLeft", js_AreKeysLeft); api_register_method(g_duk, NULL, "IsAnyKeyPressed", js_IsAnyKeyPressed); api_register_method(g_duk, NULL, "IsJoystickButtonPressed", js_IsJoystickButtonPressed); api_register_method(g_duk, NULL, "IsKeyPressed", js_IsKeyPressed); api_register_method(g_duk, NULL, "IsMouseButtonPressed", js_IsMouseButtonPressed); api_register_method(g_duk, NULL, "GetJoystickAxis", js_GetJoystickAxis); api_register_method(g_duk, NULL, "GetKey", js_GetKey); api_register_method(g_duk, NULL, "GetKeyString", js_GetKeyString); api_register_method(g_duk, NULL, "GetMouseWheelEvent", js_GetMouseWheelEvent); api_register_method(g_duk, NULL, "GetMouseX", js_GetMouseX); api_register_method(g_duk, NULL, "GetMouseY", js_GetMouseY); api_register_method(g_duk, NULL, "GetNumJoysticks", js_GetNumJoysticks); api_register_method(g_duk, NULL, "GetNumJoystickAxes", js_GetNumJoystickAxes); api_register_method(g_duk, NULL, "GetNumJoystickButtons", js_GetNumJoystickButtons); api_register_method(g_duk, NULL, "GetNumMouseWheelEvents", js_GetNumMouseWheelEvents); api_register_method(g_duk, NULL, "GetPlayerKey", js_GetPlayerKey); api_register_method(g_duk, NULL, "GetToggleState", js_GetToggleState); api_register_method(g_duk, NULL, "SetMousePosition", js_SetMousePosition); api_register_method(g_duk, NULL, "SetPlayerKey", js_SetPlayerKey); api_register_method(g_duk, NULL, "BindJoystickButton", js_BindJoystickButton); api_register_method(g_duk, NULL, "BindKey", js_BindKey); api_register_method(g_duk, NULL, "ClearKeyQueue", js_ClearKeyQueue); api_register_method(g_duk, NULL, "UnbindJoystickButton", js_UnbindJoystickButton); api_register_method(g_duk, NULL, "UnbindKey", js_UnbindKey); } static void queue_key(int keycode) { int key_index; if (s_key_queue.num_keys < 255) { key_index = s_key_queue.num_keys; ++s_key_queue.num_keys; s_key_queue.keys[key_index] = keycode; } } static void queue_wheel_event(int event) { if (s_num_wheel_events < 255) { s_wheel_queue[s_num_wheel_events] = event; ++s_num_wheel_events; } } static duk_ret_t js_AreKeysLeft(duk_context* ctx) { update_input(); duk_push_boolean(ctx, s_key_queue.num_keys > 0); return 1; } static duk_ret_t js_IsAnyKeyPressed(duk_context* ctx) { duk_push_boolean(ctx, is_any_key_down()); return 1; } static duk_ret_t js_IsJoystickButtonPressed(duk_context* ctx) { int joy_index = duk_require_int(ctx, 0); int button = duk_require_int(ctx, 1); duk_push_boolean(ctx, is_joy_button_down(joy_index, button)); return 1; } static duk_ret_t js_IsKeyPressed(duk_context* ctx) { int keycode = duk_require_int(ctx, 0); duk_push_boolean(ctx, is_key_down(keycode)); return 1; } static duk_ret_t js_IsMouseButtonPressed(duk_context* ctx) { int button; int button_id; ALLEGRO_DISPLAY* display; ALLEGRO_MOUSE_STATE mouse_state; button = duk_require_int(ctx, 0); button_id = button == MOUSE_BUTTON_RIGHT ? 2 : button == MOUSE_BUTTON_MIDDLE ? 3 : 1; al_get_mouse_state(&mouse_state); display = screen_display(g_screen); duk_push_boolean(ctx, mouse_state.display == display && al_mouse_button_down(&mouse_state, button_id)); return 1; } static duk_ret_t js_GetJoystickAxis(duk_context* ctx) { int joy_index = duk_require_int(ctx, 0); int axis_index = duk_require_int(ctx, 1); duk_push_number(ctx, get_joy_axis(joy_index, axis_index)); return 1; } static duk_ret_t js_GetKey(duk_context* ctx) { int keycode; while (s_key_queue.num_keys == 0) { do_events(); } keycode = s_key_queue.keys[0]; --s_key_queue.num_keys; memmove(s_key_queue.keys, &s_key_queue.keys[1], sizeof(int) * s_key_queue.num_keys); duk_push_int(ctx, keycode); return 1; } static duk_ret_t js_GetKeyString(duk_context* ctx) { int n_args = duk_get_top(ctx); int keycode = duk_require_int(ctx, 0); bool shift = n_args >= 2 ? duk_require_boolean(ctx, 1) : false; switch (keycode) { case ALLEGRO_KEY_A: duk_push_string(ctx, shift ? "A" : "a"); break; case ALLEGRO_KEY_B: duk_push_string(ctx, shift ? "B" : "b"); break; case ALLEGRO_KEY_C: duk_push_string(ctx, shift ? "C" : "c"); break; case ALLEGRO_KEY_D: duk_push_string(ctx, shift ? "D" : "d"); break; case ALLEGRO_KEY_E: duk_push_string(ctx, shift ? "E" : "e"); break; case ALLEGRO_KEY_F: duk_push_string(ctx, shift ? "F" : "f"); break; case ALLEGRO_KEY_G: duk_push_string(ctx, shift ? "G" : "g"); break; case ALLEGRO_KEY_H: duk_push_string(ctx, shift ? "H" : "h"); break; case ALLEGRO_KEY_I: duk_push_string(ctx, shift ? "I" : "i"); break; case ALLEGRO_KEY_J: duk_push_string(ctx, shift ? "J" : "j"); break; case ALLEGRO_KEY_K: duk_push_string(ctx, shift ? "K" : "k"); break; case ALLEGRO_KEY_L: duk_push_string(ctx, shift ? "L" : "l"); break; case ALLEGRO_KEY_M: duk_push_string(ctx, shift ? "M" : "m"); break; case ALLEGRO_KEY_N: duk_push_string(ctx, shift ? "N" : "n"); break; case ALLEGRO_KEY_O: duk_push_string(ctx, shift ? "O" : "o"); break; case ALLEGRO_KEY_P: duk_push_string(ctx, shift ? "P" : "p"); break; case ALLEGRO_KEY_Q: duk_push_string(ctx, shift ? "Q" : "q"); break; case ALLEGRO_KEY_R: duk_push_string(ctx, shift ? "R" : "r"); break; case ALLEGRO_KEY_S: duk_push_string(ctx, shift ? "S" : "s"); break; case ALLEGRO_KEY_T: duk_push_string(ctx, shift ? "T" : "t"); break; case ALLEGRO_KEY_U: duk_push_string(ctx, shift ? "U" : "u"); break; case ALLEGRO_KEY_V: duk_push_string(ctx, shift ? "V" : "v"); break; case ALLEGRO_KEY_W: duk_push_string(ctx, shift ? "W" : "w"); break; case ALLEGRO_KEY_X: duk_push_string(ctx, shift ? "X" : "x"); break; case ALLEGRO_KEY_Y: duk_push_string(ctx, shift ? "Y" : "y"); break; case ALLEGRO_KEY_Z: duk_push_string(ctx, shift ? "Z" : "z"); break; case ALLEGRO_KEY_1: duk_push_string(ctx, shift ? "!" : "1"); break; case ALLEGRO_KEY_2: duk_push_string(ctx, shift ? "@" : "2"); break; case ALLEGRO_KEY_3: duk_push_string(ctx, shift ? "#" : "3"); break; case ALLEGRO_KEY_4: duk_push_string(ctx, shift ? "$" : "4"); break; case ALLEGRO_KEY_5: duk_push_string(ctx, shift ? "%" : "5"); break; case ALLEGRO_KEY_6: duk_push_string(ctx, shift ? "^" : "6"); break; case ALLEGRO_KEY_7: duk_push_string(ctx, shift ? "&" : "7"); break; case ALLEGRO_KEY_8: duk_push_string(ctx, shift ? "*" : "8"); break; case ALLEGRO_KEY_9: duk_push_string(ctx, shift ? "(" : "9"); break; case ALLEGRO_KEY_0: duk_push_string(ctx, shift ? ")" : "0"); break; case ALLEGRO_KEY_BACKSLASH: duk_push_string(ctx, shift ? "|" : "\\"); break; case ALLEGRO_KEY_FULLSTOP: duk_push_string(ctx, shift ? ">" : "."); break; case ALLEGRO_KEY_CLOSEBRACE: duk_push_string(ctx, shift ? "}" : "]"); break; case ALLEGRO_KEY_COMMA: duk_push_string(ctx, shift ? "<" : ","); break; case ALLEGRO_KEY_EQUALS: duk_push_string(ctx, shift ? "+" : "="); break; case ALLEGRO_KEY_MINUS: duk_push_string(ctx, shift ? "_" : "-"); break; case ALLEGRO_KEY_QUOTE: duk_push_string(ctx, shift ? "\"" : "'"); break; case ALLEGRO_KEY_OPENBRACE: duk_push_string(ctx, shift ? "{" : "["); break; case ALLEGRO_KEY_SEMICOLON: duk_push_string(ctx, shift ? ":" : ";"); break; case ALLEGRO_KEY_SLASH: duk_push_string(ctx, shift ? "?" : "/"); break; case ALLEGRO_KEY_SPACE: duk_push_string(ctx, " "); break; case ALLEGRO_KEY_TAB: duk_push_string(ctx, "\t"); break; case ALLEGRO_KEY_TILDE: duk_push_string(ctx, shift ? "~" : "`"); break; default: duk_push_string(ctx, ""); } return 1; } static duk_ret_t js_GetMouseWheelEvent(duk_context* ctx) { int event; int i; while (s_num_wheel_events == 0) { do_events(); } event = s_wheel_queue[0]; --s_num_wheel_events; for (i = 0; i < s_num_wheel_events; ++i) s_wheel_queue[i] = s_wheel_queue[i + 1]; duk_push_int(ctx, event); return 1; } static duk_ret_t js_GetMouseX(duk_context* ctx) { int x; int y; screen_get_mouse_xy(g_screen, &x, &y); duk_push_int(ctx, x); return 1; } static duk_ret_t js_GetMouseY(duk_context* ctx) { int x; int y; screen_get_mouse_xy(g_screen, &x, &y); duk_push_int(ctx, y); return 1; } static duk_ret_t js_GetNumJoysticks(duk_context* ctx) { duk_push_int(ctx, s_num_joysticks); return 1; } static duk_ret_t js_GetNumJoystickAxes(duk_context* ctx) { int joy_index = duk_require_int(ctx, 0); duk_push_int(ctx, get_joy_axis_count(joy_index)); return 1; } static duk_ret_t js_GetNumJoystickButtons(duk_context* ctx) { int joy_index = duk_require_int(ctx, 0); duk_push_int(ctx, get_joy_button_count(joy_index)); return 1; } static duk_ret_t js_GetNumMouseWheelEvents(duk_context* ctx) { duk_push_int(ctx, s_num_wheel_events); return 1; } static duk_ret_t js_GetPlayerKey(duk_context* ctx) { int player = duk_require_int(ctx, 0); int key_type = duk_require_int(ctx, 1); if (player < 0 || player >= 4) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetPlayerKey(): player index out of range"); if (key_type < 0 || key_type >= PLAYER_KEY_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetPlayerKey(): invalid key type constant"); duk_push_int(ctx, get_player_key(player, key_type)); return 1; } static duk_ret_t js_GetToggleState(duk_context* ctx) { int keycode = duk_require_int(ctx, 0); int flag; if (keycode != ALLEGRO_KEY_CAPSLOCK && keycode != ALLEGRO_KEY_NUMLOCK && keycode != ALLEGRO_KEY_SCROLLLOCK) { duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "GetToggleState(): invalid toggle key constant"); } flag = keycode == ALLEGRO_KEY_CAPSLOCK ? ALLEGRO_KEYMOD_CAPSLOCK : keycode == ALLEGRO_KEY_NUMLOCK ? ALLEGRO_KEYMOD_NUMLOCK : keycode == ALLEGRO_KEY_SCROLLLOCK ? ALLEGRO_KEYMOD_SCROLLLOCK : 0x0; duk_push_boolean(ctx, (s_keymod_state & flag) != 0); return 1; } static duk_ret_t js_SetMousePosition(duk_context* ctx) { int x; int y; x = duk_require_int(ctx, 0); y = duk_require_int(ctx, 1); screen_set_mouse_xy(g_screen, x, y); return 0; } static duk_ret_t js_SetPlayerKey(duk_context* ctx) { int player = duk_require_int(ctx, 0); int key_type = duk_require_int(ctx, 1); int keycode = duk_require_int(ctx, 2); if (player < 0 || player >= 4) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetPlayerKey(): player index `%d` out of range", player); if (key_type < 0 || key_type >= PLAYER_KEY_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetPlayerKey(): invalid key type constant"); if (keycode < 0 || key_type >= ALLEGRO_KEY_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetPlayerKey(): invalid key constant"); set_player_key(player, key_type, keycode); return 0; } static duk_ret_t js_BindJoystickButton(duk_context* ctx) { int joy_index = duk_require_int(ctx, 0); int button = duk_require_int(ctx, 1); script_t* on_down_script = duk_require_sphere_script(ctx, 2, "[button-down script]"); script_t* on_up_script = duk_require_sphere_script(ctx, 3, "[button-up script]"); if (joy_index < 0 || joy_index >= MAX_JOYSTICKS) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "BindJoystickButton(): joystick index `%d` out of range", joy_index); if (button < 0 || button >= MAX_JOY_BUTTONS) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "BindJoystickButton(): button index `%d` out of range", button); bind_button(s_bound_buttons, joy_index, button, on_down_script, on_up_script); return 0; } static duk_ret_t js_BindKey(duk_context* ctx) { int keycode = duk_require_int(ctx, 0); script_t* on_down_script = duk_require_sphere_script(ctx, 1, "[key-down script]"); script_t* on_up_script = duk_require_sphere_script(ctx, 2, "[key-up script]"); if (keycode < 0 || keycode >= ALLEGRO_KEY_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "BindKey(): invalid key constant"); bind_key(s_bound_map_keys, keycode, on_down_script, on_up_script); return 0; } static duk_ret_t js_ClearKeyQueue(duk_context* ctx) { clear_key_queue(); return 0; } static duk_ret_t js_UnbindJoystickButton(duk_context* ctx) { int joy_index = duk_require_int(ctx, 0); int button = duk_require_int(ctx, 1); if (joy_index < 0 || joy_index >= MAX_JOYSTICKS) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "BindJoystickButton(): joystick index `%d` out of range", joy_index); if (button < 0 || button >= MAX_JOY_BUTTONS) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "BindJoystickButton(): button index `%d` out of range", button); bind_button(s_bound_buttons, joy_index, button, NULL, NULL); return 0; } static duk_ret_t js_UnbindKey(duk_context* ctx) { int keycode = duk_require_int(ctx, 0); if (keycode < 0 || keycode >= ALLEGRO_KEY_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "UnbindKey(): invalid key constant"); bind_key(s_bound_map_keys, keycode, NULL, NULL); return 0; } <file_sep>/src/debugger/backtrace.c #include "ssj.h" #include "backtrace.h" struct frame { char* name; char* filename; int lineno; }; struct backtrace { int num_frames; struct frame* frames; }; backtrace_t* backtrace_new(void) { backtrace_t* obj; obj = calloc(1, sizeof(backtrace_t)); return obj; } void backtrace_free(backtrace_t* obj) { int i; if (obj == NULL) return; for (i = 0; i < obj->num_frames; ++i) { free(obj->frames[i].name); free(obj->frames[i].filename); } free(obj->frames); free(obj); } int backtrace_len(const backtrace_t* obj) { return obj->num_frames; } const char* backtrace_get_call_name(const backtrace_t* obj, int index) { return obj->frames[index].name; } const char* backtrace_get_filename(const backtrace_t* obj, int index) { return obj->frames[index].filename; } int backtrace_get_linenum(const backtrace_t* obj, int index) { return obj->frames[index].lineno; } void backtrace_add(backtrace_t* obj, const char* call_name, const char* filename, int line_no) { int index; index = obj->num_frames++; obj->frames = realloc(obj->frames, obj->num_frames * sizeof(struct frame)); obj->frames[index].name = strdup(call_name); obj->frames[index].filename = strdup(filename); obj->frames[index].lineno = line_no; } void backtrace_print(const backtrace_t* obj, int active_frame, bool show_all) { const char* arrow; const char* filename; int line_no; const char* name; int i; for (i = 0; i < backtrace_len(obj); ++i) { name = backtrace_get_call_name(obj, i); filename = backtrace_get_filename(obj, i); line_no = backtrace_get_linenum(obj, i); if (i == active_frame || show_all) { arrow = i == active_frame ? "=>" : " "; if (i == active_frame) printf("\33[0;1m"); if (line_no > 0) printf("%s #%2d: %s at %s:%d\n", arrow, i, name, filename, line_no); else printf("%s #%2d: %s <system call>\n", arrow, i, name); printf("\33[m"); } } } <file_sep>/src/compiler/tileset.h #ifndef CELL__TILESET_H__INCLUDED #define CELL__TILESET_H__INCLUDED #include "image.h" #include "path.h" void build_tileset (const path_t* path, const image_t* image, int tile_width, int tile_height); #endif // CELL__TILESET_H__INCLUDED <file_sep>/src/compiler/posix.h #ifndef CELL__POSIX_H__INCLUDED #define CELL__POSIX_H__INCLUDED #if defined(_MSC_VER) #define _CRT_NONSTDC_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #define strcasecmp stricmp #define strtok_r strtok_s #if _MSC_VER < 1900 #define snprintf _snprintf #endif #endif #endif // CELL__POSIX_H__INCLUDED <file_sep>/src/engine/geometry.h #ifndef MINISPHERE__GEOMETRY_H__INCLUDED #define MINISPHERE__GEOMETRY_H__INCLUDED typedef struct point3 { int x; int y; int z; } point3_t; typedef struct rect { int x1; int y1; int x2; int y2; } rect_t; typedef struct float_rect { float x1; float y1; float x2; float y2; } float_rect_t; rect_t new_rect (int x1, int y1, int x2, int y2); float_rect_t new_float_rect (float x1, float y1, float x2, float y2); bool do_lines_intersect (rect_t a, rect_t b); bool do_rects_intersect (rect_t a, rect_t b); bool is_point_in_rect (int x, int y, rect_t bounds); void normalize_rect (rect_t* inout_rect); float_rect_t scale_float_rect (float_rect_t rect, float x_scale, float y_scale); rect_t translate_rect (rect_t rect, int x_offset, int y_offset); float_rect_t translate_float_rect (float_rect_t rect, float x_offset, float y_offset); rect_t zoom_rect (rect_t rect, double scale_x, double scale_y); bool fread_rect_16 (sfs_file_t* file, rect_t* out_rect); bool fread_rect_32 (sfs_file_t* file, rect_t* out_rect); #endif // MINISPHERE__GEOMETRY_H__INCLUDED <file_sep>/src/engine/image.c #include "minisphere.h" #include "api.h" #include "color.h" #include "surface.h" #include "image.h" struct image { unsigned int refcount; unsigned int id; ALLEGRO_BITMAP* bitmap; unsigned int cache_hits; image_lock_t lock; unsigned int lock_count; color_t* pixel_cache; int width; int height; image_t* parent; }; static duk_ret_t js_GetSystemArrow (duk_context* ctx); static duk_ret_t js_GetSystemDownArrow (duk_context* ctx); static duk_ret_t js_GetSystemUpArrow (duk_context* ctx); static duk_ret_t js_LoadImage (duk_context* ctx); static duk_ret_t js_GrabImage (duk_context* ctx); static duk_ret_t js_new_Image (duk_context* ctx); static duk_ret_t js_Image_finalize (duk_context* ctx); static duk_ret_t js_Image_toString (duk_context* ctx); static duk_ret_t js_Image_get_height (duk_context* ctx); static duk_ret_t js_Image_get_width (duk_context* ctx); static duk_ret_t js_Image_blit (duk_context* ctx); static duk_ret_t js_Image_blitMask (duk_context* ctx); static duk_ret_t js_Image_createSurface (duk_context* ctx); static duk_ret_t js_Image_rotateBlit (duk_context* ctx); static duk_ret_t js_Image_rotateBlitMask (duk_context* ctx); static duk_ret_t js_Image_transformBlit (duk_context* ctx); static duk_ret_t js_Image_transformBlitMask (duk_context* ctx); static duk_ret_t js_Image_zoomBlit (duk_context* ctx); static duk_ret_t js_Image_zoomBlitMask (duk_context* ctx); static void cache_pixels (image_t* image); static void uncache_pixels (image_t* image); static unsigned int s_next_image_id = 0; static image_t* s_sys_arrow = NULL; static image_t* s_sys_dn_arrow = NULL; static image_t* s_sys_up_arrow = NULL; image_t* create_image(int width, int height) { image_t* image; console_log(3, "creating image #%u at %ix%i", s_next_image_id, width, height); image = calloc(1, sizeof(image_t)); if ((image->bitmap = al_create_bitmap(width, height)) == NULL) goto on_error; image->id = s_next_image_id++; image->width = al_get_bitmap_width(image->bitmap); image->height = al_get_bitmap_height(image->bitmap); return ref_image(image); on_error: free(image); return NULL; } image_t* create_subimage(image_t* parent, int x, int y, int width, int height) { image_t* image; console_log(3, "creating image #%u as %ix%i subimage of image #%u", s_next_image_id, width, height, parent->id); image = calloc(1, sizeof(image_t)); if (!(image->bitmap = al_create_sub_bitmap(parent->bitmap, x, y, width, height))) goto on_error; image->id = s_next_image_id++; image->width = al_get_bitmap_width(image->bitmap); image->height = al_get_bitmap_height(image->bitmap); image->parent = ref_image(parent); return ref_image(image); on_error: free(image); return NULL; } image_t* clone_image(const image_t* src_image) { image_t* image; console_log(3, "cloning image #%u from source image #%u", s_next_image_id, src_image->id); image = calloc(1, sizeof(image_t)); if (!(image->bitmap = al_clone_bitmap(src_image->bitmap))) goto on_error; image->id = s_next_image_id++; image->width = al_get_bitmap_width(image->bitmap); image->height = al_get_bitmap_height(image->bitmap); return ref_image(image); on_error: free(image); return NULL; } image_t* load_image(const char* filename) { ALLEGRO_FILE* al_file = NULL; const char* file_ext; size_t file_size; uint8_t first_16[16]; image_t* image; void* slurp = NULL; console_log(2, "loading image #%u as `%s`", s_next_image_id, filename); image = calloc(1, sizeof(image_t)); if (!(slurp = sfs_fslurp(g_fs, filename, NULL, &file_size))) goto on_error; al_file = al_open_memfile(slurp, file_size, "rb"); // look at the first 16 bytes of the file to determine its actual type. // Allegro won't load it if the content doesn't match the file extension, so // we have to inspect the file ourselves. al_fread(al_file, first_16, 16); al_fseek(al_file, 0, ALLEGRO_SEEK_SET); file_ext = strrchr(filename, '.'); if (memcmp(first_16, "BM", 2) == 0) file_ext = ".bmp"; if (memcmp(first_16, "\211PNG\r\n\032\n", 8) == 0) file_ext = ".png"; if (memcmp(first_16, "\0xFF\0xD8", 2) == 0) file_ext = ".jpg"; if (!(image->bitmap = al_load_bitmap_f(al_file, file_ext))) goto on_error; al_fclose(al_file); free(slurp); image->width = al_get_bitmap_width(image->bitmap); image->height = al_get_bitmap_height(image->bitmap); image->id = s_next_image_id++; return ref_image(image); on_error: console_log(2, " failed to load image #%u", s_next_image_id++); if (al_file != NULL) al_fclose(al_file); free(slurp); free(image); return NULL; } image_t* read_image(sfs_file_t* file, int width, int height) { long file_pos; image_t* image; uint8_t* line_ptr; size_t line_size; ALLEGRO_LOCKED_REGION* lock = NULL; int i_y; console_log(3, "reading %ix%i image #%u from open file", width, height, s_next_image_id); image = calloc(1, sizeof(image_t)); file_pos = sfs_ftell(file); if (!(image->bitmap = al_create_bitmap(width, height))) goto on_error; if (!(lock = al_lock_bitmap(image->bitmap, ALLEGRO_PIXEL_FORMAT_ABGR_8888, ALLEGRO_LOCK_WRITEONLY))) goto on_error; line_size = width * 4; for (i_y = 0; i_y < height; ++i_y) { line_ptr = (uint8_t*)lock->data + i_y * lock->pitch; if (sfs_fread(line_ptr, line_size, 1, file) != 1) goto on_error; } al_unlock_bitmap(image->bitmap); image->id = s_next_image_id++; image->width = al_get_bitmap_width(image->bitmap); image->height = al_get_bitmap_height(image->bitmap); return ref_image(image); on_error: console_log(3, " failed!"); sfs_fseek(file, file_pos, SEEK_SET); if (lock != NULL) al_unlock_bitmap(image->bitmap); if (image != NULL) { if (image->bitmap != NULL) al_destroy_bitmap(image->bitmap); free(image); } return NULL; } image_t* read_subimage(sfs_file_t* file, image_t* parent, int x, int y, int width, int height) { long file_pos; image_t* image; image_lock_t* lock = NULL; color_t *pline; int i_y; file_pos = sfs_ftell(file); if (!(image = create_subimage(parent, x, y, width, height))) goto on_error; if (!(lock = lock_image(parent))) goto on_error; for (i_y = 0; i_y < height; ++i_y) { pline = lock->pixels + x + (i_y + y) * lock->pitch; if (sfs_fread(pline, width * 4, 1, file) != 1) goto on_error; } unlock_image(parent, lock); return image; on_error: sfs_fseek(file, file_pos, SEEK_SET); if (lock != NULL) unlock_image(parent, lock); free_image(image); return NULL; } image_t* ref_image(image_t* image) { if (image != NULL) ++image->refcount; return image; } void free_image(image_t* image) { if (image == NULL || --image->refcount > 0) return; console_log(3, "disposing image #%u no longer in use", image->id); uncache_pixels(image); al_destroy_bitmap(image->bitmap); free_image(image->parent); free(image); } ALLEGRO_BITMAP* get_image_bitmap(image_t* image) { uncache_pixels(image); return image->bitmap; } int get_image_height(const image_t* image) { return image->height; } color_t get_image_pixel(image_t* image, int x, int y) { if (image->pixel_cache == NULL) { console_log(4, "get_image_pixel() cache miss for image #%u", image->id); cache_pixels(image); } else ++image->cache_hits; return image->pixel_cache[x + y * image->width]; } int get_image_width(const image_t* image) { return image->width; } void set_image_pixel(image_t* image, int x, int y, color_t color) { ALLEGRO_BITMAP* old_target; uncache_pixels(image); old_target = al_get_target_bitmap(); al_set_target_bitmap(image->bitmap); al_draw_pixel(x + 0.5, y + 0.5, nativecolor(color)); al_set_target_bitmap(old_target); } bool apply_color_matrix(image_t* image, colormatrix_t matrix, int x, int y, int width, int height) { image_lock_t* lock; color_t* pixel; int i_x, i_y; if (!(lock = lock_image(image))) return false; uncache_pixels(image); for (i_x = x; i_x < x + width; ++i_x) for (i_y = y; i_y < y + height; ++i_y) { pixel = &lock->pixels[i_x + i_y * lock->pitch]; *pixel = color_transform(*pixel, matrix); } unlock_image(image, lock); return true; } bool apply_color_matrix_4(image_t* image, colormatrix_t ul_mat, colormatrix_t ur_mat, colormatrix_t ll_mat, colormatrix_t lr_mat, int x, int y, int w, int h) { // this function might be difficult to understand at first. the implementation // is, however, much easier to follow than the one in Sphere. basically what it // boils down to is bilinear interpolation, but with matrices. it's much more // straightforward than it sounds. int i1, i2; image_lock_t* lock; colormatrix_t mat_1, mat_2, mat_3; color_t* pixel; int i_x, i_y; if (!(lock = lock_image(image))) return false; uncache_pixels(image); for (i_y = y; i_y < y + h; ++i_y) { // thankfully, we don't have to do a full bilinear interpolation every frame. // two thirds of the work is done in the outer loop, giving us two color matrices // which we then use in the inner loop to calculate the transforms for individual // pixels. i1 = y + h - 1 - i_y; i2 = i_y - y; mat_1 = colormatrix_lerp(ul_mat, ll_mat, i1, i2); mat_2 = colormatrix_lerp(ur_mat, lr_mat, i1, i2); for (i_x = x; i_x < x + w; ++i_x) { // calculate the final matrix for this pixel and transform it i1 = x + w - 1 - i_x; i2 = i_x - x; mat_3 = colormatrix_lerp(mat_1, mat_2, i1, i2); pixel = &lock->pixels[i_x + i_y * lock->pitch]; *pixel = color_transform(*pixel, mat_3); } } unlock_image(image, lock); return true; } bool apply_image_lookup(image_t* image, int x, int y, int width, int height, uint8_t red_lu[256], uint8_t green_lu[256], uint8_t blue_lu[256], uint8_t alpha_lu[256]) { ALLEGRO_BITMAP* bitmap = get_image_bitmap(image); uint8_t* pixel; ALLEGRO_LOCKED_REGION* lock; int i_x, i_y; if ((lock = al_lock_bitmap(bitmap, ALLEGRO_PIXEL_FORMAT_ABGR_8888, ALLEGRO_LOCK_READWRITE)) == NULL) return false; uncache_pixels(image); for (i_x = x; i_x < x + width; ++i_x) for (i_y = y; i_y < y + height; ++i_y) { pixel = (uint8_t*)lock->data + i_x * 4 + i_y * lock->pitch; pixel[0] = red_lu[pixel[0]]; pixel[1] = green_lu[pixel[1]]; pixel[2] = blue_lu[pixel[2]]; pixel[3] = alpha_lu[pixel[3]]; } al_unlock_bitmap(bitmap); return true; } void blit_image(image_t* image, image_t* target_image, int x, int y) { int blend_mode_dest; int blend_mode_src; int blend_op; al_set_target_bitmap(get_image_bitmap(target_image)); al_get_blender(&blend_op, &blend_mode_src, &blend_mode_dest); al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO); al_draw_bitmap(get_image_bitmap(image), x, y, 0x0); al_set_blender(blend_op, blend_mode_src, blend_mode_dest); al_set_target_backbuffer(screen_display(g_screen)); } void draw_image(image_t* image, int x, int y) { al_draw_bitmap(image->bitmap, x, y, 0x0); } void draw_image_masked(image_t* image, color_t mask, int x, int y) { al_draw_tinted_bitmap(image->bitmap, al_map_rgba(mask.r, mask.g, mask.b, mask.alpha), x, y, 0x0); } void draw_image_scaled(image_t* image, int x, int y, int width, int height) { al_draw_scaled_bitmap(image->bitmap, 0, 0, al_get_bitmap_width(image->bitmap), al_get_bitmap_height(image->bitmap), x, y, width, height, 0x0); } void draw_image_scaled_masked(image_t* image, color_t mask, int x, int y, int width, int height) { al_draw_tinted_scaled_bitmap(image->bitmap, nativecolor(mask), 0, 0, al_get_bitmap_width(image->bitmap), al_get_bitmap_height(image->bitmap), x, y, width, height, 0x0); } void draw_image_tiled(image_t* image, int x, int y, int width, int height) { draw_image_tiled_masked(image, color_new(255, 255, 255, 255), x, y, width, height); } void draw_image_tiled_masked(image_t* image, color_t mask, int x, int y, int width, int height) { ALLEGRO_COLOR native_mask = nativecolor(mask); int img_w, img_h; bool is_drawing_held; int tile_w, tile_h; int i_x, i_y; img_w = image->width; img_h = image->height; if (img_w >= 16 && img_h >= 16) { // tile in hardware whenever possible ALLEGRO_VERTEX vbuf[] = { { x, y, 0, 0, 0, native_mask }, { x + width, y, 0, width, 0, native_mask }, { x, y + height, 0, 0, height, native_mask }, { x + width, y + height, 0, width, height, native_mask } }; al_draw_prim(vbuf, NULL, image->bitmap, 0, 4, ALLEGRO_PRIM_TRIANGLE_STRIP); } else { // texture smaller than 16x16, tile it in software (Allegro pads it) is_drawing_held = al_is_bitmap_drawing_held(); al_hold_bitmap_drawing(true); for (i_x = width / img_w; i_x >= 0; --i_x) for (i_y = height / img_h; i_y >= 0; --i_y) { tile_w = i_x == width / img_w ? width % img_w : img_w; tile_h = i_y == height / img_h ? height % img_h : img_h; al_draw_tinted_bitmap_region(image->bitmap, native_mask, 0, 0, tile_w, tile_h, x + i_x * img_w, y + i_y * img_h, 0x0); } al_hold_bitmap_drawing(is_drawing_held); } } void fill_image(image_t* image, color_t color) { int clip_x, clip_y, clip_w, clip_h; ALLEGRO_BITMAP* last_target; uncache_pixels(image); al_get_clipping_rectangle(&clip_x, &clip_y, &clip_w, &clip_h); al_reset_clipping_rectangle(); last_target = al_get_target_bitmap(); al_set_target_bitmap(image->bitmap); al_clear_to_color(al_map_rgba(color.r, color.g, color.b, color.alpha)); al_set_target_bitmap(last_target); al_set_clipping_rectangle(clip_x, clip_y, clip_w, clip_h); } bool flip_image(image_t* image, bool is_h_flip, bool is_v_flip) { int draw_flags = 0x0; ALLEGRO_BITMAP* new_bitmap; ALLEGRO_BITMAP* old_target; if (!is_h_flip && !is_v_flip) // this really shouldn't happen... return true; uncache_pixels(image); if (!(new_bitmap = al_create_bitmap(image->width, image->height))) return false; old_target = al_get_target_bitmap(); al_set_target_bitmap(new_bitmap); if (is_h_flip) draw_flags |= ALLEGRO_FLIP_HORIZONTAL; if (is_v_flip) draw_flags |= ALLEGRO_FLIP_VERTICAL; al_draw_bitmap(image->bitmap, 0, 0, draw_flags); al_set_target_bitmap(old_target); al_destroy_bitmap(image->bitmap); image->bitmap = new_bitmap; return true; } image_lock_t* lock_image(image_t* image) { ALLEGRO_LOCKED_REGION* ll_lock; if (image->lock_count == 0) { if (!(ll_lock = al_lock_bitmap(image->bitmap, ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE, ALLEGRO_LOCK_READWRITE))) return NULL; ref_image(image); image->lock.pixels = ll_lock->data; image->lock.pitch = ll_lock->pitch / 4; image->lock.num_lines = image->height; } ++image->lock_count; return &image->lock; } bool replace_image_color(image_t* image, color_t color, color_t new_color) { ALLEGRO_BITMAP* bitmap = get_image_bitmap(image); uint8_t* pixel; ALLEGRO_LOCKED_REGION* lock; int w, h; int i_x, i_y; if ((lock = al_lock_bitmap(bitmap, ALLEGRO_PIXEL_FORMAT_ABGR_8888, ALLEGRO_LOCK_READWRITE)) == NULL) return false; uncache_pixels(image); w = al_get_bitmap_width(bitmap); h = al_get_bitmap_height(bitmap); for (i_x = 0; i_x < w; ++i_x) for (i_y = 0; i_y < h; ++i_y) { pixel = (uint8_t*)lock->data + i_x * 4 + i_y * lock->pitch; if (pixel[0] == color.r && pixel[1] == color.g && pixel[2] == color.b && pixel[3] == color.alpha) { pixel[0] = new_color.r; pixel[1] = new_color.g; pixel[2] = new_color.b; pixel[3] = new_color.alpha; } } al_unlock_bitmap(bitmap); return true; } bool rescale_image(image_t* image, int width, int height) { ALLEGRO_BITMAP* new_bitmap; ALLEGRO_BITMAP* old_target; if (width == image->width && height == image->height) return true; if (!(new_bitmap = al_create_bitmap(width, height))) return false; uncache_pixels(image); old_target = al_get_target_bitmap(); al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO); al_set_target_bitmap(new_bitmap); al_draw_scaled_bitmap(image->bitmap, 0, 0, image->width, image->height, 0, 0, width, height, 0x0); al_set_target_bitmap(old_target); al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA); al_destroy_bitmap(image->bitmap); image->bitmap = new_bitmap; image->width = al_get_bitmap_width(image->bitmap); image->height = al_get_bitmap_height(image->bitmap); return true; } bool save_image(image_t* image, const char* filename) { void* buffer = NULL; size_t file_size; bool is_eof; ALLEGRO_FILE* memfile; size_t next_buf_size; bool result; next_buf_size = 65536; do { buffer = realloc(buffer, next_buf_size); memfile = al_open_memfile(buffer, next_buf_size, "wb"); next_buf_size *= 2; al_save_bitmap_f(memfile, strrchr(filename, '.'), image->bitmap); file_size = al_ftell(memfile); is_eof = al_feof(memfile); al_fclose(memfile); } while (is_eof); result = sfs_fspew(g_fs, filename, NULL, buffer, file_size); free(buffer); return result; } void unlock_image(image_t* image, image_lock_t* lock) { // if the caller provides the wrong lock pointer, the image // won't be unlocked. this prevents accidental unlocking. if (lock != &image->lock) return; if (image->lock_count == 0 || --image->lock_count > 0) return; al_unlock_bitmap(image->bitmap); free_image(image); } static void cache_pixels(image_t* image) { color_t* cache; image_lock_t* lock; void *psrc, *pdest; int i; free(image->pixel_cache); image->pixel_cache = NULL; if (!(lock = lock_image(image))) goto on_error; if (!(cache = malloc(image->width * image->height * 4))) goto on_error; console_log(4, "creating new pixel cache for image #%u", image->id); for (i = 0; i < image->height; ++i) { psrc = lock->pixels + i * lock->pitch; pdest = cache + i * image->width; memcpy(pdest, psrc, image->width * 4); } unlock_image(image, lock); image->pixel_cache = cache; image->cache_hits = 0; return; on_error: if (lock != NULL) al_unlock_bitmap(image->bitmap); } static void uncache_pixels(image_t* image) { if (image->pixel_cache == NULL) return; console_log(4, "pixel cache invalidated for image #%u, hits: %u", image->id, image->cache_hits); free(image->pixel_cache); image->pixel_cache = NULL; } void init_image_api(duk_context* ctx) { const char* filename; // load system-provided images if (g_sys_conf != NULL) { filename = kev_read_string(g_sys_conf, "Arrow", "pointer.png"); s_sys_arrow = load_image(systempath(filename)); filename = kev_read_string(g_sys_conf, "UpArrow", "up_arrow.png"); s_sys_up_arrow = load_image(systempath(filename)); filename = kev_read_string(g_sys_conf, "DownArrow", "down_arrow.png"); s_sys_dn_arrow = load_image(systempath(filename)); } // register image API functions api_register_method(ctx, NULL, "GetSystemArrow", js_GetSystemArrow); api_register_method(ctx, NULL, "GetSystemDownArrow", js_GetSystemDownArrow); api_register_method(ctx, NULL, "GetSystemUpArrow", js_GetSystemUpArrow); api_register_method(ctx, NULL, "LoadImage", js_LoadImage); api_register_method(ctx, NULL, "GrabImage", js_GrabImage); // register Image properties and methods api_register_ctor(ctx, "Image", js_new_Image, js_Image_finalize); api_register_method(ctx, "Image", "toString", js_Image_toString); api_register_prop(ctx, "Image", "height", js_Image_get_height, NULL); api_register_prop(ctx, "Image", "width", js_Image_get_width, NULL); api_register_method(ctx, "Image", "blit", js_Image_blit); api_register_method(ctx, "Image", "blitMask", js_Image_blitMask); api_register_method(ctx, "Image", "createSurface", js_Image_createSurface); api_register_method(ctx, "Image", "rotateBlit", js_Image_rotateBlit); api_register_method(ctx, "Image", "rotateBlitMask", js_Image_rotateBlitMask); api_register_method(ctx, "Image", "transformBlit", js_Image_transformBlit); api_register_method(ctx, "Image", "transformBlitMask", js_Image_transformBlitMask); api_register_method(ctx, "Image", "zoomBlit", js_Image_zoomBlit); api_register_method(ctx, "Image", "zoomBlitMask", js_Image_zoomBlitMask); } void duk_push_sphere_image(duk_context* ctx, image_t* image) { duk_push_sphere_obj(ctx, "Image", ref_image(image)); } image_t* duk_require_sphere_image(duk_context* ctx, duk_idx_t index) { return duk_require_sphere_obj(ctx, index, "Image"); } static duk_ret_t js_GetSystemArrow(duk_context* ctx) { if (s_sys_arrow == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetSystemArrow(): missing system arrow image"); duk_push_sphere_image(ctx, s_sys_arrow); return 1; } static duk_ret_t js_GetSystemDownArrow(duk_context* ctx) { if (s_sys_dn_arrow == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetSystemDownArrow(): missing system down arrow image"); duk_push_sphere_image(ctx, s_sys_dn_arrow); return 1; } static duk_ret_t js_GetSystemUpArrow(duk_context* ctx) { if (s_sys_up_arrow == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetSystemUpArrow(): missing system up arrow image"); duk_push_sphere_image(ctx, s_sys_up_arrow); return 1; } static duk_ret_t js_LoadImage(duk_context* ctx) { // LoadImage(filename); (legacy) // Constructs an Image object from an image file. // Arguments: // filename: The name of the image file, relative to ~sgm/images. const char* filename; image_t* image; filename = duk_require_path(ctx, 0, "images", true); if (!(image = load_image(filename))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Image(): unable to load image file `%s`", filename); duk_push_sphere_image(ctx, image); free_image(image); return 1; } static duk_ret_t js_GrabImage(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int w = duk_require_int(ctx, 2); int h = duk_require_int(ctx, 3); image_t* image; if (!(image = screen_grab(g_screen, x, y, w, h))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GrabImage(): unable to grab backbuffer image"); duk_push_sphere_image(ctx, image); free_image(image); return 1; } static duk_ret_t js_new_Image(duk_context* ctx) { const color_t* buffer; size_t buffer_size; const char* filename; color_t fill_color; int height; image_t* image; image_lock_t* lock; int num_args; color_t* p_line; image_t* src_image; int width; int y; num_args = duk_get_top(ctx); if (num_args >= 3 && duk_is_sphere_obj(ctx, 2, "Color")) { // create an Image filled with a single pixel value width = duk_require_int(ctx, 0); height = duk_require_int(ctx, 1); fill_color = duk_require_sphere_color(ctx, 2); if (!(image = create_image(width, height))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Image(): unable to create new image"); fill_image(image, fill_color); } else if (num_args >= 3 && (buffer = duk_get_buffer_data(ctx, 2, &buffer_size))) { // create an Image from an ArrayBuffer or similar object width = duk_require_int(ctx, 0); height = duk_require_int(ctx, 1); if (buffer_size < width * height * sizeof(color_t)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "buffer is too small to describe a %dx%d image", width, height); if (!(image = create_image(width, height))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to create image"); if (!(lock = lock_image(image))) { free_image(image); duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to lock pixels for writing"); } p_line = lock->pixels; for (y = 0; y < height; ++y) { memcpy(p_line, buffer + y * width, width * sizeof(color_t)); p_line += lock->pitch; } unlock_image(image, lock); } else if (duk_is_sphere_obj(ctx, 0, "Surface")) { // create an Image from a Surface src_image = duk_require_sphere_obj(ctx, 0, "Surface"); if (!(image = clone_image(src_image))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Image(): unable to create image from surface"); } else { // create an Image by loading an image file filename = duk_require_path(ctx, 0, NULL, false); image = load_image(filename); if (image == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Image(): unable to load image file `%s`", filename); } duk_push_sphere_image(ctx, image); free_image(image); return 1; } static duk_ret_t js_Image_finalize(duk_context* ctx) { image_t* image; image = duk_require_sphere_image(ctx, 0); free_image(image); return 0; } static duk_ret_t js_Image_get_height(duk_context* ctx) { image_t* image; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); duk_push_int(ctx, get_image_height(image)); return 1; } static duk_ret_t js_Image_get_width(duk_context* ctx) { image_t* image; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); duk_push_int(ctx, get_image_width(image)); return 1; } static duk_ret_t js_Image_toString(duk_context* ctx) { duk_push_string(ctx, "[object image]"); return 1; } static duk_ret_t js_Image_blit(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); image_t* image; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); if (!screen_is_skipframe(g_screen)) al_draw_bitmap(get_image_bitmap(image), x, y, 0x0); return 0; } static duk_ret_t js_Image_blitMask(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); color_t mask = duk_require_sphere_color(ctx, 2); image_t* image; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); if (!screen_is_skipframe(g_screen)) al_draw_tinted_bitmap(get_image_bitmap(image), al_map_rgba(mask.r, mask.g, mask.b, mask.alpha), x, y, 0x0); return 0; } static duk_ret_t js_Image_createSurface(duk_context* ctx) { image_t* image; image_t* new_image; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); if ((new_image = clone_image(image)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Image:createSurface(): unable to create new surface image"); duk_push_sphere_obj(ctx, "Surface", new_image); return 1; } static duk_ret_t js_Image_rotateBlit(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); float angle = duk_require_number(ctx, 2); image_t* image; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); if (!screen_is_skipframe(g_screen)) al_draw_rotated_bitmap(get_image_bitmap(image), image->width / 2, image->height / 2, x + image->width / 2, y + image->height / 2, angle, 0x0); return 0; } static duk_ret_t js_Image_rotateBlitMask(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); float angle = duk_require_number(ctx, 2); color_t mask = duk_require_sphere_color(ctx, 3); image_t* image; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); if (!screen_is_skipframe(g_screen)) al_draw_tinted_rotated_bitmap(get_image_bitmap(image), al_map_rgba(mask.r, mask.g, mask.b, mask.alpha), image->width / 2, image->height / 2, x + image->width / 2, y + image->height / 2, angle, 0x0); return 0; } static duk_ret_t js_Image_transformBlit(duk_context* ctx) { int x1 = duk_require_int(ctx, 0); int y1 = duk_require_int(ctx, 1); int x2 = duk_require_int(ctx, 2); int y2 = duk_require_int(ctx, 3); int x3 = duk_require_int(ctx, 4); int y3 = duk_require_int(ctx, 5); int x4 = duk_require_int(ctx, 6); int y4 = duk_require_int(ctx, 7); image_t* image; ALLEGRO_COLOR vertex_color; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); vertex_color = al_map_rgba(255, 255, 255, 255); ALLEGRO_VERTEX v[] = { { x1 + 0.5, y1 + 0.5, 0, 0, 0, vertex_color }, { x2 + 0.5, y2 + 0.5, 0, image->width, 0, vertex_color }, { x4 + 0.5, y4 + 0.5, 0, 0, image->height, vertex_color }, { x3 + 0.5, y3 + 0.5, 0, image->width, image->height, vertex_color } }; if (!screen_is_skipframe(g_screen)) al_draw_prim(v, NULL, get_image_bitmap(image), 0, 4, ALLEGRO_PRIM_TRIANGLE_STRIP); return 0; } static duk_ret_t js_Image_transformBlitMask(duk_context* ctx) { int x1 = duk_require_int(ctx, 0); int y1 = duk_require_int(ctx, 1); int x2 = duk_require_int(ctx, 2); int y2 = duk_require_int(ctx, 3); int x3 = duk_require_int(ctx, 4); int y3 = duk_require_int(ctx, 5); int x4 = duk_require_int(ctx, 6); int y4 = duk_require_int(ctx, 7); color_t mask = duk_require_sphere_color(ctx, 8); ALLEGRO_COLOR vtx_color; image_t* image; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); vtx_color = al_map_rgba(mask.r, mask.g, mask.b, mask.alpha); ALLEGRO_VERTEX v[] = { { x1 + 0.5, y1 + 0.5, 0, 0, 0, vtx_color }, { x2 + 0.5, y2 + 0.5, 0, image->width, 0, vtx_color }, { x4 + 0.5, y4 + 0.5, 0, 0, image->height, vtx_color }, { x3 + 0.5, y3 + 0.5, 0, image->width, image->height, vtx_color } }; if (!screen_is_skipframe(g_screen)) al_draw_prim(v, NULL, get_image_bitmap(image), 0, 4, ALLEGRO_PRIM_TRIANGLE_STRIP); return 0; } static duk_ret_t js_Image_zoomBlit(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); float scale = duk_require_number(ctx, 2); image_t* image; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); if (!screen_is_skipframe(g_screen)) al_draw_scaled_bitmap(get_image_bitmap(image), 0, 0, image->width, image->height, x, y, image->width * scale, image->height * scale, 0x0); return 0; } static duk_ret_t js_Image_zoomBlitMask(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); float scale = duk_require_number(ctx, 2); color_t mask = duk_require_sphere_color(ctx, 3); image_t* image; duk_push_this(ctx); image = duk_require_sphere_image(ctx, -1); duk_pop(ctx); if (!screen_is_skipframe(g_screen)) al_draw_tinted_scaled_bitmap(get_image_bitmap(image), al_map_rgba(mask.r, mask.g, mask.b, mask.alpha), 0, 0, image->width, image->height, x, y, image->width * scale, image->height * scale, 0x0); return 0; } <file_sep>/src/engine/tileset.h #ifndef MINISPHERE__TILESET_H__INCLUDED #define MINISPHERE__TILESET_H__INCLUDED #include "atlas.h" #include "image.h" typedef struct tileset tileset_t; tileset_t* tileset_new (const char* filename); tileset_t* tileset_read (sfs_file_t* file); void tileset_free (tileset_t* tileset); int tileset_len (const tileset_t* tileset); const obsmap_t* tileset_obsmap (const tileset_t* tileset, int tile_index); int tileset_get_delay (const tileset_t* tileset, int tile_index); image_t* tileset_get_image (const tileset_t* tileset, int tile_index); const lstring_t* tileset_get_name (const tileset_t* tileset, int tile_index); int tileset_get_next (const tileset_t* tileset, int tile_index); void tileset_get_size (const tileset_t* tileset, int* out_w, int* out_h); void tileset_set_delay (tileset_t* tileset, int tile_index, int delay); void tileset_set_image (tileset_t* tileset, int tile_index, image_t* image); void tileset_set_next (tileset_t* tileset, int tile_index, int next_index); bool tileset_set_name (tileset_t* tileset, int tile_index, const lstring_t* name); void tileset_draw (const tileset_t* tileset, color_t mask, float x, float y, int tile_index); void tileset_update (tileset_t* tileset); #endif // MINISPHERE__TILESET_H__INCLUDED <file_sep>/src/engine/file.h #ifndef MINISPHERE__FILE_H__INCLUDED #define MINISPHERE__FILE_H__INCLUDED typedef struct kevfile kevfile_t; kevfile_t* kev_open (sandbox_t* fs, const char* filename, bool can_create); void kev_close (kevfile_t* file); int kev_num_keys (kevfile_t* file); const char* kev_get_key (kevfile_t* file, int index); bool kev_read_bool (kevfile_t* file, const char* key, bool def_value); double kev_read_float (kevfile_t* file, const char* key, double def_value); const char* kev_read_string (kevfile_t* file, const char* key, const char* def_value); bool kev_save (kevfile_t* file); void kev_write_bool (kevfile_t* file, const char* key, bool value); void kev_write_float (kevfile_t* file, const char* key, double value); void kev_write_string (kevfile_t* file, const char* key, const char* value); void init_file_api (void); #endif // MINISPHERE__FILE_H__INCLUDED <file_sep>/src/engine/font.h #ifndef MINISPHERE__FONT_H__INCLUDED #define MINISPHERE__FONT_H__INCLUDED #include "color.h" #include "image.h" typedef struct font font_t; typedef struct wraptext wraptext_t; typedef enum text_align { TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER, TEXT_ALIGN_RIGHT } text_align_t; font_t* load_font (const char* path); font_t* clone_font (const font_t* src_font); font_t* ref_font (font_t* font); void free_font (font_t* font); int get_font_line_height (const font_t* font); void get_font_metrics (const font_t* font, int* min_width, int* max_width, int* out_line_height); image_t* get_glyph_image (const font_t* font, int codepoint); int get_glyph_width (const font_t* font, int codepoint); int get_text_width (const font_t* font, const char* text); void set_glyph_image (font_t* font, int codepoint, image_t* image); void draw_text (const font_t* font, color_t mask, int x, int y, text_align_t alignment, const char* text); wraptext_t* word_wrap_text (const font_t* font, const char* text, int width); void free_wraptext (wraptext_t* wraptext); const char* get_wraptext_line (const wraptext_t* wraptext, int line_index); int get_wraptext_line_count (const wraptext_t* wraptext); void init_font_api (duk_context* ctx); void duk_push_sphere_font (duk_context* ctx, font_t* font); #endif // MINISPHERE__FONT_H__INCLUDED <file_sep>/src/plugin/SocketExtensions.cs using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace minisphere.Gdk { static class SocketExtensions { public static bool ReceiveAll(this Socket socket, byte[] buffer, SocketFlags socketFlags = SocketFlags.None) { try { int offset = 0; while (offset < buffer.Length) { int size = socket.Receive(buffer, offset, buffer.Length - offset, socketFlags); offset += size; if (size == 0) return false; } return true; } catch (SocketException) { return false; } } } } <file_sep>/src/engine/utility.h #ifndef MINISPHERE__UTILITY_H__INCLUDED #define MINISPHERE__UTILITY_H__INCLUDED const path_t* enginepath (void); const path_t* homepath (void); const char* systempath (const char* filename); bool is_cpu_little_endian (void); void duk_push_lstring_t (duk_context* ctx, const lstring_t* string); lstring_t* duk_require_lstring_t (duk_context* ctx, duk_idx_t index); const char* duk_require_path (duk_context* ctx, duk_idx_t index, const char* origin_name, bool legacy); lstring_t* read_lstring (sfs_file_t* file, bool trim_null); lstring_t* read_lstring_raw (sfs_file_t* file, size_t length, bool trim_null); char* strnewf (const char* fmt, ...); #endif // MINISPHERE__UTILITY_H__INCLUDED <file_sep>/src/engine/matrix.c #include "minisphere.h" #include "matrix.h" struct matrix { unsigned int refcount; ALLEGRO_TRANSFORM transform; }; matrix_t* matrix_new(void) { matrix_t* matrix; matrix = calloc(1, sizeof(matrix_t)); al_identity_transform(&matrix->transform); return matrix_ref(matrix); } matrix_t* matrix_clone(const matrix_t* matrix) { matrix_t* new_matrix; new_matrix = calloc(1, sizeof(matrix_t)); al_copy_transform(&new_matrix->transform, &matrix->transform); return matrix_ref(new_matrix); } matrix_t* matrix_ref(matrix_t* matrix) { ++matrix->refcount; return matrix; } void matrix_free(matrix_t* matrix) { if (--matrix->refcount > 0) return; free(matrix); } const float* matrix_items(const matrix_t* matrix) { return &matrix->transform.m[0][0]; } const ALLEGRO_TRANSFORM* matrix_transform(const matrix_t* matrix) { return &matrix->transform; } void matrix_identity(matrix_t* matrix) { al_identity_transform(&matrix->transform); } void matrix_compose(matrix_t* matrix, const matrix_t* other) { al_compose_transform(&matrix->transform, &other->transform); } void matrix_rotate(matrix_t* matrix, float theta, float vx, float vy, float vz) { #if defined(MINISPHERE_USE_3D_TRANSFORM) al_rotate_transform_3d(&matrix->transform, vx, vy, vz, theta); #else al_rotate_transform(&matrix->transform, theta); #endif } void matrix_scale(matrix_t* matrix, float sx, float sy, float sz) { #if defined(MINISPHERE_USE_3D_TRANSFORM) al_scale_transform_3d(&matrix->transform, sx, sy, sz); #else al_scale_transform(&matrix->transform, sx, sy); #endif } void matrix_translate(matrix_t* matrix, float dx, float dy, float dz) { #if defined(MINISPHERE_USE_3D_TRANSFORM) al_translate_transform_3d(&matrix->transform, dx, dy, dz); #else al_translate_transform(&matrix->transform, dx, dy); #endif } <file_sep>/src/debugger/parser.h #ifndef SSJ__PARSER_H__INCLUDED #define SSJ__PARSER_H__INCLUDED typedef struct command command_t; typedef enum token_tag { TOK_STRING, TOK_NUMBER, TOK_FILE_LINE, } token_tag_t; command_t* command_parse (const char* string); void command_free (command_t* obj); int command_len (const command_t* obj); token_tag_t command_get_tag (const command_t* obj, int index); int command_get_int (const command_t* obj, int index); double command_get_float (const command_t* obj, int index); const char* command_get_string (const command_t* obj, int index); #endif // SSJ__PARSER_H__INCLUDED <file_sep>/src/plugin/DockPanes/ErrorPane.cs using System; using System.Drawing; using System.Media; using System.Windows.Forms; using Sphere.Plugins; using Sphere.Plugins.Interfaces; using Sphere.Plugins.Views; using minisphere.Gdk.Plugins; using minisphere.Gdk.Properties; namespace minisphere.Gdk.DockPanes { partial class ErrorPane : UserControl, IDockPane { public ErrorPane() { InitializeComponent(); } public bool ShowInViewMenu => true; public Control Control => this; public DockHint DockHint => DockHint.Bottom; public Bitmap DockIcon => Resources.ErrorIcon; public Ssj2Debugger Ssj { get; set; } public void Add(string value, bool isFatal, string filename, int line) { if (listErrors.Items.Count > 0) { listErrors.Items[0].BackColor = listErrors.BackColor; listErrors.Items[0].ForeColor = listErrors.ForeColor; } ListViewItem item = listErrors.Items.Insert(0, value, isFatal ? 1 : 0); item.SubItems.Add(filename); item.SubItems.Add(line.ToString()); if (isFatal) { item.BackColor = Color.DarkRed; item.ForeColor = Color.Yellow; } } public void Clear() { listErrors.Items.Clear(); } public void ClearHighlight() { if (listErrors.Items.Count > 0) { listErrors.Items[0].BackColor = listErrors.BackColor; listErrors.Items[0].ForeColor = listErrors.ForeColor; } } public void HideIfClean() { ClearHighlight(); if (listErrors.Items.Count == 0) { PluginManager.Core.Docking.Hide(this); } } private void listErrors_DoubleClick(object sender, EventArgs e) { if (listErrors.SelectedItems.Count > 0) { ListViewItem item = listErrors.SelectedItems[0]; string filename = Ssj.ResolvePath(item.SubItems[1].Text); int lineNumber = int.Parse(item.SubItems[2].Text); ScriptView view = PluginManager.Core.OpenFile(filename) as ScriptView; if (view == null) SystemSounds.Asterisk.Play(); else view.GoToLine(lineNumber); } } } } <file_sep>/CHANGELOG.md minisphere Changelog ==================== v3.1.0 - May 7, 2015 -------------------- * SphereFS now uses single-character aliases: `#/` for built-in engine assets, `@/` for the root of the sandbox, and `~/` for the user data directory (for save data). * Changes the user data directory name back to "minisphere" to be more friendly to Linux users. * Adds some new components to miniRT: miniRT/binary for easy loading of structured binary data, miniRT/xml for XML parsing and DOM generation, and miniRT/prim to pre-render expensive-to-draw primitives like circles. * Adds a new Transform object which allows working with transformation matrices. * Improves the Galileo API: Shapes can now be drawn directly, Groups have a `transform` property which allows their transformation matrices to be manipulated, and shader uniforms can be set using `group.setInt()`, `group.setFloat()`, and `group.setMatrix()`. * Adds new Galileo Shape types `SHAPE_LINE_LOOP` and `SHAPE_LINE_STRIP`. * minisphere now looks for CommonJS modules in `lib/` instead of `commonjs/`. * `Async()` is now called `DispatchScript()` for API consistency. * `ListeningSocket` is now called `Server`. * You can now use `-0` through `-4` on the command line to specify the engine log verbosity level. v3.0.8 - April 17, 2016 ----------------------- * Fixes a bug where minisphere would crash instead of showing an error message if it was unable to create a render context. * SSJ will now continue with the previous course of action if given a null command. This only works for certain commands. v3.0.7 - April 14, 2016 ----------------------- * Fixes an issue where persons with large ignore lists would cause an inordinate amount of lag. This was caused by the engine checking persons' ignore lists before their hitboxes. v3.0.6 - April 11, 2016 ----------------------- * Reverts to the pre-3.0.4 method of map rendering. It turns out that Allegro's sprite batcher is actually pretty awesome. v3.0.5 - April 10, 2016 ----------------------- * Fixes a performance regression in 3.0.4 related to Galileo map rendering and animated tilesets. v3.0.4 - April 9, 2016 ---------------------- * Fixes a memory management bug in Galileo which caused it to leak potentially massive amounts of memory in games which generate a lot of `Shape` objects. * Fixes a bug in the Windows build where `stdout` couldn't be redirected. * Updates the map engine to use the Galileo graphics subsystem internally, which improves rendering performance in most cases. * Fixes a segfault when rendering a Galileo primitive with no vertices defined. v3.0.3 - April 5, 2016 ---------------------- * While debugging in Sphere Studio, variables are now sorted alphabetically in the Debugger pane. * Fixes a bug where `GetDefaultShaderProgram()` would attempt to compile the same source for both the vertex and fragment shaders, causing the call to fail. * Implements `RNG.random()`, an API function which has been documented for a while without actually being present. v3.0.2 - April 1, 2016 ---------------------- * Improves the file API: The `FileStream` object now includes methods for directly reading and writing integers, strings, and floats in addition to the standard `ArrayBuffer`-based I/O. * The Windows build now uses Allegro 5.2.0, the latest stable version. * Fixes a bug in the Sphere Studio debugger where pressing F10 would perform a Step Out instead of Step Over. v3.0.1 - March 29, 2016 ----------------------- * Fixes a bug where running `minisphere` from the command line and giving an invalid or nonexistent game path would cause the engine to segfault trying to display an error message. * Adds Sphere 1.x API functions `SetLayerWidth()` and `SetLayerHeight()`. For convenience, I also added `SetLayerSize()` to set both dimensions at once. * In Sphere Studio, the Debugger pane is now hidden when not actively debugging. This helps maximize screen real estate without forcing the user to set the pane to autohide. * Fixes a bug where receiving a malformed source code request from the debugger would cause a segfault. This wasn't a security risk right now, but might have become one in the future once I add remote debugging support. v3.0.0 - March 28, 2016 ----------------------- * The Windows redistributable and GDK downloads have been combined into a single installer. The engine is so compact that there's nothing gained from having separate installers. * minisphere is now officially supported on Linux! `.deb` binary and `.tar.gz` source packages will be provided for all minisphere releases going forward. * miniRT is completely revamped and modernized. All miniRT components have been rewritten as CommonJS modules which allows them to be pulled in individually as needed, instead of all at once using a global RequireScript(). * A complete API reference for miniRT is now included with the engine. * Introducing the brand-new command-line debugger, SSJ! SSJ can be started by running `ssj <game-path>` on the command line. This brings single-step Sphere debugging to non-Windows platforms for the first time! * Strengthens the SphereFS sandbox: Using absolute file paths is no longer supported and will result in a sandbox violation error. * Adds provisional TypeScript support. minisphere uses `ts.transpile()` internally to convert TypeScript to JavaScript, so some TypeScript features may not work as expected. See the release notes for more details. * User data (screenshots, save files, etc.) is now stored in `<docs>/Sphere 2.0` instead of `<docs>/minisphere` as it was in prior versions. SPK packages can be placed into the `games` subdirectory to have the startup game automatically pick them up. * minisphere now looks for CommonJS modules in `~sgm/commonjs`. * Enhances `Assert()` behavior. If an assertion fails and the debugger is attached, choosing not to continue will cause a prompt breakpoint instead of throwing an error. If the debugger is not attached, any failing assertions will be logged to `stderr` but otherwise ignored. * Improves fullscreen behavior: Games are letter/pillarboxed to maintain their aspect ratio when switching into fullscreen mode. * Screenshots are now given meaningful names based on the game filename and current date instead of random characters. * The frame rate is now visible by default whenever a game is started using the `spherun` command, and has been moved to the lower right corner of the screen. * When the debugger is attached, the engine now shows a small "SSJ" watermark in the lower left corner of the screen as a reminder. * The engine now waits for sounds to stop playing before freeing them, even if the Sound object goes out of scope. This allows a common Sphere idiom `new Sound("munch.wav").play()` to work as expected. * With the debugger attached, you can now press F12 to pause game execution and turn over control to the attached debugger. This can be useful when trying to debug glitches that don't lead to an exception. * You can now change the minisphere Console verbosity level when developing in Sphere Studio by going to the Settings Center page. V2 (high-level logging) is the default. * Vastly improves object inspection in the Sphere Studio debugger. Object contents will be displayed in a treeview, allowing you to drill down into properties, alleviating the need to scroll through a potentially huge JSON dump. * The command to run minisphere Console from the command line has changed from `msphere` to `spherun`. This will be the standard command to start a Sphere 2.0 engine in developer mode going forward. The end-user engine has been renamed as well, to `minisphere`. * `RNG.vary()` is now named `RNG.uniform()`. * New API: `DebugPrint()`, for logging low-level debug information without cluttering the console. `DebugPrint()` output is visible only with a debugger attached. * New API: `DoEvents()`. This function can be called in a long-running loop to avoid locking up the engine when you don't need to render anything or otherwise disturb the backbuffer. * `Print()` now accepts multiple values, which are separated by spaces when printed. * The `sphere` global object alias has been renamed to `global`, which is more obvious and matches Node.js. Code relying on the `sphere` alias will need to be updated to work with minisphere 3.0. * All minisphere API functions, constructors, and constants have been marked as non-enumerable, to avoid bloating the output when examining the global object in the debugger. Everything is still fully writable and configurable, so as not to prevent monkey-patching. * Fixes memory leaks in both Cell and minisphere, including a major one in Cell's packaging code which could have caused it to run out of memory during the installation step. * minisphere will no longer fail to start if the underlying platform doesn't support shaders. Instead, the Galileo `ShaderProgram` constructor will throw an error if called. Shaders are always disabled when the engine is compiled against Allegro 5.0. v2.1.6 - December 20, 2015 -------------------------- * Fixes a 2.1.5 regression which caused the last character to be cut off of the title bar text. v2.1.5 - December 19, 2015 -------------------------- * The Sphere Studio plugin now includes a setting to test games in windowed mode. * Fixes momentarily display of "Allegro" in the title bar instead of the game title during startup. * Fixes minor audio corruption at the end of the stream when playing some WAV files. v2.1.4 - December 16, 2015 -------------------------- * When an unhandled error is encountered, the error text can now be copied to the clipboard by pressing Ctrl+C. * Fixes a bug where GrabImage and GrabSurface would grab a black screen when called from a map engine script, regardless of what was rendered that frame. v2.1.3 - December 14, 2015 -------------------------- * Fixes a bug where evaluating an expression in the debugger would use the global object for 'this' instead of the active function's proper 'this' binding. v2.1.2 - December 8, 2015 ------------------------- * Fixes a bug where JavaScript Error objects with messages of the form "not X" can be constructed with the wrong filename and line number information. * Allegro version is now logged during startup. v2.1.1 - November 25, 2015 -------------------------- * miniRT now reads initialization parameters from the game manifest. This means that, going forward, S2GM will be required to take full advantage of the library. * The Sphere Studio plugin now adds the minisphere and Cell API references to the IDE's Help menu. This ensures the API reference will always match the installed engine version. * Includes an updated version of Duktape with more descriptive JS error messages. v2.1.0 - November 1, 2015 ------------------------- * Adds support for checked API extensions. By including a 'minimumPlatform' object in the game's S2GM manifest, S2GM-compliant engines can be made to check that the minimum API requirements are met before launching the game. * Now has the ability to run JS scripts without a manifest, by executing, e.g. 'msphere script.js' at the command line. * Adds a new API function, SetScreenSize(), allowing games to change resolution at runtime. * Improves JS error messages when attempting to read properties from non-objects (e.g. "cannot read property 'foo' of undefined", as opposed to "invalid base value"). * Running a script without a game() function will no longer produce an exception. * Fixes a bug in KevFile:save() which, in certain circumstances, caused the file to be saved in a different location than it was opened from. v2.0.1 - October 30, 2015 ------------------------- * Internal handling of file paths has been overhauled, fixing several crashes (including a segfault after returning from ExecuteGame) and making paths more predictable in general. * Fixes segfaults and insane console output at higher log levels. * Fixes a memory leak in the Async() trampoline due to a missing shutdown call. * Adds an API reference for Cell to the distribution. v2.0.0 - October 26, 2015 ------------------------- * Includes a new command-line compiler and packager for Sphere games, Cell! Using Cell, you can control the build process for your game using JavaScript and even compile your game to SPK format! * More predictable path semantics: All Sphere 2.0 APIs dealing with filenames, including all constructors, are resolved relative to the game manifest. The semantics of legacy APIs such as LoadImage() remain unchanged. * New JSON-based .s2gm game manifest format allowing much more flexibility in authoring metadata for a game. All data in the .s2gm is available to scripts by calling GetGameManifest(). * The minisphere redistributable now starts in full screen mode by default. * Vastly improved Sphere Studio plugin with full support for Cell, including automated SPK packaging. * Improved debugger allows evaluating local variables and expressions at any point in the call chain. * Basic source map support. When an error occurs and during debugging, if the game was compiled with Cell's '--debug' option, the path to the corresponding file from the source directory is displayed instead of its name within the game package. * All APIs accepting ByteArrays will now also accept ArrayBuffer and TypedArray objects. ByteArray is deprecated, but retained for backward compatibility. * SoundStreams are no longer restricted to 8-bit samples. * Audialis now supports 16- and 24-bit signed as well as 32-bit floating-point for both Mixer and SoundStream objects. * New 'FileStream' object: A more robust and SphereFS compliant replacement for Sphere 1.x's RawFile, using ArrayBuffers instead of ByteArrays. * The File object has been renamed to 'KevFile' to avoid confusion with the more general-purpose RawFile and FileStream objects. * Now uses a custom build of Duktape to support 'const' in scripts. As in Sphere 1.5, 'const' values are not actually constant and are in fact simply synonyms for an equivalent 'var' declaration. v1.7.11 - September 9, 2015 --------------------------- * Re-fixes the eval bug originally fixed in 1.7.8 and accidentally reverted in 1.7.10. * Updates Duktape to allow objects with circular references to be displayed in the debugger. v1.7.10 - September 8, 2015 --------------------------- * Upgrades Duktape to the latest build, which includes several ArrayBuffer fixes. * Renames RNG.name() to RNG.string(). This is a breaking change, but makes the purpose of the function clearer. * Improves RNG.string() performance by generating only one random number per character instead of 2. * RNG.string() output can now include digits. v1.7.9 - September 7, 2015 -------------------------- * Fixes a few bugs in debugger error intercept which caused Duktape to forcibly detach the debugger after issuing certain debug commands. v1.7.8 - September 5, 2015 -------------------------- * TCP port 1208 is now used for debugging. The previous debug port was 812, which is in the well-known port range and can't be opened by a non-root user under Linux. * Fixes a bug where an error thrown during a debug eval would cause a corrupt notification message to be sent, likely crashing the debugger. v1.7.7 - September 1, 2015 -------------------------- * Fixes a bug where, when the debugger is attached, executing an infinitely recursive function would crash the engine instead of throwing a RangeError. Without the debugger attached, a double fault would be generated instead. v1.7.6 - August 29, 2015 ------------------------ * Sphere API functions are named in stack listings. This is helpful when debugging to see when, e.g. a MapEngine() call is on the stack. * Upgrades Duktape to the latest build, improving performance. * Debugging has been disabled for the Redistributable as it hurt performance even when not active. v1.7.5 - August 22, 2015 ------------------------ * The debugger will now automatically pause execution before a fatal exception is thrown to allow local variables and the callstack to be examined. v1.7.4 - August 18, 2015 ------------------------ * miniRT console output is now routed through Print() so it is visible to an attached debugger. v1.7.3 - August 17, 2015 ------------------------ * Assert() failures can now be ignored when a debugger is attached. Previously, nonfatal asserts were only enabled for minisphere Console. * Reverts recent command line option renaming which made the engine incompatible with earlier versions. Options may change in 2.0, but for now it's best to retain compatibility here. * miniRT now includes built-in console commands for BGM management: - bgm play <filename> [<fade>] - bgm push <filename> [<fade>] - bgm pop [<fade>] - bgm stop [<fade>] - bgm volume <0-1> [<fade>] v1.7.2 - August 15, 2015 ------------------------ * Debugging is now enabled only over loopback. Remote debugging isn't particularly useful without access to full matching source, and this avoids the need to add a firewall exception. * While in Active debug mode (`--debug`), the engine will automatically exit if the debugger detaches cleanly. v1.7.1 - August 12, 2015 ------------------------ * Fixes a bug where a breakpoint placed inside of a conditional block will be triggered even if the condition isn't met. v1.7.0 - August 11, 2015 ------------------------ * The included analogue.js now uses EvaluateScript() to load map scripts; this ensures their filenames are associated with the code, allowing them to be debugged. * Upgrades Duktape to the latest build, adding support for ArrayBuffer and TypedArray objects, and improving the CommonJS implementation (notably, 'module.exports' is now supported). * The debug port (812) is now kept open, allowing debuggers to be attached and detached at will. This enables a debugger to easily reconnect if the connection is lost. * The engine will now wait 30 seconds for the debugger to reconnect if the TCP connection is lost during a debug session. v1.6.1 - July 31, 2015 ---------------------- * Fixes listening sockets not taking connections from IPv4 clients. v1.6.0 - July 27, 2015 ---------------------- * minisphere can now act as a Duktape debug server by passing --debug on the command line. A debugger can attach remotely over TCP using Duktape's binary debug protocol. * EvaluateScript() now returns the result of evaluation, as if the contents of the file were passed to eval(). * Vastly improved console logging. * ByteArrays can now be resized at runtime using the new resize() method. This allows them to be used as dynamic buffers. * Sockets can now be piped via the new pipe() and unpipe() IOSocket methods. * Renames the global object to `sphere` for naming consistency with other JavaScript environments, where the global object is always lowercase (window, global, root...). v1.5.3 - July 18, 2015 ---------------------- * GetGameList() will now search, in addition to the engine directory, `~/Sphere Games` for usable games (game.sgm files and SPKs). v1.5.2 - July 16, 2015 ---------------------- * mini.BGM now supports crossfading. * The Sound:volume accessor property now expects a floating-point value instead of an integer [0-255]. Sound:get/SetVolume() retain backwards compatibility. * Log messages are now emitted preemptively, making it easier to find the source of an issue. * More useful output when running at log levels 2 and 3. * The command line is parsed much earlier in the initialization cycle. v1.5.1 - July 14, 2015 ---------------------- * Fixes an issue where attempting to create an 8-bit mixer will fail with a "cannot create hardware mixer" error. v1.5.0 - July 12, 2015 ---------------------- * NEW! Audialis API: Use Mixers to group related sounds and feed audio data directly to the audio system using the new SoundStream object. v1.4.7 - July 5, 2015 --------------------- * SphereFS '~usr/' target directory changed from '<home>/Sphere Files' to '<home>/minisphere'. * Fixes a bug where switching out of fullscreen mode can get the display stuck in limbo, not quite windowed but not quite fullscreen either. This prevented Alt+Tab from working whenever it happened, as well. * Fixes a bug where the hitbox for scaled persons falls out of alignment with the sprite as it gets bigger. v1.4.6 - July 2, 2015 --------------------- * Displays a default taskbar icon (the Spherical icon) when running a game with no icon.png provided. * Scaling of taskbar icons (icon.png) has been improved to allow images larger than 32x32 with less distortion. * Fixes a bug where screenshots taken with F12 would sometimes come out with washed-out colors. v1.4.5 - June 29, 2015 ---------------------- * Now logs game information (title, author, resolution) on startup. Log level 2 or higher will also log the game path. v1.4.4 - June 28, 2015 ---------------------- * Fixes a bug where pressing F12 to take a screenshot won't create a Screenshots directory, and thus can't save the screenshot. * miniConsole now responds accordingly to the Home and End keys. v1.4.3 - June 27, 2015 ---------------------- * Fixes a "not callable" error when attempting to call Socket:accept(). v1.4.2 - June 25, 2015 ---------------------- * Fixes a bug where changes to a Sound's pitch, volume, etc. are lost between play() calls. * Fixes a bug in Delay() causing it to hog the CPU. * Fixes several Surface blend modes not working properly, notably the default 'BLEND' mode. * Fixes broken rendering of windowstyles with gradients. * Fixes a bug where the engine would lock up if AreKeysLeft() is used in a loop to wait for a keypress. * Fixes surface.setAlpha() not actually doing anything. * Fixes surface.flipHorizontally/Vertically() not flipping the surface. * Fixes surface.setPixel() unconditionally writing black pixels. * Fixes MapToScreenX/Y() returning incorrect values for maps with parallax layers. * Fixes a minor inaccuracy in person-person obstruction causing issues in games with tile-based movement. v1.4.1 - June 22, 2015 ---------------------- * Fixes a bug where top-level variables defined in a CoffeeScript script were not available from outside when using RequireScript(). * Fixes off-by-one rendering issues for a few graphics primitives, such as Line(). v1.4.0 - June 21, 2015 ---------------------- * CoffeeScript support! * The engine and all dependencies have been recompiled optimizing for speed. This slightly increases the size of the engine but greatly improves performance for CPU-bound tasks such as ColorMatrix application. v1.3.2 - June 20, 2015 ---------------------- * More informative error message when game() function doesn't exist, no more vague "not callable" errors! * Zone scripts are now fired once immediately on the first step inside the zone, regardless of the step count set. This matches Sphere 1.5 behavior. * Fixes Z-ordering glitches after looping around a repeating map. * GetPersonX(), GetPersonY() are now properly normalized on repeating maps. v1.3.1 - June 18, 2015 ---------------------- * Fixes parallax camera sync issues, for reals this time! * Adds a new API, GetActivePerson(), which can be called inside a talk or touch script to get the name of the person responsible for triggering the event. * Fixes an engine crash when a person under the control of FollowPerson is destroyed in the middle of a diagonal movement. * Changes target of the SphereFS ~usr/ prefix to <UserDocuments>/Sphere Files. This makes it easily accessible under Windows and ensures more sane placement when the engine is run under Wine. * Fixes a regression introduced in 1.3.0 where player input is accepted even though the input person's command queue is not empty. * Fixes a bug where zones loaded from a map file may randomly not fire. * Fixes a bug where talk scripts won't run if commands were queued for the input person on the same frame the talk key is pressed. v1.3.0 - June 17, 2015 ---------------------- * SphereFS support! This provides new directory aliases (~usr/, ~sys/, ~sgm/) with more predictable semantics than the classic ~/ alias, which is of course maintained for backwards compatibility. * Sphere Package format (.spk) support! * 4-player support in map engine (AttachPlayerInput() et al.) * Support for Sphere ColorMatrix objects. * Support for zlib compression and decompression of ByteArrays. v1.2.4 - June 11, 2015 ---------------------- * Fixes mysterious "invalid base value" errors when a built-in constructor is shadowed by a global variable with the same name. v1.2.3 - June 10, 2015 ---------------------- * Fixes a bug where calling RawFile:close() may cause a crash when the RawFile object is later GC'd due a double fclose(). Affected Linux and possibly other platforms as well. * Allows GetKey() to detect Ctrl, Alt, and Shift key presses. * Fixes incorrect handling of tab characters during text rendering. * Persons positioned on a hidden layer will no longer be hidden. This matches the behavior of Sphere 1.5. * Fixes incorrect rendering of text containing non-ASCII characters. Note that some characters such as the euro sign (€) and trademark symbol (™) will be substituted with placeholders due to differences between the Unicode and Windows-1252 codepages. v1.2.2 - June 8, 2015 --------------------- * Fixes map-defined BGM not playing--by implementing the feature. Nobody can say I'm not dedicated to compatibility! v1.2.1 - June 7, 2015 --------------------- * Fixes a regression in GetCurrentZone() and GetCurrentTrigger() where an index is returned. * Fixes out-of-sync scrolling issues with parallax layers on non-repeating maps. * Fixes a bug in Font:wordWrapString() where text ending on a wrap boundary can cause the last word to be lost. v1.2.0 - June 6, 2015 --------------------- * CommonJS module support! * Globals are now accessible via the Sphere object. With this, global variables can be created from strict mode code, where it would normally be flagged as an error. This is similar to the 'window' object in a browser: Sphere.myVar = 812; Sphere.GetKey(); // etc. * New Zone and Trigger management APIs. * Included kh2Bar can now be used as both a module and with a traditional RequireSystemScript() call. * Font:clone() now works correctly. * Fixes crashes under rare circumstances in Font:wordWrapString(). Also properly wraps long stretches of characters with no whitespace. * Fixes a bug where replacing a glyph image fails to update the font metrics, causing rendering issues. * More complete API documentation. v1.1.8 - June 2, 2015 --------------------- * Fixes too-fast animation when persons are moved diagonally. * Fixes a bug where queueing diagonal movement commands has no effect. v1.1.7 - June 1, 2015 --------------------- * Fixes an occasional crash when calling ExecuteGame(). v1.1.6 - May 31, 2015 --------------------- * The third argument ('is_immediate') to the QueuePersonCommand() and QueuePersonScript() APIs is now optional. If not provided, the default is false. * Fixes a startup crash when XInput is not found or fails to initialize. * Fixes a startup crash on systems with no sound support. * Fixes some extension strings having been coalesced due to a missing comma in the source. Seriously, who ever thought coalescing string literals was a good idea? v1.1.5 - May 28, 2015 --------------------- * Improved zone and trigger handling. Triggers will now fire even if input is attached after the trigger is stepped on. This fixes triggers in Kefka's Revenge. * Fixes a bug where the input person can be moved while following another person. * Proper handling of degenerate rects in spritesets and zones, which caused collision checks to fail. * Fixes a regression where calling IsKeyPressed() in a loop to wait for key release would lock up the engine (yes, again). * Updates the map engine to use the new input routines, to take advantage of the sticky-keys fix in v1.1.3. v1.1.4 - May 26, 2015 --------------------- * Cleanup to Script Error screen: Subdirectory information is now shown for script filenames and the error location is displayed on a separate line from the error text. * Evaluating non-UTF-8 scripts with extended characters no longer causes the engine to fail. * Font:wordWrapString() now correctly handles newlines. v1.1.3 - May 25, 2015 --------------------- * GetToggleState() is implemented--finally. * Keys should no longer get "stuck" when using Alt+Tab to switch away from the engine during gameplay. * Filename of map is now shown when an error occurs in an embedded script. v1.1.2 - May 23, 2015 --------------------- * GLSL shader support! Shaders are loaded from <game_dir>/shaders by default. To use: var shader = new ShaderProgram({ vertex: 'vs.glsl', fragment: 'fs.glsl'); var group = new Group(shapeList, shader); // work with Group object as before v1.1.1 - May 20, 2015 --------------------- * Fixes an issue where windowstyles with component images smaller than 16x16 weren't tiled properly, due to an Allegro limitation. * Full MNG animation support. No FLIC though. That's an ancient format anyway though, not really worth supporting. * Fixes GradientCircle (finally!) and adds missing circle methods to Surfaces. * New RNG.name() API: Generates a random string of letters which you can use internally to differentiate objects. v1.1.0 - May 17, 2015 --------------------- This is an absolutely MASSIVE release. Note: minisphere is now BSD-licensed. This basically gives you absolute freedom to do with the engine and associated source code what you wish, so long as you don't misrepresent yourself as the author. * Fixes a ton of bugs discovered since the release of minisphere 1.0.10, including a SetPersonScript() crash when passing JS functions. * Now using Allegro 5.1.10. * Native 64-bit engine included (engine64.exe). * New "Console" builds of minisphere (console.exe and console64.exe) for Windows. This version of the engine displays a console window like a debug build (enabling minisphere's Print() function to work), but is fully optimized. * Constructors and properties for all core Sphere objects: var sound = new Sound("munch.wav"); sound.volume = 128; sound.play(false); * Massive performance improvements, both to rendering as well as resource loading. Most assets load lightning fast! * Key mappings for GetPlayerKey() can now be set programmatically via the new SetPlayerKey() API; these changes will be saved per-game and loaded along with that game's game.sgm. * Assert(), a useful debugging tool. Throws an error if the asserted condition fails, a no-op otherwise. In the Console build, also gives you the option to ignore the failed assert and continue. * Async(), queues a script to run on the next FlipScreen(). Similar to what setTimeout() does in a browser and required for, e.g. compliance with the Promises/A+ spec. * TurboSphere-inspired "Galileo" graphics API, which allows scenes to be composed ahead of time using Shape and Group objects. * TurboSphere-inspired Sockets API, with separate ListeningSocket and IOSocket objects. Sphere 1.5 sockets are still supported. * Built-in MT19937-based random number generator, including a method (`RNG.normal`) to generate normally-distributed random values. * Includes miniRT, a unified set of system scripts including a cooperative threading engine, cutscene engine, the Link query library, and a full-featured console, among other goodies. Simply add this to the top of your main script: RequireSystemScript('mini/miniRT.js'); * The engine now searches <game_dir>/scripts/lib for system scripts before looking in the system directory. * API documentation is included in the default distribution. It may be somewhat incomplete, however... * Playback position in Sounds can be set with microsecond precision. * Overhauled FollowPerson() algorithm: Followers move under their own power and are affected by obstructions, making the overall effect much more pleasing. * New API functions to manage persons with followers: GetPersonLeader() GetPersonFollowers() GetPersonFollowDistance() SetPersonFollowDistance() * New path escape: `#~/path/to/file` specifies a path which is relative to the engine's system directory. v1.0.10 - April 16, 2015 ------------------------ * Experimental 64-bit engine (needs testing). * Fixes IsKeyPressed() not recognizing modifier keys on right side of keyboard (#20). * Improves SetPersonFrame compatibility (out-of-range frame is now wrapped instead of throwing an error). * Fixes SetPersonFrame not resetting frame delay timer. * Fixes a joystick assert error when running minisphere in OS X. (#19) * Fixes wrong direction being rendered for 4-direction person sprites moving diagonally. * Fixes random deadlocks when playing sounds. * Adds some API functions from Sphere 1.6+. <file_sep>/assets/system/modules/miniRT/pacts.js /** * miniRT/pacts CommonJS module * easy-to-use promises for Sphere, based on Promises/A+ * (c) 2015-2016 <NAME> **/ if (typeof exports === 'undefined') { throw new TypeError("script must be loaded with require()"); } var pacts = module.exports = (function() { 'use strict'; function Promise(fn) { var deferred = []; var state = 'pending'; var result = undefined; var self = this; function handle(handler) { if (state == 'pending') deferred.push(handler); else DispatchScript(function() { var callback = state == 'fulfilled' ? handler.fulfiller : state == 'rejected' ? handler.rejector : undefined; if (typeof callback !== 'function') { if (state == 'fulfilled') handler.resolve(result); if (state == 'rejected') handler.reject(result); } else { handler.resolve(callback(result)); } }); } function resolve(value) { if (value === self) { reject(new TypeError("Attempt to fulfill a promise with itself")); return; } else if (state != 'pending') return; try { if ((typeof value === 'function' || typeof value === 'object') && value !== null) { var then = value.then; if (typeof then === 'function') { then.call(value, resolve, reject); return; } } state = 'fulfilled'; result = value; for (var i = 0; i < deferred.length; ++i) handle(deferred[i]); deferred = []; } catch(e) { reject(e); } } function reject(reason) { if (state != 'pending') return; state = 'rejected' result = reason; for (var i = 0; i < deferred.length; ++i) handle(deferred[i]); deferred = []; } this.toString = function() { return state != 'pending' ? "[promise: " + state + " `" + result + "`]" : "[promise: pending]"; } this.catch = function(errback) { return this.then(undefined, errback); }; this.then = function(callback, errback) { var promise = this; return new Promise(function(resolve, reject) { handle({ promise: promise, resolve: resolve, reject: reject, fulfiller: callback, rejector: errback }); }); }; this.done = function(callback, errback) { var self = arguments.length > 0 ? this.then.apply(this, arguments) : this; if (typeof errback !== 'function') self.catch(function(reason) { throw reason; }); }; try { fn.call(this, resolve, reject); } catch(e) { reject(e); } }; Promise.all = function(iterable) { return new Promise(function(resolve, reject) { var promises = []; var values = []; var numPromises = iterable.length; if (numPromises == 0) resolve([]); else { for (var i = 0; i < numPromises; ++i) { var v = iterable[i]; if (!v || typeof v.then !== 'function') v = Promise.resolve(v); promises.push(v); v.then(function(value) { values.push(value); if (values.length == numPromises) resolve(values); }, function(reason) { reject(reason); }); } } }); }; Promise.race = function(iterable) { return new Promise(function(resolve, reject) { var numPromises = iterable.length; for (var i = 0; i < numPromises; ++i) { var v = iterable[i]; if (!v || typeof v.then !== 'function') v = Promise.resolve(v); v.then(function(value) { resolve(value); }, function(reason) { reject(reason); }); } }); }; Promise.reject = function(reason) { return new Promise(function(resolve, reject) { reject(reason); }); }; Promise.resolve = function(value) { if (value instanceof Promise) return value; return new Promise(function(resolve, reject) { resolve(value); }); }; function Pact() { var numPending = 0; var handlers = []; function checkPromise(promise) { if (!(promise instanceof Promise)) Abort("argument is not a promise", -2); for (var i = handlers.length - 1; i >= 0; --i) if (handlers[i].that == promise) return handlers[i]; Abort("promise was not made from this pact", -2); }; // Pact:promise() // makes a new promise with this pact. this.promise = function() { ++numPending; var handler; var promise = new Promise(function(resolve, reject) { handler = { resolve: resolve, reject: reject }; }) promise.then( function(value) { --numPending; }, function(reason) { --numPending; } ); handler.that = promise; handlers.push(handler); return promise; }; // Pact:resolve() // resolve a promise originating from this pact. // arguments: // promise: the promise to resolve. if the promise wasn't made from this pact, // a TypeError will be thrown. // value: the value with which to resolve the promise. this.resolve = function(promise, value) { checkPromise(promise).resolve(value); }; // Pact:reject() // reject a promise originating from this pact. // arguments: // promise: the promise to reject. if the promise wasn't made from this pact, // a TypeError will be thrown. // reason: the value to reject with (usually an Error object). this.reject = function(promise, reason) { checkPromise(promise).reject(reason); }; // Pact:welsh() // reject all outstanding promises from this pact. // arguments: // reason: the value to reject with (usually an Error object). this.welsh = function(reason) { for (var i = handlers.length - 1; i >= 0; --i) handlers[i].reject(reason); }; this.toString = function() { return "[pact: " + numPending.toString() + " outstanding]"; }; } return { Pact: Pact, Promise: Promise, } })(); <file_sep>/src/engine/debugger.c #include "minisphere.h" #include "sockets.h" #include "debugger.h" struct source { char* name; lstring_t* text; }; enum appnotify { APPNFY_DEBUG_PRINT = 0x01, }; enum apprequest { APPREQ_GAME_INFO = 0x01, APPREQ_SOURCE = 0x02, }; static const int TCP_DEBUG_PORT = 1208; static bool do_attach_debugger (void); static void do_detach_debugger (bool is_shutdown); static void duk_cb_debug_detach (void* udata); static duk_idx_t duk_cb_debug_request (duk_context* ctx, void* udata, duk_idx_t nvalues); static duk_size_t duk_cb_debug_peek (void* udata); static duk_size_t duk_cb_debug_read (void* udata, char* buffer, duk_size_t bufsize); static duk_size_t duk_cb_debug_write (void* udata, const char* data, duk_size_t size); static bool s_is_attached = false; static socket_t* s_client; static bool s_have_source_map; static socket_t* s_server; static vector_t* s_sources; static bool s_want_attach; void initialize_debugger(bool want_attach, bool allow_remote) { void* data; size_t data_size; const path_t* game_path; const char* hostname; s_sources = vector_new(sizeof(struct source)); // load the source map, if one is available s_have_source_map = false; duk_push_global_stash(g_duk); duk_del_prop_string(g_duk, -1, "debugMap"); game_path = get_game_path(g_fs); if (data = sfs_fslurp(g_fs, "sourcemap.json", NULL, &data_size)) { duk_push_lstring(g_duk, data, data_size); duk_json_decode(g_duk, -1); duk_put_prop_string(g_duk, -2, "debugMap"); free(data); s_have_source_map = true; } else if (!path_is_file(game_path)) { duk_push_object(g_duk); duk_push_string(g_duk, path_cstr(game_path)); duk_put_prop_string(g_duk, -2, "origin"); duk_put_prop_string(g_duk, -2, "debugMap"); } duk_pop(g_duk); // listen for SSJ connection on TCP port 1208. the listening socket will remain active // for the duration of the session, allowing a debugger to be attached at any time. console_log(1, "listening for SSJ on TCP %i", TCP_DEBUG_PORT); hostname = allow_remote ? NULL : "127.0.0.1"; s_server = listen_on_port(hostname, TCP_DEBUG_PORT, 1024, 1); // if the engine was started in debug mode, wait for a debugger to connect before // beginning execution. s_want_attach = want_attach; if (s_want_attach && !do_attach_debugger()) exit_game(true); } void shutdown_debugger() { iter_t iter; struct source* p_source; do_detach_debugger(true); free_socket(s_server); if (s_sources != NULL) { iter = vector_enum(s_sources); while (p_source = vector_next(&iter)) { lstr_free(p_source->text); free(p_source->name); } vector_free(s_sources); } } void update_debugger(void) { socket_t* socket; if (socket = accept_next_socket(s_server)) { if (s_client != NULL) { console_log(2, "rejected connection from %s, SSJ already attached", get_socket_host(socket)); free_socket(socket); } else { console_log(1, "connected to SSJ at %s", get_socket_host(socket)); s_client = socket; duk_debugger_detach(g_duk); duk_debugger_attach_custom(g_duk, duk_cb_debug_read, duk_cb_debug_write, duk_cb_debug_peek, NULL, NULL, duk_cb_debug_request, duk_cb_debug_detach, NULL); s_is_attached = true; } } } bool is_debugger_attached(void) { return s_is_attached; } const char* get_compiled_name(const char* source_name) { // perform a reverse lookup on the source map to find the compiled name // of an asset based on its name in the source tree. this is needed to // support SSJ source code download, since SSJ only knows the source names. static char retval[SPHERE_PATH_MAX]; const char* this_source; strncpy(retval, source_name, SPHERE_PATH_MAX - 1); retval[SPHERE_PATH_MAX - 1] = '\0'; if (!s_have_source_map) return retval; duk_push_global_stash(g_duk); duk_get_prop_string(g_duk, -1, "debugMap"); if (!duk_get_prop_string(g_duk, -1, "fileMap")) duk_pop_3(g_duk); else { duk_enum(g_duk, -1, DUK_ENUM_OWN_PROPERTIES_ONLY); while (duk_next(g_duk, -1, true)) { this_source = duk_get_string(g_duk, -1); if (strcmp(this_source, source_name) == 0) strncpy(retval, duk_get_string(g_duk, -2), SPHERE_PATH_MAX - 1); duk_pop_2(g_duk); } duk_pop_n(g_duk, 4); } return retval; } const char* get_source_name(const char* compiled_name) { // note: pathname must be canonicalized using make_sfs_path() otherwise // the source map lookup will fail. static char retval[SPHERE_PATH_MAX]; strncpy(retval, compiled_name, SPHERE_PATH_MAX - 1); retval[SPHERE_PATH_MAX - 1] = '\0'; if (!s_have_source_map) return retval; duk_push_global_stash(g_duk); duk_get_prop_string(g_duk, -1, "debugMap"); if (!duk_get_prop_string(g_duk, -1, "fileMap")) duk_pop_3(g_duk); else { duk_get_prop_string(g_duk, -1, compiled_name); if (duk_is_string(g_duk, -1)) strncpy(retval, duk_get_string(g_duk, -1), SPHERE_PATH_MAX - 1); duk_pop_n(g_duk, 4); } return retval; } void cache_source(const char* name, const lstring_t* text) { struct source cache_entry; iter_t iter; struct source* p_source; if (s_sources == NULL) return; iter = vector_enum(s_sources); while (p_source = vector_next(&iter)) { if (strcmp(name, p_source->name) == 0) { lstr_free(p_source->text); p_source->text = lstr_dup(text); return; } } cache_entry.name = strdup(name); cache_entry.text = lstr_dup(text); vector_push(s_sources, &cache_entry); } void debug_print(const char* text) { duk_push_int(g_duk, APPNFY_DEBUG_PRINT); duk_push_string(g_duk, text); duk_debugger_notify(g_duk, 2); } static bool do_attach_debugger(void) { double timeout; printf("waiting for SSJ connection\n"); fflush(stdout); timeout = al_get_time() + 30.0; while (s_client == NULL && al_get_time() < timeout) { update_debugger(); delay(0.05); } if (s_client == NULL) // did we time out? printf("timed out waiting for debugger\n"); return s_client != NULL; } static void do_detach_debugger(bool is_shutdown) { if (!s_is_attached) return; // detach the debugger console_log(1, "detaching debugger"); s_is_attached = false; duk_debugger_detach(g_duk); if (s_client != NULL) { shutdown_socket(s_client); while (is_socket_live(s_client)) delay(0.05); } free_socket(s_client); s_client = NULL; if (s_want_attach && !is_shutdown) exit_game(true); // clean detach, exit } static void duk_cb_debug_detach(void* udata) { // note: if s_client is null, a TCP reset was detected by one of the I/O callbacks. // if this is the case, wait a bit for the client to reconnect. if (s_client != NULL || !do_attach_debugger()) do_detach_debugger(false); } static duk_idx_t duk_cb_debug_request(duk_context* ctx, void* udata, duk_idx_t nvalues) { void* file_data; const char* name; int request_id; size_t size; int x_size; int y_size; iter_t iter; struct source* p_source; // the first atom must be a request ID number if (nvalues < 1 || !duk_is_number(ctx, -nvalues + 0)) { duk_push_string(ctx, "missing AppRequest command number"); return -1; } request_id = duk_get_int(ctx, -nvalues + 0); switch (request_id) { case APPREQ_GAME_INFO: get_sgm_resolution(g_fs, &x_size, &y_size); duk_push_string(ctx, get_sgm_name(g_fs)); duk_push_string(ctx, get_sgm_author(g_fs)); duk_push_string(ctx, get_sgm_summary(g_fs)); duk_push_int(ctx, x_size); duk_push_int(ctx, y_size); return 5; case APPREQ_SOURCE: if (nvalues < 2) { duk_push_string(ctx, "missing filename for Source request"); return -1; } name = duk_get_string(ctx, -nvalues + 1); name = get_compiled_name(name); // check if the data is in the source cache iter = vector_enum(s_sources); while (p_source = vector_next(&iter)) { if (strcmp(name, p_source->name) == 0) { duk_push_lstring_t(ctx, p_source->text); return 1; } } // no cache entry, try loading the file via SphereFS if ((file_data = sfs_fslurp(g_fs, name, NULL, &size))) { duk_push_lstring(ctx, file_data, size); free(file_data); return 1; } duk_push_sprintf(ctx, "no source available for `%s`", name); return -1; default: duk_push_sprintf(ctx, "invalid AppRequest command number `%d`", request_id); return -1; } } static duk_size_t duk_cb_debug_peek(void* udata) { return peek_socket(s_client); } static duk_size_t duk_cb_debug_read(void* udata, char* buffer, duk_size_t bufsize) { size_t n_bytes; if (s_client == NULL) return 0; // if we return zero, Duktape will drop the session. thus we're forced // to block until we can read >= 1 byte. while ((n_bytes = peek_socket(s_client)) == 0) { if (!is_socket_live(s_client)) { // did a pig eat it? console_log(1, "TCP connection reset while debugging"); free_socket(s_client); s_client = NULL; return 0; // stupid pig } // so the system doesn't think we locked up... delay(0.05); } // let's not overflow the buffer, alright? if (n_bytes > bufsize) n_bytes = bufsize; read_socket(s_client, buffer, n_bytes); return n_bytes; } static duk_size_t duk_cb_debug_write(void* udata, const char* data, duk_size_t size) { if (s_client == NULL) return 0; // make sure we're still connected if (!is_socket_live(s_client)) { console_log(1, "TCP connection reset while debugging"); free_socket(s_client); s_client = NULL; return 0; } // send out the data write_socket(s_client, data, size); return size; } <file_sep>/src/engine/main.c #include "minisphere.h" #include "api.h" #include "async.h" #include "audialis.h" #include "debugger.h" #include "galileo.h" #include "input.h" #include "map_engine.h" #include "rng.h" #include "spriteset.h" #include <libmng.h> // enable Windows visual styles (MSVC) #ifdef _MSC_VER #pragma comment(linker, \ "\"/manifestdependency:type='Win32' "\ "name='Microsoft.Windows.Common-Controls' "\ "version='6.0.0.0' "\ "processorArchitecture='*' "\ "publicKeyToken='<KEY>' "\ "language='*'\"") #endif static bool initialize_engine (void); static void shutdown_engine (void); static bool find_startup_game (path_t* *out_path); static bool parse_command_line (int argc, char* argv[], path_t* *out_game_path, bool *out_want_fullscreen, int *out_fullscreen, int *out_verbosity, bool *out_want_throttle, bool *out_want_debug); static void print_banner (bool want_copyright, bool want_deps); static void print_usage (void); static void report_error (const char* fmt, ...); static bool verify_requirements (sandbox_t* fs); static void on_duk_fatal (duk_context* ctx, duk_errcode_t code, const char* msg); duk_context* g_duk = NULL; ALLEGRO_EVENT_QUEUE* g_events = NULL; int g_framerate = 0; sandbox_t* g_fs = NULL; path_t* g_game_path = NULL; path_t* g_last_game_path = NULL; screen_t* g_screen = NULL; kevfile_t* g_sys_conf; font_t* g_sys_font = NULL; int g_res_x, g_res_y; static jmp_buf s_jmp_exit; static jmp_buf s_jmp_restart; static const char* const ERROR_TEXT[][2] = { { "*munch*", "a hunger-pig just devoured your game!" }, { "*CRASH!*", "it's an 812-car pileup!" }, { "so, um... a funny thing happened...", "...on the way to the boss..." }, { "here's the deal.", "the game encountered an error." }, { "this game sucks!", "or maybe it's just the programmer..." }, { "cows eat kitties. pigs don't eat cows.", "they just get \"replaced\" by them." }, { "hey look, a squirrel!", "I wonder if IT'S responsible for this." }, { "sorry. it's just...", "...well, this is a trainwreck of a game." }, { "you better run, and you better hide...", "...'cause a big fat hawk just ate that guy!" }, { "an exception was thrown.", "minisphere takes exception to sucky games." }, { "honk. HONK. honk. HONK. :o)", "there's a clown behind you." }, }; int main(int argc, char* argv[]) { // HERE BE DRAGONS! // as the oldest function in the minisphere codebase by definition, this has become // something of a hairball over time, and likely quite fragile. don't be surprised if // attempting to edit it causes something to break. :o) path_t* games_path; lstring_t* dialog_name; duk_errcode_t err_code; const char* err_msg; ALLEGRO_FILECHOOSER* file_dlg; const char* filename; image_t* icon; int line_num; const path_t* script_path; bool use_conserve_cpu; int use_frameskip; bool use_fullscreen; int use_verbosity; bool want_debug; // parse the command line if (parse_command_line(argc, argv, &g_game_path, &use_fullscreen, &use_frameskip, &use_verbosity, &use_conserve_cpu, &want_debug)) { initialize_console(use_verbosity); } else return EXIT_FAILURE; print_banner(true, false); printf("\n"); // print out options console_log(1, "parsing command line"); console_log(1, " game path: %s", g_game_path != NULL ? path_cstr(g_game_path) : "<none provided>"); console_log(1, " fullscreen: %s", use_fullscreen ? "on" : "off"); console_log(1, " frameskip limit: %d frames", use_frameskip); console_log(1, " sleep when idle: %s", use_conserve_cpu ? "yes" : "no"); console_log(1, " console verbosity: V%d", use_verbosity); #if defined(MINISPHERE_SPHERUN) console_log(1, " debugger mode: %s", want_debug ? "active" : "passive"); #endif console_log(1, ""); if (!initialize_engine()) return EXIT_FAILURE; // set up jump points for script bailout console_log(1, "setting up jump points for longjmp"); if (setjmp(s_jmp_exit)) { // user closed window, script called Exit(), etc. shutdown_engine(); if (g_last_game_path != NULL) { // returning from ExecuteGame()? initialize_engine(); g_game_path = g_last_game_path; g_last_game_path = NULL; } else { return EXIT_SUCCESS; } } if (setjmp(s_jmp_restart)) { // script called RestartGame() or ExecuteGame() shutdown_engine(); console_log(1, "\nrestarting to launch new game"); console_log(1, " path: %s", path_cstr(g_game_path)); initialize_engine(); } // locate the game manifest console_log(1, "searching for a game to launch"); games_path = path_rebase(path_new("minisphere/games/"), homepath()); path_mkdir(games_path); if (g_game_path == NULL) // no game specified on command line, see if we have a startup game find_startup_game(&g_game_path); if (g_game_path != NULL) // user provided a path or startup game was found, attempt to load it g_fs = new_sandbox(path_cstr(g_game_path)); else { // no game path provided and no startup game, let user find one dialog_name = lstr_newf("%s - Select a Sphere game to launch", PRODUCT_NAME); file_dlg = al_create_native_file_dialog(path_cstr(games_path), lstr_cstr(dialog_name), "game.sgm;game.s2gm;*.spk", ALLEGRO_FILECHOOSER_FILE_MUST_EXIST); al_show_native_file_dialog(NULL, file_dlg); lstr_free(dialog_name); if (al_get_native_file_dialog_count(file_dlg) > 0) { path_free(g_game_path); g_game_path = path_new(al_get_native_file_dialog_path(file_dlg, 0)); g_fs = new_sandbox(path_cstr(g_game_path)); al_destroy_native_file_dialog(file_dlg); } else { // user clicked Cancel; as this is a valid action, we return // success, not failure. al_destroy_native_file_dialog(file_dlg); path_free(games_path); return EXIT_SUCCESS; } } path_free(games_path); if (g_fs == NULL) { // if after all that, we still don't have a valid sandbox pointer, bail out; // there's not much else we can do. #if !defined(MINISPHERE_SPHERUN) al_show_native_message_box(NULL, "Unable to Load Game", path_cstr(g_game_path), "minisphere was unable to load the game manifest or it was not found. Check to make sure the directory above exists and contains a valid Sphere game.", NULL, ALLEGRO_MESSAGEBOX_ERROR); #else fprintf(stderr, "ERROR: unable to start `%s`\n", path_cstr(g_game_path)); #endif exit_game(false); } if (!verify_requirements(g_fs)) exit_game(false); // try to create a display. if we can't get a programmable pipeline, try again but // only request bare OpenGL. keep in mind that if this happens, shader support will be // disabled. get_sgm_resolution(g_fs, &g_res_x, &g_res_y); if (!(icon = load_image("icon.png"))) icon = load_image("#/icon.png"); g_screen = screen_new(get_sgm_name(g_fs), icon, g_res_x, g_res_y, use_frameskip, !use_conserve_cpu); if (g_screen == NULL) { al_show_native_message_box(NULL, "Unable to Create Render Context", "minisphere was unable to create a render context.", "Your hardware may be too old to run minisphere, or there is a driver problem on this system. Check that your graphics drivers are installed and up-to-date.", NULL, ALLEGRO_MESSAGEBOX_ERROR); return EXIT_FAILURE; } al_set_new_bitmap_flags(ALLEGRO_NO_PREMULTIPLIED_ALPHA); al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA); g_events = al_create_event_queue(); al_register_event_source(g_events, al_get_display_event_source(screen_display(g_screen))); attach_input_display(); load_key_map(); // initialize shader support initialize_shaders(screen_have_shaders(g_screen)); // attempt to locate and load system font console_log(1, "loading system default font"); if (g_sys_conf != NULL) { filename = kev_read_string(g_sys_conf, "Font", "system.rfn"); g_sys_font = load_font(systempath(filename)); } if (g_sys_font == NULL) { al_show_native_message_box(screen_display(g_screen), "No System Font Available", "A system font is required.", "minisphere was unable to locate the system font or it failed to load. As a usable font is necessary for correct operation, minisphere will now close.", NULL, ALLEGRO_MESSAGEBOX_ERROR); return EXIT_FAILURE; } // switch to fullscreen if necessary and initialize clipping if (use_fullscreen) screen_toggle_fullscreen(g_screen); // display loading message, scripts may take a bit to compile if (want_debug) { al_clear_to_color(al_map_rgba(0, 0, 0, 255)); screen_draw_status(g_screen, "waiting for SSJ..."); al_flip_display(); al_clear_to_color(al_map_rgba(0, 0, 0, 255)); } // enable debugging support #if defined(MINISPHERE_SPHERUN) initialize_debugger(want_debug, false); #endif // display loading message, scripts may take a bit to compile al_clear_to_color(al_map_rgba(0, 0, 0, 255)); screen_draw_status(g_screen, "starting up..."); al_flip_display(); al_clear_to_color(al_map_rgba(0, 0, 0, 255)); // evaluate startup script screen_show_mouse(g_screen, false); script_path = get_sgm_script_path(g_fs); if (!evaluate_script(path_cstr(script_path))) goto on_js_error; duk_pop(g_duk); // call game() function in script duk_get_global_string(g_duk, "game"); if (duk_is_callable(g_duk, -1) && duk_pcall(g_duk, 0) != DUK_EXEC_SUCCESS) goto on_js_error; duk_pop(g_duk); exit_game(false); on_js_error: err_code = duk_get_error_code(g_duk, -1); duk_dup(g_duk, -1); err_msg = duk_safe_to_string(g_duk, -1); screen_show_mouse(g_screen, true); duk_get_prop_string(g_duk, -2, "lineNumber"); line_num = duk_get_int(g_duk, -1); duk_pop(g_duk); duk_get_prop_string(g_duk, -2, "fileName"); filename = duk_get_string(g_duk, -1); if (filename != NULL) { fprintf(stderr, "Unhandled JS exception caught by engine\n [%s:%d] %s\n", filename, line_num, err_msg); if (err_msg[strlen(err_msg) - 1] != '\n') duk_push_sprintf(g_duk, "%s:%d\n\n%s\n ", filename, line_num, err_msg); else duk_push_sprintf(g_duk, "%s\n ", err_msg); } else { fprintf(stderr, "Unhandled JS error caught by engine.\n%s\n", err_msg); duk_push_string(g_duk, err_msg); } duk_fatal(g_duk, err_code, duk_get_string(g_duk, -1)); } void delay(double time) { double end_time; double time_left; end_time = al_get_time() + time; do { time_left = end_time - al_get_time(); if (time_left > 0.001) // engine may stall with < 1ms timeout al_wait_for_event_timed(g_events, NULL, time_left); do_events(); } while (al_get_time() < end_time); } void do_events(void) { ALLEGRO_EVENT event; dyad_update(); #if defined(MINISPHERE_SPHERUN) update_debugger(); #endif update_async(); update_input(); update_audialis(); // process Allegro events while (al_get_next_event(g_events, &event)) { switch (event.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: exit_game(true); } } } noreturn exit_game(bool force_shutdown) { if (force_shutdown) { free(g_last_game_path); g_last_game_path = NULL; } longjmp(s_jmp_exit, 1); } noreturn restart_engine(void) { longjmp(s_jmp_restart, 1); } static void on_duk_fatal(duk_context* ctx, duk_errcode_t code, const char* msg) { wraptext_t* error_info; bool is_copied = true; bool is_finished; int frames_till_close; ALLEGRO_KEYBOARD_STATE keyboard; const char* line_text; int num_lines; const char* subtitle; const char* title; int title_index; int i; #ifdef MINISPHERE_USE_CLIPBOARD is_copied = false; #endif title_index = rand() % (sizeof(ERROR_TEXT) / sizeof(const char*) / 2); title = ERROR_TEXT[title_index][0]; subtitle = ERROR_TEXT[title_index][1]; if (g_sys_font == NULL) goto show_error_box; // create wraptext from error message if (!(error_info = word_wrap_text(g_sys_font, msg, g_res_x - 84))) goto show_error_box; num_lines = get_wraptext_line_count(error_info); // show error in-engine, Sphere 1.x style screen_unskip_frame(g_screen); is_finished = false; frames_till_close = 30; while (!is_finished) { al_draw_filled_rounded_rectangle(32, 48, g_res_x - 32, g_res_y - 32, 5, 5, al_map_rgba(16, 16, 16, 255)); draw_text(g_sys_font, color_new(0, 0, 0, 255), g_res_x / 2 + 1, 11, TEXT_ALIGN_CENTER, title); draw_text(g_sys_font, color_new(255, 255, 255, 255), g_res_x / 2, 10, TEXT_ALIGN_CENTER, title); draw_text(g_sys_font, color_new(0, 0, 0, 255), g_res_x / 2 + 1, 23, TEXT_ALIGN_CENTER, subtitle); draw_text(g_sys_font, color_new(255, 255, 255, 255), g_res_x / 2, 22, TEXT_ALIGN_CENTER, subtitle); for (i = 0; i < num_lines; ++i) { line_text = get_wraptext_line(error_info, i); draw_text(g_sys_font, color_new(0, 0, 0, 255), g_res_x / 2 + 1, 59 + i * get_font_line_height(g_sys_font), TEXT_ALIGN_CENTER, line_text); draw_text(g_sys_font, color_new(192, 192, 192, 255), g_res_x / 2, 58 + i * get_font_line_height(g_sys_font), TEXT_ALIGN_CENTER, line_text); } if (frames_till_close <= 0) { draw_text(g_sys_font, color_new(255, 255, 255, 255), g_res_x / 2, g_res_y - 10 - get_font_line_height(g_sys_font), TEXT_ALIGN_CENTER, is_copied ? "[Space]/[Esc] to close" : "[Ctrl+C] to copy, [Space]/[Esc] to close"); } screen_flip(g_screen, 30); if (frames_till_close <= 0) { al_get_keyboard_state(&keyboard); is_finished = al_key_down(&keyboard, ALLEGRO_KEY_ESCAPE) || al_key_down(&keyboard, ALLEGRO_KEY_SPACE); // if Ctrl+C is pressed, copy the error message and location to clipboard #ifdef MINISPHERE_USE_CLIPBOARD if ((al_key_down(&keyboard, ALLEGRO_KEY_LCTRL) || al_key_down(&keyboard, ALLEGRO_KEY_RCTRL)) && al_key_down(&keyboard, ALLEGRO_KEY_C)) { is_copied = true; al_set_clipboard_text(screen_display(g_screen), msg); } #endif } else { --frames_till_close; } } free_wraptext(error_info); shutdown_engine(); exit(EXIT_SUCCESS); show_error_box: // use a native message box only as a last resort al_show_native_message_box(NULL, "Script Error", "minisphere encountered an error during game execution.", msg, NULL, ALLEGRO_MESSAGEBOX_ERROR); shutdown_engine(); exit(EXIT_SUCCESS); } static bool initialize_engine(void) { uint32_t al_version; srand(time(NULL)); // initialize Allegro al_version = al_get_allegro_version(); console_log(1, "initializing Allegro v%u.%u.%u.%u", al_version >> 24, (al_version >> 16) & 0xFF, (al_version >> 8) & 0xFF, (al_version & 0xFF) - 1); al_set_org_name("Fat Cerberus"); al_set_app_name("minisphere"); if (!al_init()) goto on_error; if (!al_init_native_dialog_addon()) goto on_error; if (!al_init_primitives_addon()) goto on_error; if (!al_init_image_addon()) goto on_error; // initialize networking console_log(1, "initializing Dyad v%s", dyad_getVersion()); dyad_init(); dyad_setUpdateTimeout(0.0); // initialize JavaScript console_log(1, "initializing Duktape v%ld.%ld.%ld", DUK_VERSION / 10000, DUK_VERSION / 100 % 100, DUK_VERSION % 100); if (!(g_duk = duk_create_heap(NULL, NULL, NULL, NULL, &on_duk_fatal))) goto on_error; // load system configuraton console_log(1, "loading system configuration"); if (!(g_sys_conf = kev_open(NULL, "#/system.ini", false))) goto on_error; // initialize engine components initialize_async(); initialize_rng(); initialize_galileo(); initialize_audialis(); initialize_input(); initialize_spritesets(); initialize_map_engine(); initialize_scripts(); // register the Sphere API initialize_api(g_duk); return true; on_error: al_show_native_message_box(NULL, "Unable to Start", "Engine initialized failed.", "One or more components failed to initialize properly. minisphere cannot continue in this state and will now close.", NULL, ALLEGRO_MESSAGEBOX_ERROR); return false; } static void shutdown_engine(void) { save_key_map(); #if defined(MINISPHERE_SPHERUN) shutdown_debugger(); #endif shutdown_map_engine(); shutdown_input(); shutdown_scripts(); console_log(1, "shutting down Duktape"); duk_destroy_heap(g_duk); console_log(1, "shutting down Dyad"); dyad_shutdown(); shutdown_spritesets(); shutdown_audialis(); shutdown_galileo(); shutdown_async(); console_log(1, "shutting down Allegro"); screen_free(g_screen); g_screen = NULL; if (g_events != NULL) al_destroy_event_queue(g_events); g_events = NULL; free_sandbox(g_fs); g_fs = NULL; if (g_sys_conf != NULL) kev_close(g_sys_conf); g_sys_conf = NULL; al_uninstall_system(); } static bool find_startup_game(path_t* *out_path) { ALLEGRO_FS_ENTRY* engine_dir; const char* file_ext; const char* filename; ALLEGRO_FS_ENTRY* fse; int n_spk_files = 0; // prefer startup game alongside engine if one exists *out_path = path_rebase(path_new("startup/game.sgm"), enginepath()); if (al_filename_exists(path_cstr(*out_path))) return true; path_free(*out_path); // check for single SPK package alongside engine *out_path = path_dup(enginepath()); engine_dir = al_create_fs_entry(path_cstr(*out_path)); al_open_directory(engine_dir); while (fse = al_read_directory(engine_dir)) { filename = al_get_fs_entry_name(fse); file_ext = strrchr(filename, '.'); if (file_ext != NULL && strcmp(file_ext, ".spk") == 0) { if (++n_spk_files == 1) *out_path = path_new(filename); } al_destroy_fs_entry(fse); } al_close_directory(engine_dir); if (n_spk_files == 1) return true; // found an SPK // as a last resort, use the default startup game *out_path = path_rebase(path_new("system/startup.spk"), enginepath()); if (al_filename_exists(path_cstr(*out_path))) return true; path_free(*out_path); *out_path = path_rebase(path_new("../share/minisphere/system/startup.spk"), enginepath()); if (al_filename_exists(path_cstr(*out_path))) return true; path_free(*out_path); *out_path = NULL; // if we reached this point, no suitable startup game was found. path_free(*out_path); *out_path = NULL; return false; } static bool parse_command_line( int argc, char* argv[], path_t* *out_game_path, bool *out_want_fullscreen, int *out_frameskip, int *out_verbosity, bool *out_want_throttle, bool *out_want_debug) { bool parse_options = true; int i, j; // establish default settings #if defined(MINISPHERE_SPHERUN) *out_want_fullscreen = false; #else *out_want_fullscreen = true; #endif *out_game_path = NULL; *out_frameskip = 5; *out_verbosity = 0; *out_want_throttle = true; *out_want_debug = false; // process command line arguments for (i = 1; i < argc; ++i) { if (strstr(argv[i], "--") == argv[i] && parse_options) { if (strcmp(argv[i], "--") == 0) parse_options = false; else if (strcmp(argv[i], "--frameskip") == 0) { if (++i >= argc) goto missing_argument; *out_frameskip = atoi(argv[i]); } else if (strcmp(argv[i], "--no-sleep") == 0) { *out_want_throttle = false; } else if (strcmp(argv[i], "--fullscreen") == 0) { *out_want_fullscreen = true; } else if (strcmp(argv[i], "--window") == 0) { *out_want_fullscreen = false; } #if defined(MINISPHERE_SPHERUN) else if (strcmp(argv[i], "--version") == 0) { print_banner(true, true); return false; } else if (strcmp(argv[i], "--help") == 0) { print_usage(); return false; } else if (strcmp(argv[i], "--debug") == 0) { *out_want_debug = true; } else if (strcmp(argv[i], "--verbose") == 0) { if (++i >= argc) goto missing_argument; *out_verbosity = atoi(argv[i]); } else { report_error("unrecognized option `%s`\n", argv[i]); return false; } #else else if (strcmp(argv[i], "--verbose") == 0) ++i; #endif } else if (argv[i][0] == '-' && parse_options) { for (j = 1; j < (int)strlen(argv[i]); ++j) { switch (argv[i][j]) { case '0': case '1': case '2': case '3': case '4': *out_verbosity = argv[i][j] - '0'; break; case 'd': *out_want_debug = true; break; default: report_error("unrecognized option `-%c`\n", argv[i][j]); return false; } } } else { if (*out_game_path == NULL) { *out_game_path = path_new(argv[i]); if (!path_resolve(*out_game_path, NULL)) { report_error("pathname not found `%s`\n", path_cstr(*out_game_path)); path_free(*out_game_path); *out_game_path = NULL; return false; } } else { report_error("more than one game specified on command line\n"); return false; } } } #if defined(MINISPHERE_SPHERUN) if (*out_game_path == NULL) { print_usage(); return false; } #endif return true; missing_argument: report_error("missing argument for option `%s`\n", argv[i - 1]); return false; } static void print_banner(bool want_copyright, bool want_deps) { char* al_version; uint32_t al_version_id; char* duk_version; printf("%s %s JS Game Engine (%s)\n", PRODUCT_NAME, VERSION_NAME, sizeof(void*) == 4 ? "x86" : "x64"); if (want_copyright) { printf("the lightweight JavaScript-based game engine\n"); printf("(c) 2015-2016 <NAME>\n"); } if (want_deps) { al_version_id = al_get_allegro_version(); al_version = strnewf("%d.%d.%d.%d", al_version_id >> 24, (al_version_id >> 16) & 0xFF, (al_version_id >> 8) & 0xFF, (al_version_id & 0xFF) - 1); duk_version = strnewf("%ld.%ld.%ld", DUK_VERSION / 10000, DUK_VERSION / 100 % 100, DUK_VERSION % 100); printf("\n"); printf(" Allegro: v%-8s libmng: v%s\n", al_version, mng_version_text()); printf(" Duktape: v%-8s zlib: v%s\n", duk_version, zlibVersion()); printf(" Dyad.c: v%-8s\n", dyad_getVersion()); free(al_version); free(duk_version); } } static void print_usage(void) { print_banner(true, false); printf("\n"); printf("USAGE:\n"); printf(" spherun [--fullscreen | --window] [--frameskip <n>] [--no-sleep] [--debug] \n"); printf(" [--verbose <n>] <game_path> \n"); printf("\n"); printf("OPTIONS:\n"); printf(" --fullscreen Start minisphere in fullscreen mode. \n"); printf(" --window Start minisphere in windowed mode. This is the default.\n"); printf(" --frameskip Set the maximum number of consecutive frames to skip. \n"); printf(" --no-sleep Prevent the engine from sleeping between frames. \n"); printf(" -d, --debug Wait up to 30 seconds for the debugger to attach. \n"); printf(" --verbose Set the engine's verbosity level from 0 to 4. This can \n"); printf(" be abbreviated as `-n`, where n is [0-4]. \n"); printf(" --version Show which version of minisphere is installed. \n"); printf(" --help Show this help text. \n"); printf("\n"); printf("NOTE:\n"); printf(" spherun(1) is used to execute Sphere games in a development environment. If\n"); printf(" your intent is simply to play a game, use minisphere(1) instead. \n"); } static void report_error(const char* fmt, ...) { va_list ap; lstring_t* error_text; va_start(ap, fmt); error_text = lstr_vnewf(fmt, ap); va_end(ap); #if defined(MINISPHERE_SPHERUN) fprintf(stderr, "spherun: ERROR: %s", lstr_cstr(error_text)); #else al_show_native_message_box(NULL, "minisphere", "An error occurred starting the engine.", lstr_cstr(error_text), NULL, ALLEGRO_MESSAGEBOX_ERROR); #endif lstr_free(error_text); } static bool verify_requirements(sandbox_t* fs) { // NOTE: before calling this function, the Sphere API must already have been // initialized using initialize_api(). const char* extension_name; lstring_t* message; const char* recommendation = NULL; duk_size_t i; duk_push_lstring_t(g_duk, get_game_manifest(g_fs)); duk_json_decode(g_duk, -1); if (duk_get_prop_string(g_duk, -1, "minimumPlatform")) { if (duk_get_prop_string(g_duk, -1, "recommend")) { if (duk_is_string(g_duk, -1)) recommendation = duk_get_string(g_duk, -1); } duk_pop(g_duk); // check for minimum API version if (duk_get_prop_string(g_duk, -1, "apiLevel")) { if (duk_is_number(g_duk, -1)) { if (duk_get_int(g_duk, -1) > api_level()) goto is_unsupported; } } duk_pop(g_duk); // check API extensions if (duk_get_prop_string(g_duk, -1, "extensions")) { if (duk_is_array(g_duk, -1)) { for (i = 0; i < duk_get_length(g_duk, -1); ++i) { duk_get_prop_index(g_duk, -1, (duk_uarridx_t)i); extension_name = duk_get_string(g_duk, -1); duk_pop(g_duk); if (extension_name != NULL && !api_have_extension(extension_name)) goto is_unsupported; } } duk_pop(g_duk); } duk_pop(g_duk); } duk_pop(g_duk); return true; is_unsupported: if (recommendation != NULL) { message = lstr_newf( "A feature needed by this game is not supported in %s. You may need to use a later version of minisphere or a different engine to play this game." "\n\nThe game developer recommends using %s.", PRODUCT_NAME, recommendation); } else { message = lstr_newf( "A feature needed by this game is not supported in %s. You may need to use a later version of minisphere or a different engine to play this game." "\n\nNo specific recommendation was provided by the game developer.", PRODUCT_NAME); } al_show_native_message_box(NULL, "Unsupported Engine", path_cstr(g_game_path), lstr_cstr(message), NULL, ALLEGRO_MESSAGEBOX_ERROR); return false; } <file_sep>/src/engine/color.h #ifndef MINISPHERE__COLOR_H__INCLUDED #define MINISPHERE__COLOR_H__INCLUDED typedef struct color { uint8_t r; uint8_t g; uint8_t b; uint8_t alpha; } color_t; typedef struct colormatrix { int rn, rr, rg, rb; int gn, gr, gg, gb; int bn, br, bg, bb; } colormatrix_t; ALLEGRO_COLOR nativecolor (color_t color); color_t color_new (uint8_t r, uint8_t g, uint8_t b, uint8_t alpha); color_t color_lerp (color_t color, color_t other, float w1, float w2); color_t color_transform (color_t color, colormatrix_t matrix); colormatrix_t colormatrix_new (int rn, int rr, int rg, int rb, int gn, int gr, int gg, int gb, int bn, int br, int bg, int bb); colormatrix_t colormatrix_lerp (colormatrix_t mat1, colormatrix_t mat2, int w1, int w2); void init_color_api (void); void duk_push_sphere_color (duk_context* ctx, color_t color); color_t duk_require_sphere_color (duk_context* ctx, duk_idx_t index); colormatrix_t duk_require_sphere_colormatrix (duk_context* ctx, duk_idx_t index); #endif // MINISPHERE__COLOR_H__INCLUDED <file_sep>/assets/system/modules/miniRT/scenes.js /** * miniRT/scenes CommonJS module * advanced scene manager using multiple timelines and cooperative threading * (c) 2015-2016 <NAME> * * miniRT/scenes is based on the Scenario cutscene engine originally written * for Sphere 1.5. **/ if (typeof exports === 'undefined') { throw new TypeError("script must be loaded with require()"); } const link = require('link'); const threads = require('./threads'); var screenMask = new Color(0, 0, 0, 0); var scenes = module.exports = (function() { renderScenes = function() { if (screenMask.alpha > 0) { ApplyColorMask(screenMask); } }; var updateScenes = function() { return true; }; var manifest = GetGameManifest(); var priority = 99; var threadID = threads.create({ update: updateScenes, render: renderScenes, }, priority); // scenelet() // register a new scenelet. // arguments: // name: the name of the scenelet. this should be a valid JavaScript identifier (alphanumeric, no spaces). // def: an object defining the scenelet callbacks: // .start(scene, ...): called when the command begins executing to initialize the state, or for // instantaneous commands, perform the necessary action. // .update(scene): optional. a function to be called once per frame to update state data. if not // provided, scenes immediately moves on to the next command after calling start(). // this function should return true to keep the operation running, or false to // terminate it. // .getInput(scene): optional. a function to be called once per frame to check for player input and // update state data accordingly. // .render(scene): optional. a function to be called once per frame to perform any rendering // related to the command (e.g. text boxes). // .finish(scene): optional. called after command execution ends, just before Scenes executes // the next instruction in the queue. // remarks: // it is safe to call this prior to initialization. var scenelet = function(name, def) { if (name in Scene.prototype) Abort("scenes.scenelet(): scenelet ID `" + name + "` already in use", -1); Scene.prototype[name] = function() { this.enqueue({ arguments: arguments, start: def.start, getInput: def.getInput, update: def.update, render: def.render, finish: def.finish }); return this; }; }; // Scene() // construct a scene definition. function Scene() { var activation = null; var forkedQueues = []; var jumpsToFix = []; var mainThread = 0; var openBlockTypes = []; var queueToFill = []; var tasks = []; var goTo = function(address) { activation.pc = address; }; function runTimeline(ctx) { if ('opThread' in ctx) { if (threads.isRunning(ctx.opThread)) return true; else { link(tasks) .where(function(thread) { return ctx.opThread == thread }) .remove(); delete ctx.opThread; activation = ctx; if (typeof ctx.op.finish === 'function') ctx.op.finish.call(ctx.opctx, this); activation = null; } } if (ctx.pc < ctx.instructions.length) { ctx.op = ctx.instructions[ctx.pc++]; ctx.opctx = {}; if (typeof ctx.op.start === 'function') { var arglist = [ this ]; for (i = 0; i < ctx.op.arguments.length; ++i) arglist.push(ctx.op.arguments[i]); activation = ctx; ctx.op.start.apply(ctx.opctx, arglist); activation = null; } if (ctx.op.update != null) { ctx.opThread = threads.createEx(ctx.opctx, { update: ctx.op.update.bind(ctx.opctx, this), render: typeof ctx.op.render === 'function' ? ctx.op.render.bind(ctx.opctx, this) : undefined, getInput: typeof ctx.op.getInput === 'function' ? ctx.op.getInput.bind(ctx.opctx, this) : undefined, priority: priority, }); tasks.push(ctx.opThread); } else { ctx.opThread = 0; } return true; } else { if (link(ctx.forks) .where(function(thread) { return threads.isRunning(thread); }) .length() == 0) { var self = threads.self(); link(tasks) .where(function(thread) { return self == thread }) .remove(); return false; } else { return true; } } }; // Scene:isRunning() // determines whether a scene is currently playing. // Returns: // true if the scene is still executing commands; false otherwise. function isRunning() { return threads.isRunning(mainThread); }; // Scene:doIf() // during scene execution, execute a block of commands only if a specified condition is met. // arguments: // conditional: a function to be called during scene execution to determine whether to run the following // block. the function should return true to execute the block, or false to skip it. it // will be called with 'this' set to the invoking scene. function doIf(conditional) { var jump = { ifFalse: null }; jumpsToFix.push(jump); var command = { arguments: [], start: function(scene) { if (!conditional.call(scene)) { goTo(jump.ifFalse); } } }; enqueue(command); openBlockTypes.push('branch'); return this; }; // Scene:doWhile() // During scene execution, repeats a block of commands for as long as a specified condition is met. // Arguments: // conditional: A function to be called at each iteration to determine whether to continue the // loop. The function should return true to continue the loop, or false to // stop it. It will be called with 'this' set to the invoking Scene object. function doWhile(conditional) { var jump = { loopStart: queueToFill.length, ifDone: null }; jumpsToFix.push(jump); var command = { arguments: [], start: function(scene) { if (!conditional.call(scene)) { goTo(jump.ifDone); } } }; enqueue(command); openBlockTypes.push('loop'); return this; }; // Scene:end() // marks the end of a block of commands. function end() { if (openBlockTypes.length == 0) Abort("Mismatched end() in scene definition", -1); var blockType = openBlockTypes.pop(); switch (blockType) { case 'fork': var command = { arguments: [ queueToFill ], start: function(scene, instructions) { var ctx = { instructions: instructions, pc: 0, forks: [], }; var tid = threads.createEx(scene, { update: runTimeline.bind(scene, ctx) }); tasks.push(tid); activation.forks.push(tid); } }; queueToFill = forkedQueues.pop(); enqueue(command); break; case 'branch': var jump = jumpsToFix.pop(); jump.ifFalse = queueToFill.length; break; case 'loop': var command = { arguments: [], start: function(scene) { goTo(jump.loopStart); } }; enqueue(command); var jump = jumpsToFix.pop(); jump.ifDone = queueToFill.length; break; default: Abort("miniscenes internal error (unknown block type)", -1); break; } return this; }; // Scene:enqueue() // enqueues a custom scenelet. not recommended for outside use. function enqueue(command) { if (isRunning()) Abort("attempt to modify scene definition during playback", -2); queueToFill.push(command); }; // Scene:fork() // during scene execution, fork the timeline, allowing a block to run simultaneously with // the instructions after it. function fork() { forkedQueues.push(queueToFill); queueToFill = []; openBlockTypes.push('fork'); return this; }; // Scene:restart() // restart the scene from the beginning. this has the same effect as calling // .stop() and .play() back-to-back. function restart() { stop(); run(); }; // Scene:resync() // during a scene, suspend the current timeline until all of its forks have run to // completion. // remarks: // there is an implicit resync at the end of a timeline. function resync() { var command = { arguments: [], start: function(scene) { forks = activation.forks; }, update: function(scene) { return link(forks) .where(function(tid) { return threads.isRunning(tid); }) .length() > 0; } }; enqueue(command); return this; } // Scene:run() // play back the scene. // arguments: // waitUntilDone: if true, block until playback has finished. function run(waitUntilDone) { if (openBlockTypes.length > 0) Abort("unclosed block in scene definition", -1); if (isRunning()) return; var ctx = { instructions: queueToFill, pc: 0, forks: [], }; mainThread = threads.createEx(this, { update: runTimeline.bind(this, ctx) }); tasks.push(mainThread); if (waitUntilDone) threads.join(mainThread); return this; }; // Scene:stop() // immediately halt scene playback. no effect if the scene isn't playing. // remarks: // after calling this method, calling .play() afterwards will start from the // beginning. function stop() { link(tasks) .each(function(tid) { threads.kill(tid); }); }; var retobj = { isRunning: isRunning, doIf: doIf, doWhile: doWhile, end: end, enqueue: enqueue, fork: fork, restart: restart, resync: resync, run: run, stop: stop, }; Object.setPrototypeOf(retobj, Scene.prototype); return retobj; } return { scenelet: scenelet, Scene: Scene, }; })(); // .call() scenelet // Calls a function during scene execution. // Arguments: // method: The function to be called. // Remarks: // Any additional arguments provided beyond the 'method' argument will be passed // to the specified function when it is called. scenes.scenelet('call', { start: function(scene, method /*...*/) { method.apply(null, [].slice.call(arguments, 2)); } }); // .facePerson() scenelet // Changes the facing direction of a map entity. // Arguments: // person: The name of the entity whose direction to change. // direction: The name of the new direction. scenes.scenelet('facePerson', { start: function(scene, person, direction) { var faceCommand; switch (direction.toLowerCase()) { case "n": case "north": faceCommand = COMMAND_FACE_NORTH; break; case "ne": case "northeast": faceCommand = COMMAND_FACE_NORTHEAST; break; case "e": case "east": faceCommand = COMMAND_FACE_EAST; break; case "se": case "southeast": faceCommand = COMMAND_FACE_SOUTHEAST; break; case "s": case "south": faceCommand = COMMAND_FACE_SOUTH; break; case "sw": case "southwest": faceCommand = COMMAND_FACE_SOUTHWEST; break; case "w": case "west": faceCommand = COMMAND_FACE_WEST; break; case "nw": case "northwest": faceCommand = COMMAND_FACE_NORTHWEST; break; default: faceCommand = COMMAND_WAIT; } QueuePersonCommand(person, faceCommand, false); } }); // .fadeTo() scenelet // Fades the screen mask to a specified color. // Arguments: // color: The new screen mask color. // duration: The length of the fading operation, in seconds. scenes.scenelet('fadeTo', { start: function(scene, color, duration) { duration = duration !== undefined ? duration : 0.25; this.fader = new scenes.Scene() .tween(screenMask, duration, 'linear', color) .run(); }, update: function(scene) { return this.fader.isRunning(); } }); // .focusOnPerson() scenelet // Pans the camera to a point centered over a specified map entity. // Arguments: // person: The name of the entity to focus on. // duration: Optional. The length of the panning operation, in seconds. // (default: 0.25) scenes.scenelet('focusOnPerson', { start: function(scene, person, duration) { duration = duration !== undefined ? duration : 0.25; this.pan = new scenes.Scene() .panTo(GetPersonX(person), GetPersonY(person), duration) .run(); }, update: function(scene) { return this.pan.isRunning(); } }); // .followPerson() scenelet // Pans to and attaches the camera to a specified map entity. // Arguments: // person: The name of the entity to follow. scenes.scenelet('followPerson', { start: function(scene, person) { this.person = person; this.pan = new scenes.Scene() .focusOnPerson(person) .run(); }, update: function(scene) { return this.pan.isRunning(); }, finish: function(scene) { AttachCamera(this.person); } }); // .hidePerson() scenelet // Hides a map entity and prevents it from obstructing other entities. // Arguments: // person: The name of the entity to hide. scenes.scenelet('hidePerson', { start: function(scene, person) { SetPersonVisible(person, false); IgnorePersonObstructions(person, true); } }); // .killPerson() scenelet // Destroys a map entity. // Arguments: // person: The name of the entity to destroy. scenes.scenelet('killPerson', { start: function(scene, person) { DestroyPerson(person); } }); // .marquee() scenelet // Shows a scrolling marquee with the specified text. Useful for announcing boss battles. // Arguments: // text: The text to display. // backgroundColor: The background color of the marquee. // color: The text color. scenes.scenelet('marquee', { start: function(scene, text, backgroundColor, color) { if (backgroundColor === undefined) { backgroundColor = new Color(0, 0, 0, 255); } if (color === undefined) { color = new Color(255, 255, 255, 255); } this.text = text; this.color = color; this.background = backgroundColor; this.font = GetSystemFont(); this.windowSize = GetScreenWidth() + this.font.getStringWidth(this.text); this.height = this.font.getHeight() + 10; this.textHeight = this.font.getHeight(); this.fadeness = 0.0; this.scroll = 0.0; this.animation = new scenes.Scene() .tween(this, 0.25, 'linear', { fadeness: 1.0 }) .tween(this, 1.0, 'easeOutExpo', { scroll: 0.5 }) .tween(this, 1.0, 'easeInExpo', { scroll: 1.0 }) .tween(this, 0.25, 'linear', { fadeness: 0.0 }) .run(); }, render: function(scene) { var boxHeight = this.height * this.fadeness; var boxY = GetScreenHeight() / 2 - boxHeight / 2; var textX = GetScreenWidth() - this.scroll * this.windowSize; var textY = boxY + boxHeight / 2 - this.textHeight / 2; Rectangle(0, boxY, GetScreenWidth(), boxHeight, this.background); this.font.setColorMask(new Color(0, 0, 0, this.color.alpha)); this.font.drawText(textX + 1, textY + 1, this.text); this.font.setColorMask(this.color); this.font.drawText(textX, textY, this.text); }, update: function(scene) { return this.animation.isRunning(); } }); // .maskPerson() scenelet scenes.scenelet('maskPerson', { start: function(scene, name, newMask, duration) { duration = duration !== undefined ? duration : 0.25; this.name = name; this.mask = GetPersonMask(this.name); this.fade = new scenes.Scene() .tween(this.mask, duration, 'easeInOutSine', newMask) .run(); }, update: function(scene) { SetPersonMask(this.name, this.mask); return this.fade.isRunning(); } }); // .movePerson() scenelet // Instructs a map entity to move a specified distance. // Arguments: // person: The person to move. // direction: The direction in which to move the entity. // distance: The distance the entity should move. // speed: The number of pixels per frame the entity should move. // faceFirst: Optional. If this is false, the entity will move without changing its facing // direction. (default: true) scenes.scenelet('movePerson', { start: function(scene, person, direction, distance, speed, faceFirst) { faceFirst = faceFirst !== undefined ? faceFirst : true; if (!isNaN(speed)) { speedVector = [ speed, speed ]; } else { speedVector = speed; } this.person = person; this.oldSpeedVector = [ GetPersonSpeedX(person), GetPersonSpeedY(person) ]; if (speedVector != null) { SetPersonSpeedXY(this.person, speedVector[0], speedVector[1]); } else { speedVector = this.oldSpeedVector; } var xMovement; var yMovement; var faceCommand; var stepCount; switch (direction) { case "n": case "north": faceCommand = COMMAND_FACE_NORTH; xMovement = COMMAND_WAIT; yMovement = COMMAND_MOVE_NORTH; stepCount = distance / speedVector[1]; break; case "e": case "east": faceCommand = COMMAND_FACE_EAST; xMovement = COMMAND_MOVE_EAST; yMovement = COMMAND_WAIT; stepCount = distance / speedVector[0]; break; case "s": case "south": faceCommand = COMMAND_FACE_SOUTH; xMovement = COMMAND_WAIT; yMovement = COMMAND_MOVE_SOUTH; stepCount = distance / speedVector[1]; break; case "w": case "west": faceCommand = COMMAND_FACE_WEST; xMovement = COMMAND_MOVE_WEST; yMovement = COMMAND_WAIT; stepCount = distance / speedVector[0]; break; default: faceCommand = COMMAND_WAIT; xMovement = COMMAND_WAIT; yMovement = COMMAND_WAIT; stepCount = 0; } if (faceFirst) { QueuePersonCommand(this.person, faceCommand, true); } for (iStep = 0; iStep < stepCount; ++iStep) { QueuePersonCommand(this.person, xMovement, true); QueuePersonCommand(this.person, yMovement, true); QueuePersonCommand(this.person, COMMAND_WAIT, false); } return true; }, update: function(scene) { return !IsCommandQueueEmpty(this.person); }, finish: function(scene) { SetPersonSpeedXY(this.person, this.oldSpeedVector[0], this.oldSpeedVector[1]); } }); // .panTo() scenelet // Pans the map camera to center on a specified location on the map. // Arguments: // x: The X coordinate of the location to pan to. // y: The Y coordinate of the location to pan to. // duration: Optional. The length of the panning operation, in seconds. (default: 0.25) scenes.scenelet('panTo', { start: function(scene, x, y, duration) { duration = duration !== undefined ? duration : 0.25; DetachCamera(); var targetXY = { cameraX: x, cameraY: y }; this.cameraX = GetCameraX(); this.cameraY = GetCameraY(); this.pan = new scenes.Scene() .tween(this, duration, 'easeOutQuad', targetXY) .run(); }, update: function(scene) { SetCameraX(this.cameraX); SetCameraY(this.cameraY); return this.pan.isRunning(); } }); // .pause() scenelet // Delays execution of the current timeline for a specified amount of time. // Arguments: // duration: The length of the delay, in seconds. scenes.scenelet('pause', { start: function(scene, duration) { this.duration = duration; this.elapsed = 0; }, update: function(scene) { this.elapsed += 1.0 / threads.frameRate; return this.elapsed < this.duration; } }); // .playSound() scenelet // Plays a sound from a file. // fileName: The name of the file to play. scenes.scenelet('playSound', { start: function(scene, fileName) { this.sound = new Sound(fileName); this.sound.play(false); return true; }, update: function(scene) { return this.sound.isPlaying(); } }); // .showPerson() scenelet // Makes a map entity visible and enables obstruction. // Arguments: // person: The name of the entity to show. scenes.scenelet('showPerson', { start: function(scene, person) { SetPersonVisible(person, true); IgnorePersonObstructions(person, false); } }); // .spriteset() scenelet scenes.scenelet('setSprite', { start: function(scene, name, spriteFile) { var spriteset = new Spriteset(spriteFile); SetPersonSpriteset(name, spriteset); } }); // .tween() scenelet // Smoothly adjusts numeric properties of an object over a period of time. // Arguments: // object: The object containing the properties to be tweened. // duration: The length of the tweening operation, in seconds. // easingType: The name of the easing function to use, e.g. 'linear' or 'easeOutQuad'. // endValues: An object specifying the properties to tween and their final values. scenes.scenelet('tween', { start: function(scene, object, duration, easingType, endValues) { this.easers = { linear: function(t, b, c, d) { return c * t / d + b; }, easeInQuad: function(t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function(t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function(t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function(t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function(t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function(t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function(t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function(t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function(t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function(t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function(t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function(t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function(t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function(t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function(t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function(t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function(t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function(t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function(t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function(t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function(t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function(t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function(t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function(t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function(t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function(t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function(t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function(t, b, c, d) { return c - this.easeOutBounce(d-t, 0, c, d) + b; }, easeOutBounce: function(t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function(t, b, c, d) { if (t < d/2) return this.easeInBounce(t*2, 0, c, d) * .5 + b; return this.easeOutBounce(t*2-d, 0, c, d) * .5 + c*.5 + b; } }; this.change = {}; this.duration = duration; this.elapsed = 0.0; this.object = object; this.startValues = {}; this.type = easingType in this.easers ? easingType : 'linear'; var isChanged = false; for (var p in endValues) { this.change[p] = endValues[p] - object[p]; this.startValues[p] = object[p]; isChanged = isChanged || this.change[p] != 0; } var specialPropertyNames = [ 'red', 'green', 'blue', 'alpha' ]; for (var i = 0; i < specialPropertyNames.length; ++i) { var p = specialPropertyNames[i]; if (!(p in this.change) && p in endValues) { this.change[p] = endValues[p] - object[p]; this.startValues[p] = object[p]; isChanged = isChanged || this.change[p] != 0; } } if (!isChanged) { this.elapsed = this.duration; } }, update: function(scene) { this.elapsed += 1.0 / threads.frameRate; if (this.elapsed < this.duration) { for (var p in this.change) { this.object[p] = this.easers[this.type](this.elapsed, this.startValues[p], this.change[p], this.duration); } return true; } else { return false; } }, finish: function(scene) { for (var p in this.change) { this.object[p] = this.startValues[p] + this.change[p]; } } }); <file_sep>/assets/system/modules/miniRT/delegates.js /** * miniRT/delegates CommonJS module * a multicast delegate implementation inspired by .NET events * (c) 2015-2016 <NAME> **/ if (typeof exports === 'undefined') { throw new TypeError("script must be loaded with require()"); } const link = require('link'); var delegates = module.exports = (function() { return { Delegate: Delegate, }; function Delegate() { var invokeList = []; return { add: add, invoke: invoke, remove: remove, }; function haveHandler(handler, thisObj) { return link(invokeList).contains(function(v) { return v.handler == handler && v.thisObj == thisObj; }); } // Delegate:add() // registers a handler to the delegate. // arguments: // handler: a function to be called when the delegate is invoked. // thisObj: optional. an object to use for the `this` binding of // `handler`. (default: undefined) function add(handler, thisObj) { if (haveHandler(handler, thisObj)) Abort("Delegate:add(): attempt to add duplicate handler", -1); invokeList.push({ thisObj: thisObj, handler: handler }); } // Delegate:invoke() // calls all methods in this delegate's invocation list. // returns: // the return value of the last handler called. function invoke() { var lastReturn = undefined; var invokeArgs = arguments; link(invokeList).each(function(v) { lastReturn = v.handler.apply(v.thisObj, invokeArgs); }); // mirror return value of the last handler called return lastReturn; } // Delegate:remove() // remove a handler that was previously registered with add(). // remarks: // takes the same arguments, with the same semantics, as Delegate:add(). // Delegate:add() must already have been called with the same arguments. function remove(handler, thisObj) { if (!haveHandler(handler, thisObj)) Abort("Delegate:remove(): no such handler is registered", -1); link(invokeList) .where(function(v) { return v.handler == handler; }) .where(function(v) { return v.thisObj == thisObj; }) .remove(); } } })(); <file_sep>/src/engine/animation.c #include "minisphere.h" #include "api.h" #include "image.h" #include "animation.h" #include <libmng.h> static duk_ret_t js_LoadAnimation (duk_context* ctx); static duk_ret_t js_new_Animation (duk_context* ctx); static duk_ret_t js_Animation_finalize (duk_context* ctx); static duk_ret_t js_Animation_get_height (duk_context* ctx); static duk_ret_t js_Animation_get_width (duk_context* ctx); static duk_ret_t js_Animation_getDelay (duk_context* ctx); static duk_ret_t js_Animation_getNumFrames (duk_context* ctx); static duk_ret_t js_Animation_drawFrame (duk_context* ctx); static duk_ret_t js_Animation_drawZoomedFrame (duk_context* ctx); static duk_ret_t js_Animation_readNextFrame (duk_context* ctx); static mng_ptr mng_cb_malloc (mng_size_t size); static void mng_cb_free (mng_ptr ptr, mng_size_t size); static mng_bool mng_cb_openstream (mng_handle stream); static mng_bool mng_cb_closestream (mng_handle stream); static mng_ptr mng_cb_getcanvasline (mng_handle stream, mng_uint32 line_num); static mng_uint32 mng_cb_gettickcount (mng_handle stream); static mng_bool mng_cb_processheader (mng_handle stream, mng_uint32 width, mng_uint32 height); static mng_bool mng_cb_readdata (mng_handle stream, mng_ptr buf, mng_uint32 n_bytes, mng_uint32p p_readsize); static mng_bool mng_cb_refresh (mng_handle stream, mng_uint32 x, mng_uint32 y, mng_uint32 width, mng_uint32 height); static mng_bool mng_cb_settimer (mng_handle stream, mng_uint32 msecs); struct animation { unsigned int refcount; unsigned int id; unsigned int delay; sfs_file_t* file; image_t* frame; bool is_frame_ready; image_lock_t* lock; mng_handle stream; unsigned int w, h; }; static unsigned int s_next_animation_id = 0; animation_t* animation_new(const char* path) { animation_t* anim; console_log(2, "loading animation #%u as `%s`", s_next_animation_id, path); if (!(anim = calloc(1, sizeof(animation_t)))) goto on_error; if (!(anim->stream = mng_initialize(anim, mng_cb_malloc, mng_cb_free, NULL))) goto on_error; mng_setcb_openstream(anim->stream, mng_cb_openstream); mng_setcb_closestream(anim->stream, mng_cb_closestream); mng_setcb_getcanvasline(anim->stream, mng_cb_getcanvasline); mng_setcb_gettickcount(anim->stream, mng_cb_gettickcount); mng_setcb_processheader(anim->stream, mng_cb_processheader); mng_setcb_readdata(anim->stream, mng_cb_readdata); mng_setcb_refresh(anim->stream, mng_cb_refresh); mng_setcb_settimer(anim->stream, mng_cb_settimer); if (!(anim->file = sfs_fopen(g_fs, path, NULL, "rb"))) goto on_error; if (mng_read(anim->stream) != MNG_NOERROR) goto on_error; anim->id = s_next_animation_id++; if (!animation_update(anim)) goto on_error; return animation_ref(anim); on_error: console_log(2, "failed to load animation #%u", s_next_animation_id++); if (anim != NULL) { if (anim->stream != NULL) mng_cleanup(&anim->stream); if (anim->file != NULL) sfs_fclose(anim->file); if (anim->frame != NULL) { free_image(anim->frame); } free(anim); } return NULL; } animation_t* animation_ref(animation_t* animation) { ++animation->refcount; return animation; } void animation_free(animation_t* animation) { if (animation == NULL || --animation->refcount > 0) return; console_log(3, "disposing animation #%u no longer in use", animation->id); mng_cleanup(&animation->stream); sfs_fclose(animation->file); free_image(animation->frame); free(animation); } bool animation_update(animation_t* anim) { if (!(anim->lock = lock_image(anim->frame))) return false; if (!anim->is_frame_ready) mng_display(anim->stream); else if (mng_display_resume(anim->stream) != MNG_NEEDTIMERWAIT) mng_display_reset(anim->stream); unlock_image(anim->frame, anim->lock); anim->is_frame_ready = true; return true; } static mng_ptr mng_cb_malloc(mng_size_t size) { return calloc(1, size); } static void mng_cb_free(mng_ptr ptr, mng_size_t size) { free(ptr); } static mng_bool mng_cb_openstream(mng_handle stream) { return MNG_TRUE; } static mng_bool mng_cb_closestream(mng_handle stream) { return MNG_TRUE; } static mng_ptr mng_cb_getcanvasline(mng_handle stream, mng_uint32 line_num) { animation_t* anim = mng_get_userdata(stream); return anim->lock->pixels + line_num * anim->lock->pitch; } static mng_uint32 mng_cb_gettickcount(mng_handle stream) { return al_get_time() * 1000; } static mng_bool mng_cb_processheader(mng_handle stream, mng_uint32 width, mng_uint32 height) { animation_t* anim = mng_get_userdata(stream); anim->w = width; anim->h = height; free_image(anim->frame); if (!(anim->frame = create_image(anim->w, anim->h))) goto on_error; mng_set_canvasstyle(stream, MNG_CANVAS_RGBA8); return MNG_TRUE; on_error: free_image(anim->frame); return MNG_FALSE; } static mng_bool mng_cb_readdata(mng_handle stream, mng_ptr buf, mng_uint32 n_bytes, mng_uint32p p_readsize) { animation_t* anim = mng_get_userdata(stream); *p_readsize = (mng_uint32)sfs_fread(buf, 1, n_bytes, anim->file); return MNG_TRUE; } static mng_bool mng_cb_refresh(mng_handle stream, mng_uint32 x, mng_uint32 y, mng_uint32 width, mng_uint32 height) { return MNG_TRUE; } static mng_bool mng_cb_settimer(mng_handle stream, mng_uint32 msecs) { animation_t* anim = mng_get_userdata(stream); anim->delay = msecs; return MNG_TRUE; } void init_animation_api(void) { api_register_method(g_duk, NULL, "LoadAnimation", js_LoadAnimation); api_register_ctor(g_duk, "Animation", js_new_Animation, js_Animation_finalize); api_register_prop(g_duk, "Animation", "width", js_Animation_get_width, NULL); api_register_prop(g_duk, "Animation", "height", js_Animation_get_height, NULL); api_register_method(g_duk, "Animation", "getDelay", js_Animation_getDelay); api_register_method(g_duk, "Animation", "getNumFrames", js_Animation_getNumFrames); api_register_method(g_duk, "Animation", "drawFrame", js_Animation_drawFrame); api_register_method(g_duk, "Animation", "drawZoomedFrame", js_Animation_drawZoomedFrame); api_register_method(g_duk, "Animation", "readNextFrame", js_Animation_readNextFrame); } static duk_ret_t js_LoadAnimation(duk_context* ctx) { animation_t* anim; const char* filename; filename = duk_require_path(ctx, 0, "animations", true); if (!(anim = animation_new(filename))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "LoadAnimation(): unable to load animation file `%s`", filename); duk_push_sphere_obj(ctx, "Animation", anim); return 1; } static duk_ret_t js_new_Animation(duk_context* ctx) { animation_t* anim; const char* filename; filename = duk_require_path(ctx, 0, NULL, false); if (!(anim = animation_new(filename))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Animation(): unable to load animation file `%s`", filename); duk_push_sphere_obj(ctx, "Animation", anim); return 1; } static duk_ret_t js_Animation_finalize(duk_context* ctx) { animation_t* anim; anim = duk_require_sphere_obj(ctx, 0, "Animation"); animation_free(anim); return 0; } static duk_ret_t js_Animation_get_height(duk_context* ctx) { animation_t* anim; duk_push_this(ctx); anim = duk_require_sphere_obj(ctx, -1, "Animation"); duk_pop(ctx); duk_push_int(ctx, anim->h); return 1; } static duk_ret_t js_Animation_get_width(duk_context* ctx) { animation_t* anim; duk_push_this(ctx); anim = duk_require_sphere_obj(ctx, -1, "Animation"); duk_pop(ctx); duk_push_int(ctx, anim->w); return 1; } static duk_ret_t js_Animation_getDelay(duk_context* ctx) { animation_t* anim; duk_push_this(ctx); anim = duk_require_sphere_obj(ctx, -1, "Animation"); duk_pop(ctx); duk_push_uint(ctx, anim->delay); return 1; } static duk_ret_t js_Animation_getNumFrames(duk_context* ctx) { animation_t* anim; duk_push_this(ctx); anim = duk_require_sphere_obj(ctx, -1, "Animation"); duk_pop(ctx); duk_push_uint(ctx, mng_get_framecount(anim->stream)); return 1; } static duk_ret_t js_Animation_drawFrame(duk_context* ctx) { int x = duk_require_number(ctx, 0); int y = duk_require_number(ctx, 1); animation_t* anim; duk_push_this(ctx); anim = duk_require_sphere_obj(ctx, -1, "Animation"); duk_pop(ctx); draw_image(anim->frame, x, y); return 0; } static duk_ret_t js_Animation_drawZoomedFrame(duk_context* ctx) { int x = duk_require_number(ctx, 0); int y = duk_require_number(ctx, 1); double scale = duk_require_number(ctx, 2); animation_t* anim; duk_push_this(ctx); anim = duk_require_sphere_obj(ctx, -1, "Animation"); duk_pop(ctx); if (scale < 0.0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Animation:drawZoomedFrame(): scale must be positive (got: %g)", scale); draw_image_scaled(anim->frame, x, y, anim->w * scale, anim->h * scale); return 0; } static duk_ret_t js_Animation_readNextFrame(duk_context* ctx) { animation_t* anim; duk_push_this(ctx); anim = duk_require_sphere_obj(ctx, -1, "Animation"); duk_pop(ctx); animation_update(anim); return 0; } <file_sep>/src/compiler/utility.h #ifndef CELL__UTILITY_H__INCLUDED #define CELL__UTILITY_H__INCLUDED #include <stdbool.h> #include <stddef.h> void* fslurp (const char* filename, size_t *out_size); bool fspew (const void* buffer, size_t size, const char* filename); bool wildcmp (const char* filename, const char* pattern); #endif <file_sep>/src/shared/path.h #ifndef MINISPHERE__PATH_H__INCLUDED #define MINISPHERE__PATH_H__INCLUDED #include <stdbool.h> #include <stddef.h> typedef struct path path_t; path_t* path_new (const char* pathname); path_t* path_new_dir (const char* pathname); path_t* path_dup (const path_t* path); void path_free (path_t* path); const char* path_cstr (const path_t* path); const char* path_filename_cstr (const path_t* path); const char* path_hop_cstr (const path_t* path, size_t idx); path_t* path_insert_hop (path_t* path, size_t idx, const char* name); bool path_has_extension (const path_t* path, const char* extension); bool path_is_file (const path_t* path); bool path_is_rooted (const path_t* path); size_t path_num_hops (const path_t* path); bool path_hop_cmp (const path_t* path, size_t idx, const char* name); path_t* path_append (path_t* path, const char* pathname); path_t* path_append_dir (path_t* path, const char* pathname); path_t* path_cat (path_t* path, const path_t* tail); path_t* path_change_name (path_t* path, const char* filename); bool path_cmp (const path_t* path1, const path_t* path2); path_t* path_collapse (path_t* path, bool collapse_double_dots); bool path_mkdir (const path_t* path); path_t* path_rebase (path_t* path, const path_t* root); path_t* path_relativize (path_t* path, const path_t* origin); path_t* path_remove_hop (path_t* path, size_t idx); path_t* path_resolve (path_t* path, const path_t* relative_to); path_t* path_set (path_t* path, const char* pathname); path_t* path_set_dir (path_t* path, const char* pathname); path_t* path_strip (path_t* path); #endif // MINISPHERE__PATH_H__INCLUDED <file_sep>/src/engine/image.h #ifndef MINISPHERE__IMAGE_H__INCLUDED #define MINISPHERE__IMAGE_H__INCLUDED typedef struct image image_t; typedef struct image_lock { color_t* pixels; ptrdiff_t pitch; int num_lines; } image_lock_t; image_t* create_image (int width, int height); image_t* create_subimage (image_t* parent, int x, int y, int width, int height); image_t* clone_image (const image_t* image); image_t* load_image (const char* filename); image_t* read_image (sfs_file_t* file, int width, int height); image_t* read_subimage (sfs_file_t* file, image_t* parent, int x, int y, int width, int height); image_t* ref_image (image_t* image); void free_image (image_t* image); ALLEGRO_BITMAP* get_image_bitmap (image_t* image); int get_image_height (const image_t* image); color_t get_image_pixel (image_t* image, int x, int y); int get_image_width (const image_t* image); void set_image_pixel (image_t* image, int x, int y, color_t color); bool apply_color_matrix (image_t* image, colormatrix_t matrix, int x, int y, int width, int height); bool apply_color_matrix_4 (image_t* image, colormatrix_t ul_mat, colormatrix_t ur_mat, colormatrix_t ll_mat, colormatrix_t lr_mat, int x, int y, int width, int height); bool apply_image_lookup (image_t* image, int x, int y, int width, int height, uint8_t red_lu[256], uint8_t green_lu[256], uint8_t blue_lu[256], uint8_t alpha_lu[256]); void blit_image (image_t* image, image_t* target_image, int x, int y); void draw_image (image_t* image, int x, int y); void draw_image_masked (image_t* image, color_t mask, int x, int y); void draw_image_scaled (image_t* image, int x, int y, int width, int height); void draw_image_scaled_masked (image_t* image, color_t mask, int x, int y, int width, int height); void draw_image_tiled (image_t* image, int x, int y, int width, int height); void draw_image_tiled_masked (image_t* image, color_t mask, int x, int y, int width, int height); void fill_image (image_t* image, color_t color); bool flip_image (image_t* image, bool is_h_flip, bool is_v_flip); image_lock_t* lock_image (image_t* image); bool replace_image_color (image_t* image, color_t color, color_t new_color); bool rescale_image (image_t* image, int width, int height); bool save_image (image_t* image, const char* filename); void unlock_image (image_t* image, image_lock_t* lock); void init_image_api (duk_context* ctx); void duk_push_sphere_image (duk_context* ctx, image_t* image); image_t* duk_require_sphere_image (duk_context* ctx, duk_idx_t index); #endif // MINISPHERE__IMAGE_H__INCLUDED <file_sep>/src/engine/shader.h #ifndef MINISPHERE__SHADER_H__INCLUDED #define MINISPHERE__SHADER_H__INCLUDED typedef struct shader shader_t; typedef enum shader_type { SHADER_TYPE_PIXEL, SHADER_TYPE_VERTEX, SHADER_TYPE_MAX } shader_type_t; void initialize_shaders (bool enable_shading); void shutdown_shaders (void); bool are_shaders_active (void); shader_t* shader_new (const char* vs_path, const char* fs_path); shader_t* shader_ref (shader_t* shader); void shader_free (shader_t* shader); bool shader_use (shader_t* shader); void init_shader_api (void); #endif // MINISPHERE__SHADER_H__INCLUDED <file_sep>/msvs/README.md minisphere Visual Studio Solution --------------------------------- This is a Visual Studio solution you can use to compiling minisphere on Windows using Visual Studio 2015 or equivalent MSBuild. Later versions of Visual Studio may work, as well. The solution includes x86 and x64 debug and release builds. Here is where the engine will be built relative to the directory containing `src`: * Console - `msw/` (x86), `msw64/` (x64) * Release - `msw/` (x86), `msw64/` (x64) * Debug - `msvc/debug/` (x86), `msvc/debug64/` (x64) Dependencies ------------ minisphere depends on Allegro, libmng and zlib. On Windows, Allegro 5.2 is provided through NuGet, and libmng and zlib are included in the repository. As long as you have a compatible version of Visual Studio installed, no additional files are needed. <file_sep>/src/engine/windowstyle.h #include "color.h" typedef struct windowstyle windowstyle_t; windowstyle_t* load_windowstyle (const char* filename); windowstyle_t* ref_windowstyle (windowstyle_t* winstyle); void free_windowstyle (windowstyle_t* windowstyle); void draw_window (windowstyle_t* winstyle, color_t mask, int x, int y, int width, int height); void init_windowstyle_api (void); void duk_push_sphere_windowstyle (duk_context* ctx, windowstyle_t* winstyle); <file_sep>/assets/system/system.ini # System-provided assets Font=system.rfn WindowStyle=system.rws Arrow=pointer.png UpArrow=up_arrow.png DownArrow=down_arrow.png # Default shaders GalileoVertShader=shaders/galileo.vert.glsl GalileoFragShader=shaders/galileo.frag.glsl <file_sep>/src/engine/console.c #include "minisphere.h" #include "console.h" static int s_verbosity = 1; void initialize_console(int verbosity) { s_verbosity = verbosity; } int get_log_verbosity(void) { return s_verbosity; } void console_log(int level, const char* fmt, ...) { va_list ap; if (level > s_verbosity) return; va_start(ap, fmt); vprintf(fmt, ap); fputc('\n', stdout); va_end(ap); } <file_sep>/src/engine/map_engine.h #ifndef MINISPHERE__MAP_ENGINE_H__INCLUDED #define MINISPHERE__MAP_ENGINE_H__INCLUDED #include "obsmap.h" #include "persons.h" #include "tileset.h" void initialize_map_engine (void); void shutdown_map_engine (void); bool is_map_engine_running (void); rect_t get_map_bounds (void); const obsmap_t* get_map_layer_obsmap (int layer); const char* get_map_name (void); point3_t get_map_origin (void); int get_map_tile (int x, int y, int layer); const tileset_t* get_map_tileset (void); rect_t get_zone_bounds (int zone_index); int get_zone_layer (int zone_index); int get_zone_steps (int zone_index); void set_zone_bounds (int zone_index, rect_t bounds); void set_zone_script (int zone_index, script_t* script); void set_zone_steps (int zone_index, int steps); bool add_zone (rect_t bounds, int layer, script_t* script, int steps); void detach_person (const person_t* person); void normalize_map_entity_xy (double* inout_x, double* inout_y, int layer); void remove_zone (int zone_index); bool resize_map_layer (int layer, int x_size, int y_size); void init_map_engine_api (duk_context* ctx); int duk_require_map_layer (duk_context* ctx, duk_idx_t index); #endif // MINISPHERE__MAP_ENGINE_H__INCLUDED <file_sep>/src/compiler/image.c #include "image.h" #include "cell.h" struct image { uint32_t* pixels; size_t pitch; png_image* png; }; image_t* image_open(const path_t* path) { image_t* image; uint32_t* pixelbuf = NULL; png_image* png; image = calloc(1, sizeof(image_t)); png = calloc(1, sizeof(png_image)); png->version = PNG_IMAGE_VERSION; png->format = PNG_FORMAT_RGBA; if (!png_image_begin_read_from_file(png, path_cstr(path))) goto on_error; pixelbuf = malloc(PNG_IMAGE_SIZE(*png)); if (!png_image_finish_read(png, NULL, pixelbuf, 0, NULL)) goto on_error; image->png = png; image->pixels = pixelbuf; image->pitch = PNG_IMAGE_ROW_STRIDE(*png) / 4; return image; on_error: free(pixelbuf); png_image_free(png); return NULL; } void image_close(image_t* image) { if (image == NULL) return; png_image_free(image->png); free(image->pixels); free(image); } const ptrdiff_t image_get_pitch(const image_t* image) { return image->pitch; } const uint32_t* image_get_pixelbuf(const image_t* image) { return image->pixels; } int image_get_height(const image_t* image) { return image->png->height; } int image_get_width(const image_t* image) { return image->png->width; } <file_sep>/src/engine/spk.h #ifndef MINISPHERE__SPK_H__INCLUDED #define MINISPHERE__SPK_H__INCLUDED typedef struct spk spk_t; typedef struct spk_file spk_file_t; typedef enum spk_seek_origin { SPK_SEEK_SET, SPK_SEEK_CUR, SPK_SEEK_END } spk_seek_origin_t; spk_t* open_spk (const char* path); spk_t* ref_spk (spk_t* spk); void free_spk (spk_t* spk); vector_t* list_spk_filenames (spk_t* spk, const char* dirname, bool want_dirs); spk_file_t* spk_fopen (spk_t* spk, const char* path, const char* mode); void spk_fclose (spk_file_t* file); int spk_fputc (int ch, spk_file_t* file); int spk_fputs (const char* string, spk_file_t* file); size_t spk_fread (void* buf, size_t size, size_t count, spk_file_t* file); bool spk_fseek (spk_file_t* file, long long offset, spk_seek_origin_t origin); void* spk_fslurp (spk_t* spk, const char* path, size_t *out_size); long long spk_ftell (spk_file_t* file); size_t spk_fwrite (const void* buf, size_t size, size_t count, spk_file_t* file); #endif // MINISPHERE__SPK_H__INCLUDED <file_sep>/src/plugin/Debugger/DMessage.cs using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace minisphere.Gdk.Debugger { enum Request { BasicInfo = 0x10, TriggerStatus = 0x11, Pause = 0x12, Resume = 0x13, StepInto = 0x14, StepOver = 0x15, StepOut = 0x16, ListBreak = 0x17, AddBreak = 0x18, DelBreak = 0x19, GetVar = 0x1A, PutVar = 0x1B, GetCallStack = 0x1C, GetLocals = 0x1D, Eval = 0x1E, Detach = 0x1F, DumpHeap = 0x20, GetByteCode = 0x21, AppRequest = 0x22, GetHeapObjInfo = 0x23, GetObjPropDesc = 0x24, GetObjPropDescRange = 0x25, } enum Notify { Status = 0x01, Print = 0x02, Alert = 0x03, Log = 0x04, Throw = 0x05, Detaching = 0x06, AppNotify = 0x07, } enum AppRequest { GetGameInfo = 0x01, GetSource = 0x02, } enum AppNotify { DebugPrint = 0x01, } class DMessage { private DValue[] _fields; public DMessage(params dynamic[] values) { List<DValue> fields = new List<DValue>(); DValue fieldValue; foreach (dynamic value in values) { if (value is DValue) fieldValue = value; else if (value is Request || value is AppRequest) fieldValue = new DValue((int)value); else fieldValue = new DValue(value); fields.Add(fieldValue); } _fields = fields.ToArray(); } public DValue this[int index] => _fields[index]; public int Length => _fields.Length; public static DMessage Receive(Socket socket) { List<DValue> fields = new List<DValue>(); DValue value; do { if ((value = DValue.Receive(socket)) == null) return null; if (value.Tag != DValueTag.EOM) fields.Add(value); } while (value.Tag != DValueTag.EOM); return new DMessage(fields.ToArray()); } public bool Send(Socket socket) { foreach (var field in _fields) { if (!field.Send(socket)) return false; } if (!(new DValue(DValueTag.EOM).Send(socket))) return false; return true; } } } <file_sep>/src/compiler/main.c #include "cell.h" #include "assets.h" #include "build.h" static bool parse_cmdline (int argc, char* argv[]); static void print_cell_quote (void); static void print_banner (bool want_copyright, bool want_deps); static void print_usage (void); static path_t* s_in_path; static path_t* s_out_path; bool s_want_source_map; static char* s_target_name; int main(int argc, char* argv[]) { int retval = EXIT_FAILURE; build_t* build = NULL; srand((unsigned int)time(NULL)); // parse the command line if (!parse_cmdline(argc, argv)) goto shutdown; print_banner(true, false); printf("\n"); if (!(build = build_new(s_in_path, s_out_path, s_want_source_map))) goto shutdown; if (!build_prime(build, s_target_name)) goto shutdown; if (!build_run(build)) goto shutdown; retval = EXIT_SUCCESS; shutdown: if (build != NULL) { if (!build_is_ok(build, NULL, NULL)) retval = EXIT_FAILURE; } path_free(s_in_path); path_free(s_out_path); free(s_target_name); build_free(build); return retval; } static bool parse_cmdline(int argc, char* argv[]) { path_t* cellscript_path; int num_targets = 0; const char* short_args; int i; size_t i_arg; // establish default options s_in_path = path_new("./"); s_out_path = NULL; s_target_name = strdup("default"); s_want_source_map = false; // validate and parse the command line for (i = 1; i < argc; ++i) { if (strstr(argv[i], "--") == argv[i]) { if (strcmp(argv[i], "--help") == 0) { print_usage(); return false; } else if (strcmp(argv[i], "--version") == 0) { print_banner(true, true); return false; } else if (strcmp(argv[i], "--in-dir") == 0) { if (++i >= argc) goto missing_argument; path_free(s_in_path); s_in_path = path_new_dir(argv[i]); } else if (strcmp(argv[i], "--explode") == 0) { print_cell_quote(); return false; } else if (strcmp(argv[i], "--package") == 0) { if (++i >= argc) goto missing_argument; if (s_out_path != NULL) { printf("cell: too many outputs\n"); return false; } s_out_path = path_new(argv[i]); if (path_filename_cstr(s_out_path) == NULL) { printf("cell: `%s` argument cannot be a directory\n", argv[i - 1]); return false; } } else if (strcmp(argv[i], "--build") == 0) { if (++i >= argc) goto missing_argument; if (s_out_path != NULL) { printf("cell: too many outputs\n"); return false; } s_out_path = path_new_dir(argv[i]); } else if (strcmp(argv[i], "--debug") == 0) { s_want_source_map = true; } else { printf("cell: unknown option `%s`\n", argv[i]); return false; } } else if (argv[i][0] == '-') { short_args = argv[i]; for (i_arg = strlen(short_args) - 1; i_arg >= 1; --i_arg) { switch (short_args[i_arg]) { case 'b': if (++i >= argc) goto missing_argument; if (s_out_path != NULL) { printf("cell: too many outputs\n"); return false; } s_out_path = path_new_dir(argv[i]); break; case 'p': if (++i >= argc) goto missing_argument; if (s_out_path != NULL) { printf("cell: too many outputs\n"); return false; } s_out_path = path_new(argv[i]); if (path_filename_cstr(s_out_path) == NULL) { printf("cell: `%s` argument cannot be a directory\n", short_args); return false; } break; case 'd': s_want_source_map = true; break; default: printf("cell: unknown option `-%c`\n", short_args[i_arg]); return false; } } } else { free(s_target_name); s_target_name = strdup(argv[i]); } } // validate command line if (s_out_path == NULL) { print_usage(); return false; } // check if a Cellscript exists cellscript_path = path_rebase(path_new("Cellscript.js"), s_in_path); if (!path_resolve(cellscript_path, NULL)) { path_free(cellscript_path); printf("no Cellscript.js found in source directory\n"); return false; } path_free(cellscript_path); return true; missing_argument: printf("cell: `%s` requires an argument\n", argv[i - 1]); return false; } static void print_cell_quote(void) { // yes, these are entirely necessary. :o) static const char* const MESSAGES[] = { "This is the end for you!", "Very soon, I am going to explode. And when I do...", "Careful now! I wouldn't attack me if I were you...", "I'm quite volatile, and the slightest jolt could set me off!", "One minute left! There's nothing you can do now!", "If only you'd finished me off a little bit sooner...", "Ten more seconds, and the Earth will be gone!", "Let's just call our little match a draw, shall we?", "Watch out! You might make me explode!", }; printf("Cell seems to be going through some sort of transformation...\n"); printf("He's pumping himself up like a balloon!\n\n"); printf(" Cell says:\n \"%s\"\n", MESSAGES[rand() % (sizeof MESSAGES / sizeof(const char*))]); } static void print_banner(bool want_copyright, bool want_deps) { printf("Cell %s Sphere Packaging Compiler (%s)\n", VERSION_NAME, sizeof(void*) == 8 ? "x64" : "x86"); if (want_copyright) { printf("the programmable build engine for Sphere games\n"); printf("(c) 2015-2016 <NAME>\n"); } if (want_deps) { printf("\n"); printf(" Duktape: v%ld.%ld.%ld\n", DUK_VERSION / 10000, DUK_VERSION / 100 % 100, DUK_VERSION % 100); printf(" zlib: v%s\n", zlibVersion()); } } static void print_usage(void) { print_banner(true, false); printf("\n"); printf("USAGE:\n"); printf(" cell -b <out-dir> [options] [target]\n"); printf(" cell -p <out-file> [options] [target]\n"); printf("\n"); printf("OPTIONS:\n"); printf(" --in-dir Set the input directory. Without this option, Cell will \n"); printf(" look for sources in the current working directory. \n"); printf(" -b, --build Build an unpackaged Sphere game distribution. \n"); printf(" -p, --package Build a Sphere package (.spk). \n"); printf(" -d, --debug Include a debugging map in the compiled game which maps \n"); printf(" compiled assets to their corresponding source files. \n"); printf(" --version Print the version number of Cell and its dependencies. \n"); printf(" --help Print this help text. \n"); } <file_sep>/src/engine/font.c #include "minisphere.h" #include "api.h" #include "atlas.h" #include "color.h" #include "image.h" #include "unicode.h" #include "font.h" static duk_ret_t js_GetSystemFont (duk_context* ctx); static duk_ret_t js_LoadFont (duk_context* ctx); static duk_ret_t js_new_Font (duk_context* ctx); static duk_ret_t js_Font_finalize (duk_context* ctx); static duk_ret_t js_Font_toString (duk_context* ctx); static duk_ret_t js_Font_get_colorMask (duk_context* ctx); static duk_ret_t js_Font_set_colorMask (duk_context* ctx); static duk_ret_t js_Font_get_height (duk_context* ctx); static duk_ret_t js_Font_getCharacterImage (duk_context* ctx); static duk_ret_t js_Font_setCharacterImage (duk_context* ctx); static duk_ret_t js_Font_getStringHeight (duk_context* ctx); static duk_ret_t js_Font_getStringWidth (duk_context* ctx); static duk_ret_t js_Font_clone (duk_context* ctx); static duk_ret_t js_Font_drawText (duk_context* ctx); static duk_ret_t js_Font_drawTextBox (duk_context* ctx); static duk_ret_t js_Font_drawZoomedText (duk_context* ctx); static duk_ret_t js_Font_wordWrapString (duk_context* ctx); static void update_font_metrics (font_t* font); struct font { unsigned int refcount; unsigned int id; int height; int min_width; int max_width; uint32_t num_glyphs; struct font_glyph* glyphs; }; struct font_glyph { int width, height; image_t* image; }; struct wraptext { int num_lines; char* buffer; size_t pitch; }; #pragma pack(push, 1) struct rfn_header { char signature[4]; uint16_t version; uint16_t num_chars; char reserved[248]; }; struct rfn_glyph_header { uint16_t width; uint16_t height; char reserved[28]; }; #pragma pack(pop) static unsigned int s_next_font_id = 0; font_t* load_font(const char* filename) { image_t* atlas = NULL; int atlas_x, atlas_y; int atlas_size_x, atlas_size_y; sfs_file_t* file; font_t* font = NULL; struct font_glyph* glyph; struct rfn_glyph_header glyph_hdr; long glyph_start; uint8_t* grayscale; image_lock_t* lock = NULL; int max_x = 0, max_y = 0; int min_width = INT_MAX; int64_t n_glyphs_per_row; int pixel_size; struct rfn_header rfn; uint8_t *psrc; color_t *pdest; int i, x, y; console_log(2, "loading font #%u as `%s`", s_next_font_id, filename); memset(&rfn, 0, sizeof(struct rfn_header)); if ((file = sfs_fopen(g_fs, filename, NULL, "rb")) == NULL) goto on_error; if (!(font = calloc(1, sizeof(font_t)))) goto on_error; if (sfs_fread(&rfn, sizeof(struct rfn_header), 1, file) != 1) goto on_error; pixel_size = (rfn.version == 1) ? 1 : 4; if (!(font->glyphs = calloc(rfn.num_chars, sizeof(struct font_glyph)))) goto on_error; // pass 1: load glyph headers and find largest glyph glyph_start = sfs_ftell(file); for (i = 0; i < rfn.num_chars; ++i) { glyph = &font->glyphs[i]; if (sfs_fread(&glyph_hdr, sizeof(struct rfn_glyph_header), 1, file) != 1) goto on_error; sfs_fseek(file, glyph_hdr.width * glyph_hdr.height * pixel_size, SFS_SEEK_CUR); max_x = fmax(glyph_hdr.width, max_x); max_y = fmax(glyph_hdr.height, max_y); min_width = fmin(min_width, glyph_hdr.width); glyph->width = glyph_hdr.width; glyph->height = glyph_hdr.height; } font->num_glyphs = rfn.num_chars; font->min_width = min_width; font->max_width = max_x; font->height = max_y; // create glyph atlas n_glyphs_per_row = ceil(sqrt(rfn.num_chars)); atlas_size_x = max_x * n_glyphs_per_row; atlas_size_y = max_y * n_glyphs_per_row; if ((atlas = create_image(atlas_size_x, atlas_size_y)) == NULL) goto on_error; // pass 2: load glyph data sfs_fseek(file, glyph_start, SFS_SEEK_SET); if (!(lock = lock_image(atlas))) goto on_error; for (i = 0; i < rfn.num_chars; ++i) { glyph = &font->glyphs[i]; if (sfs_fread(&glyph_hdr, sizeof(struct rfn_glyph_header), 1, file) != 1) goto on_error; atlas_x = i % n_glyphs_per_row * max_x; atlas_y = i / n_glyphs_per_row * max_y; switch (rfn.version) { case 1: // RFN v1: 8-bit grayscale glyphs if (!(glyph->image = create_subimage(atlas, atlas_x, atlas_y, glyph_hdr.width, glyph_hdr.height))) goto on_error; grayscale = malloc(glyph_hdr.width * glyph_hdr.height); if (sfs_fread(grayscale, glyph_hdr.width * glyph_hdr.height, 1, file) != 1) goto on_error; psrc = grayscale; pdest = lock->pixels + atlas_x + atlas_y * lock->pitch; for (y = 0; y < glyph_hdr.height; ++y) { for (x = 0; x < glyph_hdr.width; ++x) pdest[x] = color_new(psrc[x], psrc[x], psrc[x], 255); pdest += lock->pitch; psrc += glyph_hdr.width; } break; case 2: // RFN v2: 32-bit truecolor glyphs if (!(glyph->image = read_subimage(file, atlas, atlas_x, atlas_y, glyph_hdr.width, glyph_hdr.height))) goto on_error; break; } } unlock_image(atlas, lock); sfs_fclose(file); free_image(atlas); font->id = s_next_font_id++; return ref_font(font); on_error: console_log(2, "failed to load font #%u", s_next_font_id++); sfs_fclose(file); if (font != NULL) { for (i = 0; i < rfn.num_chars; ++i) { if (font->glyphs[i].image != NULL) free_image(font->glyphs[i].image); } free(font->glyphs); free(font); } if (lock != NULL) unlock_image(atlas, lock); if (atlas != NULL) free_image(atlas); return NULL; } font_t* clone_font(const font_t* src_font) { font_t* font = NULL; int max_x = 0, max_y = 0; int min_width = INT_MAX; const struct font_glyph* src_glyph; uint32_t i; console_log(2, "cloning font #%u from source font #%u", s_next_font_id, src_font->id); if (!(font = calloc(1, sizeof(font_t)))) goto on_error; if (!(font->glyphs = calloc(src_font->num_glyphs, sizeof(struct font_glyph)))) goto on_error; font->num_glyphs = src_font->num_glyphs; // perform the clone get_font_metrics(src_font, &min_width, &max_x, &max_y); font->height = max_y; font->min_width = min_width; font->max_width = max_x; for (i = 0; i < src_font->num_glyphs; ++i) { src_glyph = &src_font->glyphs[i]; font->glyphs[i].image = ref_image(src_glyph->image); font->glyphs[i].width = src_glyph->width; font->glyphs[i].height = src_glyph->height; } font->id = s_next_font_id++; return ref_font(font); on_error: if (font != NULL) { for (i = 0; i < font->num_glyphs; ++i) { if (font->glyphs[i].image != NULL) free_image(font->glyphs[i].image); } free(font->glyphs); free(font); } return NULL; } font_t* ref_font(font_t* font) { ++font->refcount; return font; } void free_font(font_t* font) { uint32_t i; if (font == NULL || --font->refcount > 0) return; console_log(3, "disposing font #%u no longer in use", font->id); for (i = 0; i < font->num_glyphs; ++i) { free_image(font->glyphs[i].image); } free(font->glyphs); free(font); } int get_font_line_height(const font_t* font) { return font->height; } void get_font_metrics(const font_t* font, int* out_min_width, int* out_max_width, int* out_line_height) { if (out_min_width) *out_min_width = font->min_width; if (out_max_width) *out_max_width = font->max_width; if (out_line_height) *out_line_height = font->height; } image_t* get_glyph_image(const font_t* font, int codepoint) { return font->glyphs[codepoint].image; } int get_glyph_width(const font_t* font, int codepoint) { return font->glyphs[codepoint].width; } int get_text_width(const font_t* font, const char* text) { uint8_t ch_byte; uint32_t cp; uint32_t utf8state; int width = 0; for (;;) { utf8state = UTF8_ACCEPT; while (utf8decode(&utf8state, &cp, ch_byte = *text++) > UTF8_REJECT); if (utf8state == UTF8_REJECT && ch_byte == '\0') --text; // don't eat NUL terminator cp = cp == 0x20AC ? 128 : cp == 0x201A ? 130 : cp == 0x0192 ? 131 : cp == 0x201E ? 132 : cp == 0x2026 ? 133 : cp == 0x2020 ? 134 : cp == 0x2021 ? 135 : cp == 0x02C6 ? 136 : cp == 0x2030 ? 137 : cp == 0x0160 ? 138 : cp == 0x2039 ? 139 : cp == 0x0152 ? 140 : cp == 0x017D ? 142 : cp == 0x2018 ? 145 : cp == 0x2019 ? 146 : cp == 0x201C ? 147 : cp == 0x201D ? 148 : cp == 0x2022 ? 149 : cp == 0x2013 ? 150 : cp == 0x2014 ? 151 : cp == 0x02DC ? 152 : cp == 0x2122 ? 153 : cp == 0x0161 ? 154 : cp == 0x203A ? 155 : cp == 0x0153 ? 156 : cp == 0x017E ? 158 : cp == 0x0178 ? 159 : cp; cp = utf8state == UTF8_ACCEPT ? cp < (uint32_t)font->num_glyphs ? cp : 0x1A : 0x1A; if (cp == '\0') break; width += font->glyphs[cp].width; } return width; } void set_glyph_image(font_t* font, int codepoint, image_t* image) { image_t* old_image; struct font_glyph* p_glyph; p_glyph = &font->glyphs[codepoint]; old_image = p_glyph->image; p_glyph->image = ref_image(image); p_glyph->width = get_image_width(image); p_glyph->height = get_image_height(image); update_font_metrics(font); free_image(old_image); } void draw_text(const font_t* font, color_t color, int x, int y, text_align_t alignment, const char* text) { uint8_t ch_byte; uint32_t cp; int tab_width; uint32_t utf8state; if (alignment == TEXT_ALIGN_CENTER) x -= get_text_width(font, text) / 2; else if (alignment == TEXT_ALIGN_RIGHT) x -= get_text_width(font, text); tab_width = font->glyphs[' '].width * 3; al_hold_bitmap_drawing(true); for (;;) { utf8state = UTF8_ACCEPT; while (utf8decode(&utf8state, &cp, ch_byte = *text++) > UTF8_REJECT); if (utf8state == UTF8_REJECT && ch_byte == '\0') --text; // don't eat NUL terminator cp = cp == 0x20AC ? 128 : cp == 0x201A ? 130 : cp == 0x0192 ? 131 : cp == 0x201E ? 132 : cp == 0x2026 ? 133 : cp == 0x2020 ? 134 : cp == 0x2021 ? 135 : cp == 0x02C6 ? 136 : cp == 0x2030 ? 137 : cp == 0x0160 ? 138 : cp == 0x2039 ? 139 : cp == 0x0152 ? 140 : cp == 0x017D ? 142 : cp == 0x2018 ? 145 : cp == 0x2019 ? 146 : cp == 0x201C ? 147 : cp == 0x201D ? 148 : cp == 0x2022 ? 149 : cp == 0x2013 ? 150 : cp == 0x2014 ? 151 : cp == 0x02DC ? 152 : cp == 0x2122 ? 153 : cp == 0x0161 ? 154 : cp == 0x203A ? 155 : cp == 0x0153 ? 156 : cp == 0x017E ? 158 : cp == 0x0178 ? 159 : cp; cp = utf8state == UTF8_ACCEPT ? cp < (uint32_t)font->num_glyphs ? cp : 0x1A : 0x1A; if (cp == '\0') break; else if (cp == '\t') x += tab_width; else { draw_image_masked(font->glyphs[cp].image, color, x, y); x += font->glyphs[cp].width; } } al_hold_bitmap_drawing(false); } wraptext_t* word_wrap_text(const font_t* font, const char* text, int width) { char* buffer = NULL; uint8_t ch_byte; char* carry; size_t ch_size; uint32_t cp; int glyph_width; bool is_line_end = false; int line_idx; int line_width; int max_lines = 10; char* last_break; char* last_space; char* last_tab; char* line_buffer; size_t line_length; char* new_buffer; size_t pitch; uint32_t utf8state; wraptext_t* wraptext; const char *p, *start; if (!(wraptext = calloc(1, sizeof(wraptext_t)))) goto on_error; // allocate initial buffer get_font_metrics(font, &glyph_width, NULL, NULL); pitch = 4 * (glyph_width > 0 ? width / glyph_width : width) + 3; if (!(buffer = malloc(max_lines * pitch))) goto on_error; if (!(carry = malloc(pitch))) goto on_error; // run through one character at a time, carrying as necessary line_buffer = buffer; line_buffer[0] = '\0'; line_idx = 0; line_width = 0; line_length = 0; memset(line_buffer, 0, pitch); // fill line with NULs p = text; do { utf8state = UTF8_ACCEPT; start = p; while (utf8decode(&utf8state, &cp, ch_byte = *p++) > UTF8_REJECT); if (utf8state == UTF8_REJECT && ch_byte == '\0') --p; // don't eat NUL terminator ch_size = p - start; cp = cp == 0x20AC ? 128 : cp == 0x201A ? 130 : cp == 0x0192 ? 131 : cp == 0x201E ? 132 : cp == 0x2026 ? 133 : cp == 0x2020 ? 134 : cp == 0x2021 ? 135 : cp == 0x02C6 ? 136 : cp == 0x2030 ? 137 : cp == 0x0160 ? 138 : cp == 0x2039 ? 139 : cp == 0x0152 ? 140 : cp == 0x017D ? 142 : cp == 0x2018 ? 145 : cp == 0x2019 ? 146 : cp == 0x201C ? 147 : cp == 0x201D ? 148 : cp == 0x2022 ? 149 : cp == 0x2013 ? 150 : cp == 0x2014 ? 151 : cp == 0x02DC ? 152 : cp == 0x2122 ? 153 : cp == 0x0161 ? 154 : cp == 0x203A ? 155 : cp == 0x0153 ? 156 : cp == 0x017E ? 158 : cp == 0x0178 ? 159 : cp; cp = utf8state == UTF8_ACCEPT ? cp < (uint32_t)font->num_glyphs ? cp : 0x1A : 0x1A; switch (cp) { case '\n': case '\r': // explicit newline if (cp == '\r' && *p == '\n') ++text; // CRLF is_line_end = true; break; case '\t': // tab line_buffer[line_length++] = cp; line_width += get_text_width(font, " "); is_line_end = false; break; case '\0': // NUL terminator is_line_end = line_length > 0; // commit last line on EOT break; default: // default case, copy character as-is memcpy(line_buffer + line_length, start, ch_size); line_length += ch_size; line_width += get_glyph_width(font, cp); is_line_end = false; } if (is_line_end) carry[0] = '\0'; if (line_width > width || line_length >= pitch - 1) { // wrap width exceeded, carry current word to next line is_line_end = true; last_space = strrchr(line_buffer, ' '); last_tab = strrchr(line_buffer, '\t'); last_break = last_space > last_tab ? last_space : last_tab; if (last_break != NULL) // word break (space or tab) found strcpy(carry, last_break + 1); else // no word break, so just carry last character sprintf(carry, "%c", line_buffer[line_length - 1]); line_buffer[line_length - strlen(carry)] = '\0'; } if (is_line_end) { // do we need to enlarge the buffer? if (++line_idx >= max_lines) { max_lines *= 2; if (!(new_buffer = realloc(buffer, max_lines * pitch))) goto on_error; buffer = new_buffer; line_buffer = buffer + line_idx * pitch; } else line_buffer += pitch; memset(line_buffer, 0, pitch); // fill line with NULs // copy carry text into new line line_width = get_text_width(font, carry); line_length = strlen(carry); strcpy(line_buffer, carry); } } while (cp != '\0'); free(carry); wraptext->num_lines = line_idx; wraptext->buffer = buffer; wraptext->pitch = pitch; return wraptext; on_error: free(buffer); free(wraptext); return NULL; } void free_wraptext(wraptext_t* wraptext) { free(wraptext->buffer); free(wraptext); } const char* get_wraptext_line(const wraptext_t* wraptext, int line_index) { return wraptext->buffer + line_index * wraptext->pitch; } int get_wraptext_line_count(const wraptext_t* wraptext) { return wraptext->num_lines; } static void update_font_metrics(font_t* font) { int max_x = 0, max_y = 0; int min_width = INT_MAX; uint32_t i; for (i = 0; i < font->num_glyphs; ++i) { font->glyphs[i].width = get_image_width(font->glyphs[i].image); font->glyphs[i].height = get_image_height(font->glyphs[i].image); min_width = fmin(font->glyphs[i].width, min_width); max_x = fmax(font->glyphs[i].width, max_x); max_y = fmax(font->glyphs[i].height, max_y); } font->min_width = min_width; font->max_width = max_x; font->height = max_y; } void init_font_api(duk_context* ctx) { // Font API functions api_register_method(ctx, NULL, "GetSystemFont", js_GetSystemFont); // Font object api_register_method(ctx, NULL, "LoadFont", js_LoadFont); api_register_ctor(ctx, "Font", js_new_Font, js_Font_finalize); api_register_prop(ctx, "Font", "colorMask", js_Font_get_colorMask, js_Font_set_colorMask); api_register_prop(ctx, "Font", "height", js_Font_get_height, NULL); api_register_method(ctx, "Font", "getCharacterImage", js_Font_getCharacterImage); api_register_method(ctx, "Font", "getColorMask", js_Font_get_colorMask); api_register_method(ctx, "Font", "getHeight", js_Font_get_height); api_register_method(ctx, "Font", "getStringHeight", js_Font_getStringHeight); api_register_method(ctx, "Font", "getStringWidth", js_Font_getStringWidth); api_register_method(ctx, "Font", "setCharacterImage", js_Font_setCharacterImage); api_register_method(ctx, "Font", "setColorMask", js_Font_set_colorMask); api_register_method(ctx, "Font", "toString", js_Font_toString); api_register_method(ctx, "Font", "clone", js_Font_clone); api_register_method(ctx, "Font", "drawText", js_Font_drawText); api_register_method(ctx, "Font", "drawTextBox", js_Font_drawTextBox); api_register_method(ctx, "Font", "drawZoomedText", js_Font_drawZoomedText); api_register_method(ctx, "Font", "wordWrapString", js_Font_wordWrapString); } void duk_push_sphere_font(duk_context* ctx, font_t* font) { duk_push_sphere_obj(ctx, "Font", ref_font(font)); duk_push_sphere_color(ctx, color_new(255, 255, 255, 255)); duk_put_prop_string(ctx, -2, "\xFF" "color_mask"); } static duk_ret_t js_GetSystemFont(duk_context* ctx) { duk_push_sphere_font(ctx, g_sys_font); return 1; } static duk_ret_t js_LoadFont(duk_context* ctx) { const char* filename; font_t* font; filename = duk_require_path(ctx, 0, "fonts", true); font = load_font(filename); if (font == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "LoadFont(): unable to load font file `%s`", filename); duk_push_sphere_font(ctx, font); free_font(font); return 1; } static duk_ret_t js_new_Font(duk_context* ctx) { const char* filename; font_t* font; filename = duk_require_path(ctx, 0, NULL, false); font = load_font(filename); if (font == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Font(): unable to load font file `%s`", filename); duk_push_sphere_font(ctx, font); free_font(font); return 1; } static duk_ret_t js_Font_finalize(duk_context* ctx) { font_t* font; font = duk_require_sphere_obj(ctx, 0, "Font"); free_font(font); return 0; } static duk_ret_t js_Font_toString(duk_context* ctx) { duk_push_string(ctx, "[object font]"); return 1; } static duk_ret_t js_Font_getCharacterImage(duk_context* ctx) { int cp = duk_require_int(ctx, 0); font_t* font; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_pop(ctx); duk_push_sphere_image(ctx, get_glyph_image(font, cp)); return 1; } static duk_ret_t js_Font_get_colorMask(duk_context* ctx) { duk_push_this(ctx); duk_get_prop_string(ctx, -1, "\xFF" "color_mask"); duk_remove(ctx, -2); return 1; } static duk_ret_t js_Font_set_colorMask(duk_context* ctx) { font_t* font; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_dup(ctx, 0); duk_put_prop_string(ctx, -2, "\xFF" "color_mask"); duk_pop(ctx); duk_pop(ctx); return 0; } static duk_ret_t js_Font_get_height(duk_context* ctx) { font_t* font; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_pop(ctx); duk_push_int(ctx, get_font_line_height(font)); return 1; } static duk_ret_t js_Font_setCharacterImage(duk_context* ctx) { int cp = duk_require_int(ctx, 0); image_t* image = duk_require_sphere_image(ctx, 1); font_t* font; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_pop(ctx); set_glyph_image(font, cp, image); return 0; } static duk_ret_t js_Font_clone(duk_context* ctx) { font_t* dolly_font; font_t* font; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_pop(ctx); if (!(dolly_font = clone_font(font))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Font:clone(): unable to clone font"); duk_push_sphere_font(ctx, dolly_font); return 1; } static duk_ret_t js_Font_drawText(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); const char* text = duk_to_string(ctx, 2); font_t* font; color_t mask; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_get_prop_string(ctx, -1, "\xFF" "color_mask"); mask = duk_require_sphere_color(ctx, -1); duk_pop(ctx); duk_pop(ctx); if (!screen_is_skipframe(g_screen)) draw_text(font, mask, x, y, TEXT_ALIGN_LEFT, text); return 0; } static duk_ret_t js_Font_drawZoomedText(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); float scale = duk_require_number(ctx, 2); const char* text = duk_to_string(ctx, 3); ALLEGRO_BITMAP* bitmap; font_t* font; color_t mask; int text_w, text_h; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_get_prop_string(ctx, -1, "\xFF" "color_mask"); mask = duk_require_sphere_color(ctx, -1); duk_pop(ctx); duk_pop(ctx); if (!screen_is_skipframe(g_screen)) { text_w = get_text_width(font, text); text_h = get_font_line_height(font); bitmap = al_create_bitmap(text_w, text_h); al_set_target_bitmap(bitmap); draw_text(font, mask, 0, 0, TEXT_ALIGN_LEFT, text); al_set_target_backbuffer(screen_display(g_screen)); al_draw_scaled_bitmap(bitmap, 0, 0, text_w, text_h, x, y, text_w * scale, text_h * scale, 0x0); al_destroy_bitmap(bitmap); } return 0; } static duk_ret_t js_Font_drawTextBox(duk_context* ctx) { int x = duk_require_int(ctx, 0); int y = duk_require_int(ctx, 1); int w = duk_require_int(ctx, 2); int h = duk_require_int(ctx, 3); int offset = duk_require_int(ctx, 4); const char* text = duk_to_string(ctx, 5); font_t* font; int line_height; const char* line_text; color_t mask; int num_lines; int i; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_get_prop_string(ctx, -1, "\xFF" "color_mask"); mask = duk_require_sphere_color(ctx, -1); duk_pop(ctx); duk_pop(ctx); if (!screen_is_skipframe(g_screen)) { duk_push_c_function(ctx, js_Font_wordWrapString, DUK_VARARGS); duk_push_this(ctx); duk_push_string(ctx, text); duk_push_int(ctx, w); duk_call_method(ctx, 2); duk_get_prop_string(ctx, -1, "length"); num_lines = duk_get_int(ctx, -1); duk_pop(ctx); line_height = get_font_line_height(font); for (i = 0; i < num_lines; ++i) { duk_get_prop_index(ctx, -1, i); line_text = duk_get_string(ctx, -1); duk_pop(ctx); draw_text(font, mask, x + offset, y, TEXT_ALIGN_LEFT, line_text); y += line_height; } duk_pop(ctx); } return 0; } static duk_ret_t js_Font_getStringHeight(duk_context* ctx) { const char* text = duk_to_string(ctx, 0); int width = duk_require_int(ctx, 1); font_t* font; int num_lines; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_pop(ctx); duk_push_c_function(ctx, js_Font_wordWrapString, DUK_VARARGS); duk_push_this(ctx); duk_push_string(ctx, text); duk_push_int(ctx, width); duk_call_method(ctx, 2); duk_get_prop_string(ctx, -1, "length"); num_lines = duk_get_int(ctx, -1); duk_pop(ctx); duk_pop(ctx); duk_push_int(ctx, get_font_line_height(font) * num_lines); return 1; } static duk_ret_t js_Font_getStringWidth(duk_context* ctx) { const char* text = duk_to_string(ctx, 0); font_t* font; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_pop(ctx); duk_push_int(ctx, get_text_width(font, text)); return 1; } static duk_ret_t js_Font_wordWrapString(duk_context* ctx) { const char* text = duk_to_string(ctx, 0); int width = duk_require_int(ctx, 1); font_t* font; int num_lines; wraptext_t* wraptext; int i; duk_push_this(ctx); font = duk_require_sphere_obj(ctx, -1, "Font"); duk_pop(ctx); wraptext = word_wrap_text(font, text, width); num_lines = get_wraptext_line_count(wraptext); duk_push_array(ctx); for (i = 0; i < num_lines; ++i) { duk_push_string(ctx, get_wraptext_line(wraptext, i)); duk_put_prop_index(ctx, -2, i); } free_wraptext(wraptext); return 1; } <file_sep>/src/engine/persons.c #include "minisphere.h" #include "api.h" #include "color.h" #include "map_engine.h" #include "obsmap.h" #include "spriteset.h" #include "persons.h" struct person { unsigned int id; char* name; int anim_frames; char* direction; int follow_distance; int frame; bool ignore_all_persons; bool ignore_all_tiles; bool is_persistent; bool is_visible; int layer; person_t* leader; color_t mask; int mv_x, mv_y; int revert_delay; int revert_frames; double scale_x; double scale_y; script_t* scripts[PERSON_SCRIPT_MAX]; double speed_x, speed_y; spriteset_t* sprite; double theta; double x, y; int x_offset, y_offset; int max_commands; int max_history; int num_commands; int num_ignores; struct command *commands; char* *ignores; struct step *steps; }; struct step { double x, y; }; struct command { int type; bool is_immediate; script_t* script; }; static duk_ret_t js_CreatePerson (duk_context* ctx); static duk_ret_t js_DestroyPerson (duk_context* ctx); static duk_ret_t js_IsCommandQueueEmpty (duk_context* ctx); static duk_ret_t js_IsIgnoringPersonObstructions (duk_context* ctx); static duk_ret_t js_IsIgnoringTileObstructions (duk_context* ctx); static duk_ret_t js_IsPersonObstructed (duk_context* ctx); static duk_ret_t js_IsPersonVisible (duk_context* ctx); static duk_ret_t js_DoesPersonExist (duk_context* ctx); static duk_ret_t js_GetActingPerson (duk_context* ctx); static duk_ret_t js_GetCurrentPerson (duk_context* ctx); static duk_ret_t js_GetObstructingPerson (duk_context* ctx); static duk_ret_t js_GetObstructingTile (duk_context* ctx); static duk_ret_t js_GetPersonAngle (duk_context* ctx); static duk_ret_t js_GetPersonBase (duk_context* ctx); static duk_ret_t js_GetPersonData (duk_context* ctx); static duk_ret_t js_GetPersonDirection (duk_context* ctx); static duk_ret_t js_GetPersonFollowDistance (duk_context* ctx); static duk_ret_t js_GetPersonFollowers (duk_context* ctx); static duk_ret_t js_GetPersonFrame (duk_context* ctx); static duk_ret_t js_GetPersonFrameNext (duk_context* ctx); static duk_ret_t js_GetPersonFrameRevert (duk_context* ctx); static duk_ret_t js_GetPersonIgnoreList (duk_context* ctx); static duk_ret_t js_GetPersonLayer (duk_context* ctx); static duk_ret_t js_GetPersonLeader (duk_context* ctx); static duk_ret_t js_GetPersonList (duk_context* ctx); static duk_ret_t js_GetPersonMask (duk_context* ctx); static duk_ret_t js_GetPersonOffsetX (duk_context* ctx); static duk_ret_t js_GetPersonOffsetY (duk_context* ctx); static duk_ret_t js_GetPersonSpeedX (duk_context* ctx); static duk_ret_t js_GetPersonSpeedY (duk_context* ctx); static duk_ret_t js_GetPersonSpriteset (duk_context* ctx); static duk_ret_t js_GetPersonValue (duk_context* ctx); static duk_ret_t js_GetPersonX (duk_context* ctx); static duk_ret_t js_GetPersonY (duk_context* ctx); static duk_ret_t js_GetPersonXFloat (duk_context* ctx); static duk_ret_t js_GetPersonYFloat (duk_context* ctx); static duk_ret_t js_GetTalkDistance (duk_context* ctx); static duk_ret_t js_SetDefaultPersonScript (duk_context* ctx); static duk_ret_t js_SetPersonAngle (duk_context* ctx); static duk_ret_t js_SetPersonData (duk_context* ctx); static duk_ret_t js_SetPersonDirection (duk_context* ctx); static duk_ret_t js_SetPersonFollowDistance (duk_context* ctx); static duk_ret_t js_SetPersonFrame (duk_context* ctx); static duk_ret_t js_SetPersonFrameNext (duk_context* ctx); static duk_ret_t js_SetPersonFrameRevert (duk_context* ctx); static duk_ret_t js_SetPersonIgnoreList (duk_context* ctx); static duk_ret_t js_SetPersonLayer (duk_context* ctx); static duk_ret_t js_SetPersonMask (duk_context* ctx); static duk_ret_t js_SetPersonOffsetX (duk_context* ctx); static duk_ret_t js_SetPersonOffsetY (duk_context* ctx); static duk_ret_t js_SetPersonScaleAbsolute (duk_context* ctx); static duk_ret_t js_SetPersonScaleFactor (duk_context* ctx); static duk_ret_t js_SetPersonScript (duk_context* ctx); static duk_ret_t js_SetPersonSpeed (duk_context* ctx); static duk_ret_t js_SetPersonSpeedXY (duk_context* ctx); static duk_ret_t js_SetPersonSpriteset (duk_context* ctx); static duk_ret_t js_SetPersonValue (duk_context* ctx); static duk_ret_t js_SetPersonVisible (duk_context* ctx); static duk_ret_t js_SetPersonX (duk_context* ctx); static duk_ret_t js_SetPersonXYFloat (duk_context* ctx); static duk_ret_t js_SetPersonY (duk_context* ctx); static duk_ret_t js_SetTalkDistance (duk_context* ctx); static duk_ret_t js_CallDefaultPersonScript (duk_context* ctx); static duk_ret_t js_CallPersonScript (duk_context* ctx); static duk_ret_t js_ClearPersonCommands (duk_context* ctx); static duk_ret_t js_FollowPerson (duk_context* ctx); static duk_ret_t js_IgnorePersonObstructions (duk_context* ctx); static duk_ret_t js_IgnoreTileObstructions (duk_context* ctx); static duk_ret_t js_QueuePersonCommand (duk_context* ctx); static duk_ret_t js_QueuePersonScript (duk_context* ctx); static bool does_person_exist (const person_t* person); static void set_person_direction (person_t* person, const char* direction); static void set_person_name (person_t* person, const char* name); static void command_person (person_t* person, int command); static int compare_persons (const void* a, const void* b); static bool enlarge_step_history (person_t* person, int new_size); static bool follow_person (person_t* person, person_t* leader, int distance); static void free_person (person_t* person); static void record_step (person_t* person); static void sort_persons (void); static void update_person (person_t* person, bool* out_has_moved); static const person_t* s_acting_person; static const person_t* s_current_person = NULL; static script_t* s_def_scripts[PERSON_SCRIPT_MAX]; static int s_talk_distance = 8; static int s_max_persons = 0; static unsigned int s_next_person_id = 0; static int s_num_persons = 0; static unsigned int s_queued_id = 0; static person_t* *s_persons = NULL; void initialize_persons_manager(void) { console_log(1, "initializing persons manager"); memset(s_def_scripts, 0, PERSON_SCRIPT_MAX * sizeof(int)); s_num_persons = s_max_persons = 0; s_persons = NULL; s_talk_distance = 8; s_acting_person = NULL; s_current_person = NULL; } void shutdown_persons_manager(void) { int i; console_log(1, "shutting down persons manager"); for (i = 0; i < s_num_persons; ++i) free_person(s_persons[i]); for (i = 0; i < PERSON_SCRIPT_MAX; ++i) free_script(s_def_scripts[i]); free(s_persons); } person_t* create_person(const char* name, spriteset_t* spriteset, bool is_persistent, script_t* create_script) { point3_t map_origin = get_map_origin(); person_t* person; if (++s_num_persons > s_max_persons) { s_max_persons = s_num_persons * 2; s_persons = realloc(s_persons, s_max_persons * sizeof(person_t*)); } person = s_persons[s_num_persons - 1] = calloc(1, sizeof(person_t)); person->id = s_next_person_id++; person->sprite = ref_spriteset(spriteset); set_person_name(person, name); set_person_direction(person, lstr_cstr(person->sprite->poses[0].name)); person->is_persistent = is_persistent; person->is_visible = true; person->x = map_origin.x; person->y = map_origin.y; person->layer = map_origin.z; person->speed_x = 1.0; person->speed_y = 1.0; person->anim_frames = get_sprite_frame_delay(person->sprite, person->direction, 0); person->mask = color_new(255, 255, 255, 255); person->scale_x = person->scale_y = 1.0; person->scripts[PERSON_SCRIPT_ON_CREATE] = create_script; call_person_script(person, PERSON_SCRIPT_ON_CREATE, true); sort_persons(); return person; } void destroy_person(person_t* person) { int i, j; // call the person's destroy script *before* renouncing leadership. // the destroy script may want to reassign followers (they will be orphaned otherwise), so // we want to give it a chance to do so. call_person_script(person, PERSON_SCRIPT_ON_DESTROY, true); for (i = 0; i < s_num_persons; ++i) { if (s_persons[i]->leader == person) s_persons[i]->leader = NULL; } // remove the person from the engine detach_person(person); for (i = 0; i < s_num_persons; ++i) { if (s_persons[i] == person) { for (j = i; j < s_num_persons - 1; ++j) s_persons[j] = s_persons[j + 1]; --s_num_persons; --i; } } free_person(person); sort_persons(); } bool has_person_moved(const person_t* person) { return person->mv_x != 0 || person->mv_y != 0; } bool is_person_busy(const person_t* person) { return person->num_commands > 0 || person->leader != NULL; } bool is_person_following(const person_t* person, const person_t* leader) { const person_t* node; node = person; while (node = node->leader) if (node == leader) return true; return false; } bool is_person_ignored(const person_t* person, const person_t* by_person) { // note: commutative; if either person ignores the other, the function will return true int i; if (by_person->ignore_all_persons || person->ignore_all_persons) return true; for (i = 0; i < by_person->num_ignores; ++i) if (strcmp(by_person->ignores[i], person->name) == 0) return true; for (i = 0; i < person->num_ignores; ++i) if (strcmp(person->ignores[i], by_person->name) == 0) return true; return false; } bool is_person_obstructed_at(const person_t* person, double x, double y, person_t** out_obstructing_person, int* out_tile_index) { rect_t area; rect_t base, my_base; double cur_x, cur_y; bool is_obstructed = false; int layer; const obsmap_t* obsmap; int tile_w, tile_h; const tileset_t* tileset; int i, i_x, i_y; normalize_map_entity_xy(&x, &y, person->layer); get_person_xyz(person, &cur_x, &cur_y, &layer, true); my_base = translate_rect(get_person_base(person), x - cur_x, y - cur_y); if (out_obstructing_person) *out_obstructing_person = NULL; if (out_tile_index) *out_tile_index = -1; // check for obstructing persons if (!person->ignore_all_persons) { for (i = 0; i < s_num_persons; ++i) { if (s_persons[i] == person) // these persons aren't going to obstruct themselves! continue; if (s_persons[i]->layer != layer) continue; // ignore persons not on the same layer if (is_person_following(s_persons[i], person)) continue; // ignore own followers base = get_person_base(s_persons[i]); if (do_rects_intersect(my_base, base) && !is_person_ignored(person, s_persons[i])) { is_obstructed = true; if (out_obstructing_person) *out_obstructing_person = s_persons[i]; break; } } } // no obstructing person, check map-defined obstructions obsmap = get_map_layer_obsmap(layer); if (obsmap_test_rect(obsmap, my_base)) is_obstructed = true; // check for obstructing tiles // for performance reasons, the search is constrained to the immediate vicinity // of the person's sprite base. if (!person->ignore_all_tiles) { tileset = get_map_tileset(); tileset_get_size(tileset, &tile_w, &tile_h); area.x1 = my_base.x1 / tile_w; area.y1 = my_base.y1 / tile_h; area.x2 = area.x1 + (my_base.x2 - my_base.x1) / tile_w + 2; area.y2 = area.y1 + (my_base.y2 - my_base.y1) / tile_h + 2; for (i_x = area.x1; i_x < area.x2; ++i_x) for (i_y = area.y1; i_y < area.y2; ++i_y) { base = translate_rect(my_base, -(i_x * tile_w), -(i_y * tile_h)); obsmap = tileset_obsmap(tileset, get_map_tile(i_x, i_y, layer)); if (obsmap != NULL && obsmap_test_rect(obsmap, base)) { is_obstructed = true; if (out_tile_index) *out_tile_index = get_map_tile(i_x, i_y, layer); break; } } } return is_obstructed; } double get_person_angle(const person_t* person) { return person->theta; } rect_t get_person_base(const person_t* person) { rect_t base_rect; int base_x, base_y; double x, y; base_rect = zoom_rect(person->sprite->base, person->scale_x, person->scale_y); get_person_xy(person, &x, &y, true); base_x = x - (base_rect.x1 + (base_rect.x2 - base_rect.x1) / 2); base_y = y - (base_rect.y1 + (base_rect.y2 - base_rect.y1) / 2); base_rect.x1 += base_x; base_rect.x2 += base_x; base_rect.y1 += base_y; base_rect.y2 += base_y; return base_rect; } color_t get_person_mask(const person_t* person) { return person->mask; } const char* get_person_name(const person_t* person) { return person->name; } void get_person_scale(const person_t* person, double* out_scale_x, double* out_scale_y) { *out_scale_x = person->scale_x; *out_scale_y = person->scale_y; } void get_person_speed(const person_t* person, double* out_x_speed, double* out_y_speed) { if (out_x_speed) *out_x_speed = person->speed_x; if (out_y_speed) *out_y_speed = person->speed_y; } spriteset_t* get_person_spriteset(person_t* person) { return person->sprite; } void get_person_xy(const person_t* person, double* out_x, double* out_y, bool want_normalize) { *out_x = person->x; *out_y = person->y; if (want_normalize) normalize_map_entity_xy(out_x, out_y, person->layer); } void get_person_xyz(const person_t* person, double* out_x, double* out_y, int* out_layer, bool want_normalize) { *out_x = person->x; *out_y = person->y; *out_layer = person->layer; if (want_normalize) normalize_map_entity_xy(out_x, out_y, *out_layer); } void set_person_angle(person_t* person, double theta) { person->theta = theta; } void set_person_mask(person_t* person, color_t mask) { person->mask = mask; } void set_person_scale(person_t* person, double scale_x, double scale_y) { person->scale_x = scale_x; person->scale_y = scale_y; } void set_person_script(person_t* person, int type, script_t* script) { free_script(person->scripts[type]); person->scripts[type] = script; } void set_person_speed(person_t* person, double x_speed, double y_speed) { person->speed_x = x_speed; person->speed_y = y_speed; } void set_person_spriteset(person_t* person, spriteset_t* spriteset) { spriteset_t* old_spriteset; old_spriteset = person->sprite; person->sprite = ref_spriteset(spriteset); person->anim_frames = get_sprite_frame_delay(person->sprite, person->direction, 0); person->frame = 0; free_spriteset(old_spriteset); } void set_person_xyz(person_t* person, double x, double y, int layer) { person->x = x; person->y = y; person->layer = layer; sort_persons(); } bool call_person_script(const person_t* person, int type, bool use_default) { const person_t* last_person; last_person = s_current_person; s_current_person = person; if (use_default) run_script(s_def_scripts[type], false); if (does_person_exist(person)) run_script(person->scripts[type], false); s_current_person = last_person; return true; } bool compile_person_script(person_t* person, int type, const lstring_t* codestring) { const char* person_name; script_t* script; const char* script_name; person_name = get_person_name(person); script_name = type == PERSON_SCRIPT_ON_CREATE ? "onCreate" : type == PERSON_SCRIPT_ON_DESTROY ? "onDestroy" : type == PERSON_SCRIPT_ON_TOUCH ? "onTouch" : type == PERSON_SCRIPT_ON_TALK ? "onTalk" : type == PERSON_SCRIPT_GENERATOR ? "genCommands" : NULL; if (script_name == NULL) return false; script = compile_script(codestring, "%s/%s/%s.js", get_map_name(), person_name, script_name); set_person_script(person, type, script); return true; } person_t* find_person(const char* name) { int i; for (i = 0; i < s_num_persons; ++i) { if (strcmp(name, s_persons[i]->name) == 0) return s_persons[i]; } return NULL; } bool follow_person(person_t* person, person_t* leader, int distance) { const person_t* node; // prevent circular follower chains from forming if (leader != NULL) { node = leader; do if (node == person) return false; while (node = node->leader); } // add the person as a follower (or sever existing link if leader==NULL) if (leader != NULL) { if (!enlarge_step_history(leader, distance)) return false; person->leader = leader; person->follow_distance = distance; } person->leader = leader; return true; } bool queue_person_command(person_t* person, int command, bool is_immediate) { struct command* commands; bool is_aok = true; switch (command) { case COMMAND_MOVE_NORTHEAST: is_aok &= queue_person_command(person, COMMAND_MOVE_NORTH, true); is_aok &= queue_person_command(person, COMMAND_MOVE_EAST, is_immediate); return is_aok; case COMMAND_MOVE_SOUTHEAST: is_aok &= queue_person_command(person, COMMAND_MOVE_SOUTH, true); is_aok &= queue_person_command(person, COMMAND_MOVE_EAST, is_immediate); return is_aok; case COMMAND_MOVE_SOUTHWEST: is_aok &= queue_person_command(person, COMMAND_MOVE_SOUTH, true); is_aok &= queue_person_command(person, COMMAND_MOVE_WEST, is_immediate); return is_aok; case COMMAND_MOVE_NORTHWEST: is_aok &= queue_person_command(person, COMMAND_MOVE_NORTH, true); is_aok &= queue_person_command(person, COMMAND_MOVE_WEST, is_immediate); return is_aok; default: ++person->num_commands; if (person->num_commands > person->max_commands) { if (!(commands = realloc(person->commands, person->num_commands * 2 * sizeof(struct command)))) return false; person->max_commands = person->num_commands * 2; person->commands = commands; } person->commands[person->num_commands - 1].type = command; person->commands[person->num_commands - 1].is_immediate = is_immediate; person->commands[person->num_commands - 1].script = NULL; return true; } } bool queue_person_script(person_t* person, script_t* script, bool is_immediate) { ++person->num_commands; if (person->num_commands > person->max_commands) { person->max_commands = person->num_commands * 2; if (!(person->commands = realloc(person->commands, person->max_commands * sizeof(struct command)))) return false; } person->commands[person->num_commands - 1].type = COMMAND_RUN_SCRIPT; person->commands[person->num_commands - 1].is_immediate = is_immediate; person->commands[person->num_commands - 1].script = script; return true; } void render_persons(int layer, bool is_flipped, int cam_x, int cam_y) { person_t* person; spriteset_t* sprite; int w, h; double x, y; int i; for (i = 0; i < s_num_persons; ++i) { person = s_persons[i]; if (!person->is_visible || person->layer != layer) continue; sprite = person->sprite; get_sprite_size(sprite, &w, &h); get_person_xy(person, &x, &y, true); x -= cam_x - person->x_offset; y -= cam_y - person->y_offset; draw_sprite(sprite, person->mask, is_flipped, person->theta, person->scale_x, person->scale_y, person->direction, x, y, person->frame); } } void reset_persons(bool keep_existing) { unsigned int id; point3_t map_origin; person_t* person; int i, j; map_origin = get_map_origin(); for (i = 0; i < s_num_persons; ++i) { person = s_persons[i]; id = person->id; if (!keep_existing) person->num_commands = 0; if (person->is_persistent || keep_existing) { person->x = map_origin.x; person->y = map_origin.y; person->layer = map_origin.z; } else { call_person_script(person, PERSON_SCRIPT_ON_DESTROY, true); free_person(person); --s_num_persons; for (j = i; j < s_num_persons; ++j) s_persons[j] = s_persons[j + 1]; --i; } } sort_persons(); } void talk_person(const person_t* person) { const person_t* last_active; rect_t map_rect; person_t* target_person; double talk_x, talk_y; map_rect = get_map_bounds(); // check if anyone else is within earshot get_person_xy(person, &talk_x, &talk_y, true); if (strstr(person->direction, "north")) talk_y -= s_talk_distance; if (strstr(person->direction, "east")) talk_x += s_talk_distance; if (strstr(person->direction, "south")) talk_y += s_talk_distance; if (strstr(person->direction, "west")) talk_x -= s_talk_distance; is_person_obstructed_at(person, talk_x, talk_y, &target_person, NULL); // if so, call their talk script last_active = s_acting_person; s_acting_person = person; if (target_person != NULL) call_person_script(target_person, PERSON_SCRIPT_ON_TALK, true); s_acting_person = last_active; } void update_persons(void) { bool has_moved; bool is_sort_needed = false; int i; for (i = 0; i < s_num_persons; ++i) { if (s_persons[i]->leader != NULL) continue; // skip followers for now update_person(s_persons[i], &has_moved); is_sort_needed |= has_moved; } if (is_sort_needed) sort_persons(); } static bool does_person_exist(const person_t* person) { int i; for (i = 0; i < s_num_persons; ++i) if (person == s_persons[i]) return true; return false; } static void set_person_direction(person_t* person, const char* direction) { person->direction = realloc(person->direction, (strlen(direction) + 1) * sizeof(char)); strcpy(person->direction, direction); } static void set_person_name(person_t* person, const char* name) { person->name = realloc(person->name, (strlen(name) + 1) * sizeof(char)); strcpy(person->name, name); } static void command_person(person_t* person, int command) { const person_t* last_active; double new_x, new_y; person_t* person_to_touch; new_x = person->x; new_y = person->y; switch (command) { case COMMAND_ANIMATE: person->revert_frames = person->revert_delay; if (person->anim_frames > 0 && --person->anim_frames == 0) { ++person->frame; person->anim_frames = get_sprite_frame_delay(person->sprite, person->direction, person->frame); } break; case COMMAND_FACE_NORTH: set_person_direction(person, "north"); break; case COMMAND_FACE_NORTHEAST: set_person_direction(person, "northeast"); break; case COMMAND_FACE_EAST: set_person_direction(person, "east"); break; case COMMAND_FACE_SOUTHEAST: set_person_direction(person, "southeast"); break; case COMMAND_FACE_SOUTH: set_person_direction(person, "south"); break; case COMMAND_FACE_SOUTHWEST: set_person_direction(person, "southwest"); break; case COMMAND_FACE_WEST: set_person_direction(person, "west"); break; case COMMAND_FACE_NORTHWEST: set_person_direction(person, "northwest"); break; case COMMAND_MOVE_NORTH: new_y = person->y - person->speed_y; break; case COMMAND_MOVE_EAST: new_x = person->x + person->speed_x; break; case COMMAND_MOVE_SOUTH: new_y = person->y + person->speed_y; break; case COMMAND_MOVE_WEST: new_x = person->x - person->speed_x; break; } if (new_x != person->x || new_y != person->y) { // person is trying to move, make sure the path is clear of obstructions if (!is_person_obstructed_at(person, new_x, new_y, &person_to_touch, NULL)) { if (new_x != person->x) person->mv_x = new_x > person->x ? 1 : -1; if (new_y != person->y) person->mv_y = new_y > person->y ? 1 : -1; person->x = new_x; person->y = new_y; } else { // if not, and we collided with a person, call that person's touch script last_active = s_acting_person; s_acting_person = person; if (person_to_touch != NULL) call_person_script(person_to_touch, PERSON_SCRIPT_ON_TOUCH, true); s_acting_person = last_active; } } } static int compare_persons(const void* a, const void* b) { person_t* p1 = *(person_t**)a; person_t* p2 = *(person_t**)b; double x, y_p1, y_p2; int y_delta; get_person_xy(p1, &x, &y_p1, true); get_person_xy(p2, &x, &y_p2, true); y_delta = (y_p1 + p1->y_offset) - (y_p2 + p2->y_offset); if (y_delta != 0) return y_delta; else if (is_person_following(p1, p2)) return -1; else if (is_person_following(p2, p1)) return 1; else return p1->id - p2->id; } static void free_person(person_t* person) { int i; free(person->steps); for (i = 0; i < PERSON_SCRIPT_MAX; ++i) free_script(person->scripts[i]); free_spriteset(person->sprite); free(person->commands); free(person->name); free(person->direction); free(person); } static void record_step(person_t* person) { struct step* p_step; if (person->max_history <= 0) return; memmove(&person->steps[1], &person->steps[0], (person->max_history - 1) * sizeof(struct step)); p_step = &person->steps[0]; p_step->x = person->x; p_step->y = person->y; } static bool enlarge_step_history(person_t* person, int new_size) { struct step *new_steps; size_t pastmost; double last_x; double last_y; int i; if (new_size > person->max_history) { if (!(new_steps = realloc(person->steps, new_size * sizeof(struct step)))) return false; // when enlarging the history buffer, fill new slots with pastmost values // (kind of like sign extension) pastmost = person->max_history - 1; last_x = person->steps != NULL ? person->steps[pastmost].x : person->x; last_y = person->steps != NULL ? person->steps[pastmost].y : person->y; for (i = person->max_history; i < new_size; ++i) { new_steps[i].x = last_x; new_steps[i].y = last_y; } person->steps = new_steps; person->max_history = new_size; } return true; } static void sort_persons(void) { qsort(s_persons, s_num_persons, sizeof(person_t*), compare_persons); } static void update_person(person_t* person, bool* out_has_moved) { struct command command; double delta_x, delta_y; int facing; bool has_moved; bool is_finished; const person_t* last_person; struct step step; int vector; int i; person->mv_x = 0; person->mv_y = 0; if (person->revert_frames > 0 && --person->revert_frames <= 0) person->frame = 0; if (person->leader == NULL) { // no leader; use command queue // call the command generator if the queue is empty if (person->num_commands == 0) call_person_script(person, PERSON_SCRIPT_GENERATOR, true); // run through the queue, stopping after the first non-immediate command is_finished = !does_person_exist(person) || person->num_commands == 0; while (!is_finished) { command = person->commands[0]; --person->num_commands; for (i = 0; i < person->num_commands; ++i) person->commands[i] = person->commands[i + 1]; last_person = s_current_person; s_current_person = person; if (command.type != COMMAND_RUN_SCRIPT) command_person(person, command.type); else run_script(command.script, false); s_current_person = last_person; free_script(command.script); is_finished = !does_person_exist(person) // stop if person was destroyed || !command.is_immediate || person->num_commands == 0; } } else { // leader set; follow the leader! step = person->leader->steps[person->follow_distance - 1]; delta_x = step.x - person->x; delta_y = step.y - person->y; if (fabs(delta_x) > person->speed_x) command_person(person, delta_x > 0 ? COMMAND_MOVE_EAST : COMMAND_MOVE_WEST); if (!does_person_exist(person)) return; if (fabs(delta_y) > person->speed_y) command_person(person, delta_y > 0 ? COMMAND_MOVE_SOUTH : COMMAND_MOVE_NORTH); if (!does_person_exist(person)) return; vector = person->mv_x + person->mv_y * 3; facing = vector == -3 ? COMMAND_FACE_NORTH : vector == -2 ? COMMAND_FACE_NORTHEAST : vector == 1 ? COMMAND_FACE_EAST : vector == 4 ? COMMAND_FACE_SOUTHEAST : vector == 3 ? COMMAND_FACE_SOUTH : vector == 2 ? COMMAND_FACE_SOUTHWEST : vector == -1 ? COMMAND_FACE_WEST : vector == -4 ? COMMAND_FACE_NORTHWEST : COMMAND_WAIT; if (facing != COMMAND_WAIT) command_person(person, COMMAND_ANIMATE); if (!does_person_exist(person)) return; command_person(person, facing); } // check that the person didn't mysteriously disappear... if (!does_person_exist(person)) return; // they probably got eaten by a hunger-pig or something. // if the person's position changed, record it in their step history *out_has_moved = has_person_moved(person); if (*out_has_moved) record_step(person); // recursively update the follower chain for (i = 0; i < s_num_persons; ++i) { if (s_persons[i]->leader != person) continue; update_person(s_persons[i], &has_moved); *out_has_moved |= has_moved; } } void init_persons_api(void) { duk_push_global_stash(g_duk); duk_push_object(g_duk); duk_put_prop_string(g_duk, -2, "person_data"); duk_pop(g_duk); api_register_method(g_duk, NULL, "CreatePerson", js_CreatePerson); api_register_method(g_duk, NULL, "DestroyPerson", js_DestroyPerson); api_register_method(g_duk, NULL, "IsCommandQueueEmpty", js_IsCommandQueueEmpty); api_register_method(g_duk, NULL, "IsIgnoringPersonObstructions", js_IsIgnoringPersonObstructions); api_register_method(g_duk, NULL, "IsIgnoringTileObstructions", js_IsIgnoringTileObstructions); api_register_method(g_duk, NULL, "IsPersonObstructed", js_IsPersonObstructed); api_register_method(g_duk, NULL, "IsPersonVisible", js_IsPersonVisible); api_register_method(g_duk, NULL, "DoesPersonExist", js_DoesPersonExist); api_register_method(g_duk, NULL, "GetActingPerson", js_GetActingPerson); api_register_method(g_duk, NULL, "GetCurrentPerson", js_GetCurrentPerson); api_register_method(g_duk, NULL, "GetObstructingPerson", js_GetObstructingPerson); api_register_method(g_duk, NULL, "GetObstructingTile", js_GetObstructingTile); api_register_method(g_duk, NULL, "GetPersonAngle", js_GetPersonAngle); api_register_method(g_duk, NULL, "GetPersonBase", js_GetPersonBase); api_register_method(g_duk, NULL, "GetPersonData", js_GetPersonData); api_register_method(g_duk, NULL, "GetPersonDirection", js_GetPersonDirection); api_register_method(g_duk, NULL, "GetPersonFollowDistance", js_GetPersonFollowDistance); api_register_method(g_duk, NULL, "GetPersonFollowers", js_GetPersonFollowers); api_register_method(g_duk, NULL, "GetPersonFrame", js_GetPersonFrame); api_register_method(g_duk, NULL, "GetPersonFrameNext", js_GetPersonFrameNext); api_register_method(g_duk, NULL, "GetPersonFrameRevert", js_GetPersonFrameRevert); api_register_method(g_duk, NULL, "GetPersonIgnoreList", js_GetPersonIgnoreList); api_register_method(g_duk, NULL, "GetPersonLayer", js_GetPersonLayer); api_register_method(g_duk, NULL, "GetPersonLeader", js_GetPersonLeader); api_register_method(g_duk, NULL, "GetPersonList", js_GetPersonList); api_register_method(g_duk, NULL, "GetPersonMask", js_GetPersonMask); api_register_method(g_duk, NULL, "GetPersonOffsetX", js_GetPersonOffsetX); api_register_method(g_duk, NULL, "GetPersonOffsetY", js_GetPersonOffsetY); api_register_method(g_duk, NULL, "GetPersonSpeedX", js_GetPersonSpeedX); api_register_method(g_duk, NULL, "GetPersonSpeedY", js_GetPersonSpeedY); api_register_method(g_duk, NULL, "GetPersonSpriteset", js_GetPersonSpriteset); api_register_method(g_duk, NULL, "GetPersonValue", js_GetPersonValue); api_register_method(g_duk, NULL, "GetPersonX", js_GetPersonX); api_register_method(g_duk, NULL, "GetPersonXFloat", js_GetPersonXFloat); api_register_method(g_duk, NULL, "GetPersonY", js_GetPersonY); api_register_method(g_duk, NULL, "GetPersonYFloat", js_GetPersonYFloat); api_register_method(g_duk, NULL, "GetTalkDistance", js_GetTalkDistance); api_register_method(g_duk, NULL, "SetDefaultPersonScript", js_SetDefaultPersonScript); api_register_method(g_duk, NULL, "SetPersonAngle", js_SetPersonAngle); api_register_method(g_duk, NULL, "SetPersonData", js_SetPersonData); api_register_method(g_duk, NULL, "SetPersonDirection", js_SetPersonDirection); api_register_method(g_duk, NULL, "SetPersonFollowDistance", js_SetPersonFollowDistance); api_register_method(g_duk, NULL, "SetPersonFrame", js_SetPersonFrame); api_register_method(g_duk, NULL, "SetPersonFrameNext", js_SetPersonFrameNext); api_register_method(g_duk, NULL, "SetPersonFrameRevert", js_SetPersonFrameRevert); api_register_method(g_duk, NULL, "SetPersonIgnoreList", js_SetPersonIgnoreList); api_register_method(g_duk, NULL, "SetPersonLayer", js_SetPersonLayer); api_register_method(g_duk, NULL, "SetPersonMask", js_SetPersonMask); api_register_method(g_duk, NULL, "SetPersonOffsetX", js_SetPersonOffsetX); api_register_method(g_duk, NULL, "SetPersonOffsetY", js_SetPersonOffsetY); api_register_method(g_duk, NULL, "SetPersonScaleAbsolute", js_SetPersonScaleAbsolute); api_register_method(g_duk, NULL, "SetPersonScaleFactor", js_SetPersonScaleFactor); api_register_method(g_duk, NULL, "SetPersonScript", js_SetPersonScript); api_register_method(g_duk, NULL, "SetPersonSpeed", js_SetPersonSpeed); api_register_method(g_duk, NULL, "SetPersonSpeedXY", js_SetPersonSpeedXY); api_register_method(g_duk, NULL, "SetPersonSpriteset", js_SetPersonSpriteset); api_register_method(g_duk, NULL, "SetPersonValue", js_SetPersonValue); api_register_method(g_duk, NULL, "SetPersonVisible", js_SetPersonVisible); api_register_method(g_duk, NULL, "SetPersonX", js_SetPersonX); api_register_method(g_duk, NULL, "SetPersonXYFloat", js_SetPersonXYFloat); api_register_method(g_duk, NULL, "SetPersonY", js_SetPersonY); api_register_method(g_duk, NULL, "SetTalkDistance", js_SetTalkDistance); api_register_method(g_duk, NULL, "CallDefaultPersonScript", js_CallDefaultPersonScript); api_register_method(g_duk, NULL, "CallPersonScript", js_CallPersonScript); api_register_method(g_duk, NULL, "ClearPersonCommands", js_ClearPersonCommands); api_register_method(g_duk, NULL, "FollowPerson", js_FollowPerson); api_register_method(g_duk, NULL, "IgnorePersonObstructions", js_IgnorePersonObstructions); api_register_method(g_duk, NULL, "IgnoreTileObstructions", js_IgnoreTileObstructions); api_register_method(g_duk, NULL, "QueuePersonCommand", js_QueuePersonCommand); api_register_method(g_duk, NULL, "QueuePersonScript", js_QueuePersonScript); // movement script specifier constants api_register_const(g_duk, "SCRIPT_ON_CREATE", PERSON_SCRIPT_ON_CREATE); api_register_const(g_duk, "SCRIPT_ON_DESTROY", PERSON_SCRIPT_ON_DESTROY); api_register_const(g_duk, "SCRIPT_ON_ACTIVATE_TOUCH", PERSON_SCRIPT_ON_TOUCH); api_register_const(g_duk, "SCRIPT_ON_ACTIVATE_TALK", PERSON_SCRIPT_ON_TALK); api_register_const(g_duk, "SCRIPT_COMMAND_GENERATOR", PERSON_SCRIPT_GENERATOR); // person movement commands api_register_const(g_duk, "COMMAND_WAIT", COMMAND_WAIT); api_register_const(g_duk, "COMMAND_ANIMATE", COMMAND_ANIMATE); api_register_const(g_duk, "COMMAND_FACE_NORTH", COMMAND_FACE_NORTH); api_register_const(g_duk, "COMMAND_FACE_NORTHEAST", COMMAND_FACE_NORTHEAST); api_register_const(g_duk, "COMMAND_FACE_EAST", COMMAND_FACE_EAST); api_register_const(g_duk, "COMMAND_FACE_SOUTHEAST", COMMAND_FACE_SOUTHEAST); api_register_const(g_duk, "COMMAND_FACE_SOUTH", COMMAND_FACE_SOUTH); api_register_const(g_duk, "COMMAND_FACE_SOUTHWEST", COMMAND_FACE_SOUTHWEST); api_register_const(g_duk, "COMMAND_FACE_WEST", COMMAND_FACE_WEST); api_register_const(g_duk, "COMMAND_FACE_NORTHWEST", COMMAND_FACE_NORTHWEST); api_register_const(g_duk, "COMMAND_MOVE_NORTH", COMMAND_MOVE_NORTH); api_register_const(g_duk, "COMMAND_MOVE_NORTHEAST", COMMAND_MOVE_NORTHEAST); api_register_const(g_duk, "COMMAND_MOVE_EAST", COMMAND_MOVE_EAST); api_register_const(g_duk, "COMMAND_MOVE_SOUTHEAST", COMMAND_MOVE_SOUTHEAST); api_register_const(g_duk, "COMMAND_MOVE_SOUTH", COMMAND_MOVE_SOUTH); api_register_const(g_duk, "COMMAND_MOVE_SOUTHWEST", COMMAND_MOVE_SOUTHWEST); api_register_const(g_duk, "COMMAND_MOVE_WEST", COMMAND_MOVE_WEST); api_register_const(g_duk, "COMMAND_MOVE_NORTHWEST", COMMAND_MOVE_NORTHWEST); } static duk_ret_t js_CreatePerson(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); spriteset_t* spriteset; bool destroy_with_map = duk_require_boolean(ctx, 2); const char* filename; person_t* person; if (duk_is_sphere_obj(ctx, 1, "Spriteset")) // ref the spriteset so we can safely free it later. this avoids // having to check the argument type again. spriteset = ref_spriteset(duk_require_sphere_obj(ctx, 1, "Spriteset")); else { filename = duk_require_path(ctx, 1, "spritesets", true); if (!(spriteset = load_spriteset(filename))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "CreatePerson(): unable to load spriteset `%s`", filename); } // create the person and its JS-side data object person = create_person(name, spriteset, !destroy_with_map, NULL); free_spriteset(spriteset); duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "person_data"); duk_push_object(ctx); duk_put_prop_string(ctx, -2, name); duk_pop_2(ctx); return 0; } static duk_ret_t js_DestroyPerson(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "DestroyPerson(): no such person `%s`", name); destroy_person(person); return 0; } static duk_ret_t js_IsCommandQueueEmpty(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "IsCommandQueueEmpty(): no such person `%s`", name); duk_push_boolean(ctx, person->num_commands <= 0); return 1; } static duk_ret_t js_IsIgnoringPersonObstructions(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "IsIgnoringPersonObstructions(): no such person `%s`", name); duk_push_boolean(ctx, person->ignore_all_persons); return 1; } static duk_ret_t js_IsIgnoringTileObstructions(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "IsIgnoringTileObstructions(): no such person `%s`", name); duk_push_boolean(ctx, person->ignore_all_tiles); return 1; } static duk_ret_t js_DoesPersonExist(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); duk_push_boolean(ctx, find_person(name) != NULL); return 1; } static duk_ret_t js_IsPersonObstructed(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int x = duk_require_int(ctx, 1); int y = duk_require_int(ctx, 2); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "IsPersonObstructed(): no such person `%s`", name); duk_push_boolean(ctx, is_person_obstructed_at(person, x, y, NULL, NULL)); return 1; } static duk_ret_t js_IsPersonVisible(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonVisible(): no such person `%s`", name); duk_push_boolean(ctx, person->is_visible); return 1; } static duk_ret_t js_GetActingPerson(duk_context* ctx) { if (s_acting_person == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetActingPerson(): must be called from person activation script (touch/talk)"); duk_push_string(ctx, get_person_name(s_acting_person)); return 1; } static duk_ret_t js_GetCurrentPerson(duk_context* ctx) { if (s_current_person == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetCurrentPerson(): must be called from a person script"); duk_push_string(ctx, get_person_name(s_current_person)); return 1; } static duk_ret_t js_GetObstructingPerson(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int x = duk_require_int(ctx, 1); int y = duk_require_int(ctx, 2); person_t* obs_person = NULL; person_t* person; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetObstructingPerson(): map engine must be running"); if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetObstructingPerson(): no such person `%s`", name); is_person_obstructed_at(person, x, y, &obs_person, NULL); duk_push_string(ctx, obs_person != NULL ? get_person_name(obs_person) : ""); return 1; } static duk_ret_t js_GetObstructingTile(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int x = duk_require_int(ctx, 1); int y = duk_require_int(ctx, 2); person_t* person; int tile_index; if (!is_map_engine_running()) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetObstructingTile(): map engine must be running"); if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetObstructingTile(): no such person `%s`", name); is_person_obstructed_at(person, x, y, NULL, &tile_index); duk_push_int(ctx, tile_index); return 1; } static duk_ret_t js_GetPersonAngle(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonAngle(): no such person `%s`", name); duk_push_number(ctx, get_person_angle(person)); return 1; } static duk_ret_t js_GetPersonBase(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); rect_t base; person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonDirection(): no such person `%s`", name); base = get_sprite_base(get_person_spriteset(person)); duk_push_object(ctx); duk_push_int(ctx, base.x1); duk_put_prop_string(ctx, -2, "x1"); duk_push_int(ctx, base.y1); duk_put_prop_string(ctx, -2, "y1"); duk_push_int(ctx, base.x2); duk_put_prop_string(ctx, -2, "x2"); duk_push_int(ctx, base.y2); duk_put_prop_string(ctx, -2, "y2"); return 1; } static duk_ret_t js_GetPersonData(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int num_directions; int num_frames; person_t* person; spriteset_t* spriteset; int width, height; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonData(): no such person `%s`", name); spriteset = person->sprite; get_sprite_size(spriteset, &width, &height); get_spriteset_info(spriteset, NULL, &num_directions); get_spriteset_pose_info(spriteset, person->direction, &num_frames); duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "person_data"); duk_get_prop_string(ctx, -1, name); duk_push_int(ctx, num_frames); duk_put_prop_string(ctx, -2, "num_frames"); duk_push_int(ctx, num_directions); duk_put_prop_string(ctx, -2, "num_directions"); duk_push_int(ctx, width); duk_put_prop_string(ctx, -2, "width"); duk_push_int(ctx, height); duk_put_prop_string(ctx, -2, "height"); duk_push_string(ctx, person->leader ? person->leader->name : ""); duk_put_prop_string(ctx, -2, "leader"); duk_remove(ctx, -2); duk_remove(ctx, -2); return 1; } static duk_ret_t js_GetPersonDirection(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonDirection(): no such person `%s`", name); duk_push_string(ctx, person->direction); return 1; } static duk_ret_t js_GetPersonFollowDistance(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonFollowDistance(): no such person `%s`", name); if (person->leader == NULL) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "GetPersonFollowDistance(): person `%s` is not following anyone", name); duk_push_int(ctx, person->follow_distance); return 1; } static duk_ret_t js_GetPersonFollowers(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); duk_uarridx_t index = 0; person_t* person; int i; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonFollowers(): no such person `%s`", name); duk_push_array(ctx); for (i = 0; i < s_num_persons; ++i) { if (s_persons[i]->leader == person) { duk_push_string(ctx, s_persons[i]->name); duk_put_prop_index(ctx, -2, index++); } } return 1; } static duk_ret_t js_GetPersonFrame(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int num_frames; person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonFrame(): no such person `%s`", name); get_spriteset_pose_info(person->sprite, person->direction, &num_frames); duk_push_int(ctx, person->frame % num_frames); return 1; } static duk_ret_t js_GetPersonFrameNext(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonFrame(): no such person `%s`", name); duk_push_int(ctx, person->anim_frames); return 1; } static duk_ret_t js_GetPersonFrameRevert(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonFrameRevert(): no such person `%s`", name); duk_push_int(ctx, person->revert_delay); return 1; } static duk_ret_t js_GetPersonIgnoreList(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; int i; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonIgnoreList(): no such person `%s`", name); duk_push_array(ctx); for (i = 0; i < person->num_ignores; ++i) { duk_push_string(ctx, person->ignores[i]); duk_put_prop_index(ctx, -2, i); } return 1; } static duk_ret_t js_GetPersonLayer(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonLayer(): no such person `%s`", name); duk_push_int(ctx, person->layer); return 1; } static duk_ret_t js_GetPersonLeader(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonLeader(): no such person `%s`", name); duk_push_string(ctx, person->leader != NULL ? person->leader->name : ""); return 1; } static duk_ret_t js_GetPersonMask(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonMask(): no such person `%s`", name); duk_push_sphere_color(ctx, get_person_mask(person)); return 1; } static duk_ret_t js_GetPersonOffsetX(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonOffsetX(): no such person `%s`", name); duk_push_int(ctx, person->x_offset); return 1; } static duk_ret_t js_GetPersonOffsetY(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonOffsetY(): no such person `%s`", name); duk_push_int(ctx, person->y_offset); return 1; } static duk_ret_t js_GetPersonList(duk_context* ctx) { int i; duk_push_array(ctx); for (i = 0; i < s_num_persons; ++i) { duk_push_string(ctx, s_persons[i]->name); duk_put_prop_index(ctx, -2, i); } return 1; } static duk_ret_t js_GetPersonSpriteset(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); spriteset_t* new_spriteset; person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonSpriteset(): no such person `%s`", name); if ((new_spriteset = clone_spriteset(get_person_spriteset(person))) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "GetPersonSpriteset(): unable to create new spriteset"); duk_push_sphere_spriteset(ctx, new_spriteset); free_spriteset(new_spriteset); return 1; } static duk_ret_t js_GetPersonSpeedX(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; double x_speed; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonSpeedX(): no such person `%s`", name); get_person_speed(person, &x_speed, NULL); duk_push_number(ctx, x_speed); return 1; } static duk_ret_t js_GetPersonSpeedY(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; double y_speed; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonSpeedY(): no such person `%s`", name); get_person_speed(person, NULL, &y_speed); duk_push_number(ctx, y_speed); return 1; } static duk_ret_t js_GetPersonValue(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); const char* key = duk_to_string(ctx, 1); person_t* person; duk_require_type_mask(ctx, 1, DUK_TYPE_MASK_STRING | DUK_TYPE_MASK_NUMBER); if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonValue(): no such person `%s`", name); duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "person_data"); if (!duk_get_prop_string(ctx, -1, name)) { duk_pop(ctx); duk_push_object(ctx); duk_put_prop_string(ctx, -2, name); duk_get_prop_string(ctx, -1, name); } duk_get_prop_string(ctx, -1, key); duk_remove(ctx, -2); duk_remove(ctx, -2); duk_remove(ctx, -2); return 1; } static duk_ret_t js_GetPersonX(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; double x, y; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonX(): no such person `%s`", name); get_person_xy(person, &x, &y, true); duk_push_int(ctx, x); return 1; } static duk_ret_t js_GetPersonXFloat(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; double x, y; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonXFloat(): no such person `%s`", name); get_person_xy(person, &x, &y, true); duk_push_number(ctx, x); return 1; } static duk_ret_t js_GetPersonY(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; double x, y; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonY(): no such person `%s`", name); get_person_xy(person, &x, &y, true); duk_push_int(ctx, y); return 1; } static duk_ret_t js_GetPersonYFloat(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; double x, y; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "GetPersonYFloat(): no such person `%s`", name); get_person_xy(person, &x, &y, true); duk_push_number(ctx, y); return 1; } static duk_ret_t js_GetTalkDistance(duk_context* ctx) { duk_push_int(ctx, s_talk_distance); return 1; } static duk_ret_t js_SetDefaultPersonScript(duk_context* ctx) { int type = duk_require_int(ctx, 0); const char* script_name = (type == PERSON_SCRIPT_ON_CREATE) ? "synth:onCreatePerson.js" : (type == PERSON_SCRIPT_ON_DESTROY) ? "synth:onDestroyPerson.js" : (type == PERSON_SCRIPT_ON_TALK) ? "synth:onTalk.js" : (type == PERSON_SCRIPT_ON_TOUCH) ? "synth:onTouchPerson.js" : (type == PERSON_SCRIPT_GENERATOR) ? "synth:onGenCommands.js" : NULL; script_t* script = duk_require_sphere_script(ctx, 1, script_name); if (type < 0 || type >= PERSON_SCRIPT_MAX) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetDefaultPersonScript(): invalid script type constant"); free_script(s_def_scripts[type]); s_def_scripts[type] = script; return 0; } static duk_ret_t js_SetPersonAngle(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); double theta = duk_require_number(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonAngle(): no such person `%s`", name); set_person_angle(person, theta); return 0; } static duk_ret_t js_SetPersonData(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; duk_require_object_coercible(ctx, 1); if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonData(): no such person `%s`", name); duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "person_data"); duk_dup(ctx, 1); duk_put_prop_string(ctx, -2, name); return 0; } static duk_ret_t js_SetPersonDirection(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); const char* new_dir = duk_require_string(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonDirection(): no such person `%s`", name); set_person_direction(person, new_dir); return 0; } static duk_ret_t js_SetPersonFollowDistance(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int distance = duk_require_int(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonFollowDistance(): no such person `%s`", name); if (person->leader == NULL) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "SetPersonFollowDistance(): person `%s` is not following anyone", name); if (distance <= 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetPersonFollowDistance(): distance must be greater than zero (%i)", distance); if (!enlarge_step_history(person->leader, distance)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetPersonFollowDistance(): unable to enlarge leader's tracking buffer"); person->follow_distance = distance; return 0; } static duk_ret_t js_SetPersonFrame(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int frame_index = duk_require_int(ctx, 1); int num_frames; person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonFrame(): no such person `%s`", name); get_spriteset_pose_info(person->sprite, person->direction, &num_frames); person->frame = (frame_index % num_frames + num_frames) % num_frames; person->anim_frames = get_sprite_frame_delay(person->sprite, person->direction, person->frame); person->revert_frames = person->revert_delay; return 0; } static duk_ret_t js_SetPersonFrameNext(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int frames = duk_require_int(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonFrameRevert(): no such person `%s`", name); if (frames < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetPersonFrameNext(): delay must be positive (got: %i)", frames); person->anim_frames = frames; person->revert_frames = person->revert_delay; return 0; } static duk_ret_t js_SetPersonFrameRevert(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int frames = duk_require_int(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonFrameRevert(): no such person `%s`", name); if (frames < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetPersonFrameRevert(): delay must be positive (got: %i)", frames); person->revert_delay = frames; person->revert_frames = person->revert_delay; return 0; } static duk_ret_t js_SetPersonIgnoreList(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); size_t list_size; person_t* person; int i; duk_require_object_coercible(ctx, 1); if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonIgnoreList(): no such person `%s`", name); if (!duk_is_array(ctx, 1)) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetPersonIgnoreList(): ignore_list argument must be an array"); list_size = duk_get_length(ctx, 1); if (list_size > INT_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetPersonIgnoreList(): list is too large"); for (i = 0; i < person->num_ignores; ++i) { free(person->ignores[i]); } person->ignores = realloc(person->ignores, list_size * sizeof(char*)); person->num_ignores = (int)list_size; for (i = 0; i < (int)list_size; ++i) { duk_get_prop_index(ctx, 1, (duk_uarridx_t)i); person->ignores[i] = strdup(duk_require_string(ctx, -1)); duk_pop(ctx); } return 0; } static duk_ret_t js_SetPersonLayer(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int layer = duk_require_map_layer(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonLayer(): no such person `%s`", name); person->layer = layer; return 0; } static duk_ret_t js_SetPersonMask(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); color_t mask = duk_require_sphere_color(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonMask(): no such person `%s`", name); set_person_mask(person, mask); return 0; } static duk_ret_t js_SetPersonOffsetX(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int offset = duk_require_int(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonOffsetX(): no such person `%s`", name); person->x_offset = offset; return 0; } static duk_ret_t js_SetPersonOffsetY(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int offset = duk_require_int(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonOffsetY(): no such person `%s`", name); person->y_offset = offset; return 0; } static duk_ret_t js_SetPersonScaleAbsolute(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int width = duk_require_int(ctx, 1); int height = duk_require_int(ctx, 2); person_t* person; int sprite_w, sprite_h; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonScaleAbsolute(): no such person `%s`", name); if (width < 0 || height < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetPersonScaleAbsolute(): scale must be positive (got W: %i, H: %i)", width, height); get_sprite_size(get_person_spriteset(person), &sprite_w, &sprite_h); set_person_scale(person, width / sprite_w, height / sprite_h); return 0; } static duk_ret_t js_SetPersonScaleFactor(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); double scale_x = duk_require_number(ctx, 1); double scale_y = duk_require_number(ctx, 2); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonScaleFactor(): no such person `%s`", name); if (scale_x < 0.0 || scale_y < 0.0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetPersonScaleFactor(): scale must be positive (got X: %f, Y: %f })", scale_x, scale_y); set_person_scale(person, scale_x, scale_y); return 0; } static duk_ret_t js_SetPersonScript(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int type = duk_require_int(ctx, 1); lstring_t* codestring; person_t* person; script_t* script; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonScript(): no such person `%s`", name); if (type < 0 || type >= PERSON_SCRIPT_MAX) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetPersonScript(): invalid script type constant"); if (duk_is_string(ctx, 2)) { codestring = duk_require_lstring_t(ctx, 2); compile_person_script(person, type, codestring); lstr_free(codestring); } else { script = duk_require_sphere_script(ctx, 2, "[person script]"); set_person_script(person, type, script); } return 0; } static duk_ret_t js_SetPersonSpeed(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); double speed = duk_require_number(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonSpeed(): no such person `%s`", name); set_person_speed(person, speed, speed); return 0; } static duk_ret_t js_SetPersonSpeedXY(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); double x_speed = duk_require_number(ctx, 1); double y_speed = duk_require_number(ctx, 2); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonSpeed(): no such person `%s`", name); set_person_speed(person, x_speed, y_speed); return 0; } static duk_ret_t js_SetPersonSpriteset(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); spriteset_t* spriteset = duk_require_sphere_obj(ctx, 1, "Spriteset"); spriteset_t* new_spriteset; person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonSpriteset(): no such person `%s`", name); if ((new_spriteset = clone_spriteset(spriteset)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "SetPersonSpriteset(): unable to create new spriteset"); set_person_spriteset(person, new_spriteset); free_spriteset(new_spriteset); return 0; } static duk_ret_t js_SetPersonValue(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); const char* key = duk_to_string(ctx, 1); person_t* person; duk_require_valid_index(ctx, 2); duk_require_type_mask(ctx, 1, DUK_TYPE_MASK_STRING | DUK_TYPE_MASK_NUMBER); if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonValue(): no such person `%s`", name); duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "person_data"); if (!duk_get_prop_string(ctx, -1, name)) { duk_pop(ctx); duk_push_object(ctx); duk_put_prop_string(ctx, -2, name); duk_get_prop_string(ctx, -1, name); } duk_dup(ctx, 2); duk_put_prop_string(ctx, -2, key); duk_pop_2(ctx); return 0; } static duk_ret_t js_SetPersonVisible(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); bool is_visible = duk_require_boolean(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonVisible(): no such person `%s`", name); person->is_visible = is_visible; return 0; } static duk_ret_t js_SetPersonX(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int x = duk_require_int(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonX(): no such person `%s`", name); person->x = x; return 0; } static duk_ret_t js_SetPersonXYFloat(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); double x = duk_require_number(ctx, 1); double y = duk_require_number(ctx, 2); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonXYFloat(): no such person `%s`", name); person->x = x; person->y = y; return 0; } static duk_ret_t js_SetPersonY(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int y = duk_require_int(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "SetPersonY(): no such person `%s`", name); person->y = y; return 0; } static duk_ret_t js_SetTalkDistance(duk_context* ctx) { int pixels = duk_require_int(ctx, 0); if (pixels < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "SetTalkDistance(): distance must be positive (got: %i)", pixels); s_talk_distance = pixels; return 0; } static duk_ret_t js_CallDefaultPersonScript(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int type = duk_require_int(ctx, 1); const person_t* last_person; person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "CallDefaultPersonScript(): no such person `%s`", name); if (type < 0 || type >= PERSON_SCRIPT_MAX) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "CallDefaultPersonScript(): invalid script type constant"); last_person = s_current_person; s_current_person = person; run_script(s_def_scripts[type], false); s_current_person = last_person; return 0; } static duk_ret_t js_CallPersonScript(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); int type = duk_require_int(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "CallPersonScript(): no such person `%s`", name); if (type < 0 || type >= PERSON_SCRIPT_MAX) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "CallPersonScript(): invalid script type constant"); call_person_script(person, type, false); return 0; } static duk_ret_t js_ClearPersonCommands(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "ClearPersonCommands(): no such person `%s`", name); person->num_commands = 0; return 0; } static duk_ret_t js_FollowPerson(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); const char* leader_name = duk_is_null(ctx, 1) ? "" : duk_require_string(ctx, 1); int distance = leader_name[0] != '\0' ? duk_require_int(ctx, 2) : 0; person_t* leader = NULL; person_t* person; if (!(person = find_person(name))) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "FollowPerson(): no such person `%s`", name); if (!(leader_name[0] == '\0' || (leader = find_person(leader_name)))) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "FollowPerson(): no such person `%s`", leader_name); if (distance <= 0 && leader_name[0] != '\0') duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "FollowPerson(): distance must be greater than zero (%i)", distance); if (!follow_person(person, leader, distance)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FollowPerson(): circular chain is not allowed"); return 0; } static duk_ret_t js_IgnorePersonObstructions(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); bool is_ignoring = duk_require_boolean(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "IgnorePersonObstructions(): no such person `%s`", name); person->ignore_all_persons = is_ignoring; return 0; } static duk_ret_t js_IgnoreTileObstructions(duk_context* ctx) { const char* name = duk_require_string(ctx, 0); bool is_ignoring = duk_require_boolean(ctx, 1); person_t* person; if ((person = find_person(name)) == NULL) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "IgnoreTileObstructions(): no such person `%s`", name); person->ignore_all_tiles = is_ignoring; return 0; } static duk_ret_t js_QueuePersonCommand(duk_context* ctx) { int n_args = duk_get_top(ctx); const char* name = duk_require_string(ctx, 0); int command = duk_require_int(ctx, 1); bool is_immediate = n_args >= 3 ? duk_require_boolean(ctx, 2) : false; person_t* person; if (!(person = find_person(name))) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "QueuePersonCommand(): no such person `%s`", name); if (command < 0 || command >= COMMAND_RUN_SCRIPT) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "QueuePersonCommand(): invalid command type constant"); if (command >= COMMAND_MOVE_NORTH && command <= COMMAND_MOVE_NORTHWEST) { if (!queue_person_command(person, COMMAND_ANIMATE, true)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "QueuePersonCommand(): unable to queue command"); } if (!queue_person_command(person, command, is_immediate)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "QueuePersonCommand(): unable to queue command"); return 0; } static duk_ret_t js_QueuePersonScript(duk_context* ctx) { int n_args = duk_get_top(ctx); const char* name = duk_require_string(ctx, 0); lstring_t* script_name = lstr_newf("%s/%s/queueScript.js", get_map_name(), name, s_queued_id++); script_t* script = duk_require_sphere_script(ctx, 1, lstr_cstr(script_name)); bool is_immediate = n_args >= 3 ? duk_require_boolean(ctx, 2) : false; person_t* person; lstr_free(script_name); if (!(person = find_person(name))) duk_error_ni(ctx, -1, DUK_ERR_REFERENCE_ERROR, "QueuePersonScript(): no such person `%s`", name); if (!queue_person_script(person, script, is_immediate)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "QueuePersonScript(): unable to enqueue script"); return 0; } <file_sep>/src/plugin/PluginMain.cs using System; using System.IO; using System.Windows.Forms; using Microsoft.Win32; using Sphere.Plugins; using Sphere.Plugins.Interfaces; using minisphere.Gdk.DockPanes; using minisphere.Gdk.Plugins; using minisphere.Gdk.SettingsPages; using minisphere.Gdk.Properties; namespace minisphere.Gdk { public class PluginMain : IPluginMain { public string Name { get; } = "minisphere GDK"; public string Author { get; } = "<NAME>"; public string Description { get; } = "Provides support for the minisphere GDK toolchain."; public string Version { get; } = "3.1.0"; internal PluginConf Conf { get; private set; } internal int Sessions { get; set; } private ToolStripMenuItem _sphereApiRefCommand; private ToolStripMenuItem _cellApiRefCommand; private ToolStripMenuItem _miniRTApiRefCommand; public void Initialize(ISettings conf) { Conf = new PluginConf(conf); Sessions = 0; PluginManager.Register(this, new minisphereStarter(this), "minisphere"); PluginManager.Register(this, new CellCompiler(this), "Cell"); PluginManager.Register(this, new SettingsPage(this), "minisphere Setup"); Panes.Initialize(this); _sphereApiRefCommand = new ToolStripMenuItem("Spherical API Reference", Resources.EvalIcon); _sphereApiRefCommand.Click += sphereApiRefCommand_Click; _miniRTApiRefCommand = new ToolStripMenuItem("miniRT API Reference", Resources.EvalIcon); _miniRTApiRefCommand.Click += miniRTApiRefCommand_Click; _cellApiRefCommand = new ToolStripMenuItem("Cellscript API Reference", Resources.EvalIcon); _cellApiRefCommand.Click += cellApiRefCommand_Click; PluginManager.Core.AddMenuItem("Help", _sphereApiRefCommand); PluginManager.Core.AddMenuItem("Help", _miniRTApiRefCommand); PluginManager.Core.AddMenuItem("Help", _cellApiRefCommand); PluginManager.Core.UnloadProject += on_UnloadProject; } public void ShutDown() { PluginManager.Core.UnloadProject -= on_UnloadProject; PluginManager.Core.RemoveMenuItem(_sphereApiRefCommand); PluginManager.Core.RemoveMenuItem(_miniRTApiRefCommand); PluginManager.Core.RemoveMenuItem(_cellApiRefCommand); PluginManager.UnregisterAll(this); } private void sphereApiRefCommand_Click(object sender, EventArgs e) { string filePath = Path.Combine(Conf.GdkPath, "documentation", "spherical-api.txt"); PluginManager.Core.OpenFile(filePath); } private void miniRTApiRefCommand_Click(object sender, EventArgs e) { string filePath = Path.Combine(Conf.GdkPath, "documentation", "miniRT-api.txt"); PluginManager.Core.OpenFile(filePath); } private void cellApiRefCommand_Click(object sender, EventArgs e) { string filePath = Path.Combine(Conf.GdkPath, "documentation", "cellscript-api.txt"); PluginManager.Core.OpenFile(filePath); } private void on_UnloadProject(object sender, EventArgs e) { Panes.Errors.Clear(); Panes.Console.Clear(); } } class PluginConf { public PluginConf(ISettings conf) { Conf = conf; } public ISettings Conf { get; private set; } public string GdkPath { get { RegistryKey key = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{10C19C9F-1E29-45D8-A534-8FEF98C7C2FF}_is1"); if (key != null) { // minisphere GDK is installed, get path from registry string defaultPath = (string)key.GetValue(@"InstallLocation") ?? ""; string path = Conf.GetString("gdkPath", defaultPath); return !string.IsNullOrWhiteSpace(path) ? path : defaultPath; } else { // no installation key, just read from conf return Conf.GetString("gdkPath", ""); } } set { Conf.SetValue("gdkPath", value); } } public bool AlwaysUseConsole { get { return Conf.GetBoolean("alwaysUseConsole", false); } set { Conf.SetValue("alwaysUseConsole", value); } } public bool MakeDebugPackages { get { return Conf.GetBoolean("makeDebugPackages", false); } set { Conf.SetValue("makeDebugPackages", value); } } public bool TestInWindow { get { return Conf.GetBoolean("testInWindow", false); } set { Conf.SetValue("testInWindow", value); } } public int Verbosity { get { return Math.Min(Math.Max(Conf.GetInteger("verbosity", 2), 0), 4); } set { Conf.SetValue("verbosity", Math.Min(Math.Max(value, 0), 4)); } } } static class Panes { public static void Initialize(PluginMain main) { PluginManager.Register(main, Inspector = new InspectorPane(), "Debugger"); PluginManager.Register(main, Console = new ConsolePane(main.Conf), "Console"); PluginManager.Register(main, Errors = new ErrorPane(), "Exceptions"); } public static ConsolePane Console { get; private set; } public static ErrorPane Errors { get; private set; } public static InspectorPane Inspector { get; private set; } } } <file_sep>/src/engine/async.c #include "minisphere.h" #include "async.h" #include "api.h" #include "script.h" #include "vector.h" static duk_ret_t js_DispatchScript (duk_context* ctx); static unsigned int s_next_script_id = 1; static vector_t* s_scripts; bool initialize_async(void) { console_log(1, "initializing async manager"); if (!(s_scripts = vector_new(sizeof(script_t*)))) return false; return true; } void shutdown_async(void) { console_log(1, "shutting down async manager"); vector_free(s_scripts); } void update_async(void) { iter_t iter; script_t** p_script; vector_t* vector; vector = s_scripts; s_scripts = vector_new(sizeof(script_t*)); if (vector != NULL) { iter = vector_enum(vector); while (p_script = vector_next(&iter)) { run_script(*p_script, false); free_script(*p_script); } vector_free(vector); } } bool queue_async_script(script_t* script) { if (s_scripts != NULL) return vector_push(s_scripts, &script); else return false; } void init_async_api(void) { api_register_method(g_duk, NULL, "DispatchScript", js_DispatchScript); } static duk_ret_t js_DispatchScript(duk_context* ctx) { script_t* script; char* script_name; script_name = strnewf("synth:async~%u.js", s_next_script_id++); script = duk_require_sphere_script(ctx, 0, script_name); free(script_name); if (!queue_async_script(script)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to dispatch async script"); return 0; } <file_sep>/src/plugin/DockPanes/InspectorPane.cs using System; using System.Collections.Generic; using System.Drawing; using System.Media; using System.Threading.Tasks; using System.Windows.Forms; using Sphere.Plugins; using Sphere.Plugins.Interfaces; using Sphere.Plugins.Views; using minisphere.Gdk.Forms; using minisphere.Gdk.Plugins; using minisphere.Gdk.Properties; using minisphere.Gdk.Debugger; namespace minisphere.Gdk.DockPanes { partial class InspectorPane : UserControl, IDockPane { private const string ValueBoxHint = "Select a variable from the list above to see what it contains."; private bool _isEvaling = false; private int _frame = -1; private IReadOnlyDictionary<string, DValue> _vars; public InspectorPane() { InitializeComponent(); Enabled = false; } public bool ShowInViewMenu => false; public Control Control => this; public DockHint DockHint => DockHint.Right; public Bitmap DockIcon => Resources.VisibleIcon; public Ssj2Debugger Ssj { get; set; } public void Clear() { LocalsView.Items.Clear(); CallsView.Items.Clear(); } public async Task SetCallStack(Tuple<string, string, int>[] stack, int index = 0) { CallsView.BeginUpdate(); CallsView.Items.Clear(); foreach (var entry in stack) { ListViewItem item = new ListViewItem(entry.Item1 != "" ? string.Format("{0}()", entry.Item1) : "anon"); item.SubItems.Add(entry.Item2); item.SubItems.Add(entry.Item3.ToString()); CallsView.Items.Add(item); } CallsView.EndUpdate(); _frame = -1; await LoadStackFrame(index); } private async Task DoEvaluate(string expr) { var result = await Ssj.Inferior.Eval(expr, -(_frame + 1)); new ObjectViewer(Ssj.Inferior, expr, result).ShowDialog(this); } private async Task LoadStackFrame(int callIndex) { if (_frame >= 0) CallsView.Items[_frame].ForeColor = SystemColors.WindowText; _frame = callIndex; CallsView.Items[_frame].ForeColor = Color.Blue; CallsView.SelectedItems.Clear(); _vars = await Ssj.Inferior.GetLocals(-(_frame + 1)); LocalsView.BeginUpdate(); LocalsView.Items.Clear(); foreach (var k in _vars.Keys) { var item = LocalsView.Items.Add(k, 0); item.SubItems.Add(_vars[k].ToString()); } LocalsView.EndUpdate(); } private async void EvalButton_Click(object sender, EventArgs e) { await DoEvaluate(ExprTextBox.Text); } private void ExprTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter && e.Modifiers == Keys.None) { EvalButton.PerformClick(); e.Handled = true; e.SuppressKeyPress = true; } } private void ExprTextBox_TextChanged(object sender, EventArgs e) { EvalButton.Enabled = !string.IsNullOrWhiteSpace(ExprTextBox.Text) && !_isEvaling; } private async void LocalsView_DoubleClick(object sender, EventArgs e) { if (LocalsView.SelectedItems.Count > 0) { ListViewItem item = LocalsView.SelectedItems[0]; await DoEvaluate(item.Text); } } private async void CallsView_DoubleClick(object sender, EventArgs e) { if (CallsView.SelectedItems.Count > 0) { ListViewItem item = CallsView.SelectedItems[0]; string filename = Ssj.ResolvePath(item.SubItems[1].Text); int lineNumber = int.Parse(item.SubItems[2].Text); ScriptView view = PluginManager.Core.OpenFile(filename) as ScriptView; if (view == null) SystemSounds.Hand.Play(); else { await LoadStackFrame(item.Index); view.Activate(); view.GoToLine(lineNumber); } } } } } <file_sep>/src/shared/lstring.c #include "lstring.h" #include "unicode.h" #include <stdlib.h> #include <stdarg.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct lstring { size_t length; char* cstr; }; // the Windows-1252 codepage static uint32_t cp1252[256] = { (uint32_t) 0x0000, (uint32_t) 0x0001, (uint32_t) 0x0002, (uint32_t) 0x0003, (uint32_t) 0x0004, (uint32_t) 0x0005, (uint32_t) 0x0006, (uint32_t) 0x0007, (uint32_t) 0x0008, (uint32_t) 0x0009, (uint32_t) 0x000A, (uint32_t) 0x000B, (uint32_t) 0x000C, (uint32_t) 0x000D, (uint32_t) 0x000E, (uint32_t) 0x000F, (uint32_t) 0x0010, (uint32_t) 0x0011, (uint32_t) 0x0012, (uint32_t) 0x0013, (uint32_t) 0x0014, (uint32_t) 0x0015, (uint32_t) 0x0016, (uint32_t) 0x0017, (uint32_t) 0x0018, (uint32_t) 0x0019, (uint32_t) 0x001A, (uint32_t) 0x001B, (uint32_t) 0x001C, (uint32_t) 0x001D, (uint32_t) 0x001E, (uint32_t) 0x001F, (uint32_t) 0x0020, (uint32_t) 0x0021, (uint32_t) 0x0022, (uint32_t) 0x0023, (uint32_t) 0x0024, (uint32_t) 0x0025, (uint32_t) 0x0026, (uint32_t) 0x0027, (uint32_t) 0x0028, (uint32_t) 0x0029, (uint32_t) 0x002A, (uint32_t) 0x002B, (uint32_t) 0x002C, (uint32_t) 0x002D, (uint32_t) 0x002E, (uint32_t) 0x002F, (uint32_t) 0x0030, (uint32_t) 0x0031, (uint32_t) 0x0032, (uint32_t) 0x0033, (uint32_t) 0x0034, (uint32_t) 0x0035, (uint32_t) 0x0036, (uint32_t) 0x0037, (uint32_t) 0x0038, (uint32_t) 0x0039, (uint32_t) 0x003A, (uint32_t) 0x003B, (uint32_t) 0x003C, (uint32_t) 0x003D, (uint32_t) 0x003E, (uint32_t) 0x003F, (uint32_t) 0x0040, (uint32_t) 0x0041, (uint32_t) 0x0042, (uint32_t) 0x0043, (uint32_t) 0x0044, (uint32_t) 0x0045, (uint32_t) 0x0046, (uint32_t) 0x0047, (uint32_t) 0x0048, (uint32_t) 0x0049, (uint32_t) 0x004A, (uint32_t) 0x004B, (uint32_t) 0x004C, (uint32_t) 0x004D, (uint32_t) 0x004E, (uint32_t) 0x004F, (uint32_t) 0x0050, (uint32_t) 0x0051, (uint32_t) 0x0052, (uint32_t) 0x0053, (uint32_t) 0x0054, (uint32_t) 0x0055, (uint32_t) 0x0056, (uint32_t) 0x0057, (uint32_t) 0x0058, (uint32_t) 0x0059, (uint32_t) 0x005A, (uint32_t) 0x005B, (uint32_t) 0x005C, (uint32_t) 0x005D, (uint32_t) 0x005E, (uint32_t) 0x005F, (uint32_t) 0x0060, (uint32_t) 0x0061, (uint32_t) 0x0062, (uint32_t) 0x0063, (uint32_t) 0x0064, (uint32_t) 0x0065, (uint32_t) 0x0066, (uint32_t) 0x0067, (uint32_t) 0x0068, (uint32_t) 0x0069, (uint32_t) 0x006A, (uint32_t) 0x006B, (uint32_t) 0x006C, (uint32_t) 0x006D, (uint32_t) 0x006E, (uint32_t) 0x006F, (uint32_t) 0x0070, (uint32_t) 0x0071, (uint32_t) 0x0072, (uint32_t) 0x0073, (uint32_t) 0x0074, (uint32_t) 0x0075, (uint32_t) 0x0076, (uint32_t) 0x0077, (uint32_t) 0x0078, (uint32_t) 0x0079, (uint32_t) 0x007A, (uint32_t) 0x007B, (uint32_t) 0x007C, (uint32_t) 0x007D, (uint32_t) 0x007E, (uint32_t) 0x007F, (uint32_t) 0x20AC, (uint32_t) 0xFFFD, /* undefined */ (uint32_t) 0x201A, (uint32_t) 0x0192, (uint32_t) 0x201E, (uint32_t) 0x2026, (uint32_t) 0x2020, (uint32_t) 0x2021, (uint32_t) 0x02C6, (uint32_t) 0x2030, (uint32_t) 0x0160, (uint32_t) 0x2039, (uint32_t) 0x0152, (uint32_t) 0xFFFD, /* undefined */ (uint32_t) 0x017D, (uint32_t) 0xFFFD, /* undefined */ (uint32_t) 0xFFFD, /* undefined */ (uint32_t) 0x2018, (uint32_t) 0x2019, (uint32_t) 0x201C, (uint32_t) 0x201D, (uint32_t) 0x2022, (uint32_t) 0x2013, (uint32_t) 0x2014, (uint32_t) 0x02DC, (uint32_t) 0x2122, (uint32_t) 0x0161, (uint32_t) 0x203A, (uint32_t) 0x0153, (uint32_t) 0xFFFD, /* undefined */ (uint32_t) 0x017E, (uint32_t) 0x0178, (uint32_t) 0x00A0, (uint32_t) 0x00A1, (uint32_t) 0x00A2, (uint32_t) 0x00A3, (uint32_t) 0x00A4, (uint32_t) 0x00A5, (uint32_t) 0x00A6, (uint32_t) 0x00A7, (uint32_t) 0x00A8, (uint32_t) 0x00A9, (uint32_t) 0x00AA, (uint32_t) 0x00AB, (uint32_t) 0x00AC, (uint32_t) 0x00AD, (uint32_t) 0x00AE, (uint32_t) 0x00AF, (uint32_t) 0x00B0, (uint32_t) 0x00B1, (uint32_t) 0x00B2, (uint32_t) 0x00B3, (uint32_t) 0x00B4, (uint32_t) 0x00B5, (uint32_t) 0x00B6, (uint32_t) 0x00B7, (uint32_t) 0x00B8, (uint32_t) 0x00B9, (uint32_t) 0x00BA, (uint32_t) 0x00BB, (uint32_t) 0x00BC, (uint32_t) 0x00BD, (uint32_t) 0x00BE, (uint32_t) 0x00BF, (uint32_t) 0x00C0, (uint32_t) 0x00C1, (uint32_t) 0x00C2, (uint32_t) 0x00C3, (uint32_t) 0x00C4, (uint32_t) 0x00C5, (uint32_t) 0x00C6, (uint32_t) 0x00C7, (uint32_t) 0x00C8, (uint32_t) 0x00C9, (uint32_t) 0x00CA, (uint32_t) 0x00CB, (uint32_t) 0x00CC, (uint32_t) 0x00CD, (uint32_t) 0x00CE, (uint32_t) 0x00CF, (uint32_t) 0x00D0, (uint32_t) 0x00D1, (uint32_t) 0x00D2, (uint32_t) 0x00D3, (uint32_t) 0x00D4, (uint32_t) 0x00D5, (uint32_t) 0x00D6, (uint32_t) 0x00D7, (uint32_t) 0x00D8, (uint32_t) 0x00D9, (uint32_t) 0x00DA, (uint32_t) 0x00DB, (uint32_t) 0x00DC, (uint32_t) 0x00DD, (uint32_t) 0x00DE, (uint32_t) 0x00DF, (uint32_t) 0x00E0, (uint32_t) 0x00E1, (uint32_t) 0x00E2, (uint32_t) 0x00E3, (uint32_t) 0x00E4, (uint32_t) 0x00E5, (uint32_t) 0x00E6, (uint32_t) 0x00E7, (uint32_t) 0x00E8, (uint32_t) 0x00E9, (uint32_t) 0x00EA, (uint32_t) 0x00EB, (uint32_t) 0x00EC, (uint32_t) 0x00ED, (uint32_t) 0x00EE, (uint32_t) 0x00EF, (uint32_t) 0x00F0, (uint32_t) 0x00F1, (uint32_t) 0x00F2, (uint32_t) 0x00F3, (uint32_t) 0x00F4, (uint32_t) 0x00F5, (uint32_t) 0x00F6, (uint32_t) 0x00F7, (uint32_t) 0x00F8, (uint32_t) 0x00F9, (uint32_t) 0x00FA, (uint32_t) 0x00FB, (uint32_t) 0x00FC, (uint32_t) 0x00FD, (uint32_t) 0x00FE, (uint32_t) 0x00FF }; lstring_t* lstr_new(const char* cstr) { return lstr_from_buf(cstr, strlen(cstr)); } lstring_t* lstr_newf(const char* fmt, ...) { va_list ap; lstring_t* string = NULL; va_start(ap, fmt); string = lstr_vnewf(fmt, ap); va_end(ap); return string; } lstring_t* lstr_vnewf(const char* fmt, va_list args) { va_list ap; char* buffer; int buf_size; lstring_t* string = NULL; va_copy(ap, args); buf_size = vsnprintf(NULL, 0, fmt, ap) + 1; va_end(ap); buffer = malloc(buf_size); va_copy(ap, args); vsnprintf(buffer, buf_size, fmt, ap); va_end(ap); string = lstr_from_buf(buffer, buf_size - 1); free(buffer); return string; } lstring_t* lstr_from_buf(const char* buffer, size_t length) { // courtesy of <NAME>, adapted for use in minisphere. uint32_t cp; unsigned char* out_buf; lstring_t* string; uint32_t utf8state = UTF8_ACCEPT; unsigned char *p; const unsigned char *p_src; size_t i; // check that the string isn't already UTF-8 p_src = buffer; for (i = 0; i < length; ++i) { if (utf8decode(&utf8state, &cp, *p_src++) == UTF8_REJECT) break; } if (utf8state != UTF8_ACCEPT) { // note: UTF-8 conversion may expand the string by up to 3x if (!(string = malloc(sizeof(lstring_t) + length * 3 + 1))) return NULL; out_buf = (char*)string + sizeof(lstring_t); p = out_buf; p_src = buffer; for (i = 0; i < length; ++i) { cp = cp1252[*p_src++] & 0xffffUL; if (cp < 0x80) *p++ = cp; else if (cp < 0x800UL) { *p++ = (unsigned char)(0xc0 + ((cp >> 6) & 0x1f)); *p++ = (unsigned char)(0x80 + (cp & 0x3f)); } else { *p++ = (unsigned char)(0xe0 + ((cp >> 12) & 0x0f)); *p++ = (unsigned char)(0x80 + ((cp >> 6) & 0x3f)); *p++ = (unsigned char)(0x80 + (cp & 0x3f)); } } *p = '\0'; // fake NUL terminator length = p - out_buf; } else { // string is already UTF-8, copy buffer as-is if (!(string = malloc(sizeof(lstring_t) + length + 1))) return NULL; out_buf = (char*)string + sizeof(lstring_t); memcpy(out_buf, buffer, length); out_buf[length] = '\0'; // fake NUL terminator } string->cstr = out_buf; string->length = length; return string; } void lstr_free(lstring_t* string) { free(string); } const char* lstr_cstr(const lstring_t* string) { return string->cstr; } int lstr_cmp(const lstring_t* string1, const lstring_t* string2) { size_t length; // the fake NUL terminator comes in REALLY handy here, as we can just // include it in the comparison, saving us an extra check at the end. length = string1->length < string2->length ? string1->length + 1 : string2->length + 1; return memcmp(string1->cstr, string2->cstr, length); } lstring_t* lstr_dup(const lstring_t* string) { return lstr_from_buf(string->cstr, string->length); } size_t lstr_len(const lstring_t* string) { return string->length; } <file_sep>/src/compiler/assets.c #include "cell.h" #include "assets.h" typedef enum asset_type { ASSET_FILE, ASSET_RAW, ASSET_SGM, } asset_type_t; struct raw_info { void* buffer; size_t size; }; struct file_info { path_t* path; }; struct asset { path_t* name; path_t* object_path; time_t src_mtime; asset_type_t type; union { struct file_info file; struct raw_info data; sgm_info_t sgm; }; }; asset_t* asset_new_file(const path_t* path) { asset_t* asset; struct stat sb; if (stat(path_cstr(path), &sb) != 0) { fprintf(stderr, "ERROR: failed to stat `%s`\n", path_cstr(path)); return NULL; } asset = calloc(1, sizeof(asset_t)); asset->src_mtime = sb.st_mtime; asset->type = ASSET_FILE; asset->file.path = path_dup(path); return asset; } asset_t* asset_new_sgm(sgm_info_t sgm, time_t src_mtime) { asset_t* asset; asset = calloc(1, sizeof(asset_t)); asset->name = path_new("game.sgm"); asset->src_mtime = src_mtime; asset->type = ASSET_SGM; asset->sgm = sgm; return asset; } asset_t* asset_new_raw(const path_t* name, const void* buffer, size_t size, time_t src_mtime) { asset_t* asset; asset = calloc(1, sizeof(asset_t)); asset->name = path_dup(name); asset->src_mtime = src_mtime; asset->type = ASSET_RAW; asset->data.buffer = malloc(size); asset->data.size = size; memcpy(asset->data.buffer, buffer, size); return asset; } void asset_free(asset_t* asset) { switch (asset->type) { case ASSET_RAW: free(asset->data.buffer); break; case ASSET_FILE: path_free(asset->file.path); break; } path_free(asset->object_path); path_free(asset->name); free(asset); } bool asset_build(asset_t* asset, const path_t* staging_path, bool *out_is_new) { FILE* file; const char* filename; path_t* origin; struct stat sb; path_t* script_path; *out_is_new = false; asset->object_path = asset->type != ASSET_FILE ? path_rebase(path_dup(asset->name), staging_path) : path_dup(asset->file.path); filename = path_cstr(asset->object_path); if (stat(filename, &sb) == 0 && difftime(sb.st_mtime, asset->src_mtime) >= 0.0) return true; // asset is up-to-date *out_is_new = true; switch (asset->type) { case ASSET_FILE: // a file asset is just a direct copy from source to destination, so // there's nothing to build. return true; case ASSET_RAW: if (!fspew(asset->data.buffer, asset->data.size, filename)) goto on_error; return true; case ASSET_SGM: // SGMv1 requires the script name to be relative to ~/scripts script_path = path_new(asset->sgm.script); origin = path_new("scripts/"); path_collapse(script_path, true); path_relativize(script_path, origin); path_free(origin); // write out the manifest if (!(file = fopen(filename, "wt"))) goto on_error; fprintf(file, "name=%s\n", asset->sgm.name); fprintf(file, "author=%s\n", asset->sgm.author); fprintf(file, "description=%s\n", asset->sgm.description); fprintf(file, "screen_width=%d\n", asset->sgm.width); fprintf(file, "screen_height=%d\n", asset->sgm.height); fprintf(file, "script=%s\n", path_cstr(script_path)); fclose(file); path_free(script_path); return true; default: fprintf(stderr, "ERROR: internal: unknown asset type %d `%s`\n", asset->type, path_cstr(asset->name)); return false; } on_error: fprintf(stderr, "\nERROR: failed to build `%s`, errno = %d\n", path_cstr(asset->name), errno); return false; } const path_t* asset_name(const asset_t* asset) { return asset->name; } const path_t* asset_object_path(const asset_t* asset) { return asset->object_path; } <file_sep>/src/engine/spk.c #include "minisphere.h" #include "vector.h" #include "spk.h" struct spk { unsigned int refcount; unsigned int id; path_t* path; ALLEGRO_FILE* file; vector_t* index; }; struct spk_entry { char file_path[SPHERE_PATH_MAX]; size_t pack_size; size_t file_size; long offset; }; struct spk_file { spk_t* spk; uint8_t* buffer; char* filename; ALLEGRO_FILE* handle; }; #pragma pack(push, 1) struct spk_header { char signature[4]; uint16_t version; uint32_t num_files; uint32_t index_offset; uint8_t reserved[2]; }; struct spk_entry_hdr { uint16_t version; uint16_t filename_size; uint32_t offset; uint32_t file_size; uint32_t compress_size; }; #pragma pack(pop) static unsigned int s_next_spk_id = 0; spk_t* open_spk(const char* path) { spk_t* spk; struct spk_entry spk_entry; struct spk_entry_hdr spk_entry_hdr; struct spk_header spk_hdr; uint32_t i; console_log(2, "opening SPK #%u as `%s`", s_next_spk_id, path); spk = calloc(1, sizeof(spk_t)); if (!(spk->file = al_fopen(path, "rb"))) goto on_error; if (al_fread(spk->file, &spk_hdr, sizeof(struct spk_header)) != sizeof(struct spk_header)) goto on_error; if (memcmp(spk_hdr.signature, ".spk", 4) != 0) goto on_error; if (spk_hdr.version != 1) goto on_error; spk->path = path_new(path); // load the package index console_log(4, "reading package index for SPK #%u", s_next_spk_id); spk->index = vector_new(sizeof(struct spk_entry)); al_fseek(spk->file, spk_hdr.index_offset, ALLEGRO_SEEK_SET); for (i = 0; i < spk_hdr.num_files; ++i) { if (al_fread(spk->file, &spk_entry_hdr, sizeof(struct spk_entry_hdr)) != sizeof(struct spk_entry_hdr)) goto on_error; if (spk_entry_hdr.version != 1) goto on_error; spk_entry.pack_size = spk_entry_hdr.compress_size; spk_entry.file_size = spk_entry_hdr.file_size; spk_entry.offset = spk_entry_hdr.offset; al_fread(spk->file, spk_entry.file_path, spk_entry_hdr.filename_size); spk_entry.file_path[spk_entry_hdr.filename_size] = '\0'; if (!vector_push(spk->index, &spk_entry)) goto on_error; } spk->id = s_next_spk_id++; return ref_spk(spk); on_error: console_log(2, "failed to open SPK #%u", s_next_spk_id++); if (spk != NULL) { path_free(spk->path); if (spk->file != NULL) al_fclose(spk->file); vector_free(spk->index); free(spk); } return NULL; } spk_t* ref_spk(spk_t* spk) { ++spk->refcount; return spk; } void free_spk(spk_t* spk) { if (spk == NULL || --spk->refcount > 0) return; console_log(4, "disposing SPK #%u no longer in use", spk->id); vector_free(spk->index); al_fclose(spk->file); free(spk); } spk_file_t* spk_fopen(spk_t* spk, const char* path, const char* mode) { ALLEGRO_FILE* al_file = NULL; void* buffer = NULL; path_t* cache_path; spk_file_t* file = NULL; size_t file_size; const char* local_filename; path_t* local_path; console_log(4, "opening `%s` (%s) from SPK #%u", path, mode, spk->id); // get path to local cache file cache_path = path_rebase(path_new("minisphere/.spkcache/"), homepath()); path_append_dir(cache_path, path_filename_cstr(spk->path)); local_path = path_rebase(path_new(path), cache_path); path_free(cache_path); // ensure all subdirectories exist local_filename = path_cstr(local_path); if (mode[0] == 'w' || mode[0] == 'a' || strchr(mode, '+')) path_mkdir(local_path); if (!(file = calloc(1, sizeof(spk_file_t)))) goto on_error; if (al_filename_exists(local_filename)) { // local cache file already exists, open it directly console_log(4, "using locally cached file for #%u:`%s`", spk->id, path); if (!(al_file = al_fopen(local_filename, mode))) goto on_error; } else { if (!(buffer = spk_fslurp(spk, path, &file_size)) && mode[0] == 'r') goto on_error; if (strcmp(mode, "r") != 0 && strcmp(mode, "rb") != 0) { if (buffer != NULL && mode[0] != 'w') { // if a game requests write access to an existing file, // we extract it. this ensures file operations originating from // inside an SPK are transparent to the game. console_log(4, "extracting #%u:`%s`, write access requested", spk->id, path); if (!(al_file = al_fopen(local_filename, "w"))) goto on_error; al_fwrite(al_file, buffer, file_size); al_fclose(al_file); } free(buffer); buffer = NULL; if (!(al_file = al_fopen(local_filename, mode))) goto on_error; } else { // read-only: access unpacked file from memory (performance) if (!(al_file = al_open_memfile(buffer, file_size, mode))) goto on_error; } } path_free(local_path); file->buffer = buffer; file->filename = strdup(path); file->handle = al_file; file->spk = ref_spk(spk); return file; on_error: console_log(4, "failed to open `%s` from SPK #%u", path, spk->id); path_free(local_path); if (al_file != NULL) al_fclose(al_file); free(buffer); free(file); return NULL; } void spk_fclose(spk_file_t* file) { if (file == NULL) return; console_log(4, "closing `%s` from SPK #%u", file->filename, file->spk->id); al_fclose(file->handle); free(file->buffer); free(file->filename); free_spk(file->spk); free(file); } int spk_fputc(int ch, spk_file_t* file) { return al_fputc(file->handle, ch); } int spk_fputs(const char* string, spk_file_t* file) { return al_fputs(file->handle, string); } size_t spk_fread(void* buf, size_t size, size_t count, spk_file_t* file) { return al_fread(file->handle, buf, size * count) / size; } bool spk_fseek(spk_file_t* file, long long offset, spk_seek_origin_t origin) { return al_fseek(file->handle, offset, origin); } long long spk_ftell(spk_file_t* file) { return al_ftell(file->handle); } size_t spk_fwrite(const void* buf, size_t size, size_t count, spk_file_t* file) { return al_fwrite(file->handle, buf, size * count) / size; } void* spk_fslurp(spk_t* spk, const char* path, size_t *out_size) { struct spk_entry* fileinfo; void* packdata = NULL; void* unpacked = NULL; uLong unpack_size; iter_t iter; console_log(3, "unpacking `%s` from SPK #%u", path, spk->id); iter = vector_enum(spk->index); while (fileinfo = vector_next(&iter)) { if (strcasecmp(path, fileinfo->file_path) == 0) break; } if (fileinfo == NULL) goto on_error; if (!(packdata = malloc(fileinfo->pack_size))) goto on_error; al_fseek(spk->file, fileinfo->offset, ALLEGRO_SEEK_SET); if (al_fread(spk->file, packdata, fileinfo->pack_size) < fileinfo->pack_size) goto on_error; if (!(unpacked = malloc(fileinfo->file_size + 1))) goto on_error; unpack_size = (uLong)fileinfo->file_size; if (uncompress(unpacked, &unpack_size, packdata, (uLong)fileinfo->pack_size) != Z_OK) goto on_error; *((char*)unpacked + unpack_size) = '\0'; free(packdata); *out_size = unpack_size; return unpacked; on_error: console_log(3, "failed to unpack `%s` from SPK #%u", path, spk->id); free(packdata); free(unpacked); return NULL; } vector_t* list_spk_filenames(spk_t* spk, const char* dirname, bool want_dirs) { // HERE BE DRAGONS! // this function is kind of a monstrosity because the SPK format doesn't have // any real concept of a directory - each asset is stored with its full path // as its filename. as such we have to do some ugly parsing and de-duplication, // particularly in the case of directories. lstring_t* filename; char* found_dirname; bool is_in_set; vector_t* list; const char* maybe_dirname; const char* maybe_filename; const char* match; struct spk_entry* p_entry; iter_t iter, iter2; lstring_t** item; list = vector_new(sizeof(lstring_t*)); iter = vector_enum(spk->index); while (p_entry = vector_next(&iter)) { if (!want_dirs) { // list files if (!(match = strstr(p_entry->file_path, dirname))) continue; if (match != p_entry->file_path) continue; maybe_filename = match + strlen(dirname); if (dirname[strlen(dirname) - 1] != '/') { if (maybe_filename[0] != '/') continue; // oops, matched a partial file name ++maybe_filename; // account for directory separator } if (strchr(maybe_filename, '/')) continue; // ignore files in subdirectories // if we got to this point, we have a valid filename filename = lstr_newf("%s", maybe_filename); vector_push(list, &filename); } else { // list directories if (!(match = strstr(p_entry->file_path, dirname))) continue; if (match != p_entry->file_path) continue; maybe_dirname = match + strlen(dirname); if (dirname[strlen(dirname) - 1] != '/') { if (maybe_dirname[0] != '/') continue; // oops, matched a partial file name ++maybe_dirname; // account for directory separator } if (!(maybe_filename = strchr(maybe_dirname, '/'))) continue; // ignore files if (strchr(++maybe_filename, '/')) continue; // ignore subdirectories // if we got to this point, we have a valid directory name found_dirname = strdup(maybe_dirname); *strchr(found_dirname, '/') = '\0'; filename = lstr_newf("%s", found_dirname); iter2 = vector_enum(list); is_in_set = false; while (item = vector_next(&iter2)) { is_in_set |= lstr_cmp(filename, *item) == 0; } if (!is_in_set) // avoid duplicate listings vector_push(list, &filename); free(found_dirname); } } return list; } <file_sep>/src/shared/unicode.h #ifndef MINISPHERE__UNICODE_H__INCLUDED #define MINISPHERE__UNICODE_H__INCLUDED #include <stddef.h> #include <stdint.h> #define UTF8_ACCEPT 0 #define UTF8_REJECT 12 uint32_t utf8decode (uint32_t* state, uint32_t* codep, uint8_t byte); size_t utf8len (const char* string); #endif // MINISPHERE__UNICODE_H__INCLUDED <file_sep>/src/engine/console.h #ifndef MINISPHERE__CONSOLE_H__INCLUDED #define MINISPHERE__CONSOLE_H__INCLUDED void initialize_console (int verbosity); int get_log_verbosity (void); void console_log (int level, const char* fmt, ...); #endif // MINISPHERE__CONSOLE_H__INCLUDED <file_sep>/src/debugger/objview.h #ifndef SSJ__OBJECTVIEW_H__INCLUDED #define SSJ__OBJECTVIEW_H__INCLUDED #include "dvalue.h" typedef struct objview objview_t; typedef enum prop_tag { PROP_VALUE, PROP_ACCESSOR, } prop_tag_t; typedef enum prop_flag { PROP_WRITABLE = 1 << 0, PROP_ENUMERABLE = 1 << 1, PROP_CONFIGURABLE = 1 << 2, } prop_flag_t; objview_t* objview_new (void); void objview_free (objview_t* obj); int objview_len (const objview_t* obj); const char* objview_get_key (const objview_t* obj, int index); prop_tag_t objview_get_tag (const objview_t* obj, int index); unsigned int objview_get_flags (const objview_t* obj, int index); const dvalue_t* objview_get_getter (const objview_t* obj, int index); const dvalue_t* objview_get_setter (const objview_t* obj, int index); const dvalue_t* objview_get_value (const objview_t* obj, int index); void objview_add_accessor (objview_t* obj, const char* key, const dvalue_t* getter, const dvalue_t* setter, unsigned int flags); void objview_add_value (objview_t* obj, const char* key, const dvalue_t* value, unsigned int flags); #endif // SSJ__OBJECTVIEW_H__INCLUDED <file_sep>/src/engine/rng.h #ifndef MINISPHERE__RNG_H__INCLUDED #define MINISPHERE__RNG_H__INCLUDED void initialize_rng (void); void seed_rng (unsigned long seed); bool rng_chance (double odds); double rng_normal (double mean, double sigma); double rng_random (void); long rng_ranged (long lower, long upper); const char* rng_string (int length); double rng_uniform (double mean, double variance); void init_rng_api (void); #endif // MINISPHERE__RNG_H__INCLUDED <file_sep>/src/debugger/inferior.h #ifndef SSJ__INFERIOR_H__INCLUDED #define SSJ__INFERIOR_H__INCLUDED #include "backtrace.h" #include "message.h" #include "objview.h" #include "source.h" typedef struct inferior inferior_t; typedef enum resume_op { OP_RESUME, OP_STEP_OVER, OP_STEP_IN, OP_STEP_OUT, } resume_op_t; void inferiors_init (void); void inferiors_deinit (void); inferior_t* inferior_new (const char* hostname, int port); void inferior_free (inferior_t* obj); bool inferior_update (inferior_t* obj); bool inferior_attached (const inferior_t* obj); const char* inferior_author (const inferior_t* obj); bool inferior_running (const inferior_t* obj); const char* inferior_title (const inferior_t* obj); const backtrace_t* inferior_get_calls (inferior_t* obj); objview_t* inferior_get_object (inferior_t* obj, remote_ptr_t heapptr, bool get_all); const source_t* inferior_get_source (inferior_t* obj, const char* filename); objview_t* inferior_get_vars (inferior_t* obj, int frame); int inferior_add_breakpoint (inferior_t* obj, const char* filename, int linenum); bool inferior_clear_breakpoint (inferior_t* obj, int handle); void inferior_detach (inferior_t* obj); dvalue_t* inferior_eval (inferior_t* obj, const char* expr, int frame, bool* out_is_error); bool inferior_pause (inferior_t* obj); message_t* inferior_request (inferior_t* obj, message_t* msg); bool inferior_resume (inferior_t* obj, resume_op_t op); #endif // SSJ__INFERIOR_H__INCLUDED <file_sep>/src/debugger/ssj.h #ifndef SSJ__SSJ_H__INCLUDED #define SSJ__SSJ_H__INCLUDED #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif #include "posix.h" #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <inttypes.h> #include <string.h> #include <time.h> #if !defined(_WIN32) #include <unistd.h> #include <fcntl.h> #include <limits.h> #else #include <Shlwapi.h> #endif #include "lstring.h" #include "path.h" #include "vector.h" #include "version.h" bool launch_minisphere (path_t* game_path); char* strnewf (const char* fmt, ...); #endif // SSJ__SSJ_H__INCLUDED <file_sep>/src/engine/api.h #ifndef MINISPHERE__API_H__INCLUDED #define MINISPHERE__API_H__INCLUDED void initialize_api (duk_context* ctx); void shutdown_api (void); bool api_have_extension (const char* name); int api_level (void); void api_register_const (duk_context* ctx, const char* name, double value); void api_register_ctor (duk_context* ctx, const char* name, duk_c_function fn, duk_c_function finalizer); bool api_register_extension (const char* designation); void api_register_function (duk_context* ctx, const char* namespace_name, const char* name, duk_c_function fn); void api_register_method (duk_context* ctx, const char* ctor_name, const char* name, duk_c_function fn); void api_register_prop (duk_context* ctx, const char* ctor_name, const char* name, duk_c_function getter, duk_c_function setter); duk_bool_t duk_is_sphere_obj (duk_context* ctx, duk_idx_t index, const char* ctor_name); noreturn duk_error_ni (duk_context* ctx, int blame_offset, duk_errcode_t err_code, const char* fmt, ...); void duk_push_sphere_obj (duk_context* ctx, const char* ctor_name, void* udata); void* duk_require_sphere_obj (duk_context* ctx, duk_idx_t index, const char* ctor_name); #endif // MINISPHERE__API_H__INCLUDED <file_sep>/src/shared/vector.h #ifndef MINISPHERE__VECTOR_H__INCLUDED #define MINISPHERE__VECTOR_H__INCLUDED #include <stddef.h> #include <stdbool.h> #include <memory.h> typedef struct vector vector_t; typedef struct iter { vector_t* vector; void* ptr; ptrdiff_t index; } iter_t; vector_t* vector_new (size_t pitch); vector_t* vector_dup (const vector_t* vector); void vector_free (vector_t* vector); void vector_clear (vector_t* vector); size_t vector_len (const vector_t* vector); bool vector_push (vector_t* vector, const void* in_object); void vector_remove (vector_t* vector, size_t index); vector_t* vector_sort (vector_t* vector, int(*comparer)(const void* in_a, const void* in_b)); void* vector_get (const vector_t* vector, size_t index); void vector_set (vector_t* vector, size_t index, const void* in_object); iter_t vector_enum (vector_t* vector); void* vector_next (iter_t* inout_iter); void iter_remove (iter_t* iter); #endif // MINISPHERE__VECTOR_H__INCLUDED <file_sep>/src/engine/spherefs.h #ifndef MINISPHERE__SPHEREFS_H__INCLUDED #define MINISPHERE__SPHEREFS_H__INCLUDED #include "lstring.h" #include "path.h" #include "vector.h" typedef struct sandbox sandbox_t; typedef struct sfs_file sfs_file_t; typedef struct sfs_list sfs_list_t; typedef enum sfs_whence { SFS_SEEK_SET, SFS_SEEK_CUR, SFS_SEEK_END, } sfs_whence_t; sandbox_t* new_sandbox (const char* pathname); sandbox_t* ref_sandbox (sandbox_t* fs); void free_sandbox (sandbox_t* fs); const lstring_t* get_game_manifest (const sandbox_t* fs); const path_t* get_game_path (const sandbox_t* fs); void get_sgm_resolution (sandbox_t* fs, int *out_width, int *out_height); const char* get_sgm_name (sandbox_t* fs); const char* get_sgm_author (sandbox_t* fs); const char* get_sgm_summary (sandbox_t* fs); const path_t* get_sgm_script_path (sandbox_t* fs); vector_t* list_filenames (sandbox_t* fs, const char* dirname, const char* base_dir, bool want_dirs); path_t* make_sfs_path (const char* filename, const char* base_dir_name, bool legacy); sfs_file_t* sfs_fopen (sandbox_t* fs, const char* path, const char* base_dir, const char* mode); void sfs_fclose (sfs_file_t* file); bool sfs_fexist (sandbox_t* fs, const char* filename, const char* base_dir); int sfs_fputc (int ch, sfs_file_t* file); int sfs_fputs (const char* string, sfs_file_t* file); size_t sfs_fread (void* buf, size_t size, size_t count, sfs_file_t* file); bool sfs_fseek (sfs_file_t* file, long long offset, sfs_whence_t whence); bool sfs_fspew (sandbox_t* fs, const char* filename, const char* base_dir, void* buf, size_t size); void* sfs_fslurp (sandbox_t* fs, const char* filename, const char* base_dir, size_t *out_size); long long sfs_ftell (sfs_file_t* file); size_t sfs_fwrite (const void* buf, size_t size, size_t count, sfs_file_t* file); bool sfs_mkdir (sandbox_t* fs, const char* dirname, const char* base_dir); bool sfs_rmdir (sandbox_t* fs, const char* dirname, const char* base_dir); bool sfs_rename (sandbox_t* fs, const char* filename1, const char* filename2, const char* base_dir); bool sfs_unlink (sandbox_t* fs, const char* filename, const char* base_dir); #endif // MINISPHERE__SPHEREFS_H__INCLUDED <file_sep>/src/engine/screen.h #ifndef MINISPHERE__DISPLAY_H__INCLUDED #define MINISPHERE__DISPLAY_H__INCLUDED #include "image.h" #include "matrix.h" typedef struct screen screen_t; screen_t* screen_new (const char* title, image_t* icon, int x_size, int y_size, int frameskip, bool avoid_sleep); void screen_free (screen_t* obj); ALLEGRO_DISPLAY* screen_display (const screen_t* obj); bool screen_have_shaders (const screen_t* screen); bool screen_is_skipframe (const screen_t* obj); rect_t screen_get_clipping (screen_t* obj); int screen_get_frameskip (const screen_t* obj); void screen_get_mouse_xy (const screen_t* obj, int* o_x, int* o_y); void screen_set_clipping (screen_t* obj, rect_t clip_rect); void screen_set_frameskip (screen_t* obj, int max_skips); void screen_set_mouse_xy (screen_t* obj, int x, int y); void screen_draw_status (screen_t* obj, const char* text); void screen_flip (screen_t* obj, int framerate); image_t* screen_grab (screen_t* obj, int x, int y, int width, int height); void screen_queue_screenshot (screen_t* obj); void screen_resize (screen_t* obj, int x_size, int y_size); void screen_show_mouse (screen_t* obj, bool visible); void screen_toggle_fps (screen_t* obj); void screen_toggle_fullscreen (screen_t* obj); void screen_transform (screen_t* obj, const matrix_t* matrix); void screen_unskip_frame (screen_t* obj); void init_screen_api (void); #endif // MINISPHERE__DISPLAY_H__INCLUDED <file_sep>/src/engine/geometry.c #include "minisphere.h" #include "geometry.h" rect_t new_rect(int x1, int y1, int x2, int y2) { rect_t rectangle; rectangle.x1 = x1; rectangle.y1 = y1; rectangle.x2 = x2; rectangle.y2 = y2; return rectangle; } float_rect_t new_float_rect(float x1, float y1, float x2, float y2) { float_rect_t rectangle; rectangle.x1 = x1; rectangle.y1 = y1; rectangle.x2 = x2; rectangle.y2 = y2; return rectangle; } bool do_lines_intersect(rect_t a, rect_t b) { float d, q, r, s; q = (a.y1 - b.y1) * (b.x2 - b.x1) - (a.x1 - b.x1) * (b.y2 - b.y1); d = (a.x2 - a.x1) * (b.y2 - b.y1) - (a.y2 - a.y1) * (b.x2 - b.x1); if (d == 0) return false; r = q / d; q = (a.y1 - b.y1) * (a.x2 - a.x1) - (a.x1 - b.x1) * (a.y2 - a.y1); s = q / d; return !(r < 0 || r > 1 || s < 0 || s > 1); } bool do_rects_intersect(rect_t a, rect_t b) { return !(a.x1 > b.x2 || a.x2 < b.x1 || a.y1 > b.y2 || a.y2 < b.y1); } bool is_point_in_rect(int x, int y, rect_t bounds) { return x >= bounds.x1 && x < bounds.x2 && y >= bounds.y1 && y < bounds.y2; } void normalize_rect(rect_t* inout_rect) { int tmp; if (inout_rect->x1 > inout_rect->x2) { tmp = inout_rect->x1; inout_rect->x1 = inout_rect->x2; inout_rect->x2 = tmp; } if (inout_rect->y1 > inout_rect->y2) { tmp = inout_rect->y1; inout_rect->y1 = inout_rect->y2; inout_rect->y2 = tmp; } } float_rect_t scale_float_rect(float_rect_t rect, float x_scale, float y_scale) { return new_float_rect( rect.x1 * x_scale, rect.y1 * y_scale, rect.x2 * x_scale, rect.y2 * y_scale); } rect_t translate_rect(rect_t rect, int x_offset, int y_offset) { return new_rect( rect.x1 + x_offset, rect.y1 + y_offset, rect.x2 + x_offset, rect.y2 + y_offset); } float_rect_t translate_float_rect(float_rect_t rect, float x_offset, float y_offset) { return new_float_rect( rect.x1 + x_offset, rect.y1 + y_offset, rect.x2 + x_offset, rect.y2 + y_offset); } rect_t zoom_rect(rect_t rect, double scale_x, double scale_y) { return new_rect( rect.x1 * scale_x, rect.y1 * scale_y, rect.x2 * scale_x, rect.y2 * scale_y); } bool fread_rect_16(sfs_file_t* file, rect_t* out_rect) { int16_t x1, y1, x2, y2; if (sfs_fread(&x1, 2, 1, file) != 1) return false; if (sfs_fread(&y1, 2, 1, file) != 1) return false; if (sfs_fread(&x2, 2, 1, file) != 1) return false; if (sfs_fread(&y2, 2, 1, file) != 1) return false; out_rect->x1 = x1; out_rect->y1 = y1; out_rect->x2 = x2; out_rect->y2 = y2; return true; } bool fread_rect_32(sfs_file_t* file, rect_t* out_rect) { int32_t x1, y1, x2, y2; if (sfs_fread(&x1, 4, 1, file) != 1) return false; if (sfs_fread(&y1, 4, 1, file) != 1) return false; if (sfs_fread(&x2, 4, 1, file) != 1) return false; if (sfs_fread(&y2, 4, 1, file) != 1) return false; out_rect->x1 = x1; out_rect->y1 = y1; out_rect->x2 = x2; out_rect->y2 = y2; return true; } <file_sep>/src/engine/transpiler.c #include "minisphere.h" #include "transpiler.h" #include "debugger.h" static bool load_coffeescript (void); static bool load_typescript (void); void initialize_transpiler(void) { console_log(1, "initializing JS transpiler"); load_coffeescript(); load_typescript(); } void shutdown_transpiler(void) { console_log(1, "shutting down JS transpiler"); } bool transpile_to_js(lstring_t** p_source, const char* filename) { const char* extension; lstring_t* js_text; // is it a CoffeeScript file? you know, I don't even like coffee. // now, Monster drinks on the other hand... extension = strrchr(filename, '.'); if (extension != NULL && strcasecmp(extension, ".coffee") == 0) { if (!duk_get_global_string(g_duk, "CoffeeScript")) { duk_pop(g_duk); duk_push_error_object(g_duk, DUK_ERR_ERROR, "no CoffeeScript support (%s)", filename); goto on_error; } duk_get_prop_string(g_duk, -1, "compile"); duk_push_lstring_t(g_duk, *p_source); duk_push_object(g_duk); duk_push_string(g_duk, filename); duk_put_prop_string(g_duk, -2, "filename"); duk_push_true(g_duk); duk_put_prop_string(g_duk, -2, "bare"); if (duk_pcall(g_duk, 2) != DUK_EXEC_SUCCESS) { duk_remove(g_duk, -2); // remove `CoffeeScript` from stack goto on_error; } js_text = duk_require_lstring_t(g_duk, -1); cache_source(filename, js_text); duk_pop_2(g_duk); lstr_free(*p_source); *p_source = js_text; } // TypeScript? else if (extension != NULL && strcasecmp(extension, ".ts") == 0) { if (!duk_get_global_string(g_duk, "ts")) { duk_pop(g_duk); duk_push_error_object(g_duk, DUK_ERR_ERROR, "no TypeScript support (%s)", filename); goto on_error; } duk_get_prop_string(g_duk, -1, "transpile"); duk_push_lstring_t(g_duk, *p_source); duk_push_object(g_duk); duk_push_boolean(g_duk, true); duk_put_prop_string(g_duk, -2, "noImplicitUseStrict"); duk_push_string(g_duk, filename); if (duk_pcall(g_duk, 3) != DUK_EXEC_SUCCESS) { duk_remove(g_duk, -2); // remove `ts` from stack goto on_error; } js_text = duk_require_lstring_t(g_duk, -1); cache_source(filename, js_text); duk_pop_2(g_duk); lstr_free(*p_source); *p_source = js_text; } return true; on_error: // note: when we return false, the caller expects the JS error which caused the // operation to fail to be left on top of the Duktape value stack. return false; } static bool load_coffeescript(void) { if (sfs_fexist(g_fs, "#/coffee-script.js", NULL)) { if (evaluate_script("#/coffee-script.js")) { if (!duk_get_global_string(g_duk, "CoffeeScript")) { duk_pop_2(g_duk); console_log(1, " 'CoffeeScript' not defined"); goto on_error; } duk_get_prop_string(g_duk, -1, "VERSION"); console_log(1, " CoffeeScript %s", duk_get_string(g_duk, -1)); duk_pop_3(g_duk); } else { console_log(1, " error evaluating coffee-script.js"); console_log(1, " %s", duk_to_string(g_duk, -1)); duk_pop(g_duk); goto on_error; } } else { console_log(1, " coffee-script.js is missing"); goto on_error; } return true; on_error: console_log(1, " CoffeeScript support not enabled"); return false; } static bool load_typescript(void) { if (sfs_fexist(g_fs, "#/typescriptServices.js", NULL)) { if (evaluate_script("#/typescriptServices.js")) { if (!duk_get_global_string(g_duk, "ts")) { duk_pop_2(g_duk); console_log(1, " 'ts' not defined"); goto on_error; } duk_get_prop_string(g_duk, -1, "version"); console_log(1, " TypeScript %s", duk_get_string(g_duk, -1)); duk_pop_3(g_duk); } else { console_log(1, " error evaluating typescriptServices.js"); console_log(1, " %s", duk_to_string(g_duk, -1)); duk_pop(g_duk); goto on_error; } } else { console_log(1, " typescriptServices.js is missing"); goto on_error; } return true; on_error: console_log(1, " TypeScript support not enabled"); return false; } <file_sep>/assets/system/modules/miniRT/music.js /** * miniRT/music CommonJS module * a stack-based solution for managing background music * (c) 2015-2016 <NAME> **/ if (typeof exports === 'undefined') { throw new TypeError("script must be loaded with require()"); } const console = require('./console'); const scenes = require('./scenes'); var music = module.exports = (function() { var adjuster = null; var currentSound = null; var haveOverride = false; var mixer = new Mixer(44100, 16, 2); var oldSounds = []; var topmostSound = null; console.register('bgm', null, { 'adjust': function(volume, fadeTime) { adjust(volume, fadeTime); }, 'override': function(trackName, fadeTime) { try { override(trackName, fadeTime); } catch(e) { console.write("error playing `" + trackName + "`"); } }, 'play': function(trackName, fadeTime) { try { play(trackName, fadeTime); } catch(e) { console.write("error playing `" + trackName + "`"); } }, 'pop': function(fadeTime) { pop(fadeTime); }, 'push': function(trackName, fadeTime) { try { push(trackName, fadeTime); } catch(e) { console.write("error playing `" + trackName + "`"); } }, 'reset': function(fadeTime) { reset(fadeTime); }, 'stop': function(fadeTime) { play(null, fadeTime); }, }); return { isAdjusting: isAdjusting, adjust: adjust, override: override, play: play, pop: pop, push: push, reset: reset, }; function crossfade(path, fadeTime, forceChange) { fadeTime = fadeTime !== undefined ? fadeTime : 0.0; var allowChange = !haveOverride || forceChange; if (currentSound != null && allowChange) { currentSound.fader.stop(); currentSound.fader = new scenes.Scene() .tween(currentSound.stream, fadeTime, 'linear', { volume: 0.0 }) .run(); } if (path !== null) { var stream = new Sound(path, mixer); stream.volume = 0.0; stream.play(true); var fader = new scenes.Scene() .tween(stream, fadeTime, 'linear', { volume: 1.0 }) var newSound = { stream: stream, fader: fader }; if (allowChange) { currentSound = newSound; newSound.fader.run(); } return newSound; } else { return null; } } // music.isAdjusting() // get whether or not the volume level is being adjusted. function isAdjusting() { return adjuster != null && adjuster.isRunning(); }; // music.adjust() // Smoothly adjusts the volume of the current BGM. // Arguments: // newVolume: The new volume level, between 0.0 and 1.0 inclusive. // duration: Optional. The length of time, in seconds, over which to perform the adjustment. // (default: 0.0). function adjust(newVolume, duration) { duration = duration !== undefined ? duration : 0.0; newVolume = Math.min(Math.max(newVolume, 0.0), 1.0); if (adjuster != null && adjuster.isRunning()) { adjuster.stop(); } if (duration > 0.0) { adjuster = new scenes.Scene() .tween(mixer, duration, 'linear', { volume: newVolume }) .run(); } else { mixer.volume = newVolume; } }; // music.override() // override the BGM with a given track. push, pop and play operations // will be deferred until the BGM is reset by calling music.reset(). function override(path, fadeTime) { crossfade(path, fadeTime, true); haveOverride = true; }; // music.play() // change the BGM in-place, bypassing the stack. // Arguments: // path: the SphereFS-compliant path of the sound file to play. this may be // null, in which case the BGM is silenced. // fadeTime: optional. the amount of crossfade to apply, in seconds. (default: 0.0) function play(path, fadeTime) { fadeTime = fadeTime !== undefined ? fadeTime : 0.0; topmostSound = crossfade(path, fadeTime, false); }; // music.pop() // pop the previous BGM off the stack and resume playing it. // arguments: // fadeTime: optional. the amount of crossfade to apply, in seconds. (default: 0.0) // remarks: // if the BGM stack is empty, this is a no-op. function pop(fadeTime) { fadeTime = fadeTime !== undefined ? fadeTime : 0.0; if (oldSounds.length == 0) return; currentSound.fader.stop(); currentSound.fader = new scenes.Scene() .tween(currentSound.stream, fadeTime, 'linear', { volume: 0.0 }) .run(); topmostSound = oldSounds.pop(); currentSound = topmostSound; if (currentSound !== null) { currentSound.stream.volume = 0.0; currentSound.stream.play(); currentSound.fader.stop(); currentSound.fader = new scenes.Scene() .tween(currentSound.stream, fadeTime, 'linear', { volume: 1.0 }) .run(); } } // music.push() // push the current BGM onto the stack and begin playing another track. the // previous BGM can be resumed by calling music.pop(). // arguments: // path: the SphereFS path of the sound file to play // fadeTime: optional. the amount of crossfade to apply, in seconds. (default: 0.0) function push(path, fadeTime) { var oldSound = topmostSound; play(path, fadeTime); oldSounds.push(oldSound); }; // music.reset() // reset the BGM manager, which removes any outstanding overrides. function reset(fadeTime) { fadeTime = fadeTime !== undefined ? fadeTime : 0.0; if (!haveOverride) return; haveOverride = false; currentSound.fader.stop(); currentSound.fader = new scenes.Scene() .tween(currentSound.stream, fadeTime, 'linear', { volume: 0.0 }) .run(); currentSound = topmostSound; if (currentSound !== null) { currentSound.stream.volume = 0.0; currentSound.stream.play(); currentSound.fader.stop(); currentSound.fader = new scenes.Scene() .tween(currentSound.stream, fadeTime, 'linear', { volume: 1.0 }) .run(); } }; })(); <file_sep>/src/engine/file.c #include "minisphere.h" #include "api.h" #include "bytearray.h" #include "file.h" static duk_ret_t js_DoesFileExist (duk_context* ctx); static duk_ret_t js_GetDirectoryList (duk_context* ctx); static duk_ret_t js_GetFileList (duk_context* ctx); static duk_ret_t js_CreateDirectory (duk_context* ctx); static duk_ret_t js_HashRawFile (duk_context* ctx); static duk_ret_t js_RemoveDirectory (duk_context* ctx); static duk_ret_t js_RemoveFile (duk_context* ctx); static duk_ret_t js_Rename (duk_context* ctx); static duk_ret_t js_OpenFile (duk_context* ctx); static duk_ret_t js_new_KevFile (duk_context* ctx); static duk_ret_t js_KevFile_finalize (duk_context* ctx); static duk_ret_t js_KevFile_toString (duk_context* ctx); static duk_ret_t js_KevFile_get_numKeys (duk_context* ctx); static duk_ret_t js_KevFile_getKey (duk_context* ctx); static duk_ret_t js_KevFile_close (duk_context* ctx); static duk_ret_t js_KevFile_flush (duk_context* ctx); static duk_ret_t js_KevFile_read (duk_context* ctx); static duk_ret_t js_KevFile_write (duk_context* ctx); static duk_ret_t js_OpenRawFile (duk_context* ctx); static duk_ret_t js_new_RawFile (duk_context* ctx); static duk_ret_t js_RawFile_finalize (duk_context* ctx); static duk_ret_t js_RawFile_toString (duk_context* ctx); static duk_ret_t js_RawFile_get_position (duk_context* ctx); static duk_ret_t js_RawFile_set_position (duk_context* ctx); static duk_ret_t js_RawFile_get_size (duk_context* ctx); static duk_ret_t js_RawFile_close (duk_context* ctx); static duk_ret_t js_RawFile_read (duk_context* ctx); static duk_ret_t js_RawFile_readString (duk_context* ctx); static duk_ret_t js_RawFile_write (duk_context* ctx); static duk_ret_t js_new_FileStream (duk_context* ctx); static duk_ret_t js_FileStream_finalize (duk_context* ctx); static duk_ret_t js_FileStream_get_position (duk_context* ctx); static duk_ret_t js_FileStream_set_position (duk_context* ctx); static duk_ret_t js_FileStream_get_length (duk_context* ctx); static duk_ret_t js_FileStream_close (duk_context* ctx); static duk_ret_t js_FileStream_read (duk_context* ctx); static duk_ret_t js_FileStream_readDouble (duk_context* ctx); static duk_ret_t js_FileStream_readFloat (duk_context* ctx); static duk_ret_t js_FileStream_readInt (duk_context* ctx); static duk_ret_t js_FileStream_readPString (duk_context* ctx); static duk_ret_t js_FileStream_readString (duk_context* ctx); static duk_ret_t js_FileStream_readUInt (duk_context* ctx); static duk_ret_t js_FileStream_write (duk_context* ctx); static duk_ret_t js_FileStream_writeDouble (duk_context* ctx); static duk_ret_t js_FileStream_writeFloat (duk_context* ctx); static duk_ret_t js_FileStream_writeInt (duk_context* ctx); static duk_ret_t js_FileStream_writePString (duk_context* ctx); static duk_ret_t js_FileStream_writeString (duk_context* ctx); static duk_ret_t js_FileStream_writeUInt (duk_context* ctx); struct kevfile { unsigned int id; sandbox_t* fs; ALLEGRO_CONFIG* conf; char* filename; bool is_dirty; }; static bool read_vsize_int (sfs_file_t* file, intmax_t* p_value, int size, bool little_endian); static bool read_vsize_uint (sfs_file_t* file, intmax_t* p_value, int size, bool little_endian); static bool write_vsize_int (sfs_file_t* file, intmax_t value, int size, bool little_endian); static bool write_vsize_uint (sfs_file_t* file, intmax_t value, int size, bool little_endian); static unsigned int s_next_file_id = 0; kevfile_t* kev_open(sandbox_t* fs, const char* filename, bool can_create) { kevfile_t* file; ALLEGRO_FILE* memfile = NULL; void* slurp; size_t slurp_size; console_log(2, "opening kevfile #%u as `%s`", s_next_file_id, filename); file = calloc(1, sizeof(kevfile_t)); if (slurp = sfs_fslurp(fs, filename, NULL, &slurp_size)) { memfile = al_open_memfile(slurp, slurp_size, "rb"); if (!(file->conf = al_load_config_file_f(memfile))) goto on_error; al_fclose(memfile); free(slurp); } else { console_log(3, " `%s` doesn't exist", filename); if (!can_create || !(file->conf = al_create_config())) goto on_error; } file->fs = ref_sandbox(fs); file->filename = strdup(filename); file->id = s_next_file_id++; return file; on_error: console_log(2, " failed to open kevfile #%u", s_next_file_id++); if (memfile != NULL) al_fclose(memfile); if (file->conf != NULL) al_destroy_config(file->conf); free(file); return NULL; } void kev_close(kevfile_t* file) { if (file == NULL) return; console_log(3, "disposing kevfile #%u no longer in use", file->id); if (file->is_dirty) kev_save(file); al_destroy_config(file->conf); free_sandbox(file->fs); free(file); } int kev_num_keys(kevfile_t* file) { ALLEGRO_CONFIG_ENTRY* iter; const char* key; int sum; sum = 0; key = al_get_first_config_entry(file->conf, NULL, &iter); while (key != NULL) { ++sum; key = al_get_next_config_entry(&iter); } return sum; } const char* kev_get_key(kevfile_t* file, int index) { ALLEGRO_CONFIG_ENTRY* iter; const char* name; int i = 0; name = al_get_first_config_entry(file->conf, NULL, &iter); while (name != NULL) { if (i == index) return name; ++i; name = al_get_next_config_entry(&iter); } return NULL; } bool kev_read_bool(kevfile_t* file, const char* key, bool def_value) { const char* string; bool value; string = kev_read_string(file, key, def_value ? "true" : "false"); value = strcasecmp(string, "true") == 0; return value; } double kev_read_float(kevfile_t* file, const char* key, double def_value) { char def_string[500]; const char* string; double value; sprintf(def_string, "%g", def_value); string = kev_read_string(file, key, def_string); value = atof(string); return value; } const char* kev_read_string(kevfile_t* file, const char* key, const char* def_value) { const char* value; console_log(2, "reading key `%s` from kevfile #%u", key, file->id); if (!(value = al_get_config_value(file->conf, NULL, key))) value = def_value; return value; } bool kev_save(kevfile_t* file) { void* buffer = NULL; size_t file_size; bool is_aok = false; ALLEGRO_FILE* memfile; size_t next_buf_size; sfs_file_t* sfs_file = NULL; console_log(3, "saving kevfile #%u as `%s`", file->id, file->filename); next_buf_size = 4096; while (!is_aok) { buffer = realloc(buffer, next_buf_size); memfile = al_open_memfile(buffer, next_buf_size, "wb"); next_buf_size *= 2; al_save_config_file_f(memfile, file->conf); is_aok = !al_feof(memfile); file_size = al_ftell(memfile); al_fclose(memfile); memfile = NULL; } if (!(sfs_file = sfs_fopen(file->fs, file->filename, NULL, "wt"))) goto on_error; sfs_fwrite(buffer, file_size, 1, sfs_file); sfs_fclose(sfs_file); free(buffer); return true; on_error: if (memfile != NULL) al_fclose(memfile); sfs_fclose(sfs_file); free(buffer); return false; } void kev_write_bool(kevfile_t* file, const char* key, bool value) { console_log(3, "writing boolean to kevfile #%u, key `%s`", file->id, key); al_set_config_value(file->conf, NULL, key, value ? "true" : "false"); file->is_dirty = true; } void kev_write_float(kevfile_t* file, const char* key, double value) { char string[500]; console_log(3, "writing number to kevfile #%u, key `%s`", file->id, key); sprintf(string, "%g", value); al_set_config_value(file->conf, NULL, key, string); file->is_dirty = true; } void kev_write_string(kevfile_t* file, const char* key, const char* value) { console_log(3, "writing string to kevfile #%u, key `%s`", file->id, key); al_set_config_value(file->conf, NULL, key, value); file->is_dirty = true; } static bool read_vsize_int(sfs_file_t* file, intmax_t* p_value, int size, bool little_endian) { // NOTE: supports decoding values up to 48-bit (6 bytes). don't specify // size > 6 unless you want a segfault! uint8_t data[6]; int mul = 1; int i; if (sfs_fread(data, 1, size, file) != size) return false; // variable-sized int decoding adapted from Node.js if (little_endian) { *p_value = data[i = 0]; while (++i < size && (mul *= 0x100)) *p_value += data[i] * mul; } else { *p_value = data[i = size - 1]; while (i > 0 && (mul *= 0x100)) *p_value += data[--i] * mul; } if (*p_value >= mul * 0x80) *p_value -= pow(2, 8 * size); return true; } static bool read_vsize_uint(sfs_file_t* file, intmax_t* p_value, int size, bool little_endian) { // NOTE: supports decoding values up to 48-bit (6 bytes). don't specify // size > 6 unless you want a segfault! uint8_t data[6]; int mul = 1; int i; if (sfs_fread(data, 1, size, file) != size) return false; // variable-sized uint decoding adapted from Node.js if (little_endian) { *p_value = data[i = 0]; while (++i < size && (mul *= 0x100)) *p_value += data[i] * mul; } else { *p_value = data[--size]; while (size > 0 && (mul *= 0x100)) *p_value += data[--size] * mul; } return true; } static bool write_vsize_int(sfs_file_t* file, intmax_t value, int size, bool little_endian) { // NOTE: supports encoding values up to 48-bit (6 bytes). don't specify // size > 6 unless you want a segfault! uint8_t data[6]; int mul = 1; int sub = 0; int i; // variable-sized int encoding adapted from Node.js if (little_endian) { data[i = 0] = value & 0xFF; while (++i < size && (mul *= 0x100)) { if (value < 0 && sub == 0 && data[i - 1] != 0) sub = 1; data[i] = (value / mul - sub) & 0xFF; } } else { data[i = size - 1] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub == 0 && data[i + 1] != 0) sub = 1; data[i] = (value / mul - sub) & 0xFF; } } return sfs_fwrite(data, 1, size, file) == size; } static bool write_vsize_uint(sfs_file_t* file, intmax_t value, int size, bool little_endian) { // NOTE: supports encoding values up to 48-bit (6 bytes). don't specify // size > 6 unless you want a segfault! uint8_t data[6]; int mul = 1; int i; // variable-sized uint encoding adapted from Node.js if (little_endian) { data[i = 0] = value & 0xFF; while (++i < size && (mul *= 0x100)) data[i] = (value / mul) & 0xFF; } else { data[i = size - 1] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) data[i] = (value / mul) & 0xFF; } return sfs_fwrite(data, 1, size, file) == size; } void init_file_api(void) { // File API functions api_register_method(g_duk, NULL, "DoesFileExist", js_DoesFileExist); api_register_method(g_duk, NULL, "GetDirectoryList", js_GetDirectoryList); api_register_method(g_duk, NULL, "GetFileList", js_GetFileList); api_register_method(g_duk, NULL, "CreateDirectory", js_CreateDirectory); api_register_method(g_duk, NULL, "HashRawFile", js_HashRawFile); api_register_method(g_duk, NULL, "RemoveDirectory", js_RemoveDirectory); api_register_method(g_duk, NULL, "RemoveFile", js_RemoveFile); api_register_method(g_duk, NULL, "Rename", js_Rename); // File object api_register_method(g_duk, NULL, "OpenFile", js_OpenFile); api_register_ctor(g_duk, "KevFile", js_new_KevFile, js_KevFile_finalize); api_register_prop(g_duk, "KevFile", "numKeys", js_KevFile_get_numKeys, NULL); api_register_method(g_duk, "KevFile", "toString", js_KevFile_toString); api_register_method(g_duk, "KevFile", "getKey", js_KevFile_getKey); api_register_method(g_duk, "KevFile", "getNumKeys", js_KevFile_get_numKeys); api_register_method(g_duk, "KevFile", "close", js_KevFile_close); api_register_method(g_duk, "KevFile", "flush", js_KevFile_flush); api_register_method(g_duk, "KevFile", "read", js_KevFile_read); api_register_method(g_duk, "KevFile", "write", js_KevFile_write); // RawFile object api_register_method(g_duk, NULL, "OpenRawFile", js_OpenRawFile); api_register_ctor(g_duk, "RawFile", js_new_RawFile, js_RawFile_finalize); api_register_method(g_duk, "RawFile", "toString", js_RawFile_toString); api_register_prop(g_duk, "RawFile", "length", js_RawFile_get_size, NULL); api_register_prop(g_duk, "RawFile", "position", js_RawFile_get_position, js_RawFile_set_position); api_register_prop(g_duk, "RawFile", "size", js_RawFile_get_size, NULL); api_register_method(g_duk, "RawFile", "getPosition", js_RawFile_get_position); api_register_method(g_duk, "RawFile", "setPosition", js_RawFile_set_position); api_register_method(g_duk, "RawFile", "getSize", js_RawFile_get_size); api_register_method(g_duk, "RawFile", "close", js_RawFile_close); api_register_method(g_duk, "RawFile", "read", js_RawFile_read); api_register_method(g_duk, "RawFile", "readString", js_RawFile_readString); api_register_method(g_duk, "RawFile", "write", js_RawFile_write); // FileStream object api_register_ctor(g_duk, "FileStream", js_new_FileStream, js_FileStream_finalize); api_register_prop(g_duk, "FileStream", "length", js_FileStream_get_length, NULL); api_register_prop(g_duk, "FileStream", "position", js_FileStream_get_position, js_FileStream_set_position); api_register_prop(g_duk, "FileStream", "size", js_FileStream_get_length, NULL); api_register_method(g_duk, "FileStream", "close", js_FileStream_close); api_register_method(g_duk, "FileStream", "read", js_FileStream_read); api_register_method(g_duk, "FileStream", "readDouble", js_FileStream_readDouble); api_register_method(g_duk, "FileStream", "readFloat", js_FileStream_readFloat); api_register_method(g_duk, "FileStream", "readInt", js_FileStream_readInt); api_register_method(g_duk, "FileStream", "readPString", js_FileStream_readPString); api_register_method(g_duk, "FileStream", "readString", js_FileStream_readString); api_register_method(g_duk, "FileStream", "readUInt", js_FileStream_readUInt); api_register_method(g_duk, "FileStream", "write", js_FileStream_write); api_register_method(g_duk, "FileStream", "writeDouble", js_FileStream_writeDouble); api_register_method(g_duk, "FileStream", "writeFloat", js_FileStream_writeFloat); api_register_method(g_duk, "FileStream", "writeInt", js_FileStream_writeInt); api_register_method(g_duk, "FileStream", "writePString", js_FileStream_writePString); api_register_method(g_duk, "FileStream", "writeString", js_FileStream_writeString); api_register_method(g_duk, "FileStream", "writeUInt", js_FileStream_writeUInt); } static duk_ret_t js_DoesFileExist(duk_context* ctx) { const char* filename; filename = duk_require_path(ctx, 0, NULL, true); duk_push_boolean(ctx, sfs_fexist(g_fs, filename, NULL)); return 1; } static duk_ret_t js_GetDirectoryList(duk_context* ctx) { int n_args = duk_get_top(ctx); const char* dirname = n_args >= 1 ? duk_require_path(ctx, 0, NULL, true) : ""; vector_t* list; lstring_t* *p_filename; iter_t iter; list = list_filenames(g_fs, dirname, NULL, true); duk_push_array(ctx); iter = vector_enum(list); while (p_filename = vector_next(&iter)) { duk_push_string(ctx, lstr_cstr(*p_filename)); duk_put_prop_index(ctx, -2, (duk_uarridx_t)iter.index); lstr_free(*p_filename); } vector_free(list); return 1; } static duk_ret_t js_GetFileList(duk_context* ctx) { const char* directory_name; vector_t* list; int num_args; iter_t iter; lstring_t* *p_filename; num_args = duk_get_top(ctx); directory_name = num_args >= 1 ? duk_require_path(ctx, 0, NULL, true) : "save"; list = list_filenames(g_fs, directory_name, NULL, false); duk_push_array(ctx); iter = vector_enum(list); while (p_filename = vector_next(&iter)) { duk_push_string(ctx, lstr_cstr(*p_filename)); duk_put_prop_index(ctx, -2, (duk_uarridx_t)iter.index); lstr_free(*p_filename); } vector_free(list); return 1; } static duk_ret_t js_CreateDirectory(duk_context* ctx) { const char* name; name = duk_require_path(ctx, 0, "save", true); if (!sfs_mkdir(g_fs, name, NULL)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "CreateDirectory(): unable to create directory `%s`", name); return 0; } static duk_ret_t js_HashRawFile(duk_context* ctx) { sfs_file_t* file; const char* filename; filename = duk_require_path(ctx, 0, NULL, true); file = sfs_fopen(g_fs, filename, "other", "rb"); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "HashRawFile(): unable to open file `%s` for reading"); sfs_fclose(file); // TODO: implement raw file hashing duk_error_ni(ctx, -1, DUK_ERR_ERROR, "HashRawFile(): function is not yet implemented"); } static duk_ret_t js_RemoveDirectory(duk_context* ctx) { const char* name; name = duk_require_path(ctx, 0, "save", true); if (!sfs_rmdir(g_fs, name, NULL)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "CreateDirectory(): unable to remove directory `%s`", name); return 0; } static duk_ret_t js_RemoveFile(duk_context* ctx) { const char* filename; filename = duk_require_path(ctx, 0, "save", true); if (!sfs_unlink(g_fs, filename, NULL)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RemoveFile(): unable to delete file `%s`", filename); return 0; } static duk_ret_t js_Rename(duk_context* ctx) { const char* name1; const char* name2; name1 = duk_require_path(ctx, 0, "save", true); name2 = duk_require_path(ctx, 1, "save", true); if (!sfs_rename(g_fs, name1, name2, NULL)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Rename(): unable to rename file `%s` to `%s`", name1, name2); return 0; } static duk_ret_t js_OpenFile(duk_context* ctx) { kevfile_t* file; const char* filename; filename = duk_require_path(ctx, 0, "save", true); if (!(file = kev_open(g_fs, filename, true))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "OpenFile(): unable to create or open file `%s`", filename); duk_push_sphere_obj(ctx, "KevFile", file); return 1; } static duk_ret_t js_new_KevFile(duk_context* ctx) { kevfile_t* file; const char* filename; filename = duk_require_path(ctx, 0, NULL, false); if (!(file = kev_open(g_fs, filename, true))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "File(): unable to create or open file `%s`", filename); duk_push_sphere_obj(ctx, "KevFile", file); return 1; } static duk_ret_t js_KevFile_finalize(duk_context* ctx) { kevfile_t* file; file = duk_require_sphere_obj(ctx, 0, "KevFile"); kev_close(file); return 0; } static duk_ret_t js_KevFile_toString(duk_context* ctx) { duk_push_string(ctx, "[object file]"); return 1; } static duk_ret_t js_KevFile_get_numKeys(duk_context* ctx) { kevfile_t* file; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "KevFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "File:getNumKeys(): file was closed"); duk_push_int(ctx, kev_num_keys(file)); return 1; } static duk_ret_t js_KevFile_getKey(duk_context* ctx) { int index = duk_require_int(ctx, 0); kevfile_t* file; const char* key; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "KevFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "File:getKey(): file was closed"); if (key = kev_get_key(file, index)) duk_push_string(ctx, key); else duk_push_null(ctx); return 1; } static duk_ret_t js_KevFile_flush(duk_context* ctx) { kevfile_t* file; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "KevFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "File:flush(): file was closed"); kev_save(file); return 0; } static duk_ret_t js_KevFile_close(duk_context* ctx) { kevfile_t* file; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "KevFile"); duk_pop(ctx); kev_close(file); duk_push_this(ctx); duk_push_pointer(ctx, NULL); duk_put_prop_string(ctx, -2, "\xFF" "udata"); duk_pop(ctx); return 0; } static duk_ret_t js_KevFile_read(duk_context* ctx) { const char* key = duk_to_string(ctx, 0); bool def_bool; double def_num; const char* def_string; kevfile_t* file; const char* value; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "KevFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "File:read(): file was closed"); switch (duk_get_type(ctx, 1)) { case DUK_TYPE_BOOLEAN: def_bool = duk_get_boolean(ctx, 1); duk_push_boolean(ctx, kev_read_bool(file, key, def_bool)); break; case DUK_TYPE_NUMBER: def_num = duk_get_number(ctx, 1); duk_push_number(ctx, kev_read_float(file, key, def_num)); break; default: def_string = duk_to_string(ctx, 1); value = kev_read_string(file, key, def_string); duk_push_string(ctx, value); break; } return 1; } static duk_ret_t js_KevFile_write(duk_context* ctx) { const char* key = duk_to_string(ctx, 0); kevfile_t* file; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "KevFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "File:write(): file was closed"); kev_write_string(file, key, duk_to_string(ctx, 1)); return 0; } static duk_ret_t js_OpenRawFile(duk_context* ctx) { // OpenRawFile(filename); // Arguments: // filename: The name of the file to open, relative to @/other. // writable: Optional. If true, the file is truncated to zero size and // opened for writing. (default: false) const char* filename; bool writable; sfs_file_t* file; int n_args = duk_get_top(ctx); filename = duk_require_path(ctx, 0, "other", true); writable = n_args >= 2 ? duk_require_boolean(ctx, 1) : false; file = sfs_fopen(g_fs, filename, NULL, writable ? "w+b" : "rb"); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "OpenRawFile(): unable to open file `%s` for %s", filename, writable ? "writing" : "reading"); duk_push_sphere_obj(ctx, "RawFile", file); return 1; } static duk_ret_t js_new_RawFile(duk_context* ctx) { // new RawFile(filename); // Arguments: // filename: The name of the file to open. SphereFS-compliant. // writable: Optional. If true, the file is truncated to zero size and // opened for writing. (default: false) const char* filename; bool writable; sfs_file_t* file; int n_args = duk_get_top(ctx); filename = duk_require_path(ctx, 0, NULL, false); writable = n_args >= 2 ? duk_require_boolean(ctx, 1) : false; file = sfs_fopen(g_fs, filename, NULL, writable ? "w+b" : "rb"); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "OpenRawFile(): unable to open file `%s` for %s", filename, writable ? "writing" : "reading"); duk_push_sphere_obj(ctx, "RawFile", file); return 1; } static duk_ret_t js_RawFile_finalize(duk_context* ctx) { sfs_file_t* file; file = duk_require_sphere_obj(ctx, 0, "RawFile"); if (file != NULL) sfs_fclose(file); return 0; } static duk_ret_t js_RawFile_toString(duk_context* ctx) { duk_push_string(ctx, "[object rawfile]"); return 1; } static duk_ret_t js_RawFile_get_position(duk_context* ctx) { sfs_file_t* file; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "RawFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:position: file was closed"); duk_push_int(ctx, sfs_ftell(file)); return 1; } static duk_ret_t js_RawFile_set_position(duk_context* ctx) { int new_pos = duk_require_int(ctx, 0); sfs_file_t* file; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "RawFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:position: file was closed"); if (!sfs_fseek(file, new_pos, SEEK_SET)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:position: Failed to set read/write position"); return 0; } static duk_ret_t js_RawFile_get_size(duk_context* ctx) { sfs_file_t* file; long file_pos; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "RawFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:size: file was closed"); file_pos = sfs_ftell(file); sfs_fseek(file, 0, SEEK_END); duk_push_int(ctx, sfs_ftell(file)); sfs_fseek(file, file_pos, SEEK_SET); return 1; } static duk_ret_t js_RawFile_close(duk_context* ctx) { sfs_file_t* file; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "RawFile"); duk_push_pointer(ctx, NULL); duk_put_prop_string(ctx, -2, "\xFF" "udata"); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:close(): file was closed"); sfs_fclose(file); return 0; } static duk_ret_t js_RawFile_read(duk_context* ctx) { int n_args = duk_get_top(ctx); long num_bytes = n_args >= 1 ? duk_require_int(ctx, 0) : 0; bytearray_t* array; sfs_file_t* file; long pos; void* read_buffer; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "RawFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:read(): file was closed"); if (n_args < 1) { // if no arguments, read entire file back to front pos = sfs_ftell(file); num_bytes = (sfs_fseek(file, 0, SEEK_END), sfs_ftell(file)); sfs_fseek(file, 0, SEEK_SET); } if (num_bytes <= 0 || num_bytes > INT_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "RawFile:read(): read size out of range (%u)", num_bytes); if (!(read_buffer = malloc(num_bytes))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:read(): unable to allocate buffer for file read"); num_bytes = (long)sfs_fread(read_buffer, 1, num_bytes, file); if (n_args < 1) // reset file position after whole-file read sfs_fseek(file, pos, SEEK_SET); if (!(array = bytearray_from_buffer(read_buffer, (int)num_bytes))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:read(): unable to create byte array"); duk_push_sphere_bytearray(ctx, array); return 1; } static duk_ret_t js_RawFile_readString(duk_context* ctx) { int n_args = duk_get_top(ctx); long num_bytes = n_args >= 1 ? duk_require_int(ctx, 0) : 0; sfs_file_t* file; long pos; void* read_buffer; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "RawFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:read(): file was closed"); if (n_args < 1) { // if no arguments, read entire file back to front pos = sfs_ftell(file); num_bytes = (sfs_fseek(file, 0, SEEK_END), sfs_ftell(file)); sfs_fseek(file, 0, SEEK_SET); } if (num_bytes <= 0 || num_bytes > INT_MAX) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "RawFile:read(): read size out of range (%i)", num_bytes); if (!(read_buffer = malloc(num_bytes))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:read(): unable to allocate buffer for file read"); num_bytes = (long)sfs_fread(read_buffer, 1, num_bytes, file); if (n_args < 1) // reset file position after whole-file read sfs_fseek(file, pos, SEEK_SET); duk_push_lstring(ctx, read_buffer, num_bytes); return 1; } static duk_ret_t js_RawFile_write(duk_context* ctx) { bytearray_t* array; const void* data; sfs_file_t* file; duk_size_t write_size; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "RawFile"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:write(): file was closed"); if (duk_is_string(ctx, 0)) data = duk_get_lstring(ctx, 0, &write_size); else if (duk_is_sphere_obj(ctx, 0, "ByteArray")) { array = duk_require_sphere_obj(ctx, 0, "ByteArray"); data = get_bytearray_buffer(array); write_size = get_bytearray_size(array); } else { data = duk_require_buffer_data(ctx, 0, &write_size); } if (sfs_fwrite(data, 1, write_size, file) != write_size) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "RawFile:write(): error writing to file"); return 0; } static duk_ret_t js_new_FileStream(duk_context* ctx) { // new FileStream(filename); // Arguments: // filename: The SphereFS path of the file to open. // mode: A string specifying how to open the file, in the same format as // would be passed to C fopen(). sfs_file_t* file; const char* filename; const char* mode; filename = duk_require_path(ctx, 0, NULL, false); mode = duk_require_string(ctx, 1); file = sfs_fopen(g_fs, filename, NULL, mode); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to open file `%s` in mode `%s`", filename, mode); duk_push_sphere_obj(ctx, "FileStream", file); return 1; } static duk_ret_t js_FileStream_finalize(duk_context* ctx) { sfs_file_t* file; file = duk_require_sphere_obj(ctx, 0, "FileStream"); if (file != NULL) sfs_fclose(file); return 0; } static duk_ret_t js_FileStream_get_position(duk_context* ctx) { sfs_file_t* file; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_push_number(ctx, sfs_ftell(file)); return 1; } static duk_ret_t js_FileStream_set_position(duk_context* ctx) { sfs_file_t* file; long long new_pos; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); new_pos = duk_require_number(ctx, 0); sfs_fseek(file, new_pos, SFS_SEEK_SET); return 0; } static duk_ret_t js_FileStream_get_length(duk_context* ctx) { sfs_file_t* file; long file_pos; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); file_pos = sfs_ftell(file); sfs_fseek(file, 0, SEEK_END); duk_push_number(ctx, sfs_ftell(file)); sfs_fseek(file, file_pos, SEEK_SET); return 1; } static duk_ret_t js_FileStream_close(duk_context* ctx) { sfs_file_t* file; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_push_pointer(ctx, NULL); duk_put_prop_string(ctx, -2, "\xFF" "udata"); sfs_fclose(file); return 0; } static duk_ret_t js_FileStream_read(duk_context* ctx) { // FileStream:read([numBytes]); // Reads data from the stream, returning it in an ArrayBuffer. // Arguments: // numBytes: Optional. The number of bytes to read. If not provided, the // entire file is read. int argc; void* buffer; sfs_file_t* file; int num_bytes; long pos; argc = duk_get_top(ctx); num_bytes = argc >= 1 ? duk_require_int(ctx, 0) : 0; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (argc < 1) { // if no arguments, read entire file back to front pos = sfs_ftell(file); num_bytes = (sfs_fseek(file, 0, SEEK_END), sfs_ftell(file)); sfs_fseek(file, 0, SEEK_SET); } if (num_bytes < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "string length must be zero or greater"); buffer = duk_push_fixed_buffer(ctx, num_bytes); num_bytes = (int)sfs_fread(buffer, 1, num_bytes, file); if (argc < 1) // reset file position after whole-file read sfs_fseek(file, pos, SEEK_SET); duk_push_buffer_object(ctx, -1, 0, num_bytes, DUK_BUFOBJ_ARRAYBUFFER); return 1; } static duk_ret_t js_FileStream_readDouble(duk_context* ctx) { int argc; uint8_t data[8]; sfs_file_t* file; bool little_endian; double value; int i; argc = duk_get_top(ctx); little_endian = argc >= 1 ? duk_require_boolean(ctx, 0) : false; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (sfs_fread(data, 1, 8, file) != 8) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to read double from file"); if (little_endian == is_cpu_little_endian()) memcpy(&value, data, 8); else { for (i = 0; i < 8; ++i) ((uint8_t*)&value)[i] = data[7 - i]; } duk_push_number(ctx, value); return 1; } static duk_ret_t js_FileStream_readFloat(duk_context* ctx) { int argc; uint8_t data[8]; sfs_file_t* file; bool little_endian; float value; int i; argc = duk_get_top(ctx); little_endian = argc >= 1 ? duk_require_boolean(ctx, 0) : false; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (sfs_fread(data, 1, 4, file) != 4) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to read float from file"); if (little_endian == is_cpu_little_endian()) memcpy(&value, data, 4); else { for (i = 0; i < 4; ++i) ((uint8_t*)&value)[i] = data[3 - i]; } duk_push_number(ctx, value); return 1; } static duk_ret_t js_FileStream_readInt(duk_context* ctx) { int argc; sfs_file_t* file; bool little_endian; int num_bytes; intmax_t value; argc = duk_get_top(ctx); num_bytes = duk_require_int(ctx, 0); little_endian = argc >= 2 ? duk_require_boolean(ctx, 1) : false; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (num_bytes < 1 || num_bytes > 6) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "int byte size must be in [1-6] range"); if (!read_vsize_int(file, &value, num_bytes, little_endian)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to read int from file"); duk_push_number(ctx, (double)value); return 1; } static duk_ret_t js_FileStream_readPString(duk_context* ctx) { int argc; void* buffer; sfs_file_t* file; intmax_t length; bool little_endian; int uint_size; argc = duk_get_top(ctx); uint_size = duk_require_int(ctx, 0); little_endian = argc >= 2 ? duk_require_boolean(ctx, 1) : false; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (uint_size < 1 || uint_size > 4) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "length bytes must be in [1-4] range (got: %d)", uint_size); if (!read_vsize_uint(file, &length, uint_size, little_endian)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to read pstring from file"); buffer = malloc((size_t)length); if (sfs_fread(buffer, 1, (size_t)length, file) != (size_t)length) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to read pstring from file"); duk_push_lstring(ctx, buffer, (size_t)length); free(buffer); return 1; } static duk_ret_t js_FileStream_readString(duk_context* ctx) { // FileStream:readString([numBytes]); // Reads data from the stream, returning it in an ArrayBuffer. // Arguments: // numBytes: Optional. The number of bytes to read. If not provided, the // entire file is read. int argc; void* buffer; sfs_file_t* file; int num_bytes; long pos; argc = duk_get_top(ctx); num_bytes = argc >= 1 ? duk_require_int(ctx, 0) : 0; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (argc < 1) { // if no arguments, read entire file back to front pos = sfs_ftell(file); num_bytes = (sfs_fseek(file, 0, SEEK_END), sfs_ftell(file)); sfs_fseek(file, 0, SEEK_SET); } if (num_bytes < 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "string length must be zero or greater"); buffer = malloc(num_bytes); num_bytes = (int)sfs_fread(buffer, 1, num_bytes, file); if (argc < 1) // reset file position after whole-file read sfs_fseek(file, pos, SEEK_SET); duk_push_lstring(ctx, buffer, num_bytes); free(buffer); return 1; } static duk_ret_t js_FileStream_readUInt(duk_context* ctx) { int argc; sfs_file_t* file; bool little_endian; int num_bytes; intmax_t value; argc = duk_get_top(ctx); num_bytes = duk_require_int(ctx, 0); little_endian = argc >= 2 ? duk_require_boolean(ctx, 1) : false; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (num_bytes < 1 || num_bytes > 6) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "uint byte size must be in [1-6] range"); if (!read_vsize_uint(file, &value, num_bytes, little_endian)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to read uint from file"); duk_push_number(ctx, (double)value); return 1; } static duk_ret_t js_FileStream_write(duk_context* ctx) { const void* data; sfs_file_t* file; duk_size_t num_bytes; duk_require_stack_top(ctx, 1); data = duk_require_buffer_data(ctx, 0, &num_bytes); duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (sfs_fwrite(data, 1, num_bytes, file) != num_bytes) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to write data to file"); return 0; } static duk_ret_t js_FileStream_writeDouble(duk_context* ctx) { int argc; uint8_t data[8]; sfs_file_t* file; bool little_endian; double value; int i; argc = duk_get_top(ctx); value = duk_require_number(ctx, 0); little_endian = argc >= 2 ? duk_require_boolean(ctx, 1) : false; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (little_endian == is_cpu_little_endian()) memcpy(data, &value, 8); else { for (i = 0; i < 8; ++i) data[i] = ((uint8_t*)&value)[7 - i]; } if (sfs_fwrite(data, 1, 8, file) != 8) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to write double to file"); return 0; } static duk_ret_t js_FileStream_writeFloat(duk_context* ctx) { int argc; uint8_t data[4]; sfs_file_t* file; bool little_endian; float value; int i; argc = duk_get_top(ctx); value = duk_require_number(ctx, 0); little_endian = argc >= 2 ? duk_require_boolean(ctx, 1) : false; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (little_endian == is_cpu_little_endian()) memcpy(data, &value, 4); else { for (i = 0; i < 4; ++i) data[i] = ((uint8_t*)&value)[3 - i]; } if (sfs_fwrite(data, 1, 4, file) != 4) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to write float to file"); return 0; } static duk_ret_t js_FileStream_writeInt(duk_context* ctx) { int argc; sfs_file_t* file; bool little_endian; intmax_t min_value; intmax_t max_value; int num_bytes; intmax_t value; argc = duk_get_top(ctx); value = (intmax_t)duk_require_number(ctx, 0); num_bytes = duk_require_int(ctx, 1); little_endian = argc >= 3 ? duk_require_boolean(ctx, 2) : false; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (num_bytes < 1 || num_bytes > 6) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "int byte size must be in [1-6] range"); min_value = pow(-2, num_bytes * 8 - 1); max_value = pow(2, num_bytes * 8 - 1) - 1; if (value < min_value || value > max_value) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "value is unrepresentable in `%d` bytes", num_bytes); if (!write_vsize_int(file, value, num_bytes, little_endian)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to write int to file"); return 0; } static duk_ret_t js_FileStream_writePString(duk_context* ctx) { int argc; sfs_file_t* file; bool little_endian; intmax_t max_len; intmax_t num_bytes; const char* string; duk_size_t string_len; int uint_size; argc = duk_get_top(ctx); string = duk_require_lstring(ctx, 0, &string_len); uint_size = duk_require_int(ctx, 1); little_endian = argc >= 3 ? duk_require_boolean(ctx, 2) : false; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (uint_size < 1 || uint_size > 4) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "length bytes must be in [1-4] range", uint_size); max_len = pow(2, uint_size * 8) - 1; num_bytes = (intmax_t)string_len; if (num_bytes > max_len) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "string is too long for `%d`-byte length", uint_size); if (!write_vsize_uint(file, num_bytes, uint_size, little_endian) || sfs_fwrite(string, 1, string_len, file) != string_len) { duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to write pstring to file"); } return 0; } static duk_ret_t js_FileStream_writeString(duk_context* ctx) { const void* data; sfs_file_t* file; duk_size_t num_bytes; duk_require_stack_top(ctx, 1); data = duk_get_lstring(ctx, 0, &num_bytes); duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (sfs_fwrite(data, 1, num_bytes, file) != num_bytes) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to write string to file"); return 0; } static duk_ret_t js_FileStream_writeUInt(duk_context* ctx) { int argc; sfs_file_t* file; bool little_endian; intmax_t max_value; int num_bytes; intmax_t value; argc = duk_get_top(ctx); value = (intmax_t)duk_require_number(ctx, 0); num_bytes = duk_require_int(ctx, 1); little_endian = argc >= 3 ? duk_require_boolean(ctx, 2) : false; duk_push_this(ctx); file = duk_require_sphere_obj(ctx, -1, "FileStream"); duk_pop(ctx); if (file == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "FileStream was closed"); if (num_bytes < 1 || num_bytes > 6) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "uint byte size must be in [1-6] range"); max_value = pow(2, num_bytes * 8) - 1; if (value < 0 || value > max_value) duk_error_ni(ctx, -1, DUK_ERR_TYPE_ERROR, "value is unrepresentable in `%d` bytes", num_bytes); if (!write_vsize_uint(file, value, num_bytes, little_endian)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "unable to write int to file"); return 0; } <file_sep>/src/engine/sockets.c #include "minisphere.h" #include "api.h" #include "bytearray.h" #include "sockets.h" static void on_dyad_accept (dyad_Event* e); static void on_dyad_receive (dyad_Event* e); static duk_ret_t js_GetLocalName (duk_context* ctx); static duk_ret_t js_GetLocalAddress (duk_context* ctx); static duk_ret_t js_ListenOnPort (duk_context* ctx); static duk_ret_t js_OpenAddress (duk_context* ctx); static duk_ret_t js_new_Socket (duk_context* ctx); static duk_ret_t js_Socket_finalize (duk_context* ctx); static duk_ret_t js_Socket_get_remoteAddress (duk_context* ctx); static duk_ret_t js_Socket_get_remotePort (duk_context* ctx); static duk_ret_t js_Socket_toString (duk_context* ctx); static duk_ret_t js_Socket_isConnected (duk_context* ctx); static duk_ret_t js_Socket_getPendingReadSize (duk_context* ctx); static duk_ret_t js_Socket_close (duk_context* ctx); static duk_ret_t js_Socket_read (duk_context* ctx); static duk_ret_t js_Socket_readString (duk_context* ctx); static duk_ret_t js_Socket_write (duk_context* ctx); static duk_ret_t js_new_Server (duk_context* ctx); static duk_ret_t js_Server_finalize (duk_context* ctx); static duk_ret_t js_Server_close (duk_context* ctx); static duk_ret_t js_Server_accept (duk_context* ctx); static duk_ret_t js_new_IOSocket (duk_context* ctx); static duk_ret_t js_IOSocket_finalize (duk_context* ctx); static duk_ret_t js_IOSocket_get_bytesPending (duk_context* ctx); static duk_ret_t js_IOSocket_get_remoteAddress (duk_context* ctx); static duk_ret_t js_IOSocket_get_remotePort (duk_context* ctx); static duk_ret_t js_IOSocket_isConnected (duk_context* ctx); static duk_ret_t js_IOSocket_close (duk_context* ctx); static duk_ret_t js_IOSocket_pipe (duk_context* ctx); static duk_ret_t js_IOSocket_read (duk_context* ctx); static duk_ret_t js_IOSocket_readString (duk_context* ctx); static duk_ret_t js_IOSocket_unpipe (duk_context* ctx); static duk_ret_t js_IOSocket_write (duk_context* ctx); struct socket { unsigned int refcount; unsigned int id; dyad_Stream* stream; dyad_Stream* stream_ipv6; uint8_t* buffer; size_t buffer_size; size_t pend_size; socket_t* pipe_target; int max_backlog; int num_backlog; dyad_Stream* *backlog; }; unsigned int s_next_socket_id = 0; socket_t* connect_to_host(const char* hostname, int port, size_t buffer_size) { socket_t* socket = NULL; dyad_Stream* stream = NULL; console_log(2, "connecting socket #%u to %s:%i", s_next_socket_id, hostname, port); socket = calloc(1, sizeof(socket_t)); socket->buffer = malloc(buffer_size); socket->buffer_size = buffer_size; if (!(socket->stream = dyad_newStream())) goto on_error; dyad_setNoDelay(socket->stream, true); dyad_addListener(socket->stream, DYAD_EVENT_DATA, on_dyad_receive, socket); if (dyad_connect(socket->stream, hostname, port) == -1) goto on_error; socket->id = s_next_socket_id++; return ref_socket(socket); on_error: console_log(2, "failed to connect socket #%u", s_next_socket_id++); if (socket != NULL) { free(socket->buffer); if (socket->stream != NULL) dyad_close(stream); free(socket); } return NULL; } socket_t* listen_on_port(const char* hostname, int port, size_t buffer_size, int max_backlog) { int backlog_size; socket_t* socket = NULL; dyad_Stream* stream = NULL; console_log(2, "opening socket #%u to listen on %i", s_next_socket_id, port); if (max_backlog > 0) console_log(3, " backlog: up to %i", max_backlog); socket = calloc(1, sizeof(socket_t)); if (max_backlog == 0) socket->buffer = malloc(buffer_size); else socket->backlog = malloc(max_backlog * sizeof(dyad_Stream*)); socket->max_backlog = max_backlog; socket->buffer_size = buffer_size; if (!(socket->stream = dyad_newStream())) goto on_error; dyad_setNoDelay(socket->stream, true); dyad_addListener(socket->stream, DYAD_EVENT_ACCEPT, on_dyad_accept, socket); backlog_size = max_backlog > 0 ? max_backlog : 16; if (hostname == NULL) { if (!(socket->stream_ipv6 = dyad_newStream())) goto on_error; dyad_setNoDelay(socket->stream_ipv6, true); dyad_addListener(socket->stream_ipv6, DYAD_EVENT_ACCEPT, on_dyad_accept, socket); if (dyad_listenEx(socket->stream, "0.0.0.0", port, max_backlog) == -1) goto on_error; if (dyad_listenEx(socket->stream_ipv6, "::", port, max_backlog) == -1) goto on_error; } else { if (dyad_listenEx(socket->stream, hostname, port, max_backlog) == -1) goto on_error; } socket->id = s_next_socket_id++; return ref_socket(socket); on_error: console_log(2, "failed to open socket #%u", s_next_socket_id++); if (socket != NULL) { free(socket->backlog); free(socket->buffer); if (socket->stream != NULL) dyad_close(stream); free(socket); } return NULL; } socket_t* ref_socket(socket_t* socket) { if (socket != NULL) ++socket->refcount; return socket; } void free_socket(socket_t* socket) { unsigned int threshold; int i; if (socket == NULL) return; // handle the case where a socket is piped into itself. // the circular reference will otherwise prevent the socket from being freed. threshold = socket->pipe_target == socket ? 1 : 0; if (--socket->refcount > threshold) return; console_log(3, "disposing socket #%u no longer in use", socket->id); for (i = 0; i < socket->num_backlog; ++i) dyad_end(socket->backlog[i]); dyad_end(socket->stream); if (socket->stream_ipv6 != NULL) dyad_end(socket->stream_ipv6); free_socket(socket->pipe_target); free(socket); } bool is_socket_live(socket_t* socket) { int state; state = dyad_getState(socket->stream); return state == DYAD_STATE_CONNECTED || state == DYAD_STATE_CLOSING; } bool is_socket_server(socket_t* socket) { return dyad_getState(socket->stream) == DYAD_STATE_LISTENING; } const char* get_socket_host(socket_t* socket) { return dyad_getAddress(socket->stream); } int get_socket_port(socket_t* socket) { return dyad_getPort(socket->stream); } socket_t* accept_next_socket(socket_t* listener) { socket_t* socket; int i; if (listener->num_backlog == 0) return NULL; console_log(2, "spawning new socket #%u for connection to socket #%u", s_next_socket_id, listener->id); console_log(2, " remote address: %s:%d", dyad_getAddress(listener->backlog[0]), dyad_getPort(listener->backlog[0])); // construct a socket object for the new connection socket = calloc(1, sizeof(socket_t)); socket->buffer = malloc(listener->buffer_size); socket->buffer_size = listener->buffer_size; socket->stream = listener->backlog[0]; dyad_addListener(socket->stream, DYAD_EVENT_DATA, on_dyad_receive, socket); // we accepted the connection, remove it from the backlog --listener->num_backlog; for (i = 0; i < listener->num_backlog; ++i) listener->backlog[i] = listener->backlog[i + 1]; socket->id = s_next_socket_id++; return ref_socket(socket); } size_t peek_socket(const socket_t* socket) { return socket->pend_size; } void pipe_socket(socket_t* socket, socket_t* destination) { socket_t* old_target; console_log(2, "piping socket #%u into destination socket #%u", socket->id, destination->id); old_target = socket->pipe_target; socket->pipe_target = ref_socket(destination); free_socket(old_target); if (socket->pipe_target != NULL && socket->pend_size > 0) { console_log(4, "piping %zd bytes into socket #%u", socket->pend_size, destination->id); write_socket(destination, socket->buffer, socket->pend_size); socket->pend_size = 0; } } size_t read_socket(socket_t* socket, uint8_t* buffer, size_t n_bytes) { n_bytes = n_bytes <= socket->pend_size ? n_bytes : socket->pend_size; console_log(4, "reading %zd bytes from socket #%u", n_bytes, socket->id); memcpy(buffer, socket->buffer, n_bytes); memmove(socket->buffer, socket->buffer + n_bytes, socket->pend_size - n_bytes); socket->pend_size -= n_bytes; return n_bytes; } void shutdown_socket(socket_t* socket) { console_log(2, "shutting down socket #%u", socket->id); dyad_end(socket->stream); } void write_socket(socket_t* socket, const uint8_t* data, size_t n_bytes) { console_log(4, "writing %zd bytes to socket #%u", n_bytes, socket->id); dyad_write(socket->stream, data, (int)n_bytes); } static void on_dyad_accept(dyad_Event* e) { int new_backlog_len; socket_t* socket = e->udata; if (socket->max_backlog > 0) { // BSD-style socket with backlog: listener stays open, game must accept new sockets new_backlog_len = socket->num_backlog + 1; if (new_backlog_len <= socket->max_backlog) { console_log(4, "taking connection from %s:%i on socket #%u", dyad_getAddress(e->remote), dyad_getPort(e->remote), socket->id); socket->backlog[socket->num_backlog++] = e->remote; } else { console_log(4, "backlog full fpr socket #%u, refusing %s:%i", socket->id, dyad_getAddress(e->remote), dyad_getPort(e->remote), socket->id); dyad_close(e->remote); } } else { // no backlog: listener closes on first connection (legacy socket) console_log(2, "rebinding socket #%u to %s:%i", socket->id, dyad_getAddress(e->remote), dyad_getPort(e->remote)); dyad_removeAllListeners(socket->stream, DYAD_EVENT_ACCEPT); dyad_close(socket->stream); socket->stream = e->remote; dyad_addListener(socket->stream, DYAD_EVENT_DATA, on_dyad_receive, socket); } } static void on_dyad_receive(dyad_Event* e) { size_t new_pend_size; socket_t* socket = e->udata; if (socket->pipe_target != NULL) { // if the socket is a pipe, pass the data through to the destination console_log(4, "piping %d bytes from socket #%u to socket #%u", e->size, socket->id, socket->pipe_target->id); write_socket(socket->pipe_target, e->data, e->size); } else { // buffer any data received until read() is called new_pend_size = socket->pend_size + e->size; if (new_pend_size > socket->buffer_size) { socket->buffer_size = new_pend_size * 2; socket->buffer = realloc(socket->buffer, socket->buffer_size); } memcpy(socket->buffer + socket->pend_size, e->data, e->size); socket->pend_size += e->size; } } void init_sockets_api(void) { // core Sockets API functions api_register_method(g_duk, NULL, "GetLocalAddress", js_GetLocalAddress); api_register_method(g_duk, NULL, "GetLocalName", js_GetLocalName); // Socket object (Sphere 1.5-style socket) api_register_method(g_duk, NULL, "ListenOnPort", js_ListenOnPort); api_register_method(g_duk, NULL, "OpenAddress", js_OpenAddress); api_register_ctor(g_duk, "Socket", js_new_Socket, js_Socket_finalize); api_register_prop(g_duk, "Socket", "remoteAddress", js_IOSocket_get_remoteAddress, NULL); api_register_prop(g_duk, "Socket", "remotePort", js_IOSocket_get_remotePort, NULL); api_register_method(g_duk, "Socket", "toString", js_Socket_toString); api_register_method(g_duk, "Socket", "isConnected", js_Socket_isConnected); api_register_method(g_duk, "Socket", "getPendingReadSize", js_Socket_getPendingReadSize); api_register_method(g_duk, "Socket", "close", js_Socket_close); api_register_method(g_duk, "Socket", "read", js_Socket_read); api_register_method(g_duk, "Socket", "readString", js_Socket_readString); api_register_method(g_duk, "Socket", "write", js_Socket_write); // Server object api_register_ctor(g_duk, "Server", js_new_Server, js_Server_finalize); api_register_method(g_duk, "Server", "close", js_Server_close); api_register_method(g_duk, "Server", "accept", js_Server_accept); // IOSocket object api_register_ctor(g_duk, "IOSocket", js_new_IOSocket, js_IOSocket_finalize); api_register_prop(g_duk, "IOSocket", "bytesPending", js_IOSocket_get_bytesPending, NULL); api_register_prop(g_duk, "IOSocket", "remoteAddress", js_IOSocket_get_remoteAddress, NULL); api_register_prop(g_duk, "IOSocket", "remotePort", js_IOSocket_get_remotePort, NULL); api_register_method(g_duk, "IOSocket", "isConnected", js_IOSocket_isConnected); api_register_method(g_duk, "IOSocket", "close", js_IOSocket_close); api_register_method(g_duk, "IOSocket", "pipe", js_IOSocket_pipe); api_register_method(g_duk, "IOSocket", "read", js_IOSocket_read); api_register_method(g_duk, "IOSocket", "readString", js_IOSocket_readString); api_register_method(g_duk, "IOSocket", "unpipe", js_IOSocket_unpipe); api_register_method(g_duk, "IOSocket", "write", js_IOSocket_write); } static duk_ret_t js_GetLocalAddress(duk_context* ctx) { duk_push_string(ctx, "127.0.0.1"); return 1; } static duk_ret_t js_GetLocalName(duk_context* ctx) { duk_push_string(ctx, "localhost"); return 1; } static duk_ret_t js_ListenOnPort(duk_context* ctx) { duk_require_int(ctx, 0); js_new_Socket(ctx); return 1; } static duk_ret_t js_OpenAddress(duk_context* ctx) { duk_require_string(ctx, 0); duk_require_int(ctx, 1); js_new_Socket(ctx); return 1; } static duk_ret_t js_new_Socket(duk_context* ctx) { const char* ip; int port; socket_t* socket; if (duk_is_number(ctx, 0)) { port = duk_require_int(ctx, 0); if (socket = listen_on_port(NULL, port, 1024, 0)) duk_push_sphere_obj(ctx, "Socket", socket); else duk_push_null(ctx); } else { ip = duk_require_string(ctx, 0); port = duk_require_int(ctx, 1); if ((socket = connect_to_host(ip, port, 1024)) != NULL) duk_push_sphere_obj(ctx, "Socket", socket); else duk_push_null(ctx); } return 1; } static duk_ret_t js_Socket_finalize(duk_context* ctx) { socket_t* socket; socket = duk_require_sphere_obj(ctx, 0, "Socket"); free_socket(socket); return 1; } static duk_ret_t js_Socket_get_remoteAddress(duk_context* ctx) { socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "Socket"); duk_pop(ctx); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:remoteAddress - Socket has been closed"); if (!is_socket_live(socket)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:remoteAddress - Socket is not connected"); duk_push_string(ctx, dyad_getAddress(socket->stream)); return 1; } static duk_ret_t js_Socket_get_remotePort(duk_context* ctx) { socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "Socket"); duk_pop(ctx); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:remotePort - Socket has been closed"); if (!is_socket_live(socket)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:remotePort - Socket is not connected"); duk_push_int(ctx, dyad_getPort(socket->stream)); return 1; } static duk_ret_t js_Socket_toString(duk_context* ctx) { duk_push_string(ctx, "[object socket]"); return 1; } static duk_ret_t js_Socket_isConnected(duk_context* ctx) { socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "Socket"); duk_pop(ctx); if (socket != NULL) duk_push_boolean(ctx, is_socket_live(socket)); else duk_push_false(ctx); return 1; } static duk_ret_t js_Socket_getPendingReadSize(duk_context* ctx) { socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "Socket"); duk_pop(ctx); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:getPendingReadSize(): socket has been closed"); duk_push_uint(ctx, (duk_uint_t)peek_socket(socket)); return 1; } static duk_ret_t js_Socket_close(duk_context* ctx) { socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "Socket"); duk_push_null(ctx); duk_put_prop_string(ctx, -2, "\xFF" "udata"); duk_pop(ctx); if (socket != NULL) free_socket(socket); return 1; } static duk_ret_t js_Socket_read(duk_context* ctx) { int length = duk_require_int(ctx, 0); bytearray_t* array; void* read_buffer; socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "Socket"); duk_pop(ctx); if (length <= 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Socket:read(): must read at least 1 byte (got: %i)", length); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:read(): socket has been closed"); if (!is_socket_live(socket)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:read(): socket is not connected"); if (!(read_buffer = malloc(length))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:read(): unable to allocate read buffer"); read_socket(socket, read_buffer, length); if (!(array = bytearray_from_buffer(read_buffer, length))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:read(): unable to create byte array"); duk_push_sphere_bytearray(ctx, array); return 1; } static duk_ret_t js_Socket_readString(duk_context* ctx) { size_t length = duk_require_uint(ctx, 0); uint8_t* buffer; socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "Socket"); duk_pop(ctx); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:readString(): socket has been closed"); if (!is_socket_live(socket)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:readString(): socket is not connected"); if (!(buffer = malloc(length))) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:readString(): unable to allocate read buffer"); read_socket(socket, buffer, length); duk_push_lstring(ctx, (char*)buffer, length); free(buffer); return 1; } static duk_ret_t js_Socket_write(duk_context* ctx) { bytearray_t* array; const uint8_t* payload; socket_t* socket; size_t write_size; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "Socket"); duk_pop(ctx); if (duk_is_string(ctx, 0)) payload = (uint8_t*)duk_get_lstring(ctx, 0, &write_size); else { array = duk_require_sphere_bytearray(ctx, 0); payload = get_bytearray_buffer(array); write_size = get_bytearray_size(array); } if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:write(): socket has been closed"); if (!is_socket_live(socket)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Socket:write(): socket is not connected"); write_socket(socket, payload, write_size); return 0; } static duk_ret_t js_new_Server(duk_context* ctx) { int n_args = duk_get_top(ctx); int port = duk_require_int(ctx, 0); int max_backlog = n_args >= 2 ? duk_require_int(ctx, 1) : 16; socket_t* socket; if (max_backlog <= 0) duk_error_ni(ctx, -1, DUK_ERR_RANGE_ERROR, "Server(): backlog size must be greater than zero (got: %i)", max_backlog); if (socket = listen_on_port(NULL, port, 1024, max_backlog)) duk_push_sphere_obj(ctx, "Server", socket); else duk_push_null(ctx); return 1; } static duk_ret_t js_Server_finalize(duk_context* ctx) { socket_t* socket; socket = duk_require_sphere_obj(ctx, 0, "Server"); free_socket(socket); return 0; } static duk_ret_t js_Server_accept(duk_context* ctx) { socket_t* new_socket; socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "Server"); duk_pop(ctx); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "Server:accept(): socket has been closed"); new_socket = accept_next_socket(socket); if (new_socket) duk_push_sphere_obj(ctx, "IOSocket", new_socket); else duk_push_null(ctx); return 1; } static duk_ret_t js_Server_close(duk_context* ctx) { socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "Server"); duk_push_null(ctx); duk_put_prop_string(ctx, -2, "\xFF" "udata"); duk_pop(ctx); if (socket != NULL) free_socket(socket); return 0; } static duk_ret_t js_new_IOSocket(duk_context* ctx) { const char* hostname = duk_require_string(ctx, 0); int port = duk_require_int(ctx, 1); socket_t* socket; if ((socket = connect_to_host(hostname, port, 1024)) != NULL) duk_push_sphere_obj(ctx, "IOSocket", socket); else duk_push_null(ctx); return 1; } static duk_ret_t js_IOSocket_finalize(duk_context* ctx) { socket_t* socket; socket = duk_require_sphere_obj(ctx, 0, "IOSocket"); free_socket(socket); return 0; } static duk_ret_t js_IOSocket_get_bytesPending(duk_context* ctx) { // get IOSocket:bytesPending // Returns the number of bytes in the socket's receive buffer. socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "IOSocket"); duk_pop(ctx); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:bytesPending: Socket has been closed"); duk_push_uint(ctx, (duk_uint_t)socket->pend_size); return 1; } static duk_ret_t js_IOSocket_get_remoteAddress(duk_context* ctx) { socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "IOSocket"); duk_pop(ctx); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:remoteAddress - Socket has been closed"); if (!is_socket_live(socket)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:remoteAddress - Socket is not connected"); duk_push_string(ctx, dyad_getAddress(socket->stream)); return 1; } static duk_ret_t js_IOSocket_get_remotePort(duk_context* ctx) { socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "IOSocket"); duk_pop(ctx); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:remotePort - Socket has been closed"); if (!is_socket_live(socket)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:remotePort - Socket is not connected"); duk_push_int(ctx, dyad_getPort(socket->stream)); return 1; } static duk_ret_t js_IOSocket_isConnected(duk_context* ctx) { socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "IOSocket"); duk_pop(ctx); if (socket != NULL) duk_push_boolean(ctx, is_socket_live(socket)); else duk_push_false(ctx); return 1; } static duk_ret_t js_IOSocket_close(duk_context* ctx) { // IOSocket:close(); // Closes the socket, after which no further I/O may be performed // with it. socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "IOSocket"); duk_push_null(ctx); duk_put_prop_string(ctx, -2, "\xFF" "udata"); duk_pop(ctx); if (socket != NULL) free_socket(socket); return 0; } static duk_ret_t js_IOSocket_pipe(duk_context* ctx) { // IOSocket:pipe(destSocket); // Pipes all data received by a socket into another socket. // Arguments: // destSocket: The IOSocket into which to pipe received data. socket_t* dest_socket; socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "IOSocket"); duk_pop(ctx); dest_socket = duk_require_sphere_obj(ctx, 0, "IOSocket"); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:pipe(): socket has been closed"); if (dest_socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:pipe(): destination socket has been closed"); pipe_socket(socket, dest_socket); // return destination socket (enables pipe chaining) duk_dup(ctx, 0); return 1; } static duk_ret_t js_IOSocket_unpipe(duk_context* ctx) { // IOSocket:unpipe(); // Undoes a previous call to pipe(), reverting the socket to normal // behavior. socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "IOSocket"); duk_pop(ctx); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:pipe(): socket has been closed"); pipe_socket(socket, NULL); return 0; } static duk_ret_t js_IOSocket_read(duk_context* ctx) { // IOSocket:read(numBytes); // Reads from a socket, returning the data in an ArrayBuffer. // Arguments: // numBytes: The maximum number of bytes to read. void* buffer; size_t bytes_read; duk_size_t num_bytes; socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "IOSocket"); duk_pop(ctx); num_bytes = duk_require_uint(ctx, 0); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:read(): socket has been closed"); if (!is_socket_live(socket)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:read(): socket is not connected"); buffer = duk_push_fixed_buffer(ctx, num_bytes); bytes_read = read_socket(socket, buffer, num_bytes); duk_push_buffer_object(ctx, -1, 0, bytes_read, DUK_BUFOBJ_ARRAYBUFFER); return 1; } static duk_ret_t js_IOSocket_readString(duk_context* ctx) { // IOSocket:read(numBytes); // Reads data from a socket and returns it as a UTF-8 string. // Arguments: // numBytes: The maximum number of bytes to read. uint8_t* buffer; size_t num_bytes; socket_t* socket; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "IOSocket"); duk_pop(ctx); num_bytes = duk_require_uint(ctx, 0); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:readString(): socket has been closed"); if (!is_socket_live(socket)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:readString(): socket is not connected"); read_socket(socket, buffer = malloc(num_bytes), num_bytes); duk_push_lstring(ctx, (char*)buffer, num_bytes); free(buffer); return 1; } static duk_ret_t js_IOSocket_write(duk_context* ctx) { // IOSocket:write(data); // Writes data into the socket. // Arguments: // data: The data to write; this can be either a JS string or an // ArrayBuffer. const uint8_t* payload; socket_t* socket; duk_size_t write_size; duk_push_this(ctx); socket = duk_require_sphere_obj(ctx, -1, "IOSocket"); duk_pop(ctx); if (duk_is_string(ctx, 0)) payload = (uint8_t*)duk_get_lstring(ctx, 0, &write_size); else payload = duk_require_buffer_data(ctx, 0, &write_size); if (socket == NULL) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:write(): socket has been closed"); if (!is_socket_live(socket)) duk_error_ni(ctx, -1, DUK_ERR_ERROR, "IOSocket:write(): socket is not connected"); write_socket(socket, payload, write_size); return 0; } <file_sep>/src/debugger/session.c #include "ssj.h" #include "session.h" #include "help.h" #include "inferior.h" #include "parser.h" enum auto_action { AUTO_NONE, AUTO_LIST, AUTO_CONTINUE, AUTO_STEP_IN, AUTO_STEP_OUT, AUTO_STEP_OVER, AUTO_UP_DOWN, }; struct breakpoint { int handle; char* filename; int linenum; }; struct session { enum auto_action auto_action; struct breakpoint* breaks; int frame; inferior_t* inferior; int list_num_lines; char* list_filename; int list_linenum; int num_breaks; int up_down_direction; }; const char* const command_db[] = { "backtrace", "bt", "", "breakpoint", "bp", "~f", "clearbreak", "cb", "n", "continue", "c", "", "down", "d", "~n", "eval", "e", "s", "examine", "x", "s", "frame", "f", "~n", "list", "l", "~nf", "stepover", "s", "", "stepin", "si", "", "stepout", "so", "", "up", "u", "~n", "vars", "v", "", "where", "w", "", "quit", "q", "", "help", "h", "~s", }; static void autoselect_frame (session_t* obj); static void clear_auto_action (session_t* obj); static void do_command_line (session_t* obj); static const char* find_verb (const char* abbrev, const char* *o_pattern); static const char* resolve_command (command_t* cmd); static void handle_backtrace (session_t* obj, command_t* cmd); static void handle_breakpoint (session_t* obj, command_t* cmd); static void handle_clearbreak (session_t* obj, command_t* cmd); static void handle_eval (session_t* obj, command_t* cmd, bool is_verbose); static void handle_frame (session_t* obj, command_t* cmd); static void handle_help (session_t* obj, command_t* cmd); static void handle_list (session_t* obj, command_t* cmd); static void handle_resume (session_t* obj, command_t* cmd, resume_op_t op); static void handle_up_down (session_t* obj, command_t* cmd, int direction); static void handle_vars (session_t* obj, command_t* cmd); static void handle_where (session_t* obj, command_t* cmd); static void handle_quit (session_t* obj, command_t* cmd); static void preview_frame (session_t* obj, int frame); static bool validate_args (const command_t* this, const char* verb_name, const char* pattern); session_t* session_new(inferior_t* inferior) { session_t* obj; obj = calloc(1, sizeof(session_t)); obj->inferior = inferior; return obj; } void session_free(session_t* obj) { free(obj); } void session_run(session_t* obj, bool run_now) { if (run_now) { inferior_resume(obj->inferior, OP_RESUME); } if (inferior_attached(obj->inferior)) { autoselect_frame(obj); preview_frame(obj, obj->frame); } while (inferior_attached(obj->inferior)) do_command_line(obj); printf("SSJ session terminated.\n"); } static const char* find_verb(const char* abbrev, const char* *o_pattern) { const char* full_name; const char* matches[100]; int num_commands; int num_matches = 0; const char* short_name; int i; num_commands = sizeof(command_db) / sizeof(command_db[0]) / 3; for (i = 0; i < num_commands; ++i) { full_name = command_db[0 + i * 3]; short_name = command_db[1 + i * 3]; if (strcmp(abbrev, short_name) == 0) { matches[0] = full_name; num_matches = 1; // canonical short name is never ambiguous if (o_pattern != NULL) *o_pattern = command_db[2 + i * 3]; break; } if (strstr(full_name, abbrev) == full_name) { matches[num_matches] = full_name; if (num_matches == 0 && o_pattern != NULL) *o_pattern = command_db[2 + i * 3]; ++num_matches; } } if (num_matches == 1) return matches[0]; else if (num_matches > 1) { printf("`%s`: abbreviated name is ambiguous between:\n", abbrev); for (i = 0; i < num_matches; ++i) printf(" * %s\n", matches[i]); return NULL; } else { printf("`%s`: unrecognized command name.\n", abbrev); return NULL; } } static void autoselect_frame(session_t* obj) { const backtrace_t* calls; calls = inferior_get_calls(obj->inferior); obj->frame = 0; while (backtrace_get_linenum(calls, obj->frame) == 0) ++obj->frame; } static void clear_auto_action(session_t* obj) { switch (obj->auto_action) { case AUTO_LIST: free(obj->list_filename); break; } obj->auto_action = AUTO_NONE; } static void do_command_line(session_t* obj) { char buffer[4096]; const backtrace_t* calls; char ch; command_t* command; const char* filename; const char* function_name; int line_no; char* synth; const char* verb; int idx; calls = inferior_get_calls(obj->inferior); function_name = backtrace_get_call_name(calls, obj->frame); filename = backtrace_get_filename(calls, obj->frame); line_no = backtrace_get_linenum(calls, obj->frame); if (line_no != 0) printf("\n\33[36;1m%s:%d %s\33[m\n\33[33;1m(ssj)\33[m ", filename, line_no, function_name); else printf("\n\33[36;1msyscall %s\33[m\n\33[33;1m(ssj)\33[m ", function_name); idx = 0; ch = getchar(); while (ch != '\n') { if (idx >= 4095) { printf("string is too long to parse.\n"); buffer[0] = '\0'; break; } buffer[idx++] = ch; ch = getchar(); } buffer[idx] = '\0'; if (!(command = command_parse(buffer))) goto finished; // if the command line is empty, this is a cue from the user that we should // repeat the last command. the implementation of this is a bit hacky and would benefit // from some refactoring in the future. if (!(verb = resolve_command(command))) { command_free(command); command = NULL; switch (obj->auto_action) { case AUTO_CONTINUE: command = command_parse("continue"); break; case AUTO_LIST: synth = strnewf("list %d \"%s\":%d", obj->list_num_lines, obj->list_filename, obj->list_linenum); command = command_parse(synth); free(synth); break; case AUTO_STEP_IN: command = command_parse("stepin"); break; case AUTO_STEP_OUT: command = command_parse("stepout"); break; case AUTO_STEP_OVER: command = command_parse("stepover"); break; case AUTO_UP_DOWN: if (obj->up_down_direction > 0) command = command_parse("up"); else if (obj->up_down_direction < 0) command = command_parse("down"); else // crash prevention command = command_parse("frame"); break; default: printf("nothing to repeat, please enter a valid SSJ command.\n"); printf("type 'help' to see a list of usable commands.\n"); goto finished; } if (!(verb = resolve_command(command))) goto finished; } // figure out which handler to run based on the command name. this could // probably be refactored to get rid of the massive if/elseif tower, but for // now it serves its purpose. clear_auto_action(obj); if (strcmp(verb, "quit") == 0) handle_quit(obj, command); else if (strcmp(verb, "help") == 0) handle_help(obj, command); else if (strcmp(verb, "backtrace") == 0) handle_backtrace(obj, command); else if (strcmp(verb, "breakpoint") == 0) handle_breakpoint(obj, command); else if (strcmp(verb, "up") == 0) handle_up_down(obj, command, +1); else if (strcmp(verb, "down") == 0) handle_up_down(obj, command, -1); else if (strcmp(verb, "clearbreak") == 0) handle_clearbreak(obj, command); else if (strcmp(verb, "continue") == 0) handle_resume(obj, command, OP_RESUME); else if (strcmp(verb, "eval") == 0) handle_eval(obj, command, false); else if (strcmp(verb, "examine") == 0) handle_eval(obj, command, true); else if (strcmp(verb, "frame") == 0) handle_frame(obj, command); else if (strcmp(verb, "list") == 0) handle_list(obj, command); else if (strcmp(verb, "stepover") == 0) handle_resume(obj, command, OP_STEP_OVER); else if (strcmp(verb, "stepin") == 0) handle_resume(obj, command, OP_STEP_IN); else if (strcmp(verb, "stepout") == 0) handle_resume(obj, command, OP_STEP_OUT); else if (strcmp(verb, "vars") == 0) handle_vars(obj, command); else if (strcmp(verb, "where") == 0) handle_where(obj, command); else printf("`%s`: not implemented.\n", verb); finished: command_free(command); } static const char* resolve_command(command_t* command) { const char* pattern; const char* verb; if (command_len(command) < 1) return NULL; if (!(verb = find_verb(command_get_string(command, 0), &pattern))) return NULL; return validate_args(command, verb, pattern) ? verb : NULL; } static void handle_backtrace(session_t* obj, command_t* cmd) { const backtrace_t* calls; if (!(calls = inferior_get_calls(obj->inferior))) return; backtrace_print(calls, obj->frame, true); } static void handle_breakpoint(session_t* obj, command_t* cmd) { const char* filename; int handle; int linenum; const source_t* source; int i; if (command_len(cmd) < 2) { if (obj->num_breaks <= 0) printf("no breakpoints are currently set.\n"); else { for (i = 0; i < obj->num_breaks; ++i) { printf("#%2d: breakpoint at %s:%d\n", i, obj->breaks[i].filename, obj->breaks[i].linenum); } } } else { filename = command_get_string(cmd, 1); linenum = command_get_int(cmd, 1); if ((handle = inferior_add_breakpoint(obj->inferior, filename, linenum)) < 0) printf("SSJ was unable to set the breakpoint.\n"); else { i = obj->num_breaks++; obj->breaks = realloc(obj->breaks, obj->num_breaks * sizeof(struct breakpoint)); obj->breaks[i].handle = handle; obj->breaks[i].filename = strdup(command_get_string(cmd, 1)); obj->breaks[i].linenum = command_get_int(cmd, 1); printf("breakpoint #%2d set at %s:%d.\n", i, obj->breaks[i].filename, obj->breaks[i].linenum); if ((source = inferior_get_source(obj->inferior, filename))) source_print(source, linenum, 1, 0); } } } static void handle_clearbreak(session_t* obj, command_t* cmd) { const char* filename; int handle; int index; int linenum; const source_t* source; index = command_get_int(cmd, 1); if (obj->num_breaks <= 0) printf("no breakpoints to clear.\n"); else if (index > obj->num_breaks) printf("invalid breakpoint index, valid range is 0-%d.", obj->num_breaks); else { handle = obj->breaks[index].handle; filename = obj->breaks[index].filename; linenum = obj->breaks[index].linenum; if (!inferior_clear_breakpoint(obj->inferior, handle)) return; printf("cleared breakpoint #%2d at %s:%d.\n", index, obj->breaks[index].filename, obj->breaks[index].linenum); if ((source = inferior_get_source(obj->inferior, filename))) source_print(source, linenum, 1, 0); } } static void handle_resume(session_t* obj, command_t* cmd, resume_op_t op) { switch (op) { case OP_RESUME: obj->auto_action = AUTO_CONTINUE; break; case OP_STEP_IN: obj->auto_action = AUTO_STEP_IN; break; case OP_STEP_OUT: obj->auto_action = AUTO_STEP_OUT; break; case OP_STEP_OVER: obj->auto_action = AUTO_STEP_OVER; break; } inferior_resume(obj->inferior, op); if (inferior_attached(obj->inferior)) { autoselect_frame(obj); preview_frame(obj, obj->frame); } } static void handle_eval(session_t* obj, command_t* cmd, bool is_verbose) { const char* expr; const dvalue_t* getter; remote_ptr_t heapptr; bool is_accessor; bool is_error; int max_len = 0; objview_t* object; unsigned int prop_flags; const char* prop_key; const dvalue_t* setter; dvalue_t* result; int i = 0; expr = command_get_string(cmd, 1); result = inferior_eval(obj->inferior, expr, obj->frame, &is_error); if (dvalue_tag(result) != DVALUE_OBJ) { printf(is_error ? "error: " : "= "); dvalue_print(result, is_verbose); printf("\n"); } else { heapptr = dvalue_as_ptr(result); if (!(object = inferior_get_object(obj->inferior, heapptr, is_verbose))) return; if (objview_len(object) == 0) { printf("object has no properties.\n"); return; } if (!is_verbose) printf("= {\n"); for (i = 0; i < objview_len(object); ++i) { prop_key = objview_get_key(object, i); if ((int)strlen(prop_key) > max_len) max_len = (int)strlen(prop_key); } for (i = 0; i < objview_len(object); ++i) { is_accessor = objview_get_tag(object, i) == PROP_ACCESSOR; prop_key = objview_get_key(object, i); prop_flags = objview_get_flags(object, i); if (!(prop_flags & PROP_ENUMERABLE) && !is_verbose) continue; if (is_verbose) { printf("%s%s%s%s %-*s ", prop_flags & PROP_ENUMERABLE ? "e" : "-", prop_flags & PROP_WRITABLE ? "w" : "-", is_accessor ? "a" : "-", prop_flags & PROP_CONFIGURABLE ? "c" : "-", max_len, prop_key); } else { printf(" \"%s\": ", prop_key); } if (!is_accessor) dvalue_print(objview_get_value(object, i), is_verbose); else { getter = objview_get_getter(object, i); setter = objview_get_setter(object, i); printf("get "); dvalue_print(getter, is_verbose); printf(", set "); dvalue_print(setter, is_verbose); } printf("\n"); } objview_free(object); if (!is_verbose) printf("}\n"); } dvalue_free(result); } static void handle_frame(session_t* obj, command_t* cmd) { const backtrace_t* calls; int frame; if (!(calls = inferior_get_calls(obj->inferior))) return; frame = obj->frame; if (command_len(cmd) >= 2) frame = command_get_int(cmd, 1); if (frame < 0 || frame >= backtrace_len(calls)) printf("stack frame #%2d doesn't exist.\n", frame); else { obj->frame = frame; preview_frame(obj, obj->frame); } } static void handle_help(session_t* obj, command_t* cmd) { const char* verb; if (command_len(cmd) > 1) { if (!(verb = find_verb(command_get_string(cmd, 1), NULL))) return; help_print(verb); } else help_print(NULL); } static void handle_list(session_t* obj, command_t* cmd) { const char* active_filename; int active_lineno = 0; const backtrace_t* calls; const char* filename; int lineno; int num_lines = 10; const source_t* source; calls = inferior_get_calls(obj->inferior); active_filename = backtrace_get_filename(calls, obj->frame); active_lineno = backtrace_get_linenum(calls, obj->frame); filename = active_filename; lineno = active_lineno; if (command_len(cmd) >= 2) num_lines = command_get_int(cmd, 1); if (command_len(cmd) >= 3) { filename = command_get_string(cmd, 2); lineno = command_get_int(cmd, 2); } if (!(source = inferior_get_source(obj->inferior, filename))) printf("source unavailable for %s.\n", filename); else { if (strcmp(filename, active_filename) != 0) active_lineno = 0; source_print(source, lineno, num_lines, active_lineno); obj->list_num_lines = num_lines; obj->list_filename = strdup(filename); obj->list_linenum = lineno + num_lines; obj->auto_action = AUTO_LIST; } } static void handle_up_down(session_t* obj, command_t* cmd, int direction) { const backtrace_t* calls; int new_frame; int num_steps; if (!(calls = inferior_get_calls(obj->inferior))) return; new_frame = obj->frame + direction; if (new_frame >= backtrace_len(calls)) printf("innermost frame: can't go up any further.\n"); else if (new_frame < 0) printf("outermost frame: can't go down any further.\n"); else { num_steps = command_len(cmd) >= 2 ? command_get_int(cmd, 1) : 1; new_frame = obj->frame + num_steps * direction; obj->frame = new_frame < 0 ? 0 : new_frame >= backtrace_len(calls) ? backtrace_len(calls) - 1 : new_frame; preview_frame(obj, obj->frame); } obj->auto_action = AUTO_UP_DOWN; obj->up_down_direction = direction; } static void handle_vars(session_t* obj, command_t* cmd) { const backtrace_t* calls; const char* call_name; const dvalue_t* value; const objview_t* vars; const char* var_name; int i; if (!(calls = inferior_get_calls(obj->inferior))) return; if (!(vars = inferior_get_vars(obj->inferior, obj->frame))) return; if (objview_len(vars) == 0) { call_name = backtrace_get_call_name(calls, obj->frame); printf("%s has no local variables.\n", call_name); } for (i = 0; i < objview_len(vars); ++i) { var_name = objview_get_key(vars, i); value = objview_get_value(vars, i); printf("var %s = ", var_name); dvalue_print(value, false); printf("\n"); } } static void handle_where(session_t* obj, command_t* cmd) { int frame = 0; const backtrace_t* calls; if (!(calls = inferior_get_calls(obj->inferior))) return; while (backtrace_get_linenum(calls, frame) <= 0) ++frame; preview_frame(obj, obj->frame); } static void handle_quit(session_t* obj, command_t* cmd) { inferior_detach(obj->inferior); } static void preview_frame(session_t* obj, int frame) { const backtrace_t* calls; const char* filename; int lineno; const source_t* source; if (!(calls = inferior_get_calls(obj->inferior))) return; backtrace_print(calls, frame, false); filename = backtrace_get_filename(calls, frame); lineno = backtrace_get_linenum(calls, frame); if (lineno == 0) printf("system call - no source provided\n"); else { if (!(source = inferior_get_source(obj->inferior, filename))) printf("source unavailable for %s.\n", filename); else source_print(source, lineno, 1, lineno); } } static bool validate_args(const command_t* this, const char* verb_name, const char* pattern) { int index = 0; int want_num_args; token_tag_t want_tag; const char* want_type; const char *p_type; if (strchr(pattern, '~')) want_num_args = (int)(strchr(pattern, '~') - pattern); else want_num_args = (int)strlen(pattern); if (command_len(this) - 1 < want_num_args) { printf("`%s`: expected at least %d arguments.\n", verb_name, want_num_args); return false; } p_type = pattern; while (index < command_len(this) - 1) { if (*p_type == '~') ++p_type; if (*p_type == '\0') break; switch (*p_type) { case 's': want_tag = TOK_STRING; want_type = "string"; break; case 'n': want_tag = TOK_NUMBER; want_type = "number"; break; case 'f': want_tag = TOK_FILE_LINE; want_type = "file:line"; break; } if (command_get_tag(this, index + 1) != want_tag) goto wrong_type; ++p_type; ++index; } return true; wrong_type: printf("`%s`: expected a %s for argument %d.\n", verb_name, want_type, index + 1); return false; } <file_sep>/src/compiler/utility.c #include "cell.h" #include "utility.h" void* fslurp(const char* filename, size_t *out_size) { void* buffer; FILE* file = NULL; if (!(file = fopen(filename, "rb"))) return false; *out_size = (fseek(file, 0, SEEK_END), ftell(file)); if (!(buffer = malloc(*out_size))) goto on_error; fseek(file, 0, SEEK_SET); if (fread(buffer, 1, *out_size, file) != *out_size) goto on_error; fclose(file); return buffer; on_error: return NULL; } bool fspew(const void* buffer, size_t size, const char* filename) { FILE* file = NULL; if (!(file = fopen(filename, "wb"))) return false; fwrite(buffer, size, 1, file); fclose(file); return true; } bool wildcmp(const char* filename, const char* pattern) { const char* cp = NULL; const char* mp = NULL; bool is_match = 0; // check filename against the specified filter string while (*filename != '\0' && *pattern != '*') { if (*pattern != *filename && *pattern != '?') return false; ++pattern; ++filename; } while (*filename != '\0') { if (*pattern == '*') { if (*++pattern == '\0') return true; mp = pattern; cp = filename + 1; } else if (*pattern == *filename || *pattern == '?') { pattern++; filename++; } else { pattern = mp; filename = cp++; } } while (*pattern == '*') pattern++; return *pattern == '\0'; } <file_sep>/src/debugger/posix.h #ifndef SSJ__POSIX_H__INCLUDED #define SSJ__POSIX_H__INCLUDED #if defined(_MSC_VER) #define _CRT_NONSTDC_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #define strcasecmp stricmp #define strtok_r strtok_s #if _MSC_VER < 1900 #define snprintf _snprintf #endif #endif #endif // SSJ__POSIX_H__INCLUDED
b2b2590a5a7b95c9b8e1aae5f49ae4c8a479cd0c
[ "Markdown", "JavaScript", "Makefile", "INI", "C#", "C" ]
141
C
svaarala/minisphere
87ae7f3c81808e90fec59f59d09f134adb852e28
539d4ef6b020e7873c255e7a6b747b7796fa0dd1
refs/heads/master
<repo_name>jm-cruz-d/pipelines-project<file_sep>/src/cleanWS.py def subChar(DF, column, old, new): DF[column] = DF[column].str.replace(old, new) return DF def changeType(DF, column, types): DF[column] = DF[column].astype(types) return DF def combCol(DF, nameNew, column1, column2): DF[nameNew] = DF[column1]+DF[column2] return DF def impCsv(DF, name): return DF.to_csv(name, header=True, index=False)<file_sep>/src/webscrp.py import pandas as pd import numpy as np import re as re import requests from bs4 import BeautifulSoup import cleanWS as cw url = "https://es.wikipedia.org/wiki/Trofeo_Pichichi" #Open the Page def getPage(url): res = requests.get(url) html = res.text soup = BeautifulSoup(html, 'html.parser') return soup pichi = getPage(url) #Create pichichi table def getPichichi(soup, postable, row, cellSeason, cellPlayers, cellGoals): table = soup.find_all('table')[postable] rows = table.find_all('tr')[row:] pichichi = [] for row in rows: cells = row.find_all('td') pichichi.append({ "season": re.sub("[()\\n]", "", cells[cellSeason].find('a').text), "players": re.sub("[0-9]?[()\\n]", "", cells[cellPlayers].text), "goals": int(re.sub("[()\\n]", "", cells[cellGoals].text)[:2]) }) return pd.DataFrame(pichichi) pc = getPichichi(pichi, 1, 76, 0, 1, 5) def subThings(DF, column, text): DF[column] = DF[column].replace('\[?[0-9]+\]?', text) return DF pc = subThings(pc, 'players', "") def convSeas(DF, column, range1, range2): lista = list(range(range1,range2)) DF[column]=lista return DF pc = convSeas(pc, 'season', 2000, 2020) #Select Capocannoniere (Pichichi Italy) pichIt=getPage("http://www.lalanternadelpopolo.it/Calcio%20-%20Capocannonieri%20Campionato%20Italia%20Albo%20d'Oro%20Vincitori.htm") def getCapo(soup): table = pichIt.find_all('table')[3] rows = table.select('tr')[77:97] capo = [] for row in rows: cells = row.find_all('td') capo.append({ "season": cells[0].text.strip(), "players": cells[1].text.strip(), "goals": cells[2].text.strip()}) return pd.DataFrame(capo) capo = getCapo(pichIt) #Delete Rows, just in case of two top scorers def deleteRow(DF, row): DF = DF.drop(row) return DF capo = deleteRow(capo, 16) #Select Top score form Premier League top = getPage('https://www.worldfootball.net/top_scorer/eng-premier-league/') def getTop(soup): table = top.find_all('table')[0] rows = table.select('tr')[1:24] rows tp = [] for row in rows: cells = row.find_all('td') tp.append({ "season": cells[0].text.strip(), "players": cells[2].text.strip(), "goals": cells[5].text.strip()}) return pd.DataFrame(tp) premierT = getTop(top) premierT = deleteRow(premierT, [1,2,11]) premierT = convSeas(premierT, 'season', 2000, 2020) #Select top League 1, Eredivisie and Bundesliga(Refactorizando) french = getPage('https://es.wikipedia.org/wiki/Anexo:M%C3%A1ximos_goleadores_de_la_Liga_Francesa') holl = getPage('https://es.wikipedia.org/wiki/Anexo:M%C3%A1ximos_goleadores_de_la_Eredivisie') bund = getPage('https://es.wikipedia.org/wiki/Anexo:Estad%C3%ADsticas_de_la_Bundesliga_de_Alemania') def getWiki(soup, postable, posrows, posSeason, posPlayers, posGoals): table = soup.find_all('table')[postable] rows = table.find_all('tr')[posrows:] wiki = [] for row in rows: cells = row.find_all('td') wiki.append({ "season": cells[posSeason].text.strip(), "players": cells[posPlayers].text.strip(), "goals": cells[posGoals].text.strip()}) return pd.DataFrame(wiki) holland = getWiki(holl, 0, 44, 0, 1, 2) frenchs = getWiki(french, 0, 62, 0, 1, 3) bundSc = getWiki(bund, 3, 37, 0, 1, 3) hollT = convSeas(holland, 'season', 2000, 2019) frenchT = convSeas(frenchs, 'season', 2000, 2018) bundT = convSeas(bundSc, 'season', 2000, 2019) #Cleaning with cleanWS bundT = cw.subChar(bundT, 'players', 'ž', 'z') bundT = cw.subChar(bundT, 'players', ' <NAME>', '') bundT = cw.subChar(bundT, 'players', ' <NAME>', '') bundT = cw.subChar(bundT, 'players', ' <NAME>', '') frenchT = cw.subChar(frenchT, 'players', 'CisséPauleta', 'Cissé') frenchT = cw.subChar(frenchT, 'players', 'ć', 'c') frenchT = cw.subChar(frenchT, 'players', ' Nené', '') hollT = cw.subChar(hollT, 'players', 'ž', 'z') premierT = cw.subChar(premierT, 'players', 'Kun\s.+', '<NAME>') premierT = cw.subChar(premierT, 'players', 'Su.+', 'Suárez') premierT = cw.subChar(premierT, 'players', 'Ma.+', 'Mané') spainT = cw.subChar(pc, 'players', '\s\[[0-9]+\]', '') italyT = capo #Change types with cleanWS bundT = cw.changeType(bundT, 'season', str) frenchT = cw.changeType(frenchT, 'season', str) hollT = cw.changeType(hollT, 'season', str) premierT = cw.changeType(premierT, 'season', str) spainT = cw.changeType(spainT, 'season', str) italyT = cw.changeType(italyT, 'season', str) #Combine columns bundT = cw.combCol(bundT, 'Comb', 'players', 'season') frenchT = cw.combCol(frenchT, 'Comb', 'players', 'season') hollT = cw.combCol(hollT, 'Comb', 'players', 'season') premierT = cw.combCol(premierT, 'Comb', 'players', 'season') spainT = cw.combCol(spainT, 'Comb', 'players', 'season') italyT = cw.combCol(italyT, 'Comb', 'players', 'season') #Import to csv cw.impCsv(bundT, './output/bundT.csv') cw.impCsv(frenchT, './output/frenchT.csv') cw.impCsv(hollT, './output/hollT.csv') cw.impCsv(premierT, './output/premierT.csv') cw.impCsv(spainT, './output/spainT.csv') cw.impCsv(italyT, './output/italyT.csv') <file_sep>/src/clean.py import pandas as pd import numpy as np import re as re import chardet #Character encoding auto-detection in Python import cleanWS as cw lfile = './input/top250-00-19.csv' #Open DataFrame def openDf(file): with open(file, 'rb') as f: result = chardet.detect(f.read()) return pd.read_csv(file, encoding=result['encoding']) df = openDf(lfile) #Delete columns with more than 1000 nulls def nullOut(x): null_cols = x.isnull().sum() return x.drop((list(null_cols[null_cols>1000].index)), axis=1) df=nullOut(df) #Delete columns of any DF, parameter "x" is DF and the parameter "y" must be a list def dropCol(x, y): return x.drop(columns=y) df=dropCol(df,['Position','League_to', 'Age']) #Converter to millions, parameter "x" is DF and the parameter "y" is a column def convMill(x, y): x[y]=x[y]/10**6 return x df = convMill(df, 'Transfer_fee') #Makes filters, parameter "x" is DF, the parameter "y" is a column name and "ligas" is a list with the elements that #you want to filter in column "y" def generaFiltros(x, y, ligas): prob = x[(x[y].isin(ligas))] return prob slclig = ['Bundesliga','LaLiga','Premier League','League One', 'Serie A', 'Eredivisie'] df = generaFiltros(df, 'League_from', slclig) #Convert Season in Summer transfermarket and ints values def convertSeason(DF, column, length): se = sorted(list(set(DF[column]))) lista=[] for s in se: lista.append(s[:length]) for col in DF[column]: for i in range(0,len(lista)): if col == se[i]: DF[column] = DF[column].replace({col: lista[i]}) return DF df = convertSeason(df, 'Season', 4) def changeType(DF, column, types): DF[column] = DF[column].astype(types) return DF df = changeType(df, 'Season', int) def changeNamecol(DF, column, newname): DF = DF.rename(columns={column: newname}) return DF df = changeNamecol(df, 'Season', 'Summer') #Combine columns df = cw.changeType(df, 'Summer', str) df = cw.combCol(df, 'Comb', 'Name', 'Summer') #Import DF to csv cw.impCsv(df, './output/TransferLeagues.csv')<file_sep>/README.md ### Pipelines-project # Are football teams influented by the top scorer? This project compares a Dataset with transfers since 2000 and top scorers from Bundesliga, LaLiga, League One, Premier League, Serie A and Eredivisie. Inroducing the year and the league, you can check if the top scorer was signed by some teams. You can use the command -h to know which parameters you must insert. https://github.com/jm-cruz-d/pipelines-project<file_sep>/main.py import sys import argparse import subprocess import chardet import pandas as pd from fpdf import FPDF def openDf(file): with open(file, 'rb') as f: result = chardet.detect(f.read()) return pd.read_csv(file, encoding=result['encoding']) transfers = openDf('./output/TransferLeagues.csv') Bundesliga = openDf('./output/bundT.csv') LaLiga = openDf('./output/spainT.csv') Premier_League = openDf('./output/premierT.csv') League_One = openDf('./output/frenchT.csv') Serie_A = openDf('./output/italyT.csv') Eredivisie = openDf('./output/hollT.csv') def recibeConfig(): parser = argparse.ArgumentParser(description='¿Será el pichichi el fichaje del verano?') parser.add_argument('--summer', help='Summer transfer market between 2000-2019') parser.add_argument('--league', help='Select league Bundesliga: "./output/bundT.csv", LaLiga: "./output/spainT.csv", Premier_League: "./output/premierT.csv", League_One: "./output/frenchT.csv", Serie_A: "./output/italyT.csv", Eredivisie: "./output/hollT.csv"') args = parser.parse_args() #print(args) return args def main(): config = recibeConfig() newDF=transfers[0:0] league = openDf(config.league) year = int(config.summer) for name in transfers['Comb']: for player in league['Comb']: if name == player: newDF = newDF.append(transfers.loc[transfers['Comb'] == name]) if newDF.empty: return 'Not coincidence' else: return newDF[newDF['Summer']==year] #Try to create a PDF with result #def createPDF(x): # pdf = FPDF() # pdf.add_page() # pdf.image("./output/castolo.jpeg", x=60, y=30, w=100) # pdf.set_font("Arial", size=12) # pdf.ln(85) # move 85 down # pdf.cell(200, 5, txt=x, ln=1, align="C") # return pdf.output("./output/result.pdf") #createPDF(main()) if __name__=="__main__": print(main())
b068547980a428c5b2532fc552113703725d5cfe
[ "Markdown", "Python" ]
5
Python
jm-cruz-d/pipelines-project
ad1ef1c45f3762f3e2738d00a45d7fc5f4f5b86e
3d4ecb1656636610c721bfc661fa274c0f0e2146
refs/heads/master
<repo_name>islamshu/maba<file_sep>/app/Http/Controllers/SliderController.php <?php namespace App\Http\Controllers; use App\Slider; use Illuminate\Http\Request; class SliderController extends Controller { public function __construct() { $this->middleware(['permission:read-slider'])->only('index'); $this->middleware(['permission:create-slider'])->only('create'); $this->middleware(['permission:update-slider'])->only('edit'); $this->middleware(['permission:delete-slider'])->only('destroy'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view ('admin.sliders')->with('sliders', Slider::get()); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view ('admin.addSlider'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $request->validate([ 'text'=> 'required', 'image' => 'required' ]); $request_data = $request->except(['image']); $path = $request->image->store('sliders'); $request_data['image']=$path; Slider::create($request_data); return redirect('admin/sliders'); } /** * Display the specified resource. * * @param \App\Slider $slider * @return \Illuminate\Http\Response */ public function show(Slider $slider) { // } /** * Show the form for editing the specified resource. * * @param \App\Slider $slider * @return \Illuminate\Http\Response */ public function edit(Slider $slider) { return view ('admin.EditSlider')->with('slider',$slider); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Slider $slider * @return \Illuminate\Http\Response */ public function update(Request $request, Slider $slider) { $request->validate([ 'text'=> 'required', 'image' => 'required' ]); $request_data = $request->except(['image']); if($request->image !=null) { $path = $request->image->store('sliders'); $slider->image =$path; } $request_data['image']=$path; $slider->update($request_data); return redirect('admin/sliders'); } /** * Remove the specified resource from storage. * * @param \App\Slider $slider * @return \Illuminate\Http\Response */ public function destroy( $id) { Slider::destroy($id); return redirect('/admin/sliders'); } } <file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use App\User; use Hash; use Illuminate\Http\Request; class UserController extends Controller { public function __construct() { $this->middleware(['permission:read-users'])->only('index'); $this->middleware(['permission:create-users'])->only('create'); $this->middleware(['permission:update-users'])->only('edit'); $this->middleware(['permission:delete-users'])->only('destroy'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view ('admin.users')->with('users' , User::get()); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view ('admin.addUser'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $request->validate([ 'firstName' => 'required', 'lastName' => 'required', 'email' => 'required', 'password' => '<PASSWORD>', ]); $request_data =$request->except(['password_confiramtion']); // $path= $request->image->store('Users'); // $request_data['image']=$path; $user =User::create($request_data); $user->attachRole('admin'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit(User $user) { return view ('admin.editUser')->with('user' ,$user); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, User $user) { $request->validate([ 'firstName' => 'required', 'lastName' => 'required', 'email' => 'required', ]); $request_data =$request->except(['permissions']); $user->update($request_data); $user->syncPermissions($request->permissions); return redirect('/admin/users'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { User::destroy($id); return redirect('/admin/users'); } } <file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::get('/','HomeController@index'); Route::get('/products/{id}','HomeController@show'); Route::get('/logout','Auth\LoginController@logout'); Route::get('/lgoin','Auth\LoginController@login'); Route::resource('/profile', 'ProfileController'); Route::resource('/cart', 'CartController'); Route::get('pdf','ProductController@generatePDF'); Route::get('login/facebook', 'Auth\LoginController@redirectToFacebook')->name('fblogin'); Route::get('login/facebook/callback','Auth\LoginController@handelFacebookCallback')->name('fbcallback'); Route::resource('/admin/users', 'UserController')->middleware(['auth']); Route::resource('/admin/products', 'ProductController')->middleware(['auth']); Route::resource('/admin/sliders', 'SliderController')->middleware(['auth']); <file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use App\Product; use App\Slider; use Illuminate\Http\Request; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ // public function __construct() // { // $this->middleware('auth'); // } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index(Request $request) { $product = Product::when($request->search, function ($q) use ($request) { return $q->where('name','like', '%' . $request->search . '%')-> orWhere('title','like', '%' . $request->search . '%'); }) ->latest()->paginate(5); $slider =Slider::get(); return view('products') ->with('products' , $product) ->with('sliders' , $slider); } public function show($id){ return view('product')->with('product' , Product::find($id)); } public function about(){ return view('about'); } } <file_sep>/app/Http/Controllers/ProductController.php <?php namespace App\Http\Controllers; use App\Product; use Illuminate\Http\Request; use PDF; class ProductController extends Controller { public function __construct() { $this->middleware(['permission:read-products'])->only('index'); $this->middleware(['permission:create-products'])->only('create'); $this->middleware(['permission:update-products'])->only('edit'); $this->middleware(['permission:delete-products'])->only('destroy'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('admin.Products')->with('products',Product::get()); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.addProduct'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $path = $request->imageURL->store('products'); $product = new Product(); $product->name = $request->name; $product->title = $request->title; $product->subtitle = $request->subtitle; $product->price = $request->price; $product->description = $request->description; $product->imageURL = $path; $product->save(); return redirect('/admin/products'); } /** * Display the specified resource. * * @param \App\Product $product * @return \Illuminate\Http\Response */ public function show(Product $product) { // } /** * Show the form for editing the specified resource. * * @param \App\Product $product * @return \Illuminate\Http\Response */ public function edit(Product $product) { return view('admin.editProduct')->with('product',$product); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Product $product * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $product = Product::find($id); if($request->image !=null) { $path= $request->images->store('products'); $product->image =$path; } $product->name = $request->name; $product->title = $request->title; $product->subtitle = $request->subtitle; $product->price = $request->price; $product->description = $request->description; $product->save(); return redirect('/admin/products'); } /** * Remove the specified resource from storage. * * @param \App\Product $product * @return \Illuminate\Http\Response */ public function destroy($id) { Product::destroy($id); return redirect('/admin/products'); } public function generatePDF(){ $pdf = PDF::loadView('PDF.products', ['products'=> Product::get()]); return $pdf->download('pdf.pdf'); } }
26fa6b73a7688e2d3950d4666feeeb76925d65af
[ "PHP" ]
5
PHP
islamshu/maba
9c0cf048e8d7ff939704ec4a2dd206b2829bb079
f52b5a7ad4bbb30ae5a2c15127efa3d1a3d1113f
refs/heads/master
<file_sep>$( function () { $('form').submit( function (e){ e.preventDefault(); var programType = $('.programType').val(); var educationLevel = $('.educationLevel').val(); if (programType === null && educationLevel === null) { console.log('all logos light up'); $('.logoWrapper').html(""); $('.logoWrapper').html("<table class=logosTable><tr><td><img src='images/aci - color.png'><td><img src='images/acm - color.png'><td><img src='images/AFE color.png'><td><img src='images/aci - color.png'><tr><td><img src='images/acm - color.png'><td><img src='images/aci - color.png'><td><img src='images/acm - color.png'><td><img src='images/AFE color.png'></table>") } else if (programType === 'scholarship' && educationLevel === null) { $('.logoWrapper').html(""); } else if (programType === null && educationLevel === 'kindergarten') { $('.logoWrapper').html(""); } else if (programType === 'scholarship' && educationLevel === 'kindergarten') { $('.logoWrapper').html(""); } else if (programType === 'scholarship' && educationLevel === 'highSchool') { $('.logoWrapper').html(""); } else if (programType === 'loan' && educationLevel === null) { $('.logoWrapper').html(""); } else if (programType === 'scholarship' && educationLevel === null) { $('.logoWrapper').html(""); } }); });
87984e3c6d3a5a8940a901e9022a347a44546cde
[ "JavaScript" ]
1
JavaScript
ryeh88/Society-Education-Programs
ad195de83352b6c7c2119ee82c07ab94b27af111
fd9e7fb6880c8b149bcc903e8e97aab84c0d6a7f
refs/heads/master
<repo_name>nolanjacobson/thegraph-cryptogoats<file_sep>/cryptogoats-nextjs/components/CryptoGoats/index.js export { default } from './CryptoGoats' <file_sep>/cryptogoats-nextjs/pages/index.js import React, { Component } from "react"; import { gql } from "apollo-boost"; import { ApolloClient } from "apollo-client"; import { InMemoryCache } from "apollo-cache-inmemory"; import { ApolloProvider, Query } from "react-apollo"; import { Grid, LinearProgress, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Button, } from "@material-ui/core"; import Error from "../components/Error/Error"; import CryptoGoats from "../components/CryptoGoats/CryptoGoats"; import { HttpLink } from "apollo-link-http"; if (!process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT) { throw new Error( "NEXT_PUBLIC_GRAPHQL_ENDPOINT environment variable not defined" ); } const client = new ApolloClient({ link: new HttpLink({ uri: process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT }), cache: new InMemoryCache(), }); const CRYPTOGOATS_QUERY = gql` { cryptoGoats { id owner goatName goatMetadata goatRandomness } } `; export default class Home extends Component { constructor(props) { super(props); this.state = { withImage: false, withName: false, orderBy: "displayName", showHelpDialog: false, }; } toggleHelpDialog = () => { this.setState((state) => ({ ...state, showHelpDialog: !state.showHelpDialog, })); }; gotoQuickStartGuide = () => { window.location.href = "https://thegraph.com/docs/quick-start"; }; render() { return ( <ApolloProvider client={client}> <div className="App"> <Grid container direction="column"> <Query query={CRYPTOGOATS_QUERY}> {({ data, error, loading }) => { return loading ? ( <LinearProgress variant="query" style={{ width: "100%" }} /> ) : error ? ( <Error error={error} /> ) : ( <> <CryptoGoats cryptoGoats={data.cryptoGoats} /> </> ); }} </Query> </Grid> </div> </ApolloProvider> ); } } <file_sep>/cryptogoats-subgraph/src/mapping.ts import { BigInt, } from "@graphprotocol/graph-ts" import { CryptoGoats, Approval, ApprovalForAll, NewGoat, OwnershipTransferred, Transfer, UpdatedGoatMetadata } from "../generated/CryptoGoats/CryptoGoats" import { CryptoGoat } from "../generated/schema" export function handleNewGoat(event: NewGoat): void { let cryptoGoat = new CryptoGoat(event.params.goatId.toHex()) cryptoGoat.owner = event.transaction.from; cryptoGoat.goatName = event.params.name cryptoGoat.goatRandomness = 100 cryptoGoat.goatMetadata = null cryptoGoat.save() } export function handleUpdatedGoatMetadata(event: UpdatedGoatMetadata): void { let id = event.params.goatId.toHex(); let cryptoGoat = CryptoGoat.load(id); cryptoGoat.goatMetadata = event.params.goatMetadata; cryptoGoat.save() } export function handleTransfer(event: Transfer): void { let id = event.params.tokenId.toHex(); let cryptoGoat = CryptoGoat.load(id); cryptoGoat.owner = event.params.to; cryptoGoat.save() } <file_sep>/cryptogoats-subgraph/scripts/create_goat.js const CryptoGoat = artifacts.require('./CryptoGoat.sol') module.exports = async (callback) => { const registry = await CryptoGoat.deployed() console.log('Account address:', registry.address) const tx = await registry.requestNewRandomGoat(77239, "<NAME>") const tx2 = await registry.requestNewRandomGoat(7777777, "<NAME>") const tx3 = await registry.requestNewRandomGoat(7, "<NAME>") const tx4 = await registry.requestNewRandomGoat(777, "<NAME>") callback(tx.tx) } <file_sep>/README.md # The Graph + Chainlink + NFT's In this repository, you will find two folders. The first folder contains a simple NextJS server-side React application that is read-only and renders an array of NFT's on the Rinkeby testnet that represent "CryptoGoats". You should be able to see their picture which is hosted and pinned on IPFS via Pinata, their unique Id in the collection of CryptoGoats, the current owner of the NFT, and their randomly generated stats where I leveraged Chainlink VRF function in the second folder for on-chain randomness. The second repository contains a suite of folders with a smart contract that represents the ERC-721 NFT's, migrations, truffle scripts to generate the CryptoGoats and their IPFS metadata, and a simple subgraph that maps over `NewGoat`, `UpdatedGoatMetadata`, and `Transfer` events. The subgraph can be found on The Graph at the following url: https://thegraph.com/explorer/subgraph/nolanjacobson/cryptogoats <file_sep>/cryptogoats-subgraph/migrations/2_deploy_contract.js const CryptoGoat = artifacts.require('./CryptoGoats.sol') const RINKEBY_VRF_COORDINATOR = '0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B' const RINKEBY_LINKTOKEN = '0x01be23585060835e02b77ef475b0cc51aa1e0709' const RINKEBY_KEYHASH = '0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311' module.exports = async function(deployer) { await deployer.deploy(CryptoGoat, RINKEBY_VRF_COORDINATOR, RINKEBY_LINKTOKEN, RINKEBY_KEYHASH) }
b243f66f10a6f91b21da1ef89cb287ec4fd474a6
[ "JavaScript", "TypeScript", "Markdown" ]
6
JavaScript
nolanjacobson/thegraph-cryptogoats
0b66550689d70e92647092b29cdb756b214a5f2e
4eef5219fb13b6ed914a979ab695b81c2aeb2ddd
refs/heads/main
<file_sep>import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router'; import Home from '../views/root/Home.vue'; const routes: RouteRecordRaw[] = [ { path: '/', name: 'Home', component: Home, redirect: '/index', children: [ { path: '/index', name: 'HomeView', component: () => import(/* webpackChunkName: "HomeView" */ '../views/home/HomeView.vue'), }, { path: '/category', name: 'CategoryView', component: () => import(/* webpackChunkName: "CategoryView" */ '../views/category/CategoryView.vue'), }, { path: '/about', name: 'About', component: () => import(/* webpackChunkName: "about" */ '../views/AboutWeb/About.vue'), }, { path: '/tags', name: 'Tags', component: () => import(/* webpackChunkName: "tags" */ '../views/tags/TagsView.vue'), }, { path: '/event', name: 'Event', component: () => import(/* webpackChunkName: "event" */ '../views/event/EventView.vue'), }, { path: '/other', name: 'Other', component: () => import(/* webpackChunkName: "other" */ '../views/other/OtherView.vue'), }, ], }, ]; const router = createRouter({ history: createWebHashHistory(process.env.BASE_URL), routes, }); export default router; <file_sep>import mitt from 'mitt'; declare module '@vue/runtime-core' { export interface ComponentCustomProperties { emitter: typeof mitt; $validate: (data: object, rule: object) => boolean; } } <file_sep>import {createApp} from 'vue'; import App from './App.vue'; import router from './router'; import mitt from 'mitt'; import '@/assets/css/init.css'; import '@/assets/font/css/font-awesome.min.css'; const emitter = mitt(); const app = createApp(App); app.config.globalProperties.emitter = emitter; app.use(router); app.mount('#app'); <file_sep>const utils = { isPhone: (): boolean => !!(navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i)), throttle: (fn: any, self: any, time: number = 1000) => { let flag: boolean = true; return (...args: any[]) => { if (flag) { flag = false; setTimeout(() => { flag = true; fn.call(self, ...args); }, time); } }; }, debounce: (fn: any, self: any, time: number = 1000) => { let timeLock: any = null return function (...args: any[]) { clearTimeout(timeLock) timeLock = setTimeout(() => { fn.call(self, ...args) }, time) } }, }; export default utils; <file_sep>import service from '@/request/request'; export function getHomeInfo(data: any) { return service({ url: '/test', method: 'post', }); }
6539c1d6e6f26bddb449f1699b7551afc3eee90b
[ "TypeScript" ]
5
TypeScript
ssieie/zx_blog
b45365bb80bb3f0609221e15794758dd98804d48
587ab797ca0aaf33d2f3f8da9e40006cc8320f3c
refs/heads/master
<repo_name>gmavkitx/vwkit-matrix<file_sep>/matrix-module-common/src/main/java/matrix/module/common/helper/Assert.java package matrix.module.common.helper; import java.util.regex.Pattern; /** * @author wangcheng */ public class Assert { /** * 判断不为空 * * @param content 内容 * @param varName 参数名称 */ public static void isNotNull(Object content, String varName) { boolean isTrue = content == null || (content.getClass() == String.class && "".equals(content)); if (isTrue) { throw new IllegalArgumentException(varName + " not be null!"); } } /** * 判断字符串长度最小值 * * @param content 内容 * @param length 长度 * @param varName 参数名称 */ public static void minLength(String content, Integer length, String varName) { Assert.isNotNull(content, varName); if (content.length() < length) { throw new IllegalArgumentException(varName + "长度不允许小于" + length + "!"); } } /** * 判断字符串长度最大值 * * @param content 内容 * @param length 长度 * @param varName 参数名称 */ public static void maxLength(String content, Integer length, String varName) { Assert.isNotNull(content, varName); if (content.length() > length) { throw new IllegalArgumentException(varName + "长度不允许大于" + length + "!"); } } /** * 判断数字最小值 * * @param content 内容 * @param varName 参数名称 */ public static void minNum(Integer content, Integer minNum, String varName) { Assert.isNotNull(content, varName); if (content < minNum) { throw new IllegalArgumentException(varName + "数字不允许小于" + minNum + "!"); } } /** * 判断数字最大值 * * @param content 内容 * @param varName 参数名称 */ public static void maxNum(Integer content, Integer maxNum, String varName) { Assert.isNotNull(content, varName); if (content > maxNum) { throw new IllegalArgumentException(varName + "数字不允许大于" + maxNum + "!"); } } /** * 不满足正则 * * @param regex 正则 * @param content 内容 * @param msg 信息 * @param flag 标记 */ public static void matchRegex(String regex, String content, String msg, Integer flag) { if (flag == null) { if (!Pattern.compile(regex).matcher(content).matches()) { throw new IllegalArgumentException(msg); } } else { if (!Pattern.compile(regex, flag).matcher(content).matches()) { throw new IllegalArgumentException(msg); } } } /** * 状态不为True */ public static void state(Boolean value, String msg) { if (!value) { throw new IllegalArgumentException(msg); } } } <file_sep>/matrix-module-common/src/main/java/matrix/module/common/utils/PackageScanUtil.java package matrix.module.common.utils; import java.io.File; import java.util.ArrayList; import java.util.List; /** * 包扫描工具 * * @author wangcheng */ public class PackageScanUtil { /** * 获取文件列表 * * @param fileList 参数 * @param filePath 参数 * @return List */ private static List<File> getFileList(List<File> fileList, String filePath) { File[] files = (new File(filePath.toString())).listFiles(); if (files != null && files.length > 0) { for (File file : files) { if (!file.isDirectory()) { fileList.add(file); } else { getFileList(fileList, file.getAbsolutePath()); } } } return fileList; } /** * 获取class列表 * * @param packageName 参数 * @return List */ private static List<Class<?>> getClasses(String packageName) { List<Class<?>> classList = new ArrayList<Class<?>>(); String dirPath = PackageScanUtil.class.getResource("/").getPath() + packageName.replace(".", File.separator); List<File> fileList = getFileList(new ArrayList<>(), dirPath); for (File file : fileList) { String classPath = file.getAbsolutePath().replace(File.separator, "."); classPath = classPath.substring(classPath.indexOf(packageName), classPath.indexOf(".class")); try { classList.add(Class.forName(classPath)); } catch (ClassNotFoundException ignored) { } } return classList; } /** * 扫描 * * @param packageName 参数 * @param callback 参数 */ public static void scan(String packageName, CallBack callback) { List<Class<?>> classList = getClasses(packageName); if (classList.size() > 0 && callback != null) { callback.invoke(classList); } else { System.err.println(packageName + ".未找到class"); } } public interface CallBack { /** * 调用 * * @param classList 参数 */ void invoke(List<Class<?>> classList); } } <file_sep>/matrix-module-based-starter/src/main/java/matrix/module/based/config/GlobalExceptionAutoConfiguration.java package matrix.module.based.config; import matrix.module.common.bean.Result; import matrix.module.common.constant.BaseCodeConstant; import matrix.module.common.exception.GlobalControllerException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author wangcheng */ @Configuration @ControllerAdvice public class GlobalExceptionAutoConfiguration { private static Logger logger = LogManager.getLogger(GlobalExceptionAutoConfiguration.class); @ExceptionHandler(GlobalControllerException.class) @ResponseStatus(code = HttpStatus.OK) @ResponseBody public Result<?> defaultHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) { logger.error(e); return Result.fail(e.getMessage()).setResultCode(BaseCodeConstant.FAIL); } }
4bbb268891f8b5e402f3e4e829b35cbe0c6b88e1
[ "Java" ]
3
Java
gmavkitx/vwkit-matrix
7b72f1aa9dc213f15818d320001772fc1f6e0e95
e08385fcaaa3eecc5c4692d0cc752436bf0c3d55
refs/heads/master
<file_sep>package br.com.service; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.gson.JsonObject; import br.com.queue.RedisMQ; import br.com.repository.model.DefaultResponse; @Service public class PubService { private static final String SUB_CHANNEL = "sub-channel"; private final RedisMQ redisMQ; @Autowired public PubService(RedisMQ redisMQ) { this.redisMQ = redisMQ; } public DefaultResponse pub() { String randomMessageUUID = this.generateRandomUUID(); this.sendMessage(SUB_CHANNEL, this.generateMessageEntityAsString(randomMessageUUID)); return new DefaultResponse(true, "Message generated with random UUID: " + randomMessageUUID); } private void sendMessage(String channel, String message) { this.redisMQ.pushNotification(channel, message); } private String generateRandomUUID() { return UUID.randomUUID().toString(); } private String generateMessageEntityAsString(String uuid) { JsonObject message = new JsonObject(); message.addProperty("value", uuid); return message.toString(); } } <file_sep># Redis PubSub with RPUSH and RPOP - Spring boot simple implementation This project has 2 simple systems, both connected to redis. One produce messages and publish at redis, and the other consumes these messages and write them in a hsql database. ## Run project * Install docker https://www.docker.com At root folder, where docker-compose.yml file is located, run the following commands: * docker-compose build * docker-compose up -d ## API Endpoints ### Publish message * http://localhost:8083/pub/ * `method`: POST * response: ```json { "success": true, "message": "Message generated with random UUID: cb897567-4452-4662-bbd2-8f465ce707a2" } ``` ## APP Web * http://localhost:8084/sub <file_sep>version: '3' services: redis: image: redis container_name: redis command: redis-server ports: - "6379:6379" networks: - app_net pub: links: - redis build: dockerfile: ./Dockerfile context: ./pub image: manoelsilva/pub container_name: pub ports: - "8083:8083" networks: - app_net depends_on: - redis sub: links: - redis build: dockerfile: ./Dockerfile context: ./sub image: manoelsilva/sub container_name: sub ports: - "8084:8084" networks: - app_net depends_on: - redis networks: app_net: driver: bridge<file_sep>FROM maven:3.3-jdk-8 MAINTAINER <NAME> COPY . /pub WORKDIR /pub RUN mvn clean compile package WORKDIR /pub/target ENTRYPOINT java -jar pub-0.0.1-SNAPSHOT-spring-boot.jar EXPOSE 8083<file_sep>package br.com.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import br.com.service.SubService; @Controller public class SubController { private SubService service; @Autowired public SubController(SubService service) { this.service = service; } @GetMapping(value = { "/", "home" }) public String home(ModelMap model) { model.addAttribute("messages", service.getMessages()); return "home"; } } <file_sep>CREATE TABLE messages ( id INTEGER PRIMARY KEY, value VARCHAR(355) );<file_sep>redis.cluster-support=false spring.redis.cluster.nodes[0]= redis.host=redis redis.port=6379<file_sep>package br.com.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.gson.Gson; import br.com.repository.MessageRepository; import br.com.repository.entity.Message; import lombok.extern.log4j.Log4j; @Service @Log4j public class SubService { private MessageRepository repository; @Autowired public SubService(MessageRepository repository) { this.repository = repository; } public void buildMessages(String json) { this.repository.save(this.extractMessageFromJson(json)); } public List<Message> getMessages() { return this.repository.findAll(); } private Message extractMessageFromJson(String json) { log.info("json at extractMessageFromJson(String json): " + json); return new Gson().fromJson(json, Message.class); } } <file_sep>package br.com.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import br.com.repository.entity.Message; @Repository public interface MessageRepository extends CrudRepository<Message, Long>{ @Override List<Message> findAll(); } <file_sep>server.contextPath=/pub server.port=${port:8083}<file_sep>package br.com.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import br.com.repository.model.DefaultResponse; import br.com.service.PubService; @RestController public class PubController { private PubService service; @Autowired public PubController(PubService service) { this.service = service; } @PostMapping({ "", "/" }) public ResponseEntity<DefaultResponse> publishMessage() { return ResponseEntity.ok(this.service.pub()); } } <file_sep>FROM maven:3.3-jdk-8 MAINTAINER <NAME> COPY . /sub WORKDIR /sub RUN mvn clean compile package WORKDIR /sub/target ENTRYPOINT java -jar sub-0.0.1-SNAPSHOT-spring-boot.jar EXPOSE 8084
64cf137774bcaa5c7378a9566a9a936af3fcf7fa
[ "SQL", "YAML", "Markdown", "INI", "Java", "Dockerfile" ]
12
Java
ManoelSilva/redis-pubSub
4eaea0df6978b44dc5c46266a6577cbc5e7472d5
dbc8e0f134f61439cf3231096c80834e26a6c07d
refs/heads/master
<file_sep>import View from 'beff/View'; import template from 'hgn!../templates/zoom-slider'; export default View.extend({ mustache: template, init({ cropWidth, cropHeight, allowTransparency, initialScale }) { this._cropWidth = cropWidth; this._cropHeight = cropHeight; this._initialScale = initialScale || 1.0; this._lowerBoundFn = allowTransparency ? Math.min : Math.max; this._super(); this.on('image-loaded', (imageDimensions) => this._calculateScaleAttrs(imageDimensions)); }, rendered() { this._$slider = this.$view.find('.js-scale-slider'); this._$slider.on('input', () => this.trigger('scale', this._currentScale())); }, reset() { this._$slider.val(100).trigger('change'); }, disable() { this.$view.addClass('disabled'); this._$slider.prop('disabled', true); }, enable() { this.$view.removeClass('disabled'); this._$slider.prop('disabled', false); }, _calculateScaleAttrs(imageDimensions) { const widthScaleMin = this._cropWidth / imageDimensions.width; const heightScaleMin = this._cropHeight / imageDimensions.height; this._scaleMin = this._lowerBoundFn(widthScaleMin, heightScaleMin); this._scaleStep = (1.0 - this._scaleMin) / 100; if (this._initialScale) { const initialValue = Math.max(this._initialScale - this._scaleMin, 0); this._$slider.val(Math.round(initialValue / this._scaleStep)).trigger('change'); delete this._initialScale; } }, _currentScale() { if (!this._scaleMin || !this._scaleStep) { return; } const value = this._$slider.val(); if (value === 100) { return 1.0; } return this._scaleMin + (value * this._scaleStep); } });
e989eaca92051c69c7ae7f2e3be97cd1d8fa3850
[ "JavaScript" ]
1
JavaScript
mrjoelkemp/helicropter
231fe405f613db66f82c1f3eef986ce5e0e4c0f6
acf64fbbd62fae333b13f00b37149440c517205c
refs/heads/master
<repo_name>ZhangCrystal/react-redux-promise-demo<file_sep>/app/index.js import React from 'react'; import {createStore, applyMiddleware, compose} from 'redux'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import promiseMiddleware from "redux-promise"; import rootReducer from "./reducers"; import logger from 'redux-logger' import "babel-polyfill"; import App from './pages/App'; const isProduction = process.env.NODE_ENV === "production"; const store = isProduction ? compose(applyMiddleware(promiseMiddleware,logger))(createStore)(rootReducer) : compose( applyMiddleware(promiseMiddleware,logger), window.devToolsExtension ? window.devToolsExtension() : (f) => f, )(createStore)(rootReducer); ReactDOM.render( <Provider store={store}> <div> <App /> </div> </Provider>, document.getElementById('app') );
400e72c972690b2b73564476ffde39b70c5b3cdb
[ "JavaScript" ]
1
JavaScript
ZhangCrystal/react-redux-promise-demo
a3da0c7629c328cfd322d8eb64a4dfb44a04fa7d
7dc6174b6767878431ede0d050e94c538c0c5995
refs/heads/master
<file_sep>import '@testing-library/jest-dom'; import { getHeroeById, getHeroesByOwner } from '../../base/08-imp-exp'; import heroes from '../../base/data/heroes'; describe('Tests in heroes functions', () => { test('Must return an hero by id', () => { const id = 1; const heroe = getHeroeById(id); const heroeData = heroes.find((heroe) => heroe.id === id); expect(heroe).toEqual(heroeData); }); test('Must return undefined if hero does not exist', () => { const id = 10; const heroe = getHeroeById(id); const heroeData = undefined; expect(heroe).toBe(heroeData); }); test('Must retrun DC heroes', () => { const owner = 'DC'; const heroesArr = getHeroesByOwner(owner); const heroesData = heroes.filter((heroe) => heroe.owner === owner); expect(heroesArr).toEqual(heroesData); }); test('Must retrun marvel heores', () => { const owner = 'Marvel'; const heroesArrLength = getHeroesByOwner(owner); const heroesDataLength = heroes.filter((heroe) => heroe.owner === owner); expect(heroesArrLength.length).toBe(heroesDataLength.length); }); });<file_sep>import React , { useState } from 'react'; import PropTypes from 'prop-types' const CounterApp = ({value = 10}) =>{ const [ counter, setCounter ] = useState(value); //HandleApp const handleApp =(e) => setCounter( (c)=>c+1 ); const handleAppReset =(e) =>{ // setCounter(counter+1); setCounter( (c)=>value ); } const handleAppSubstract =(e) =>{ // setCounter(counter+1); setCounter( (c)=>c-1 ); } return( <> <h1>CounterApp</h1> <h2> { counter } </h2> <button onClick={ handleApp }>+1</button> <button onClick={ handleAppReset }>Reset</button> <button onClick={ handleAppSubstract }>-1</button> </> ); } CounterApp.propTypes ={ value: PropTypes.number } export default CounterApp;<file_sep>import '@testing-library/jest-dom'; import { getUser, getUsuarioActivo } from "../../base/05-funciones"; describe('Tests at 05-funciones', () => { test('getUser Must return an object', () => { const userTest = { uid: 'ABC123', username: 'El_Papi1502' }; const user = getUser(); expect(user).toEqual(userTest); }); test('getUserActvie must return an object', () => { const nombre = 'Ernech'; const userTest = { uid: 'ABC567', username: nombre }; const user = getUsuarioActivo(nombre); expect(user).toEqual(userTest); }); });<file_sep>import '@testing-library/jest-dom'; import { retornaArreglo } from "../../base/07-deses-arr"; describe('Deses tests', () => { test('Must return an string and a number', () => { const [strings, numbers] = retornaArreglo(); // expect(arr).toEqual( // ['ABC', 123] // ) expect(strings).toBe('ABC'); expect(typeof strings).toBe('string'); expect(numbers).toBe(123); expect(typeof numbers).toBe('number'); }); });
7fb84c1029c64688a42256c35ea2894b266be547
[ "JavaScript" ]
4
JavaScript
Ernech/Counter-App-React
c566f64311b8958e781554745fa0dccb0431da6a
f87f50f048f5497b122246fd1e72ba2361d06030
refs/heads/master
<file_sep>Rails.application.routes.draw do devise_for :users # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html root to: "pages#home" get 'bookings', to: 'bookings#index' resources :bikes, only: [:index, :show, :new, :create] do resources :bookings, only: [:create] end resources :bookings, only: [:update] end #if statement with bookings for renter bookings for bikes # bookings.user # bookings.bike <file_sep>class CreateBikes < ActiveRecord::Migration[6.0] def change create_table :bikes do |t| t.string :category t.string :brand t.integer :price_per_day t.string :status t.string :brake_type t.integer :number_of_gears t.references :user, null: false, foreign_key: true t.timestamps end end end <file_sep>import Typed from 'typed.js'; const loadDynamicBannerText = () => { const text = document.querySelector('#banner-typed-text'); if (text) { new Typed('#banner-typed-text', { strings: ["For a New Experience", "a Dream", "a Goal", "BikeBNB"], typeSpeed: 50, loop: false }); }; } export { loadDynamicBannerText }; <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts 'Start seeding users...' Bike.destroy_all User.destroy_all photo = URI.open('https://static.vecteezy.com/system/resources/thumbnails/002/002/253/small_2x/beautiful-woman-wearing-sunglasses-avatar-character-icon-free-vector.jpg') user = User.create(email: "<EMAIL>", password: "<PASSWORD>") user.photo.attach(io: photo, filename: 'ari.png', content_type: 'image/png') photo = URI.open('https://cdn3.vectorstock.com/i/1000x1000/26/07/girl-icon-woman-avatar-face-icon-cartoon-style-vector-24742607.jpg') user = User.create(email: "<EMAIL>", password: "<PASSWORD>") user.photo.attach(io: photo, filename: 'hellen.png', content_type: 'image/png') photo = URI.open('https://miro.medium.com/max/525/1*lyyXmbeoK5JiIBNCnzzjjg.png') user = User.create(email: "<EMAIL>", password: "<PASSWORD>") user.photo.attach(io: photo, filename: 'eriko.png', content_type: 'image/png') photo = URI.open('https://p7.hiclipart.com/preview/118/942/565/computer-icons-avatar-child-user-avatar.jpg') user = User.create(email: "<EMAIL>", password: "<PASSWORD>") user.photo.attach(io: photo, filename: 'graciella.png', content_type: 'image/png') puts "...done seeding users." puts "Start seeding bikes..." photo = URI.open('https://images.pexels.com/photos/545004/pexels-photo-545004.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260') bike = Bike.new( brand: "Gazelle", price_per_day: 50, category: "Cruiser", address: "Rue de Marseille, Lyon 7e Arrondissement, Auvergne-Rhône-Alpes, France", number_of_gears: 4, status: "available", user_id: 1, description: "Almost new bike for rent!" ) bike.photo.attach(io: photo, filename: 'bike.png', content_type: 'image/png') bike.save! photo = URI.open('https://images.pexels.com/photos/5445300/pexels-photo-5445300.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260') bike = Bike.new( brand: "BMX", price_per_day: 20, category: "Cruiser", address: "Brusselsestraat 11, Maastricht, Netherlands", number_of_gears: 1, status: "available", user_id: 2, description: "Reformed functional bike" ) bike.photo.attach(io: photo, filename: 'bike.png', content_type: 'image/png') bike.save! photo = URI.open('https://upload.wikimedia.org/wikipedia/commons/b/bc/Dutch_bicycle.jpg') bike = Bike.new( brand: "BMX", price_per_day: 30, category: "Cruiser", address: "Scheveningen, Den Haag, Netherlands", number_of_gears: 12, status: "available", user_id: 3, description: "Awesome bike for bikers experts" ) bike.photo.attach(io: photo, filename: 'bike.png', content_type: 'image/png') bike.save! photo = URI.open('https://images.unsplash.com/photo-1485965120184-e220f721d03e?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8YmljeWNsZXxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&w=1000&q=80') bike = Bike.new( brand: "Touring Bike", price_per_day: 10, category: "Cruiser", address: "Heidestrasse 36, Frankfurt", number_of_gears: 1, status: "available", user_id: 4, description: "Vintage bike ready to be rented" ) bike.photo.attach(io: photo, filename: 'bike.png', content_type: 'image/png') bike.save! photo = URI.open('https://cremecycles.com/images/glowne/16.jpg') bike = Bike.new( brand: "Touring Bike", price_per_day: 10, category: "Cruiser", address: "109 Rue du bac, Paris, France", number_of_gears: 1, status: "available", user_id: 1, description: "Beautiful and confortable " ) bike.photo.attach(io: photo, filename: 'bike.png', content_type: 'image/png') bike.save! photo = URI.open('https://polebicycles.com/wp-content/uploads/2021/03/pole-taival-tr-late-2020-ds-2560x1707.jpg') bike = Bike.new( brand: "Touring Bike", price_per_day: 10, category: "Cruiser", address: "Keizersgracht, Amsterdam", number_of_gears: 24, status: "available", user_id: 2, description: "Childhood bike in excelent shape" ) bike.photo.attach(io: photo, filename: 'bike.png', content_type: 'image/png') bike.save! photo = URI.open('https://cdn.shopify.com/s/files/1/1245/1481/products/2_DIAMOND_BLACK_1_1024x1024.jpg?v=1597774901') bike = Bike.new( brand: "Touring Bike", price_per_day: 10, category: "Cruiser", address: "Keizersgracht, Amsterdam", number_of_gears: 24, status: "available", user_id: 3, description: "Nice and easy to go around with" ) bike.photo.attach(io: photo, filename: 'bike.png', content_type: 'image/png') bike.save! puts "...done seeding bikes!" <file_sep>class Bike < ApplicationRecord belongs_to :user has_one_attached :photo geocoded_by :address after_validation :geocode, if: :will_save_change_to_address? CATEGORIES = ['Road Bike', 'Cruiser', 'Fixed Gear', 'Mountain Bike', 'BMX', 'Touring Bike', 'Recumbent Bike', 'Folding Bike', 'Utility Bike'] BRAKES = ['Hand brake', 'Pedal brake', 'Hand and pedal brakes'] AVAILABLE = ['available', 'not available'] validates :brand, presence: true validates :price_per_day, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 } validates :category, presence: true, inclusion: { in: CATEGORIES } validates :brake_type, inclusion: { in: BRAKES }, allow_blank: true validates :number_of_gears, numericality: { only_integer: true, greater_than_or_equal_to: 0 }, allow_blank: true validates :status, inclusion: { in: AVAILABLE }, allow_blank: true validates :photo, presence: true validates :address, presence: true end <file_sep>class BookingsController < ApplicationController def index # @list_bookings = Booking.all @bookings = policy_scope(Booking) @owner = current_user.bikes.any? @bookings_as_renter = current_user.bookings if @owner @my_bikes = current_user.bikes @bookings_as_owner = Booking.where(bike_id: @my_bikes.pluck(:id)) end end def create @booking = Booking.new(start_date: Date.parse(booking_params[:start_date]), end_date: Date.parse(booking_params[:end_date])) authorize @booking @bike = Bike.find(params[:bike_id]) @booking.user = current_user @booking.status = "pending" @booking.total_price = (Date.parse(booking_params[:end_date]) - Date.parse(booking_params[:start_date])).to_i * @bike.price_per_day @booking.bike = @bike if @booking.save redirect_to bikes_path else redirect_to bike_path(@bike) end end def update @booking = Booking.find(params[:id]) authorize @booking if params[:query] == "accept" @booking.status = "accepted" end if params[:query] == "reject" @booking.status = "rejected" end @booking.save! redirect_to bookings_path end private def booking_params params.require(:booking).permit(:start_date, :end_date) end def bookings # return the (array?) of bookings for a particular user # find by user id? # @booking.user = current_user current_user.bookings = Booking.find(params[:user_id]) end end <file_sep>class BikesController < ApplicationController skip_before_action :authenticate_user!, only: [:index, :show] def home end def index if params[:query].present? @bikes = policy_scope(Bike).near(params[:query], 10) else @bikes = policy_scope(Bike).order(created_at: :desc) end @markers = @bikes.geocoded.map do |bike| { lat: bike.latitude, lng: bike.longitude, info_window: render_to_string(partial: "info_window", locals: { bike: bike }), image_url: helpers.asset_url('bicycle.png') } end end def show @bike = Bike.find(params[:id]) authorize @bike @markers = [{ lat: @bike.latitude, lng: @bike.longitude, info_window: render_to_string(partial: "info_window", locals: { bike: @bike }), image_url: helpers.asset_url('bicycle.png') }] @booking = Booking.new end def new @bike = Bike.new authorize @bike end def create @bike = Bike.new(bike_params) authorize @bike @bike.user = current_user if @bike.save redirect_to bikes_path else render :new end end private def bike_params params.require(:bike).permit(:user_id, :category, :brand, :brake_type, :price_per_day, :status, :number_of_gears, :photo, :address, :description) end end
3fb276c71aa8f385592bbb7388f6d585eaeda584
[ "JavaScript", "Ruby" ]
7
Ruby
akspyro/bikebnb
cd3815e0b85dd5421cb0698b60738fa82037fc7b
57e514fa59b91c9475ac93df4916d1bec3541d9b
refs/heads/main
<repo_name>ocamlmycaml/adityadharacom<file_sep>/src/lib/firebase.ts import { initializeApp } from 'firebase/app'; import { getAuth, GoogleAuthProvider } from 'firebase/auth'; import { getFirestore } from 'firebase/firestore'; const firebaseConfig = { apiKey: 'AIzaSyCR6gf0bRO5Jixgm1p3WEOnksaKyG59LkY', authDomain: 'mysite-286621.firebaseapp.com', projectId: 'mysite-286621', storageBucket: 'mysite-286621.appspot.com', messagingSenderId: '226312838239', appId: '1:226312838239:web:1e62cb253a393af1898fea', measurementId: 'G-HBWC3LCTFN' }; initializeApp(firebaseConfig); export const auth = getAuth(); export const googleProvider = new GoogleAuthProvider(); export const db = getFirestore();
250d49397b9b008ef01bc56b1f299544af66a370
[ "TypeScript" ]
1
TypeScript
ocamlmycaml/adityadharacom
fa4950b4d3e7b0b3da94b921d80ca9c839bf03e5
9471e6b9957281541451eb6fe2b7dbe9e175fe9a
refs/heads/master
<repo_name>Szpansky/quiz<file_sep>/app/src/main/java/com/apps/szpansky/quiz/Tasks/GetQuestion.java package com.apps.szpansky.quiz.Tasks; import android.content.Context; import android.content.Intent; import android.support.v4.app.FragmentManager; import com.apps.szpansky.quiz.ShowQuestionActivity; import com.apps.szpansky.quiz.SimpleData.QuestionData; import com.apps.szpansky.quiz.SimpleData.UserData; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.URL; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; /** * That class extend BasicTask and implement doInBackground method * That class gt WeakReference for context in constructor */ public class GetQuestion extends BasicTask { QuestionData questionData; UserData userData; private final WeakReference<Context> context; private String questionURL; /** * Constructor need site main address, userdata object, questionDataObject, fragment reference and context * @param siteAddress * @param userData * @param questionData * @param fragmentManager * @param context */ public GetQuestion(String siteAddress, UserData userData, QuestionData questionData, FragmentManager fragmentManager, Context context) { questionURL = siteAddress + "JSON/user/get_question/?insecure=cool&cookie=" + userData.getCookie() + "&user_id=" + userData.getUserId(); this.questionData = questionData; this.userData = userData; setFragmentManager(fragmentManager); this.context = new WeakReference<>(context); } @Override protected Boolean doInBackground(Void... params) { try { URL url = new URL(questionURL); OkHttpClient client = new OkHttpClient(); Request.Builder builder = new Request.Builder(); Request request = builder.url(url).build(); Response respond = client.newCall(request).execute(); String json = respond.body().string(); try { JSONObject object = new JSONObject(json); if (object.getString("status").equals("ok")) { questionData.setId(object.getJSONObject("pytanie").getString("id")); questionData.setText(object.getJSONObject("pytanie").getString("tekst")); questionData.setLink(object.getJSONObject("pytanie").getString("link")); questionData.setPoints(object.getJSONObject("pytanie").getString("punkty")); } else { setError("Problem podczas pobierania danych"); return false; } if (questionData.getId().equals("-1")) { setError("Dziś już odpowiadałeś, wróć jutro lub kliknij przycisk \"Omiń blokadę\""); return false; } if (questionData.getId().equals("-2")) { setError("Brak pytań"); return false; } return true; } catch (JSONException e) { e.printStackTrace(); setError("Problem podczas pobierania danych"); return false; } } catch (IOException e) { e.printStackTrace(); setError("Brak połączenia"); return false; } } @Override protected void onSuccessExecute() { if(context.get()!=null){ Intent startQuestion = new Intent(context.get(), ShowQuestionActivity.class); startQuestion.putExtra("userData", userData); startQuestion.putExtra("questionData", questionData); startQuestion.addFlags(FLAG_ACTIVITY_NEW_TASK); context.get().startActivity(startQuestion); } } } <file_sep>/app/src/main/java/com/apps/szpansky/quiz/LoginActivity.java package com.apps.szpansky.quiz; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import com.apps.szpansky.quiz.SimpleData.UserData; import com.apps.szpansky.quiz.Tasks.RetrievePassword; import com.apps.szpansky.quiz.Tasks.UserLogin; import com.apps.szpansky.quiz.Tools.MySharedPreferences; /** * Class show content for login activity, check data that user was imputed */ public class LoginActivity extends AppCompatActivity { RetrievePassword mPasswordTask = null; UserLogin userLogin = null; UserData userData; private AutoCompleteTextView mEmailView; private EditText mPasswordView; private CheckBox saveLoginData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mEmailView = findViewById(R.id.email); mPasswordView = findViewById(R.id.password); saveLoginData = findViewById(R.id.save_login_data); saveLoginData.setChecked(MySharedPreferences.getSaveLoginDataIsSet(this)); saveLoginData.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MySharedPreferences.setSaveLoginData(getBaseContext(), isChecked); if (!isChecked) { MySharedPreferences.setLogin(getBaseContext(), ""); MySharedPreferences.setPassword(getBaseContext(), ""); } else { MySharedPreferences.setLogin(getBaseContext(), mEmailView.getText().toString()); MySharedPreferences.setPassword(getBaseContext(), mPasswordView.getText().toString()); } } }); if (MySharedPreferences.getSaveLoginDataIsSet(this)) { mEmailView.setText(MySharedPreferences.getLogin(this)); mPasswordView.setText(MySharedPreferences.getPassword(this)); } Button mEmailSignInButton = findViewById(R.id.email_sign_in_button); Button retrievePassword = findViewById(R.id.retrieve_password_button); Button createAccountButton = findViewById(R.id.create_account_button); createAccountButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent createAccount = new Intent(getBaseContext(), NewAccountActivity.class); startActivity(createAccount); } }); retrievePassword.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { attemptResetPassword(); } }); mEmailSignInButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } }); } private void attemptResetPassword() { mEmailView.setError(null); final String email = mEmailView.getText().toString(); boolean cancel = false; View focusView = null; if (TextUtils.isEmpty(email)) { mEmailView.setError(getString(R.string.error_field_required)); focusView = mEmailView; cancel = true; } else if (!isEmailValid(email)) { mEmailView.setError(getString(R.string.error_invalid_email)); focusView = mEmailView; cancel = true; } if (cancel) { focusView.requestFocus(); } else { mPasswordTask = new RetrievePassword(getString(R.string.site_address), email, getSupportFragmentManager()); mPasswordTask.execute(); } } private void attemptLogin() { mEmailView.setError(null); mPasswordView.setError(null); final String email = mEmailView.getText().toString(); final String password = mPasswordView.getText().toString(); boolean cancel = false; View focusView = null; if (TextUtils.isEmpty(password)) { mPasswordView.setError(getString(R.string.error_field_required)); focusView = mPasswordView; cancel = true; } else if (!isPasswordValid(password)) { mPasswordView.setError(getString(R.string.error_invalid_password)); focusView = mPasswordView; cancel = true; } if (TextUtils.isEmpty(email)) { mEmailView.setError(getString(R.string.error_field_required)); focusView = mEmailView; cancel = true; } else if (!isEmailValid(email)) { mEmailView.setError(getString(R.string.error_invalid_email)); focusView = mEmailView; cancel = true; } if (cancel) { focusView.requestFocus(); } else { MySharedPreferences.setLogin(this, mEmailView.getText().toString().trim()); MySharedPreferences.setPassword(this, mPasswordView.getText().toString().trim()); newLoginTask(); } } /** * That function check that imputed email is correct * @param email * @return boolen */ private boolean isEmailValid(String email) { return !(email.contains("\"") || email.contains(" ") || email.contains("?") || email.contains("&")); } /** * That function check that imputed password is correct * @param password * @return boolean */ private boolean isPasswordValid(String password) { return !(password.contains("\"") || password.contains(" ") || password.contains("?") || password.contains("&")); } private void newLoginTask() { String email = mEmailView.getText().toString(); String password = mPasswordView.getText().toString(); userData = new UserData(); userLogin = new UserLogin(getString(R.string.site_address), email, password, userData, getSupportFragmentManager(),getBaseContext()); userLogin.execute((Void) null); } }
8e8bb9ef4a89c52a7c749b7b3151c67957a241ce
[ "Java" ]
2
Java
Szpansky/quiz
1f220224356a1d4a55ba92318834ad69128411b6
5024f91332e1cd59a46a64835d756944b4a1b3ab
refs/heads/master
<file_sep>#Load the data TrainData <- read.table("C:\\Users\\ivyzh\\Desktop\\Machine Learning\\HW1\\GradedHW1-Train-Data.csv", header=T,sep=",",stringsAsFactors = F,na.strings="") ValData <- read.table("C:\\Users\\ivyzh\\Desktop\\Machine Learning\\HW1\\GradedHW1-Validation-Data.csv", header=T,sep=",",stringsAsFactors = F,na.strings="") TestData <- read.table("C:\\Users\\ivyzh\\Desktop\\Machine Learning\\HW1\\GradedHW1-Test-Data.csv", header=T,sep=",",stringsAsFactors = F,na.strings="") # set the x variables x <- c('Lot.Area', 'Total.Bsmt.SF', 'Gr.Liv.Area', 'Full.Bath', 'Bedroom.AbvGr','Year.Built','SalePrice') # compute the Building Age (in years) as of 2010 TrainData <- TrainData[,x] TrainData$'Building.Age' <- 2010 - TrainData$Year.Built TrainData$Year.Built <- NULL ValData <- ValData[,x] ValData$'Building.Age' <- 2010 - ValData$Year.Built ValData$Year.Built <- NULL TestData <- TestData[,x] TestData$'Building.Age' <- 2010 - TestData$Year.Built TestData$Year.Built <- NULL # examine the individual variables (both the x's and the y) sapply(TrainData,function(x) any(is.na(x))) sapply(ValData,function(x) any(is.na(x))) sapply(TestData,function(x) any(is.na(x))) # find the variables show strong right skewness with upper tail outliers par(mfrow = c(3, 3)) for(i in names(TrainData)) { boxplot(TrainData[,i], xlab = i) } # remove the NA in validation ValData <- ValData[-which(is.na(ValData$Total.Bsmt.SF)),] # find the K without transforming library(FNN) ks <- 1:40 rmse <- c() for(k in ks) { fit=knn.reg(train = TrainData[,-6] , test =ValData[,-6] , y=TrainData[,6] , k = k)$pred rmse[k] <- sqrt(mean((fit - ValData[,6])^2)) } plot(ks,rmse, xlab = "K", ylab = "RMSE", type = "o",main = "Plot of RMSE and K") match(min(rmse),rmse) min(rmse) fit=knn.reg(train = TrainData[,-6] , test =TestData[,-6] , y=TrainData[,6] , k = 12)$pred print(sqrt(mean((fit - TestData[,6])^2))) # Standarlized for(i in 1:7){ mu <- mean(TrainData[,i]) sigma <- sd(TrainData[,i]) sca_Train[,i] <- (TrainData[,i]-mu)/sigma sca_Test[,i] <- (TestData[,i]-mu)/sigma sca_Val[,i] <- (ValData[,i]-mu)/sigma } sca_Train[,6] = TrainData[,6] sca_Test[,6] = TestData[,6] sca_Val[,6] = ValData[,6] sca_rmse <- c() for(k in ks) { fit=knn.reg(train = sca_Train[,-6] , test =sca_Val[,-6] , y = sca_Train[,6] , k = k)$pred sca_rmse[k] <- sqrt(mean((fit - ValData[,6])^2)) } plot(ks,sca_rmse, xlab = "K", ylab = "Standarlized RMSE", type = "o",main = "Plot of Standardized RMSE and K") sca_rmse[1] sca_rmse[20] match(min(sca_rmse),sca_rmse) min(sca_rmse) fit=knn.reg(train = sca_Train[,-6] , test = sca_Test[,-6] , y=sca_Train[,6] , k = 12)$pred print(sqrt(mean((fit - TestData[,6])^2))) # Transformation log_Train[,c(1,2,3,6)] = log(TrainData[,c(1,2,3,6)]+1/3) log_Train[,4:5] = TrainData[,4:5] log_Train[,7] = sqrt(TrainData[,7]) log_Test[,c(1,2,3,6)] = log(TestData[,c(1,2,3,6)]+1/3) log_Test[,4:5] = TestData[,4:5] log_Test[,7] = sqrt(TestData[,7]) log_Val[,c(1,2,3,6)] = log(ValData[,c(1,2,3,6)]+1/3) log_Val[,4:5] = ValData[,4:5] log_Val[,7] = sqrt(ValData[,7]) log_rmse = numeric(40) for(k in ks) { fit=knn.reg(train = log_Train[,-6] ,test = log_Val[,-6] , y = log_Train[,6] , k = k)$pred log_rmse[k] <- sqrt(mean((fit - log_Val[,6])^2)) } log_rmse plot(ks,log_rmse, xlab = "K", ylab = "Transformed RMSE", type = "o",main = "Plot of Transformed RMSE and K") match(min(log_rmse),log_rmse) min(log_rmse) fit=knn.reg(train = log_Train[,-6] , test =log_Test[,-6] , y= log_Train[,6] , k = 7)$pred print(sqrt(mean((fit - log_Test[,6])^2))) print(sqrt(mean((exp(fit) - exp(log_Test[,6]))^2))) # Standarlized Transformation sf_Train = TrainData sf_Test = TestData sf_Val = ValData for(i in 1:7){ mu <- mean(log_Train[,i]) sigma <- sd(log_Train[,i]) sf_Train[,i] <- (log_Train[,i]-mu)/sigma sf_Test[,i] <- (log_Test[,i]-mu)/sigma sf_Val[,i] <- (log_Val[,i]-mu)/sigma } sf_Train[,6] = log_Train[,6] sf_Test[,6] = log_Test[,6] sf_Val[,6] = log_Val[,6] sf_rmse <- c() for(k in ks) { fit=knn.reg(train = sf_Train[,-6] , test =sf_Val[,-6] , y=sf_Train[,6] , k = k)$pred sf_rmse[k] <- sqrt(mean((fit - log_Val[,6])^2)) } plot(ks,sf_rmse, xlab = "K", ylab = "Standarlized Transformated RMSE", type = "o",main = "Plot of Standardized Transformed RMSE and K") match(min(sf_rmse),sf_rmse) min(sf_rmse) fit=knn.reg(train = sf_Train[,-6] , test =sf_Test[,-6] , y= sf_Train[,6] , k = 10)$pred print(sqrt(mean((fit - log_Test[,6])^2))) print(sqrt(mean((exp(fit) - exp(log_Test[,6]))^2)))
7c7f24dbb1aebd287812eadecf3fb08184871855
[ "R" ]
1
R
ivyzhou0220/Machine-Learning-1
48e6f452177189d36cdae98fd5a6f5a74b98604c
2ec866dc7cdc8f58bbc132d10b1126ee42dd0e00
refs/heads/master
<file_sep><?php namespace frontend\models; use yii\db\ActiveRecord; /** * This is the model class for table "topic". * * @property int $id * @property int $area_id * @property int $type_work_id * @property string $topic_name * * @property Keyword[] $keywords * @property Question[] $questions * @property TestingArea $area * @property TypeWork $typeWork */ class Topic extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'topic'; } /** * @inheritdoc */ public function rules() { return [ [['area_id', 'type_work_id', 'topic_name'], 'required'], [['area_id', 'type_work_id'], 'default', 'value' => null], [['area_id', 'type_work_id'], 'integer'], [['topic_name'], 'string', 'max' => 32], [['area_id'], 'exist', 'skipOnError' => true, 'targetClass' => TestingArea::className(), 'targetAttribute' => ['area_id' => 'id']], [['type_work_id'], 'exist', 'skipOnError' => true, 'targetClass' => TypeWork::className(), 'targetAttribute' => ['type_work_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'area_id' => 'Area ID', 'type_work_id' => 'Type Work ID', 'topic_name' => 'Topic Name', ]; } /** * @return \yii\db\ActiveQuery */ public function getKeywords() { return $this->hasMany(Keyword::className(), ['topic_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getQuestions() { return $this->hasMany(Question::className(), ['topic_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getArea() { return $this->hasOne(TestingArea::className(), ['id' => 'area_id']); } /** * @return \yii\db\ActiveQuery */ public function getTypeWork() { return $this->hasOne(TypeWork::className(), ['id' => 'type_work_id']); } }<file_sep><?php namespace frontend\models; /** * This is the model class for table "test". * * @property int $id * @property int $area_id * @property string $access_start_time * @property string $time_passage * * @property Attempt[] $attempts * @property TestingArea $area * @property TestQuestion[] $testQuestions */ class Test extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'test'; } /** * @inheritdoc */ public function rules() { return [ [['area_id', 'access_start_time', 'time_passage'], 'required'], [['area_id'], 'default', 'value' => null], [['area_id'], 'integer'], [['access_start_time', 'time_passage'], 'safe'], [['area_id'], 'exist', 'skipOnError' => true, 'targetClass' => TestingArea::className(), 'targetAttribute' => ['area_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'area_id' => 'Area ID', 'access_start_time' => 'Access Start Time', 'time_passage' => 'Time Passage', ]; } /** * @return \yii\db\ActiveQuery */ public function getAttempts() { return $this->hasMany(Attempt::className(), ['test_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getArea() { return $this->hasOne(TestingArea::className(), ['id' => 'area_id']); } /** * @return \yii\db\ActiveQuery */ public function getTestQuestions() { return $this->hasMany(TestQuestion::className(), ['test_id' => 'id']); } } <file_sep><?php namespace frontend\models; /** * This is the model class for table "keyword". * * @property int $topic_id * @property string $keyword * * @property Topic $topic */ class Keyword extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'keyword'; } /** * @inheritdoc */ public function rules() { return [ [['topic_id', 'keyword'], 'required'], [['topic_id'], 'default', 'value' => null], [['topic_id'], 'integer'], [['keyword'], 'string', 'max' => 255], [['topic_id'], 'exist', 'skipOnError' => true, 'targetClass' => Topic::className(), 'targetAttribute' => ['topic_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'topic_id' => 'Topic ID', 'keyword' => 'Keyword', ]; } /** * @return \yii\db\ActiveQuery */ public function getTopic() { return $this->hasOne(Topic::className(), ['id' => 'topic_id']); } } <file_sep><?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model frontend\models\Question */ /* @var $form yii\widgets\ActiveForm */ $this->title = 'Create Question'; $this->params['breadcrumbs'][] = ['label' => 'Questions', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="question-create"> <h1><?= Html::encode($this->title) ?></h1> <div class="question-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'topic_id')->hiddenInput()->label(false) ?> <?= $form->field($model, 'question_text')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'question_price')->textInput() ?> <div id="answers"></div> <hr> <div class="form-group" id="ind"> <?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?> <?= Html::button('Добавить ответ', ['class' => 'btn btn-success', 'onclick' => 'AddAnswer()']) ?> </div> <?php ActiveForm::end(); ?> </div> </div> <script> var count = 0; function AddAnswer() { var divAnswer = $('<div>', {class: 'row form-group'}).appendTo('#answers'); var checkbox = $('<input>', { type: 'checkbox', name: 'Answer[correct_answer][' + count + ']' }); var divCheckbox = $('<div>', {class: 'col-lg-2'}).appendTo(divAnswer); $('<label>') .append(checkbox) .append(' Правильный ответ') .appendTo(divCheckbox); var divText = $('<div>', {class: 'col-lg-9'}).appendTo(divAnswer); $('<input>', { type: 'text', class: 'form-control', name: 'Answer[answer_text][' + count + ']' }).appendTo(divText); var divButton = $('<div>', {class: 'col-lg-1'}).appendTo(divAnswer); $('<button>', { html: 'X', type: 'button', class: 'btn btn-danger', click: function () { DeleteAnswer(divAnswer); } }).appendTo(divButton); count++; } function DeleteAnswer(item) { item.remove(); } </script><file_sep><?php use yii\grid\GridView; use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $module frontend\models\Module */ /* @var $dataProviderTest yii\data\ActiveDataProvider */ /* @var $dataProviderTypeWork yii\data\ActiveDataProvider */ $this->title = $module->module_name; $this->params['breadcrumbs'][] = ['label' => 'Модули', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="module-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Update', ['update', 'id' => $module->id], ['class' => 'btn btn-primary']) ?> <?= Html::a('Delete', ['delete', 'id' => $module->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <?php try { echo DetailView::widget([ 'model' => $module, 'attributes' => [ 'id', 'area_id', 'discipline_id', 'module_name', ], ]); } catch (Exception $exception) { echo $exception; } ?> <hr> <h1><?= Html::encode('Типы работ') ?></h1> <?php try { echo GridView::widget([ 'dataProvider' => $dataProviderTypeWork, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], //'id', //'area_id', //'module_id', [ 'attribute' => 'type_work_name', 'content' => function ($typeWork) { return Html::a($typeWork->type_work_name, ['type-work/view', 'id' => $typeWork->id]); } ], //['class' => 'yii\grid\ActionColumn'], ], ]); } catch (Exception $exception) { echo $exception; } ?> <hr> <h1><?= Html::encode('Тесты по модулю') ?></h1> <p> <?= Html::a('Добавить тест', ['test/create', 'id' => $module->id, 'level' => '3'], ['class' => 'btn btn-success']) ?> </p> <?php try { echo GridView::widget([ 'dataProvider' => $dataProviderTest, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', 'area_id', 'access_start_time', 'time_passage', ['class' => 'yii\grid\ActionColumn'], ], ]); } catch (Exception $exception) { echo $exception; } ?> </div><file_sep><?php namespace frontend\models; use yii\db\ActiveRecord; /** * This is the model class for table "answer". * * @property int $id * @property int $question_id * @property string $answer_text * @property bool $correct_answer * * @property Question $question * @property Result[] $results */ class Answer extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'answer'; } /** * @inheritdoc */ public function rules() { return [ [['question_id', 'answer_text', 'correct_answer'], 'required'], [['question_id'], 'default', 'value' => null], [['question_id'], 'integer'], [['correct_answer'], 'boolean'], [['answer_text'], 'string', 'max' => 255], [['question_id'], 'exist', 'skipOnError' => true, 'targetClass' => Question::className(), 'targetAttribute' => ['question_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'question_id' => 'Question ID', 'answer_text' => 'Answer Text', 'correct_answer' => 'Correct Answer', ]; } /** * @return \yii\db\ActiveQuery */ public function getQuestion() { return $this->hasOne(Question::className(), ['id' => 'question_id']); } /** * @return \yii\db\ActiveQuery */ public function getResults() { return $this->hasMany(Result::className(), ['answer_id' => 'id']); } }<file_sep><?php namespace frontend\controllers; use frontend\models\Module; use frontend\models\Test; use frontend\models\TestingArea; use frontend\models\TypeWork; use Yii; use yii\data\ActiveDataProvider; use yii\filters\VerbFilter; use yii\web\Controller; use yii\web\NotFoundHttpException; /** * ModuleController implements the CRUD actions for Module model. */ class ModuleController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ]; } /** * Lists all Module models. * @return mixed */ public function actionIndex() { $dataProvider = new ActiveDataProvider(['query' => Module::find()]); return $this->render('index', ['dataProvider' => $dataProvider]); } /** * Displays a single Module model. * @param integer $id Идентификатор модуля. * @return mixed * @throws NotFoundHttpException if the model cannot be found * @throws \Exception * @throws \Throwable */ public function actionView($id) { $module = $this->findModel($id); $userId = Yii::$app->getUser()->getIdentity()->getId(); $queryTest = Test::find() ->where(['area_id' => $module->area_id]); $queryTypeWork = TypeWork::find() ->joinWith(['teacher.user'], false) ->where(['module_id' => $id]) ->andWhere(['user.id' => $userId]); $dataProviderTest = new ActiveDataProvider(['query' => $queryTest]); $dataProviderTypeWork = new ActiveDataProvider(['query' => $queryTypeWork]); return $this->render('view', [ 'module' => $module, 'dataProviderTest' => $dataProviderTest, 'dataProviderTypeWork' => $dataProviderTypeWork, ]); } /** * Creates a new Module model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $module = new Module(); if ($module->load(Yii::$app->request->post()) && $module->validate()) { $testingArea = new TestingArea(); $testingArea->level = 2; if ($testingArea->save()) { $module->area_id = $testingArea->id; if ($module->save(false)) { return $this->redirect(['view', 'id' => $module->id]); } } } return $this->render('create', ['model' => $module]); } /** * Updates an existing Module model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed * @throws NotFoundHttpException if the model cannot be found */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } return $this->render('update', ['model' => $model]); } /** * Deletes an existing Module model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed * @throws NotFoundHttpException if the model cannot be found * @throws \Exception * @throws \Throwable * @throws \yii\db\StaleObjectException */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Module model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Module the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Module::findOne($id)) !== null) { return $model; } throw new NotFoundHttpException('The requested page does not exist.'); } }<file_sep><?php namespace frontend\controllers; use Exception; use frontend\models\Answer; use frontend\models\Question; use Yii; use yii\data\ActiveDataProvider; use yii\filters\VerbFilter; use yii\web\Controller; use yii\web\NotFoundHttpException; /** * QuestionController implements the CRUD actions for Question model. */ class QuestionController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ]; } /** * Lists all Question models. * @return mixed */ public function actionIndex() { $dataProvider = new ActiveDataProvider(['query' => Question::find()]); return $this->render('index', ['dataProvider' => $dataProvider]); } /** * Displays a single Question model. * @param integer $id * @return mixed * @throws NotFoundHttpException if the model cannot be found */ public function actionView($id) { return $this->render('view', ['model' => $this->findModel($id)]); } /** * Creates a new Question model. * If creation is successful, the browser will be redirected to the 'view' page. * @param integer $id Идентификатор темы. * @return mixed * @throws Exception */ public function actionCreate($id) { $model = new Question(); if ($model->load(Yii::$app->request->post()) && $model->save()) { $answerText = $_POST['Answer']['answer_text']; $correctAnswer = $_POST['Answer']['correct_answer']; foreach ($answerText as $key => $value) { $answer = new Answer(); $answer->answer_text = $value; $answer->question_id = $model->id; $answer->correct_answer = isset($correctAnswer[$key]); if ($answer->save()) { throw new Exception('Неудалось сохранить ответ на вопрос.'); } } return $this->redirect(['topic/view', 'id' => $id]); } $model->topic_id = $id; //return $this->render('create', ['model' => $model]); return $this->render('Test', ['model' => $model]); } /** * Updates an existing Question model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed * @throws NotFoundHttpException if the model cannot be found */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } return $this->render('update', ['model' => $model]); } /** * Deletes an existing Question model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed * @throws NotFoundHttpException if the model cannot be found * @throws Exception * @throws \Throwable * @throws \yii\db\StaleObjectException */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Question model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Question the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Question::findOne($id)) !== null) { return $model; } throw new NotFoundHttpException('The requested page does not exist.'); } }<file_sep><?php namespace frontend\models; use yii\db\ActiveRecord; /** * This is the model class for table "module". * * @property int $id * @property int $area_id * @property int $discipline_id * @property string $module_name * * @property Discipline $discipline * @property TestingArea $area * @property TypeWork[] $typeWorks */ class Module extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'module'; } /** * @inheritdoc */ public function rules() { return [ [['area_id', 'discipline_id', 'module_name'], 'required'], [['area_id', 'discipline_id'], 'default', 'value' => null], [['area_id', 'discipline_id'], 'integer'], [['module_name'], 'string', 'max' => 32], [['discipline_id'], 'exist', 'skipOnError' => true, 'targetClass' => Discipline::className(), 'targetAttribute' => ['discipline_id' => 'id']], [['area_id'], 'exist', 'skipOnError' => true, 'targetClass' => TestingArea::className(), 'targetAttribute' => ['area_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'area_id' => 'Area ID', 'discipline_id' => 'Discipline ID', 'module_name' => 'Module Name', ]; } /** * @return \yii\db\ActiveQuery */ public function getDiscipline() { return $this->hasOne(Discipline::className(), ['id' => 'discipline_id']); } /** * @return \yii\db\ActiveQuery */ public function getArea() { return $this->hasOne(TestingArea::className(), ['id' => 'area_id']); } /** * @return \yii\db\ActiveQuery */ public function getTypeWorks() { return $this->hasMany(TypeWork::className(), ['module_id' => 'id']); } }<file_sep><?php namespace frontend\models; /** * This is the model class for table "question". * * @property int $id * @property int $topic_id * @property string $question_text * @property int $question_price * * @property Answer[] $answers * @property Topic $topic * @property Result[] $results * @property TestQuestion[] $testQuestions */ class Question extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'question'; } /** * @inheritdoc */ public function rules() { return [ [['topic_id', 'question_text', 'question_price'], 'required'], [['topic_id', 'question_price'], 'default', 'value' => null], [['topic_id', 'question_price'], 'integer'], [['question_text'], 'string', 'max' => 255], [['topic_id'], 'exist', 'skipOnError' => true, 'targetClass' => Topic::className(), 'targetAttribute' => ['topic_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'topic_id' => 'Topic ID', 'question_text' => 'Question Text', 'question_price' => 'Question Price', ]; } /** * @return \yii\db\ActiveQuery */ public function getAnswers() { return $this->hasMany(Answer::className(), ['question_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getTopic() { return $this->hasOne(Topic::className(), ['id' => 'topic_id']); } /** * @return \yii\db\ActiveQuery */ public function getResults() { return $this->hasMany(Result::className(), ['question_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getTests() { return $this->hasMany(Test::className(), ['id' => 'question_id']) ->viaTable('test_question', ['test_id' => 'id']); } }<file_sep><?php namespace frontend\controllers; use frontend\models\Test; use frontend\models\TestingArea; use frontend\models\TypeWork; use Yii; use yii\data\ActiveDataProvider; use yii\filters\VerbFilter; use yii\web\Controller; use yii\web\NotFoundHttpException; /** * TypeWorkController implements the CRUD actions for TypeWork model. */ class TypeWorkController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ]; } /** * Lists all TypeWork models. * @return mixed */ public function actionIndex() { $dataProvider = new ActiveDataProvider(['query' => TypeWork::find()]); return $this->render('index', ['dataProvider' => $dataProvider]); } /** * Displays a single TypeWork model. * @param integer $id Идентификатор типа работы. * @return mixed * @throws NotFoundHttpException if the model cannot be found */ public function actionView($id) { $typeWork = $this->findModel($id); $queryTest = Test::find()->where(['area_id' => $typeWork->area_id]); $dataProviderTest = new ActiveDataProvider(['query' => $queryTest]); $dataProviderTopic = new ActiveDataProvider(['query' => $typeWork->getTopics()]); return $this->render('view', [ 'typeWork' => $typeWork, 'dataProviderTest' => $dataProviderTest, 'dataProviderTopic' => $dataProviderTopic, ]); } /** * Creates a new TypeWork model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $typeWork = new TypeWork(); if ($typeWork->load(Yii::$app->request->post()) && $typeWork->validate()) { $testingArea = new TestingArea(); $testingArea->level = 2; if ($testingArea->save()) { $typeWork->area_id = $testingArea->id; if ($typeWork->save(false)) { return $this->redirect(['view', 'id' => $typeWork->id]); } } } return $this->render('create', ['model' => $typeWork]); } /** * Updates an existing TypeWork model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed * @throws NotFoundHttpException if the model cannot be found */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } return $this->render('update', ['model' => $model]); } /** * Deletes an existing TypeWork model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed * @throws NotFoundHttpException if the model cannot be found * @throws \Exception * @throws \Throwable * @throws \yii\db\StaleObjectException */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the TypeWork model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return TypeWork the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = TypeWork::findOne($id)) !== null) { return $model; } throw new NotFoundHttpException('The requested page does not exist.'); } }<file_sep><?php namespace frontend\models; use yii\db\ActiveRecord; /** * This is the model class for table "discipline". * * @property int $id * @property int $area_id * @property string $discipline_name * * @property TestingArea $area * @property DisciplineGroup[] $disciplineGroups * @property Module[] $modules */ class Discipline extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'discipline'; } /** * @inheritdoc */ public function rules() { return [ [['area_id', 'discipline_name'], 'required'], [['area_id'], 'default', 'value' => null], [['area_id'], 'integer'], [['discipline_name'], 'string', 'max' => 255], [['area_id'], 'exist', 'skipOnError' => true, 'targetClass' => TestingArea::className(), 'targetAttribute' => ['area_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'area_id' => 'Area ID', 'discipline_name' => 'Discipline Name', ]; } /** * @return \yii\db\ActiveQuery */ public function getArea() { return $this->hasOne(TestingArea::className(), ['id' => 'area_id']); } /** * @return \yii\db\ActiveQuery */ public function getDisciplineGroups() { return $this->hasMany(DisciplineGroup::className(), ['discipline_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getModules() { return $this->hasMany(Module::className(), ['discipline_id' => 'id']); } }<file_sep><?php namespace frontend\models; /** * This is the model class for table "attempt". * * @property int $id * @property int $student_id * @property int $test_id * @property string $testing_time * * @property Student $student * @property Test $test * @property Result[] $results */ class Attempt extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'attempt'; } /** * @inheritdoc */ public function rules() { return [ [['student_id', 'test_id', 'testing_time'], 'required'], [['student_id', 'test_id'], 'default', 'value' => null], [['student_id', 'test_id'], 'integer'], [['testing_time'], 'safe'], [['student_id'], 'exist', 'skipOnError' => true, 'targetClass' => Student::className(), 'targetAttribute' => ['student_id' => 'id']], [['test_id'], 'exist', 'skipOnError' => true, 'targetClass' => Test::className(), 'targetAttribute' => ['test_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'student_id' => 'Student ID', 'test_id' => 'Test ID', 'testing_time' => 'Testing Time', ]; } /** * @return \yii\db\ActiveQuery */ public function getStudent() { return $this->hasOne(Student::className(), ['id' => 'student_id']); } /** * @return \yii\db\ActiveQuery */ public function getTest() { return $this->hasOne(Test::className(), ['id' => 'test_id']); } /** * @return \yii\db\ActiveQuery */ public function getResults() { return $this->hasMany(Result::className(), ['attempt_id' => 'id']); } } <file_sep><?php use yii\grid\GridView; use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $typeWork frontend\models\TypeWork */ /* @var $dataProviderTest yii\data\ActiveDataProvider */ /* @var $dataProviderTopic yii\data\ActiveDataProvider */ $this->title = $typeWork->type_work_name; $this->params['breadcrumbs'][] = ['label' => 'Типы работ', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="type-work-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Изменить', ['update', 'id' => $typeWork->id], ['class' => 'btn btn-primary']) ?> <?= Html::a('Удалить', ['delete', 'id' => $typeWork->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <?php try { echo DetailView::widget([ 'model' => $typeWork, 'attributes' => [ 'id', 'area_id', 'teacher_id', 'module_id', 'type_work_name', ], ]); } catch (Exception $exception) { echo $exception; } ?> <hr> <h1><?= Html::encode('Темы') ?></h1> <?php try { echo GridView::widget([ 'dataProvider' => $dataProviderTopic, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], //'id', //'area_id', //'type_work_id', //'module_name', [ 'attribute' => 'topic_name', 'content' => function ($topic) { return Html::a($topic->topic_name, ['topic/view', 'id' => $topic->id]); } ], //['class' => 'yii\grid\ActionColumn'], ], ]); } catch (Exception $exception) { echo $exception; } ?> <hr> <h1><?= Html::encode('Тесты по типу работы') ?></h1> <p> <?= Html::a('Добавить тест', ['test/create', 'id' => $typeWork->id, 'level' => '2'], ['class' => 'btn btn-success']) ?> </p> <?php try { echo GridView::widget([ 'dataProvider' => $dataProviderTest, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', 'area_id', 'access_start_time', 'time_passage', ['class' => 'yii\grid\ActionColumn'], ], ]); } catch (Exception $exception) { echo $exception; } ?> </div><file_sep><?php namespace frontend\models; use yii\db\ActiveRecord; /** * This is the model class for table "type_work". * * @property int $id * @property int $area_id * @property int $teacher_id * @property int $module_id * @property string $type_work_name * * @property Topic[] $topics * @property Module $module * @property Teacher $teacher * @property TestingArea $area */ class TypeWork extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'type_work'; } /** * @inheritdoc */ public function rules() { return [ [['area_id', 'teacher_id', 'module_id', 'type_work_name'], 'required'], [['area_id', 'teacher_id', 'module_id'], 'default', 'value' => null], [['area_id', 'teacher_id', 'module_id'], 'integer'], [['type_work_name'], 'string', 'max' => 32], [['module_id'], 'exist', 'skipOnError' => true, 'targetClass' => Module::className(), 'targetAttribute' => ['module_id' => 'id']], [['teacher_id'], 'exist', 'skipOnError' => true, 'targetClass' => Teacher::className(), 'targetAttribute' => ['teacher_id' => 'id']], [['area_id'], 'exist', 'skipOnError' => true, 'targetClass' => TestingArea::className(), 'targetAttribute' => ['area_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'area_id' => 'Area ID', 'teacher_id' => 'Teacher ID', 'module_id' => 'Module ID', 'type_work_name' => 'Type Work Name', ]; } /** * @return \yii\db\ActiveQuery */ public function getTopics() { return $this->hasMany(Topic::className(), ['type_work_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getModule() { return $this->hasOne(Module::className(), ['id' => 'module_id']); } /** * @return \yii\db\ActiveQuery */ public function getTeacher() { return $this->hasOne(Teacher::className(), ['id' => 'teacher_id']); } /** * @return \yii\db\ActiveQuery */ public function getArea() { return $this->hasOne(TestingArea::className(), ['id' => 'area_id']); } }<file_sep><?php namespace frontend\models; /** * This is the model class for table "testing_area". * * @property int $id * @property int $level * * @property Discipline[] $disciplines * @property Module[] $modules * @property Test[] $tests * @property Topic[] $topics * @property TypeWork[] $typeWorks */ class TestingArea extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'testing_area'; } /** * @inheritdoc */ public function rules() { return [ [['level'], 'required'], [['level'], 'default', 'value' => null], [['level'], 'integer'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'level' => 'Level', ]; } /** * @return \yii\db\ActiveQuery */ public function getDisciplines() { return $this->hasMany(Discipline::className(), ['area_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getModules() { return $this->hasMany(Module::className(), ['area_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getTests() { return $this->hasMany(Test::className(), ['area_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getTopics() { return $this->hasMany(Topic::className(), ['area_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getTypeWorks() { return $this->hasMany(TypeWork::className(), ['area_id' => 'id']); } }
5d9ea7e14a7b3327ae604f3de97a32cf2726caa3
[ "PHP" ]
16
PHP
Pushkarev-Ilya/FOS
848229adac615d9c0d6e8a76e00bee7049825d31
e7904f01f70335941507b88a5e5f3b3dc1e9a5fc
refs/heads/master
<file_sep># WalkCalculator.github.io walk distance calculator <file_sep>package com.WalkCalculator.demo.entity; public class WalkDetailDto { private int distance; private String dateTime; private int personId; public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } public String getDateTime() { return dateTime; } public void setDateTime(String dateTime) { this.dateTime = dateTime; } public int getPersonId() { return personId; } public void setPersonId(int personId) { this.personId = personId; } } <file_sep>package com.WalkCalculator.demo.controller; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.WalkCalculator.demo.entity.PersonInfoDto; import com.WalkCalculator.demo.entity.WalkDetailDto; import com.WalkCalculator.demo.service.WalkCalculatorService; @RestController @RequestMapping("") public class WalkCalulatorController { @Autowired public WalkCalculatorService walkService; @PostMapping(path="/saveDetail") public String saveTraveledDistance(@RequestBody WalkDetailDto walkDto, HttpServletResponse response ){ System.out.println("walked distance: " + walkDto.getDistance()); long id = walkService.saveWalkDetail(walkDto); if(id>0) { return "saved successfully"; } return "exception occured"; } @GetMapping(path="/PersonDetail") public int getPersonDetail(@RequestBody PersonInfoDto infoDto) { System.out.println(""+infoDto.getId() ); return walkService.getPersonwalkDetail(infoDto); } } <file_sep>package com.WalkCalculator.demo.config; public class WebConfig { }
aa97b1e097db3dce76c07c50f9a46f200570416f
[ "Markdown", "Java" ]
4
Markdown
ashutoshnp/WalkCalculator.github.io
de74c2bb59a7bbc98984d159ab699409cdbb4df3
038df4716f18d8d242aced436f055b19124f45cc
refs/heads/master
<file_sep>function showMessage(m){ alert(m); } showMessage("Zure datuak:")
0d4eb170319efce61a08662e7190ce67ec07c91a
[ "JavaScript" ]
1
JavaScript
Jauregi13/Lab01JSF
37618416343df002f1044bc80846905ec3dcf991
72514a99fc822a17c6e5a51de4724fdb39686dfc
refs/heads/master
<file_sep>CFLAGS = -Wall -Werror DFLAGS = -g all: gcc shell.c -o shell shell: gcc shell.c -o shell gdb: @echo "Entering GDB" gdb ./shell leaks: shell @echo "Calling Valgrind to check for leaks" gcc shell.c -o shell && valgrind ./shell clean: rm -f shell <file_sep>#ifndef shell_h #define shell_h #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> //max sizes #define MAX_STRING 250 #define MESSSAGE "sh-0.1: " #define NEW_LINE_CMD "> " char *built_in_cmds[3] = {"exit","help","cd"}; //functions shell.c int process_built_cmd(char *cmd); void print_help(void); #endif <file_sep>#include "shell.h" int main(int argc, char *argv[]) { char cmd[MAX_STRING]; char current_char; int loc = 0; printf("%s\n", "Welcome to shell remake 101\n"); while(1){//add check for MAX_STRING write(1, MESSSAGE, 8);//initial shell message int loc = 0; while(read(0, &current_char, 1) > 0 && current_char != '\n'){ //this will take care of the " entered during input of string if(current_char == '\"'){//check if they will iput more char temp = current_char;//save current char if(read(0, &current_char, 1) > 0 && current_char == '\n'){ //it is " do not save it write(1, NEW_LINE_CMD, 2);//print > while(read(0, &current_char, 1) > 0 && current_char != '\"'){ if(current_char == '\n'){ write(1, NEW_LINE_CMD, 2); continue; }else{ cmd[loc++] = current_char; } } }else{ cmd[loc++] = temp; cmd[loc++] = current_char; } }else cmd[loc++] = current_char; } //null terminate string if(current_char == '\n') cmd[loc] = '\0'; else cmd[loc+1] = '\0'; printf("Command got %s\n",cmd ); process_built_cmd(cmd); } return 0; } int process_built_cmd(char *cmd){ if(strcmp(cmd,"exit")==0){ printf("%s\n", "Exiting."); exit(0); }else if(strcmp(cmd,"help")==0){ print_help(); return 0; } return 1; } void print_help(void){ printf("%s\n", "The following are the allowed commands: \n \t\texit\n\t\thelp\n"); } int process_cmd(char *cmd){ return 0; }
28eadb584616fc111a00d6293a587a9802ee4c86
[ "C", "Makefile" ]
3
Makefile
p0dxD/shell-2
d358c5937183b1ed12ad0171ab69c95d4b71566e
f1b6a7727ed74f104a2dec82390b96297cf5f8ad
refs/heads/master
<repo_name>somenumboola/usersgate<file_sep>/README.md # usersgate [![Development In progress](https://img.shields.io/badge/development-In_progress-yellow.svg)](https://img.shields.io/badge/development-In_progress-yellow.svg) [![No stable version](https://img.shields.io/badge/stable-none-lightgrey.svg)](https://img.shields.io/badge/stable-none-lightgrey.svg) Authorization &amp;&amp; User manipulation module for kohana framework<file_sep>/classes/Kohana/User/Observer.php <?php defined('SYSPATH') or die('No direct script access.'); interface Kohana_User_Observer extends Kohana_Tools_Observer, Kohana_User_Skeleton { function offsetSet($name, $newval, $oldval); function offsetUnset($name, $oldval); function __toString(); } <file_sep>/classes/Kohana/Tools/Observer.php <?php defined('SYSPATH') or die('No direct script access.'); interface Kohana_Tools_Observer { function observed(Kohana_Tools_Observed $o); } <file_sep>/classes/Kohana/User.php <?php defined('SYSPATH') or die('No direct script access.'); class Kohana_User extends Kohana_User_Core {} <file_sep>/classes/Kohana/User/Permission/Composer.php <?php class Kohana_User_Permission_Composer implements Iterator { protected $permissions = array(); protected $entity; protected $i = 0; /** * keymaker * generate unique array key for binding of entity and permission * @param type $entity * @param type $path * @return type */ protected static function keymaker($entity, $path) { return md5( strtr( ':enityIdentifier@:permissionPath', array( ':entityIdentifier' => $entity->getIdentifier(), ':permissionPath' => $path ) ) ); } /** * Initiator of composer * Setter of * @param Kohana_Tools_PermissionOwner $entity * @throws Kohana_Exception */ public function __construct($entity) { if ( !is_object($entity) || ! ($entity instanceof Kohana_Tools_PermissionOwner) ) { throw new Kohana_Exception( 'Only permission owners can invoke and own permission composer! ' . 'Entity :entity is not instance of ' . 'Kohana_Tools_PermissionOwner', array( ':entity' => var_export($entity, true) ) ); } $this->entity = $entity; } /** * Get instance object of permission by path * @param string $path */ public function get($path) { return Arr::get( $this->permissions, self::keymaker($this->entity, $path), FALSE ); } /** * attach * Creates linkage between entity and permission * @param User_Permission $p */ public function attach(User_Permission $p) { $key = self::keymaker($this->entity, $p->path); if (isset($this->permissions[$key])) { throw new Kohana_Exception( 'Permission duplicate attempt! :entityType already has ' . 'permission :permissionPath !!!', array( ':entityType' => ($this->entity instanceof User) ? 'User' : 'Group' ) ); } // Database writing // TODO: Apply database writing $this->permissions[$key] = $p; } /** * detach * Destroy linkage between entity and permission * @param User_Permission $p */ public function detach(User_Permission $p) { // Database writing // TODO: Apply database writing } /** * rewind * Delegate iteration process to secured inner array of permissions * @return type */ public function rewind() { $this->i = 0; } /** * next * Delegate iteration process to secured inner array of permissions * @return User_Permission */ public function next() { $this->i++; } /** * current * Delegate iteration process to secured inner array of permissions * @return User_Permission */ public function current() { return Arr::get($this->permissions, $this->key()); } /** * key * Delegate iteration process to secured inner array of permissions * Overrloading generic key that represents binding between permission and entity * by permission path * @return string */ public function key() { return Arr::get(array_keys($this->permissions), $this->i, FALSE); } /** * valid * Delegate iteration process to secured inner array of permissions * @return bool */ public function valid() { return !is_null($this->current()); } } <file_sep>/classes/Kohana/User/Observed.php <?php defined('SYSPATH') or die('No direct script access.'); abstract class Kohana_User_Observed extends ArrayObject { protected $_observers = array(); public function __construct() { $config = Kohana::$config ->load('users') ->get('observers', array()); $className = Arr::get($config, 'name', ''); foreach (Arr::get($config, 'active', array()) as $observerName) { if ( class_exists( $class = strtr( $className, array( ':class' => $observerName ) ) ) ) { $this->attach(new $class()); } } parent::__construct(array(), ArrayObject::STD_PROP_LIST); } public function attach(Kohana_User_Observer $ob) { $this->_observers["{$ob}"] = $ob; return $this; } public function detach(Kohana_User_Observer $ob) { unset($this->_observers["{$ob}"]); return $this; } public function notify($method, array $arguments = array()) { foreach ($this->_observers as $observer) { if (method_exists($observer, $method)) { call_user_func_array(array($observer, $method), $arguments); } } return $this; } public function offsetSet($index, $value) { $oldValue = $this->offsetExists($index) ? $this[$index] : null; parent::offsetSet($index, $value); $this->notify( __FUNCTION__, array( $index, $value, $oldValue ) ); } public function offsetUnset($index) { $oldValue = $this->offsetExists($index) ? $this[$index] : null; parent::offsetUnset($index); $this->notify( __FUNCTION__, array( $index, $oldValue ) ); } public function exchangeArray($input) { throw new Kohana_Exception( "Direct call of :method forbidden!", array( ':method' => __METHOD__ ) ); } } <file_sep>/classes/Kohana/User/Core.php <?php defined('SYSPATH') or die('No direct script access.'); abstract class Kohana_User_Core extends Kohana_User_Observed implements Kohana_Tools_Observed, Kohana_Tools_PermissionOwner, Kohana_User_Skeleton { protected static $permissions = null; public function getIdentifier() { } public function setIdentifier() { } public function register() { // Code $this->notify(__FUNCTION__); } public function suspend() { // Code $this->notify(__FUNCTION__); } /** * permissions * Permission composer invoker * @return Kohana_User_Permission_Composer */ public function permissions() { return self::$permissions ? : self::$permissions = new Kohana_User_Permission_Composer($this); } /** * Shortcut for User_Permission::factory() * @see MODPATH/usersgate/classes/Kohana/User/Permission.php * @param string $path * @return bool|int */ public function allowed($path) { return User_Permission::factory($path, $this); } } <file_sep>/classes/Kohana/Tools/Observed.php <?php defined('SYSPATH') or die('No direct script access.'); interface Kohana_Tools_Observed { function attach(Kohana_User_Observer $ob); function detach(Kohana_User_Observer $ob); function notify($method, array $arguments = array()); } <file_sep>/classes/User/Permission.php <?php class User_Permission extends Kohana_User_Permission { } <file_sep>/classes/Kohana/User/Permission.php <?php class Kohana_User_Permission { /** * Defines that user has partial permission (one of child permissions) */ const PARTIAL_OWNERSHIP = 1; /** * Defines that user has exact permission or parental permission */ const DIRECT_OWNERSHIP = 2; public $path = ''; /** * factory * Creates instance of permission. * If second argument passed - attempts to immediately check if it * has partial or direct (any) ownership of this permission * * @param string $path * @param User $u * @return User_Permission */ public static function factory($path, User $u = null) { $instance = new static($path); if (!is_null($u)) { return $instance->own($u); } return $instance; } public function __construct($path) { var_dump(User_Permission::explicate($path)); } /** * own * General check method * Checks if current permission owned by providen user * In case if user does not own current permission returns FALSE * In case of partial ownership returns User_Permission::PARTIAL_OWNERSHIP (1) * In case of direct ownership returns User_Permission::DIRECT_OWNERSHIP (2) * * @param User $u * @return bool|int */ public function own(User $u) { } /** * explicate * * Creates array of all possible parental paths that * leads to current permission * * @param string $path * @param string $delimiter * @return array */ public static function explicate($path, $delimiter = '.') { $explication = array(); $pieces = explode($delimiter, $path); while ($level = array_shift($pieces)) { $explication[] = ($explication) ? end($explication) . $delimiter . $level : $level; } return $explication; } } <file_sep>/classes/Kohana/Tools/Identified.php <?php interface Kohana_Tools_Identified { function getIdentifier(); function setIdentifier(); } <file_sep>/classes/User/Permission/Composer.php <?php class User_Permission_Composer extends Kohana_User_Permission_Composer {} <file_sep>/config/users.php <?php return array( 'observers' => array( 'name' => 'User_Observer_:name', 'active' => array( ) ) );<file_sep>/classes/Kohana/User/Skeleton.php <?php defined('SYSPATH') or die('No direct script access.'); interface Kohana_User_Skeleton { function register(); function suspend(); function allowed($path); }
913a6b2106960153eb6de934d60a4c8b4576ce9c
[ "Markdown", "PHP" ]
14
Markdown
somenumboola/usersgate
832b8f809fbc9cff82f1a90ccb364adf05c81e4e
0608a682d7812d0bc0991fae012cdac10b86c6ac
refs/heads/master
<repo_name>aravindanil816git/challenge-dictionary-lookup<file_sep>/index.js import fetch from 'node-fetch'; const srcTxtUrl = "http://norvig.com/big.txt"; const specialChars = /[`~!@#$%^&*()_|+\-=?;:'"0123456789\n,.<>\{\}\[\]\\\/]/gi; const dictLookUpBaseUrl = 'https://dictionary.yandex.net/api/v1/dicservice.json/lookup'; const apiKey = '<KEY>'; const dictLang = 'en-en'; const dictLookUpUrl = `${dictLookUpBaseUrl}?key=${apiKey}&lang=${dictLang}&text`; const TOP_N = 10; fetch(srcTxtUrl) .then(res => res.text()) .then(res => { const processedText = removeSpecialChars(res); const wordCountDict = findWordCount(processedText); for(let i =0; i < TOP_N; i++){ fetchWordFromDictionary(wordCountDict[i]); } }) .catch(err => console.log("Error reading source text", err)); const removeSpecialChars = (text) => { return text.replace(specialChars, ''); } const findWordCount = (text) => { const wordArray = text.split(' ').filter(function(i){return i}); const wordCountDict = {}; wordArray.map((word) => { if (wordCountDict[word]) { wordCountDict[word] = wordCountDict[word] + 1; } else { wordCountDict[word] = 1; } }); // eg: {"that": 8572, in:"17765"} const wordCountArray = []; Object.keys(wordCountDict).map(item => { wordCountArray.push( { word: item , count: wordCountDict[item]} )}); /* eg: [ {word:"that",count: 8572},{word:"in",count: 17765} ] */ wordCountArray.sort((a,b) => {return b.count - a.count}); return wordCountArray; } const fetchWordFromDictionary = ({word, count}) => { fetch(`${dictLookUpUrl}=${word}`) .then(res => res.json()) .then(res => { console.log({word: word, output: {...processLookUpResponse(res), count: count}}); }) .catch(err => console.log("Error while looking up word in the dictionary",err)) } const processLookUpResponse = (res) => { let response = {}; res.def.map(item => { response["pos"] = item.pos}); const synonyms = []; res.def.map(def => {def.tr && def.tr.map(item => {item.syn && item.syn.map(syn => { return synonyms.push(syn.text)} )}) }); response["syns"] = synonyms; return response; } <file_sep>/readme.md # challenge-dictionary-lookup ### Please run the below commands to start the project To install dependencies: npm install To start the project: npm start
210cb7f72f566bd01c5f0e517750a3122f934f32
[ "JavaScript", "Markdown" ]
2
JavaScript
aravindanil816git/challenge-dictionary-lookup
f868594234523f761fb098d6de6657fef17343cc
201953e1dc53cc7b335a9c5d0b6590f54ae23b28
refs/heads/master
<repo_name>rew4332/contestApp<file_sep>/src/main/java/com/example/loveyoplus/myapplication/Test9Activity.java package com.example.loveyoplus.myapplication; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Random; /** * Created by loveyoplus on 2017/2/21. */ public class Test9Activity extends AppCompatActivity implements View.OnClickListener { RelativeLayout rl[]; ImageView iv[],answerIv; int tag[],answerNum,soundAnswer=-1; TextView tv[],timer; int[] result,soundResult; private Handler mHandler; MediaPlayer mp[]; final int GAMETIME=1000*1;//遊戲時間 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_t9); getSupportActionBar().hide(); //隱藏標題 getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN); //隱藏狀態 result = new int[2]; soundResult= new int[2]; tv = new TextView[3]; tv[0]= (TextView) findViewById(R.id.textView2); tv[1]= (TextView) findViewById(R.id.textView6);timer=tv[1]; tv[2]= (TextView) findViewById(R.id.textView5); mp = new MediaPlayer[3]; mp[0] = MediaPlayer.create(this, R.raw.drumsound); mp[1] = MediaPlayer.create(this, R.raw.pianosound); mp[2] = MediaPlayer.create(this, R.raw.trumpetsound); tv[0].setText("選下列所顯示之圖案並\n" + "音樂響起選取樂器"); answerIv = (ImageView)findViewById(R.id.imageView); rl = new RelativeLayout[23]; iv = new ImageView[23]; for(int i=0;i<23;i++){ iv[i] =(ImageView) findViewById(getResources().getIdentifier("iv" + (i + 1), "id", getPackageName())); rl[i] =(RelativeLayout) findViewById(getResources().getIdentifier("rl" + (i + 1), "id", getPackageName())); rl[i].setOnClickListener(this); } //抓取資源tag[x][0]=獲取圖片id tag = new int[5]; for(int i = 0;i<5;i++){ tag[i] = getResources().getIdentifier("t7_"+(i+1),"drawable",getPackageName()); } mHandler = new Handler(); mHandler.post(countdowntimer); mHandler.post(soundtimer); setQuestion(); answerNum=setImageView(); while(answerNum<4){ setQuestion(); answerNum=setImageView(); } } private Runnable soundtimer = new Runnable() { public void run() { new CountDownTimer(100000, 4000) { @Override public void onTick(long millisUntilFinished) { //倒數秒數中要做的事 removeSoundAllMark(); if(millisUntilFinished<=99000){ if(soundAnswer!=-1)soundResult[0]++; setSoundQuestion(); Log.d("setSoundQ answer",soundAnswer+""); mp[soundAnswer].start(); } } @Override public void onFinish() { } }.start(); } }; private Runnable countdowntimer = new Runnable() { public void run() { new CountDownTimer(GAMETIME, 1000) { @Override public void onTick(long millisUntilFinished) { //倒數秒數中要做的事 timer.setText("倒數時間:"+new SimpleDateFormat("m").format(millisUntilFinished)+":"+ new SimpleDateFormat("s").format(millisUntilFinished)); } @Override public void onFinish() { timer.setText("倒數時間:結束"); for(int i=0;i<20;i++) { rl[i].setVisibility(View.INVISIBLE); } Intent intent = new Intent(); intent.setClass(Test9Activity.this, Test10Activity.class); startActivity(intent); finish(); } }.start(); } }; public void setSoundQuestion(){ Random rand = new Random(); int selected = rand.nextInt(3); soundAnswer=selected; } public boolean isSoundAnswer(RelativeLayout r){ if(soundAnswer==0&&r==rl[20])return true; else if(soundAnswer==1&&r==rl[21])return true; else if(soundAnswer==2&&r==rl[22])return true; return false; } public int setImageView(){ int answerNum=0; for(int i=0;i<20;i++){ Random random = new Random(); int selected= random.nextInt(tag.length)+1; if((int)answerIv.getTag()==selected)answerNum++; iv[i].setImageResource(getResources().getIdentifier("t7_"+(selected),"drawable",getPackageName())); rl[i].setTag(selected); } return answerNum; } public void setQuestion(){ Random random = new Random(); int selected= random.nextInt(tag.length)+1; Object o = getResources().getIdentifier("t7_"+(selected),"drawable",getPackageName()); answerIv.setImageResource((int)o); answerIv.setTag(selected); } public boolean isAnswer(RelativeLayout r){ for(int i= 0 ;i<20;i++){ if(r==rl[i]&&(int)rl[i].getTag()==(int)answerIv.getTag()){ Log.e("isAnswer","true"); return true; } } Log.e("isAnswer","false"); return false; } public void removeAllMark(){ for(int i=0;i<20;i++){ rl[i].setOnClickListener(this); int count=((ViewGroup)rl[i]).getChildCount(); //Log.e(i+"count:",count+""); if(count>1) { ((ViewGroup) rl[i]).removeViewAt(1); } } } public void removeSoundAllMark(){ for(int i=20;i<23;i++){ int count=((ViewGroup)rl[i]).getChildCount(); //Log.e(i+"count:",count+""); if(count>1) { ((ViewGroup) rl[i]).removeViewAt(1); } } } @Override public void onClick(View v) { if((RelativeLayout)v==rl[20]||(RelativeLayout)v==rl[21]||(RelativeLayout)v==rl[22]){ RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT); params.width = ((RelativeLayout)v).getWidth(); params.height = ((RelativeLayout)v).getHeight(); ImageView ivX ; ivX = new ImageView(this); ivX.setImageResource(R.drawable.circle); ivX.setLayoutParams(params); Log.e("sound:","ok"); if(soundAnswer==-1); else if(isSoundAnswer((RelativeLayout)v)){ Log.d("sound result","true"); soundAnswer=-1; soundResult[1]++; ((RelativeLayout)v).addView(ivX); } else { Log.d("sound result","false"); soundResult[0]++; soundAnswer=-1; ((RelativeLayout)v).addView(ivX); } } else if(isAnswer((RelativeLayout)v)){ RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT); params.width = ((RelativeLayout)v).getWidth(); params.height = ((RelativeLayout)v).getHeight(); ImageView ivX ; ivX = new ImageView(this); ivX.setImageResource(R.drawable.circle); ivX.setLayoutParams(params); ((RelativeLayout)v).addView(ivX); ((RelativeLayout)v).setOnClickListener(null); answerNum--; if(answerNum==0){ result[1]++; removeAllMark(); setQuestion(); answerNum=setImageView(); while(answerNum<4){ setQuestion(); answerNum=setImageView(); } } } else{ result[0]++; removeAllMark(); setQuestion(); answerNum=setImageView(); while(answerNum<4){ setQuestion(); answerNum=setImageView(); } } tv[2].setText("Image:\n\t O:"+result[1]+"X:"+result[0]+"\nSound:\n\tO:"+soundResult[1]+"X:"+soundResult[0]); } } <file_sep>/src/main/java/com/example/loveyoplus/myapplication/Test5Activity.java package com.example.loveyoplus.myapplication; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import android.os.Handler; /** * Created by loveyoplus on 2017/2/24. */ public class Test5Activity extends AppCompatActivity implements View.OnTouchListener { private ArrayList<String> stationNameList; // 放置題目站名之區塊(右側) private ArrayList<ArrayList<Float>> stationPositionList; // 放置捷運圖之區塊(左側) public int remainNum; // 未被許取之站點數量 LinearLayout stationBar; // 放置題目站名之區塊(右側) RelativeLayout touchMap; // 放置捷運圖之區塊(左側) TextView tvTimer; // 計時器區塊 TextView tvTitle; // 題目描述區塊 int[] result; private Handler mHandler; // 計時物件之執行序 // 計時物件 private Runnable countdowntimer = new Runnable() { public void run() { new CountDownTimer(60000, 1000) { @Override public void onTick(long millisUntilFinished) { tvTimer.setText("倒數時間:"+new SimpleDateFormat("m").format(millisUntilFinished)+":"+ new SimpleDateFormat("s").format(millisUntilFinished)); } @Override public void onFinish() { tvTimer.setText("倒數時間:結束");Intent intent = new Intent(); intent.setClass(Test5Activity.this, Test6Activity.class); startActivity(intent); finish(); } }.start(); } }; private final int QUESTION_NUM = 15; // 題目要求之站數 String s=""; ImageView stationListener; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_t5); getSupportActionBar().hide(); //隱藏標題 getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN); //隱藏狀態 stationListener = new ImageView(this); result = new int[2]; // Initialization of Env Paramater this.GenStationList(); stationBar = (LinearLayout) findViewById(R.id.stationBar); touchMap = (RelativeLayout) findViewById(R.id.r1); tvTimer = (TextView) findViewById(R.id.tvTimer); tvTitle = (TextView) findViewById(R.id.tvTitle); touchMap.setOnTouchListener(this); // Initialization of Layout List<Integer> stationIds = this.PickUpStationIds(QUESTION_NUM); remainNum = QUESTION_NUM; for (int id: stationIds) { this.BindEvent(id, touchMap, stationBar); } // Timing mHandler = new Handler(); mHandler.post(countdowntimer); } protected void GenStationList() { ArrayList<String> station_name = new ArrayList<>(); ArrayList<ArrayList<Float>> station_poses = new ArrayList<>(); // 紅線 station_name.add("圓山"); station_poses.add(new ArrayList<Float>() {{ add(170.0f); add(128.0f); }}); station_name.add("民權西路"); station_poses.add(new ArrayList<Float>() {{ add(170.0f); add(192.0f); }}); station_name.add("雙連"); station_poses.add(new ArrayList<Float>() {{ add(170.0f); add(249.0f); }}); station_name.add("中山"); station_poses.add(new ArrayList<Float>() {{ add(170.0f); add(311.0f); }}); station_name.add("台北車站"); station_poses.add(new ArrayList<Float>() {{ add(170.0f); add(384.0f); }}); station_name.add("台大醫院"); station_poses.add(new ArrayList<Float>() {{ add(170.0f); add(426.0f); }}); station_name.add("中正紀念堂"); station_poses.add(new ArrayList<Float>() {{ add(202.0f); add(471.0f); }}); station_name.add("東門"); station_poses.add(new ArrayList<Float>() {{ add(281.0f); add(471.0f); }}); station_name.add("大安森林公園"); station_poses.add(new ArrayList<Float>() {{ add(429.0f); add(471.0f); }}); station_name.add("大安"); station_poses.add(new ArrayList<Float>() {{ add(513.0f); add(473.0f); }}); station_name.add("信義安和"); station_poses.add(new ArrayList<Float>() {{ add(653.0f); add(471.0f); }}); station_name.add("台北101/世貿"); station_poses.add(new ArrayList<Float>() {{ add(787.0f); add(471.0f); }}); // 橘線 station_name.add("大橋頭"); station_poses.add(new ArrayList<Float>() {{ add(84.0f); add(187.0f); }}); station_name.add("中山國小"); station_poses.add(new ArrayList<Float>() {{ add(304.0f); add(188.0f); }}); station_name.add("行天宮"); station_poses.add(new ArrayList<Float>() {{ add(364.0f); add(249.0f); }}); station_name.add("頂溪"); station_poses.add(new ArrayList<Float>() {{ add(190.0f); add(561.0f); }}); station_name.add("永安市場"); station_poses.add(new ArrayList<Float>() {{ add(151.0f); add(596.0f); }}); // 咖啡線 station_name.add("松山機場"); station_poses.add(new ArrayList<Float>() {{ add(512.0f); add(135.0f); }}); station_name.add("中山國中"); station_poses.add(new ArrayList<Float>() {{ add(512.0f); add(222.0f); }}); station_name.add("科技大樓"); station_poses.add(new ArrayList<Float>() {{ add(513.0f); add(516.0f); }}); station_name.add("六張犁"); station_poses.add(new ArrayList<Float>() {{ add(597.0f); add(562.0f); }}); station_name.add("麟光"); station_poses.add(new ArrayList<Float>() {{ add(638.0f); add(604.0f); }}); // 綠線 station_name.add("南京三民"); station_poses.add(new ArrayList<Float>() {{ add(806.0f); add(306.0f); }}); station_name.add("台北小巨蛋"); station_poses.add(new ArrayList<Float>() {{ add(676.0f); add(306.0f); }}); station_name.add("南京復興"); station_poses.add(new ArrayList<Float>() {{ add(512.0f); add(310.0f); }}); station_name.add("松江南京"); station_poses.add(new ArrayList<Float>() {{ add(364.0f); add(308.0f); }}); station_name.add("北門"); station_poses.add(new ArrayList<Float>() {{ add(78.0f); add(334.0f); }}); station_name.add("西門"); station_poses.add(new ArrayList<Float>() {{ add(77.0f); add(426.0f); }}); station_name.add("小南門"); station_poses.add(new ArrayList<Float>() {{ add(114.0f); add(464.0f); }}); station_name.add("古亭"); station_poses.add(new ArrayList<Float>() {{ add(240.0f); add(507.0f); }}); station_name.add("台電大樓"); station_poses.add(new ArrayList<Float>() {{ add(279.0f); add(545.0f); }}); station_name.add("公館"); station_poses.add(new ArrayList<Float>() {{ add(309.0f); add(579.0f); }}); station_name.add("萬隆"); station_poses.add(new ArrayList<Float>() {{ add(347.0f); add(613.0f); }}); // 藍線 station_name.add("市政府"); station_poses.add(new ArrayList<Float>() {{ add(779.0f); add(383.0f); }}); station_name.add("國父紀念館"); station_poses.add(new ArrayList<Float>() {{ add(691.0f); add(382.0f); }}); station_name.add("忠孝敦化"); station_poses.add(new ArrayList<Float>() {{ add(598.0f); add(381.0f); }}); station_name.add("忠孝復興"); station_poses.add(new ArrayList<Float>() {{ add(512.0f); add(383.0f); }}); station_name.add("忠孝新生"); station_poses.add(new ArrayList<Float>() {{ add(363.0f); add(381.0f); }}); station_name.add("善導寺"); station_poses.add(new ArrayList<Float>() {{ add(273.0f); add(381.0f); }}); this.stationNameList = station_name; this.stationPositionList = station_poses; } protected List PickUpStationIds(int number) { int stationNum = this.stationNameList.size(); ArrayList<Integer> idList = new ArrayList<Integer>(); int i; for (i = 0; i < stationNum; ++ i) { idList.add(new Integer(i)); } Collections.shuffle(idList); return idList.subList(0, number - 1); } protected void BindEvent(final int id, final RelativeLayout touchMap, final LinearLayout displayBar) { String stationName = this.stationNameList.get(id); float stationPostionX = this.stationPositionList.get(id).get(0); float stationPostionY = this.stationPositionList.get(id).get(1); TextView stationNameText = new TextView(this); stationNameText.setText(stationName); stationNameText.setId(100 + id); displayBar.addView(stationNameText); //RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT); ImageView stationListener = new ImageView(this); stationListener.setMinimumWidth(40); stationListener.setMinimumHeight(40); stationListener.setImageResource(R.drawable.dot); stationListener.setAlpha(0.2f); stationListener.setId(200 + id); stationListener.setX(stationPostionX - 20); stationListener.setY(stationPostionY - 20); stationListener.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { displayBar.removeView(findViewById(100 + id)); touchMap.removeView(findViewById(200 + id)); remainNum --; } }); touchMap.addView(stationListener); } @Override public boolean onTouch(View v, MotionEvent event) { /* int touchX = (int) event.getX(); int touchY = (int) event.getY(); int imageX = touchX ; int imageY = touchY ; stationListener.setMinimumWidth(40); stationListener.setMinimumHeight(40); stationListener.setImageResource(R.drawable.dot); stationListener.setAlpha(0.0f); stationListener.setX(touchX+20); stationListener.setY(touchY+20); Log.v("Image x >>>",imageX+""); Log.v("Image y >>>",imageY+"\n"); if(event.getAction()==MotionEvent.ACTION_DOWN){ ((RelativeLayout)v).removeView(stationListener); ((RelativeLayout)v).addView(stationListener); } if(event.getAction()==MotionEvent.ACTION_UP) { s += (imageX+40) + "," + (imageY+40) + ";"; Log.e("x,y;", s + ""); } */ return true; } } <file_sep>/src/main/java/com/example/loveyoplus/myapplication/Test6Activity.java package com.example.loveyoplus.myapplication; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Random; /** * Created by loveyoplus on 2017/2/17. */ public class Test6Activity extends AppCompatActivity implements View.OnClickListener { RelativeLayout rl[]; ImageView iv[][]; TextView tv[],timer; ImageView answerIv; int[] result; private Handler mHandler; int randomNumLen=37; final int GAMETIME=1000*1;//遊戲時間 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_t6); getSupportActionBar().hide(); //隱藏標題 getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN); //隱藏狀態 rl= new RelativeLayout[9]; iv = new ImageView[9][3]; tv = new TextView[3]; result = new int[2]; tv[0] =(TextView) findViewById(R.id.textView2); tv[1] =(TextView) findViewById(R.id.textView6); tv[2] =(TextView) findViewById(R.id.textView5); tv[0].setText("找出下面所顯示之注音符號"); timer = tv[1]; answerIv= (ImageView) findViewById(R.id.imageView); for(int i=0;i<9;i++) { rl[i] = (RelativeLayout) findViewById(getResources().getIdentifier("rl" + (i + 1), "id", getPackageName())); rl[i].setOnClickListener(this); iv[i][0] = (ImageView) findViewById(getResources().getIdentifier("iv" + (i + 1), "id", getPackageName())); iv[i][1] = new ImageView(this); iv[i][2] = new ImageView(this); rl[i].addView(iv[i][1]); rl[i].addView(iv[i][2]); } mHandler = new Handler(); mHandler.post(countdowntimer); setImage(); setQuestion(); } private Runnable countdowntimer = new Runnable() { public void run() { new CountDownTimer(GAMETIME, 1000) { @Override public void onTick(long millisUntilFinished) { //倒數秒數中要做的事 timer.setText("倒數時間:"+new SimpleDateFormat("m").format(millisUntilFinished)+":"+ new SimpleDateFormat("s").format(millisUntilFinished)); } @Override public void onFinish() { timer.setText("倒數時間:結束"); for(int i=0;i<9;i++) { rl[i].setVisibility(View.INVISIBLE); } Intent intent = new Intent(); intent.setClass(Test6Activity.this, Test7Activity.class); startActivity(intent); finish(); } }.start(); } }; public boolean isAnswer(RelativeLayout r){ for(int i= 0 ;i<9;i++){ if(r==rl[i]&&i==(int)answerIv.getTag()){ Log.e("isAnswer","true"); return true; } } Log.e("isAnswer","false"); return false; } public void setQuestion(){ Random random = new Random(); int selected=random.nextInt(9*3); Object o =iv[(int)(selected/3)][selected%3].getTag(); answerIv.setTag((int)selected/3); answerIv.setImageResource((int)o); } public void setImage(){ String randomNum[]={"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"}; for(int i = 0 ;i<9;i++){ for(int j =0;j<3;j++){ Random random = new Random(); int selected= random.nextInt(randomNumLen-(i*3+j)); Object o = getResources().getIdentifier("t6_"+randomNum[selected],"drawable",getPackageName()); iv[i][j].setImageResource((Integer) o); iv[i][j].setTag(o); randomNum[selected]=randomNum[randomNumLen-1-(i*3+j)]; } } } @Override public void onClick(View v) { if(isAnswer((RelativeLayout) v)) { result[1]++; } else result[0]++; tv[2].setText("O:"+result[1]+"X:"+result[0]); setImage(); setQuestion(); } }
754fc19cf40b4254f27e5bb3362e04b98810ec55
[ "Java" ]
3
Java
rew4332/contestApp
02cd30f77d41f0792ef937df60043f82383628e5
7d12a09f408966bb70683fe519dedea872cd9a17
refs/heads/master
<file_sep>import {child_process_tools} from "./index"; let cmd = new child_process_tools({type: 'console', cwd: './'}) cmd.spawn('dir') cmd.spawn('mkdir test') cmd.spawn('cd test') // cmd.end() cmd.on('command', (d) => { console.log(d); }); <file_sep>'use strict'; import {spawn} from "child_process"; import {EventEmitter} from "events"; import * as os from 'os' import * as iconv from 'iconv-lite' export class child_process_tools extends EventEmitter { auto_console: any; config: any command: any constructor(config: { type: 'console' | 'html', cwd: './' }) { super(); this.config = config this.auto_console = {} this.command = spawn(this.getSystemCode().shell, [], {cwd: this.config.cwd, shell: true}) /** * 通过 *.on('command',(data)=>{}) 来获取返回数据 */ this.command.stdout.on('data', (data: any) => { this.emit('command', this.format(data)) }); this.command.stderr.on('data', (data: any) => { this.emit('command', this.format(data)) }); this.command.on('error', (data: any) => { this.emit('command', this.format(data)) }); this.command.on('close', (data: any) => { this.emit('command', {msg:'子进程退出!',code:data}) }); this.command.on('exit', (data: any) => { this.emit('command', {msg:'子进程退出!',code:data}) }); } getSystemCode () { //cp936 || 'GBK'; if (os.platform() === "win32") { this.auto_console.shell = "cmd.exe"; this.auto_console.coding = 'cp936'; } else { this.auto_console.shell = "/bin/sh"; this.auto_console.coding = 'UTF-8'; } return this.auto_console; }; format(e: any) { e = this.iconvs(e) //根据配置来判断输出那种格式 if (this.config.type === "html") { return e.replace(/<DIR>/g, '&lt;DIR&gt;').replace(/</g, "&lt;").replace(/>/g, "&gt;"); } return e } iconvs(e: any) { //解决不支持GBK return iconv.decode(e, this.getSystemCode().coding); }; spawn(command: string) { this.command.stdin.write(command) this.command.stdin.write('\n') } end(){ this.command.stdin.end(); } }
45f820ad31075123f5fb3ae0f4f3f8e00b6a6dd5
[ "TypeScript" ]
2
TypeScript
RoueSu/node_child_process_tools
3a45c8e5ee52ab881172148e855a5e967df920cc
af016df597fa9c88a07161cbe0f5b8e0ab3795c9
refs/heads/master
<repo_name>fireworld/Mvp<file_sep>/app/src/main/java/cc/iceworld/mvp/toolbox/net/Callback.java package cc.iceworld.mvp.toolbox.net; import android.support.annotation.NonNull; /** * Created by cxx on 16/7/13. * <EMAIL> */ public interface Callback<T> { void onStart(); void onSuccess(@NonNull T t); void onFailure(int code, @NonNull String msg); void onFinish(); } <file_sep>/app/src/main/java/cc/iceworld/mvp/presenter/BasePresenter.java package cc.iceworld.mvp.presenter; import android.support.annotation.CallSuper; import android.support.annotation.NonNull; import cc.iceworld.mvp.api.IBase; /** * Created by cxx on 16/6/20. * <EMAIL> */ public class BasePresenter<V extends IBase.View> implements IBase.Presenter { /** * 在 View 销毁时会连同销毁 Presenter,此时 mView 会被置空,因此在网络请求回调中 mView 可能为空。 */ protected V mView; public BasePresenter(@NonNull V view) { mView = view; } @CallSuper @Override public void onCreate() { } @CallSuper @Override public void onStart() { } @CallSuper @Override public void onResume() { } @CallSuper @Override public void onPause() { } @CallSuper @Override public void onStop() { } @CallSuper @Override public void onDestroy() { mView = null; } protected final boolean viewEnable() { return mView != null && mView.isActive(); } } <file_sep>/app/src/main/java/cc/iceworld/mvp/model/LoginModel.java package cc.iceworld.mvp.model; import android.os.AsyncTask; import android.os.SystemClock; import cc.iceworld.mvp.api.ILoginModel; import cc.iceworld.mvp.bean.User; import cc.iceworld.mvp.toolbox.net.Callback; /** * Created by cxx on 16/7/13. * <EMAIL> */ public class LoginModel implements ILoginModel { public static final String USER_NAME = "cxx"; public static final String USER_PASSWORD = "<PASSWORD>"; public void login(final String username, final String password, final Callback<User> callback) { new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { callback.onStart(); } @Override protected Boolean doInBackground(String... strings) { SystemClock.sleep(1500); return USER_NAME.equals(strings[0]) && USER_PASSWORD.equals(strings[1]); } @Override protected void onPostExecute(Boolean aBoolean) { if (aBoolean) { callback.onSuccess(new User(username, password)); } else { callback.onFailure(-1, "username or password error"); } callback.onFinish(); } }.execute(username, password); } } <file_sep>/app/src/main/java/cc/iceworld/mvp/LaunchActivity.java package cc.iceworld.mvp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import cc.iceworld.mvp.view.activity.DemoActivity; import cc.iceworld.mvp.view.dialog.DemoDialogFragment; import cc.iceworld.mvp.view.fragment.DemoFragment; /** * Created by cxx on 16-6-24. * <EMAIL> */ public class LaunchActivity extends Activity implements View.OnClickListener { private LinearLayout mRootView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_launch); mRootView = (LinearLayout) findViewById(R.id.ll_root); findViewById(R.id.btn_to_demo_activity).setOnClickListener(this); findViewById(R.id.btn_to_demo_fragment).setOnClickListener(this); findViewById(R.id.btn_show_demo_dialog_fragment).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_to_demo_activity: startActivity(new Intent(this, DemoActivity.class)); break; case R.id.btn_to_demo_fragment: mRootView.removeAllViews(); getFragmentManager().beginTransaction().replace(R.id.ll_root, new DemoFragment()).commit(); break; case R.id.btn_show_demo_dialog_fragment: new DemoDialogFragment().show(getFragmentManager(), "DemoDialogFragment"); break; default: break; } } } <file_sep>/app/src/main/java/cc/iceworld/mvp/toolbox/net/WeakCallback.java package cc.iceworld.mvp.toolbox.net; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.lang.ref.WeakReference; import cc.iceworld.mvp.api.IBase; /** * Created by cxx on 16/7/13. * <EMAIL> */ public abstract class WeakCallback<V extends IBase.View, T> implements Callback<T> { private WeakReference<V> ref; public WeakCallback(V view) { this.ref = new WeakReference<>(view); } @Nullable private V getView() { return ref != null ? ref.get() : null; } private static boolean isEnable(IBase.View v) { return v != null && v.isActive(); } @Override public final void onStart() { V v = getView(); if (isEnable(v)) { onStart(v); } } @Override public final void onSuccess(@NonNull T t) { V v = getView(); if (isEnable(v)) { onSuccess(v, t); } } @Override public final void onFailure(int code, @NonNull String msg) { V v = getView(); if (isEnable(v)) { onFailure(v, code, msg); } } @Override public final void onFinish() { V v = getView(); if (isEnable(v)) { onFinish(v); } } public void onStart(@NonNull V view) { } public abstract void onSuccess(@NonNull V view, @NonNull T t); public abstract void onFailure(@NonNull V view, int code, @NonNull String msg); public void onFinish(@NonNull V view) { } } <file_sep>/app/src/main/java/cc/iceworld/mvp/view/fragment/BaseFragment.java package cc.iceworld.mvp.view.fragment; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import cc.iceworld.mvp.api.IBase; import cc.iceworld.mvp.toolbox.FakeLayoutInflater; /** * Created by cxx on 16/6/20. * <EMAIL> */ public abstract class BaseFragment<P extends IBase.Presenter> extends Fragment implements IBase.View<P> { private boolean mOnCreateOfPresenterNeedCall = true; protected P mPresenter; protected View mRootView; private boolean mIsActive = false; @Override public final void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPresenter = getPresenter(); } @Nullable @Override public final View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); if (mRootView == null) { mRootView = initView(FakeLayoutInflater.from(inflater), container, savedInstanceState); mOnCreateOfPresenterNeedCall = true; } return mRootView; } protected abstract View initView(@NonNull FakeLayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState); @CallSuper @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mIsActive = true; if (mOnCreateOfPresenterNeedCall && mPresenter != null) { mPresenter.onCreate(); mOnCreateOfPresenterNeedCall = false; } } @CallSuper @Override public void onStart() { super.onStart(); if (mPresenter != null) { mPresenter.onStart(); } } @CallSuper @Override public void onResume() { super.onResume(); if (mPresenter != null) { mPresenter.onResume(); } } @CallSuper @Override public void onPause() { if (mPresenter != null) { mPresenter.onPause(); } super.onPause(); } @CallSuper @Override public void onStop() { if (mPresenter != null) { mPresenter.onStop(); } super.onStop(); } @CallSuper @Override public void onDestroyView() { super.onDestroyView(); } @CallSuper @Override public void onDestroy() { mIsActive = false; if (mPresenter != null) { mPresenter.onDestroy(); mPresenter = null; } mRootView = null; super.onDestroy(); } @Override public boolean isActive() { return mIsActive; } @Override public void toast(@NonNull CharSequence text) { Activity a = getActivity(); if (a != null) { Toast.makeText(a.getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } } @Override public void toast(@StringRes int resId) { Activity a = getActivity(); if (a != null) { Toast.makeText(a.getApplicationContext(), resId, Toast.LENGTH_SHORT).show(); } } } <file_sep>/app/src/main/java/cc/iceworld/mvp/view/fragment/DemoFragment.java package cc.iceworld.mvp.view.fragment; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TableLayout; import android.widget.TextView; import cc.iceworld.mvp.R; import cc.iceworld.mvp.api.IDemo; import cc.iceworld.mvp.bean.User; import cc.iceworld.mvp.presenter.DemoPresenter; import cc.iceworld.mvp.toolbox.FakeLayoutInflater; /** * Created by cxx on 16-6-24. * <EMAIL> */ public class DemoFragment extends BaseFragment<IDemo.Presenter> implements IDemo.View { private TableLayout mRootTl; private TextView mLoginResultTv; private EditText mUsernameEt; private EditText mPasswordEt; private Button mSubmitBtn; @Override protected View initView(@NonNull FakeLayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.view_demo, container); mRootTl = (TableLayout) view.findViewById(R.id.tl_root); mLoginResultTv = (TextView) view.findViewById(R.id.tv_login_result); mUsernameEt = (EditText) view.findViewById(R.id.et_username); mPasswordEt = (EditText) view.findViewById(R.id.et_password); mSubmitBtn = (Button) view.findViewById(R.id.btn_submit); mSubmitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mPresenter.toLogin(); } }); return view; } @Override public String getUsername() { return mUsernameEt.getText().toString(); } @Override public String getPassword() { return mPasswordEt.getText().toString(); } @Override public void setSubmitEnabled(boolean enabled) { mSubmitBtn.setEnabled(enabled); } @Override public void setUsernameError(@NonNull String tip) { mUsernameEt.setError(tip); } @Override public void setPasswordError(@NonNull String tip) { mPasswordEt.setError(tip); } @Override public void onLoginSuccess(@NonNull User user) { setResult(Color.parseColor("#ffff00"), user.getUsername() + " login success!"); } @Override public void onLoginFailure(String msg) { setResult(Color.parseColor("#0000ff"), msg); } private void setResult(int color, String tip) { mRootTl.setBackgroundColor(color); mLoginResultTv.setText(tip); } @NonNull @Override public IDemo.Presenter getPresenter() { return new DemoPresenter(this); } } <file_sep>/app/src/main/java/cc/iceworld/mvp/presenter/DemoPresenter.java package cc.iceworld.mvp.presenter; import android.support.annotation.NonNull; import cc.iceworld.mvp.api.IDemo; import cc.iceworld.mvp.api.ILoginModel; import cc.iceworld.mvp.bean.User; import cc.iceworld.mvp.model.LoginModel; import cc.iceworld.mvp.toolbox.TextTools; import cc.iceworld.mvp.toolbox.net.WeakCallback; /** * Created by cxx on 16-6-24. * <EMAIL> */ public class DemoPresenter extends BasePresenter<IDemo.View> implements IDemo.Presenter { private ILoginModel mModel = new LoginModel(); private String mUsername; private String mPassword; public DemoPresenter(@NonNull IDemo.View view) { super(view); } @Override public void onCreate() { super.onCreate(); // no data need init } @Override public void toLogin() { if (!checkToLogin()) return; mModel.login(mUsername, mPassword, new WeakCallback<IDemo.View, User>(mView) { @Override public void onStart(@NonNull IDemo.View view) { view.toast("login..."); view.setSubmitEnabled(false); } @Override public void onSuccess(@NonNull IDemo.View view, @NonNull User user) { view.onLoginSuccess(user); } @Override public void onFailure(@NonNull IDemo.View view, int code, @NonNull String msg) { view.onLoginFailure(msg); } @Override public void onFinish(@NonNull IDemo.View view) { view.setSubmitEnabled(true); } }); } private boolean checkToLogin() { boolean result = true; String username = mView.getUsername(); if (TextTools.isEmpty(username)) { mView.setUsernameError("empty"); result = false; } String password = mView.getPassword(); if (TextTools.isEmpty(password) || password.length() < 6) { mView.setPasswordError("less than 6"); result = false; } if (result) { mUsername = username; mPassword = <PASSWORD>; } return result; } }
3fc15c7ea721006a08d0c6e0b4e767c9bf8a3fdb
[ "Java" ]
8
Java
fireworld/Mvp
81ec82ae892a0b198c8c6f13d76758c04874451c
e0ad6a021cd951400e516018e5be525e3eaf3375
refs/heads/master
<repo_name>Server4001/in-place-with-mongoid<file_sep>/app/models/user.rb class User include Mongoid::Document include Mongoid::Timestamps field :first_name, type: String field :last_name, type: String field :bio, type: String field :country, type: String field :privacy, type: Boolean field :birthday, type: Date field :email, type: String validates :first_name, presence: true validates :last_name, presence: true validates :bio, length: { minimum: 5, maximum: 75 } validates :email, presence: true, format: { with: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i, message: "must be in the format _____@____.___" } end
c02260c0014bf2b1d6f09e9afcd1e8acf7272153
[ "Ruby" ]
1
Ruby
Server4001/in-place-with-mongoid
df89c3ee92214dbf876b92ce9a88fac1c501ed95
136566f659ebe06af6631527719870f81b24a5bc
refs/heads/main
<file_sep> # <NAME> def main(): #escribe tu código abajo de esta línea papel = int(input('Dame el número de papeles:')) plumones = int(input('Dame el número de plumones:')) maximo = plumones * 35 print('El número máximo de tarjetas que se pueden hacer es:'+ str(maximo)) if __name__ == '__main__': main() <file_sep> #Volumen de un prisma rectangular def rectangulo(base,altura): area = base * altura return area def prisma(AREA_TOTAL, ancho): volumen = AREA_TOTAL * ancho print( 'El volumen del prisma es: '+ str(volumen)) def main(): #escribe tu código abajo de esta línea+ base = float(input('Dame la base:')) altura = float(input('Dame la altura:')) ancho = float(input('Dame el ancho:')) AREA_TOTAL = rectangulo(base,altura) print('El area del rectángulo es:' + str(AREA_TOTAL)) prisma(AREA_TOTAL, ancho) if __name__ == '__main__': main() <file_sep> #Año bisiesto def main(): #escribe tu código abajo de esta línea año = int(input('Ingresa el año:')) if año % 4 != 0: año = print(str('False')) elif año % 4 == 0 and año % 100 != 0: año = print(str('True')) elif año % 4 == 0 and año % 100 == 0 and año % 400 != 0: año = print(str('False')) elif año % 4 == 0 and año % 100 == 0 and año % 400 == 0: año = print(str('True')) if __name__ == '__main__': main()
708ec0aa2835218bd2e44ac84c24390583f9c09c
[ "Python" ]
3
Python
C-CCM-TC1028-102-2113/tarea-3-programas-que-usan-funciones-Diegozaldivar
2719b0f03988d6d6e7bcb6f3bc13cc2c7305865e
ab00ee040436f4909496949e3564434e328fc52d
refs/heads/master
<repo_name>lotharJiang/Question-Answering-System<file_sep>/answer_questions.py import csv import gensim from gensim.models import Word2Vec import utils import json import math import numpy as np import spacy import re from nltk.tokenize import word_tokenize, TreebankWordTokenizer, sent_tokenize import sys, getopt from sklearn.metrics import classification_report as c_report from sklearn.utils import shuffle from vector_space_model import VectorSpaceModel from nltk.corpus import stopwords def main(argv): method = 'bm25' k1 = 1.5 b = 0.5 k3 = 0 try: opts, args = getopt.getopt(argv, "m:b:", ["method=", "bm25="]) except getopt.GetoptError: sys.exit(2) for opt, arg in opts: if opt in ("-m", "--method"): if arg == '1': method = 'bm25' elif arg == '2': method = 'tfidf' elif arg == '3': method = 'tf' elif opt in ("-b", "--bm25"): parameters = arg.split(',') k1 = float(parameters[0].strip()) b = float(parameters[1].strip()) k3 = float(parameters[2].strip()) doc_path = 'data/documents.json' training_path = 'data/training.json' develop_path = 'data/devel.json' testing_path = 'data/testing.json' doc_set = utils.get_dataset(doc_path) dataset = utils.get_dataset(testing_path) questions = [] for query in dataset: questions.append(query['question']) questions_classes = utils.question_classify(questions) nlp = spacy.load('en_core_web_sm') results = [] for i in range(len(dataset)): query = dataset[i] candidates = [] should_have_candidate = False # If the question class is not 'other', there should be candidate answer entities in retrieved sentences if questions_classes[i] != 'other': should_have_candidate = True question = query['question'] answer = None # Build vector space model to retrieve the top 3 relevant paragraphs para_corpus = doc_set[query['docid']]['text'] para_vsm = VectorSpaceModel(para_corpus, [k1, b, k3]) match_paras = para_vsm.get_top_k_doc(question, k=3, method=method) # Build vector space model to retrieve the top 3 relevant sentences sent_corpus = [] for para in match_paras: sent_corpus += sent_tokenize(doc_set[query['docid']]['text'][para[0]]) sent_vsm = VectorSpaceModel(sent_corpus, [k1, b, k3]) match_sents = sent_vsm.get_top_k_doc(question, k=3, method=method) if should_have_candidate: # Find entities with expected types in candidate sentences for sent in match_sents: match_sent = sent_corpus[sent[0]] entities = utils.entity_recognition(match_sent, nlp) if questions_classes[i] == 'hum': for e in entities: # 'Human' questions mostly start by 'Who', so they may also expect organization as answer if (e[1] == 'PERSON' or e[1] == 'ORG') and e[0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'date': for e in entities: if (e[1] == 'DATE' or e[1] == 'TIME') and e[0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'money': for e in entities: if e[1] == 'MONEY' and e[0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'gpe': for e in entities: if e[1] == 'GPE' and e[0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'loc': for e in entities: if (e[1] == 'LOC' or e[1] == 'FAC') and e[0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'num': for e in entities: if (e[1] == 'CARDINAL' or e[1] == 'QUANTITY') and e[ 0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'ord': for e in entities: if (e[1] == 'ORDINAL') and e[0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'percent': for e in entities: if (e[1] == 'PERCENT') and e[0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'event': for e in entities: if (e[1] == 'EVENT') and e[0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'art': for e in entities: if (e[1] == 'WORK_OF_ART') and e[0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'lang': for e in entities: if (e[1] == 'LANGUAGE') and e[0].lower() not in question.lower(): candidates.append(e) elif questions_classes[i] == 'org': for e in entities: if (e[1] == 'ORG') and e[0].lower() not in question.lower(): candidates.append(e) if len(candidates) > 0: answer = '' for candidate in candidates: answer += ' ' + candidate[0] break # If question is tagged with no expected answer type. # Or there are no expected entities in top 3 relevant sentences. if answer is None: # Consider the answer is included in the top 1 relevant sentence match_sent = sent_corpus[match_sents[0][0]] non_candidates = utils.preprocess(question) punctuation = r'[\s+\.\!\/_,$%^*()+:;\-\[\]\"\'`]+|[+——!,。?、~@#¥%……&*()]+' # Remove the tokens in question, punctuations, replicate tokens and tokens which are not noun or adjective. rough_answer = utils.preprocess(match_sent, True) for word in rough_answer[:]: if word[0] in non_candidates or word[1] in candidates or re.match(punctuation, word[0]) or not ( word[2].startswith('J') or word[2].startswith('N')): continue candidates.append(word[1]) answer = ' '.join(w for w in candidates).strip() answer = answer.lower().strip() print (question+'\n'+questions_classes[i]+'\n'+answer+'\n') results.append([query['id'], answer]) # Save all results utils.save_csv("sphinx_bane.csv", ["id", "answer"], results) if __name__ == "__main__": main(sys.argv[1:]) <file_sep>/train_classifier.py import tensorflow as tf import numpy as np import os import utils from sklearn.utils import shuffle from question_classifier import QuestionClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import precision_recall_fscore_support # Get training set, vocabulary and question classes x_train, y_train, vocabulary, classes = utils.get_training_dataset_info() # Shuffle dataset x_shuffled,y_shuffled = shuffle(x_train,y_train) # Split dataset x_train,x_dev,y_train,y_dev = train_test_split(x_shuffled, y_shuffled, test_size=0.1) # Create directory checkpoint_dir = 'classifier_model/checkpoints/' checkpoint_prefix = checkpoint_dir + "classifier_model" if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) tf.reset_default_graph() sess = tf.Session() with sess.as_default(): classifier = QuestionClassifier( input_size=x_train.shape[1], n_classes=len(classes), vocabulary_size=len(vocabulary)) saver = tf.train.Saver(tf.global_variables(), max_to_keep=None) init = tf.global_variables_initializer() sess.run(init) loss_dev = [] accuracy_dev = [] precision_dev = [] recall_dev = [] f1score_dev = [] step = 0 # Get training batches batches = utils.batch_generater( list(zip(x_train, y_train)), batch_size=128, num_epochs=10) for batch in batches: x_batch, y_batch = zip(*batch) # Training _ = sess.run(classifier.train_op, feed_dict={classifier.question: x_batch, classifier.label: y_batch, classifier.dropout_rate: 0.5}) step += 1 # Evaluate the classifier_model every 100 steps if step % 100 == 0: y_true = np.argmax(y_dev, 1) # Get labels, loss and accuracy y_predict, loss, accuracy = sess.run( [classifier.predictions, classifier.loss, classifier.accuracy], feed_dict={classifier.question: x_dev, classifier.label: y_dev, classifier.dropout_rate: 1.0}) # Calculate precision, recall, f1-score precision, recall, f1score, _ = precision_recall_fscore_support(y_true, y_predict, average='macro') print("\nEvaluation:") print("Step:\t"+str(step)) print("Loss:\t"+str(loss)) print("Accuracy:\t"+str(accuracy)) print("Precision:\t"+str(precision)) print("Recall:\t"+str(recall)) print("F1-score:\t"+str(f1score)) loss_dev.append(loss) accuracy_dev.append(accuracy) precision_dev.append(precision) recall_dev.append(recall) f1score_dev.append(f1score) # Save the classifier_model every 100 steps if step % 100 == 0: path = saver.save(sess, checkpoint_prefix, global_step=step) # Save the evaluating results np.save('loss_dev.npy', np.array(loss_dev)) np.save('accuracy_dev.npy', np.array(accuracy_dev)) np.save('precision_dev.npy', np.array(precision_dev)) np.save('recall_dev.npy', np.array(recall_dev)) np.save('f1score_dev.npy', np.array(f1score_dev))<file_sep>/README.md # Question-Answering-System ## File Structure - **data**<br>A directory contains document data as well as training, devloping and testing dataset for the system, including training set for CNN question classifier. - **classifier_model**<br>A directory contains checkpoint files for CNN question classifier. - **answer_questions.py**<br>A python file aims to acquire answers of given question from given document. - **vector_space_model.py**<br>A python file contains a class 'VectorSpaceModel'. It is utilized in the information retrieval phase in the system. - **question_classifier.py**<br>A python file contains a class 'QuestionClassifier'. It is a convolutional neural network question classification model. - **train_classifier.py**<br>A python file which is used to train the CNN question classifier. - **utils.py**<br>A python file contains many userful tools in this system. E.g., text preprocessing, reading/writing csv file, etc. ## Usage As the pretrained model of the CNN question classifier is not provided, the model needs to be trained before answering questions. It should take no more than an hour on a CPU device. Run the following command: - **python3 train_classifier.py** Once the training finishes, the system is ready to run. It provides several options to do the information retrieval. **Parameters** - m: the method to use in information retrieval. 1. A variant of BM25 2. Cosine distance using tfidf 3. Cosine distance using tf - b: BM25 parameter, format: k1,b,k3 For instance, if you want to do the information retrieval using BM25 with parameters k1 = 1.5, b = 0.5, k3 = 0, you should run the following command: - **python3 answer_questions.py -m 1 -b 1.5,0.5,0** When the execution ends, the results will be output to a CSV file under the same direcotry. <file_sep>/utils.py from gensim.models.word2vec import Word2Vec from nltk.tokenize import word_tokenize, sent_tokenize from nltk.corpus import stopwords from nltk import pos_tag from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet import numpy as np import spacy import json import re from sklearn.utils import shuffle from collections import Counter import string import csv import tensorflow as tf from spacy.symbols import nsubj, VERB import matplotlib.pyplot as plt from scipy.interpolate import spline from question_classifier import QuestionClassifier def read_csv(filename): csvfile = open(filename, "r") read = csv.reader(csvfile) data = [] for line in read: data.append(line) csvfile.close() return data def save_csv(filename, header, data): with open(filename, "w") as csvfile: writer = csv.writer(csvfile) writer.writerow(header) writer.writerows(data) def get_dataset(path): with open(path) as f: dataset_str = f.read() dataset = json.loads(dataset_str) return dataset def get_wordnet_pos(treebank_tag): if treebank_tag.startswith('J'): return wordnet.ADJ elif treebank_tag.startswith('V'): return wordnet.VERB elif treebank_tag.startswith('N'): return wordnet.NOUN elif treebank_tag.startswith('R'): return wordnet.ADV else: return None def preprocess(text, with_raw_info=False): lemmatizer = WordNetLemmatizer() stopWords = set(stopwords.words('english')) corpus = [] for sent in sent_tokenize(text): # Tokenization & POS Tagging tagged_sentence = pos_tag(word_tokenize(sent)) for word, pos in tagged_sentence: wordnet_pos = get_wordnet_pos(pos) or wordnet.NOUN # Lemmatization preprocessed_token = lemmatizer.lemmatize(word.lower(), pos=wordnet_pos) # Removal of Stop Words if preprocessed_token not in stopWords: # Return the processed token with raw token and its POS tags if with_raw_info: corpus.append((preprocessed_token, word, pos)) else: corpus.append(preprocessed_token) return corpus # NER Tagging using Spacy def entity_recognition(text, nlp): entity_names = [] doc = nlp(text) for ent in doc.ents: entity_names.append((ent.text, ent.label_, (ent.start, ent.end))) return entity_names # Tag the expected entity in answer # It is used for the generation of training set for CNN question classifier def ner_tag_answer(para, ans, nlp): entities = entity_recognition(para, nlp) s, e = find_raw_answer_position(para, ans) if s is None or e is None: return 'Other' possible_entity = [] for ent in entities: if max(s, ent[2][0]) < min(e, ent[2][1]): possible_entity.append(ent[1]) if len(possible_entity) == 0: return 'Other' return possible_entity[0] # Normalize sentences for question classifier def normalize_sentence(sents): sents = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", sents) sents = re.sub(r"\'s", " \'s", sents) sents = re.sub(r"\'ve", " \'ve", sents) sents = re.sub(r"n\'t", " n\'t", sents) sents = re.sub(r"\'re", " \'re", sents) sents = re.sub(r"\'d", " \'d", sents) sents = re.sub(r"\'ll", " \'ll", sents) sents = re.sub(r",", " , ", sents) sents = re.sub(r"!", " ! ", sents) sents = re.sub(r"\(", " \( ", sents) sents = re.sub(r"\)", " \) ", sents) sents = re.sub(r"\?", " \? ", sents) sents = re.sub(r"\s{2,}", " ", sents) return sents.strip().lower() # Acquire training dataset for question classifier def get_trainingset(question_classes, data_path_prefix): x_train = [] y_train = [] for c in range(len(question_classes)): label = [0] * len(question_classes) label[c] = 1 data = list(open(data_path_prefix + question_classes[c] + '.txt', "r").readlines()) data = [ques.strip() for ques in data] x_train += data y_train += [label] * len(data) return (x_train, y_train) # Build vocabulary def build_vocabulary(sents): word_count = 0 vocabulary = dict() for sent in sents: for word in sent: if word not in vocabulary: vocabulary[word] = word_count word_count += 1 return vocabulary # Preprocess questions by padding def processed_sentences(sents, max_length=100, vocabulary=None): sents = [s.strip() for s in sents] sents = [normalize_sentence(sent) for sent in sents] sents = [s.split(" ") for s in sents] processed_sents = [] pad_token = "<PAD/>" # Training if vocabulary is None: max_length = max([len(sent) for sent in sents]) processed_sents = [sent + [pad_token] * (max_length - len(sent)) for sent in sents] else: for sent in sents: for word in sent[:]: if word not in vocabulary: # Omit the words not in vocabulary sent.remove(word) # Omit the words over length restriction if len(sent) > max_length: sent = sent[:max_length] processed_sents.append(sent + [pad_token] * (max_length - len(sent))) return processed_sents # Get training dataset and process data def get_training_dataset_info(): # Totally 13 question classes question_classes = ['num', 'percent', 'money', 'ord', 'date', 'gpe', 'loc', 'hum', 'org', 'event', 'art', 'lang', 'other'] x_train, y_train = get_trainingset(question_classes, 'data/qustion_classifier_training/train_') processed_x_train = processed_sentences(x_train) vocabulary = build_vocabulary(processed_x_train) processed_x_train = np.array([[vocabulary[word] for word in sent] for sent in processed_x_train]) y_train = np.array(y_train) return (processed_x_train, y_train, vocabulary, question_classes) # Generates a batch iterator for a dataset. def batch_generater(data, batch_size, num_epochs, to_shuffle=True): data = np.array(data) data_size = len(data) num_batches_per_epoch = int(len(data) / batch_size) + 1 for _ in range(num_epochs): if to_shuffle: shuffled_data = shuffle(data) else: shuffled_data = data for batch_num in range(num_batches_per_epoch): start_index = batch_num * batch_size end_index = min((batch_num + 1) * batch_size, data_size) yield shuffled_data[start_index:end_index] def question_classify(dataset): x_train, _ , vocabulary, classes = get_training_dataset_info() max_length = max([len(sent) for sent in x_train]) x_test = processed_sentences(dataset, max_length, vocabulary) x_test = np.array([[vocabulary[word] for word in sent] for sent in x_test]) checkpoint_file = tf.train.latest_checkpoint('classifier_model/checkpoints/') tf.reset_default_graph() sess = tf.Session() with sess.as_default(): classifier = QuestionClassifier( input_size=x_train.shape[1], n_classes=len(classes), vocabulary_size=len(vocabulary)) saver = tf.train.Saver() saver.restore(sess, checkpoint_file) batches = batch_generater(x_test, 100, 1, to_shuffle=False) all_predictions = [] for x_test_batch in batches: batch_predictions = sess.run(classifier.predictions, {classifier.question: x_test_batch, classifier.dropout_rate: 1.0}) all_predictions = np.concatenate([all_predictions, batch_predictions]) y_predict = [] for predict in all_predictions: y_predict.append(classes[int(predict)]) return y_predict # Following functions are used on the evaluation def evaluate_CNN_question_classfier(): loss = np.load('loss_dev.npy') accuracy = np.load('accuracy_dev.npy') precision = np.load('precision_dev.npy') recall = np.load('recall_dev.npy') f1score = np.load('f1score_dev.npy') x = [i for i in range(len(loss)) if i % 10 == 0] xtick = [(str((x_) * 100)) for x_ in x] best_checkpoint = np.argmax(accuracy) plt.plot(loss, 'r', linestyle='-', label='Cross Entropy Loss') plt.plot(accuracy, 'g', linestyle='-', label='Accuracy') plt.plot(precision, 'y', linestyle='-', label='Precision') plt.plot(recall, 'b', linestyle='-', label='Recall') plt.plot(f1score, 'brown', linestyle='-', label='F1-Score') plt.axhline(y=accuracy[best_checkpoint], color='grey', ls="--", linewidth=1) plt.text(len(loss), accuracy[best_checkpoint], round(accuracy[best_checkpoint], 4), ha='center', va='bottom') plt.xticks(x, xtick) plt.xlabel('Training Steps') plt.legend() plt.show() def evaluate_information_retrieval(): bm25 = [0.71, 0.68, 0.69] now1 = [0.73, 0.72, 0.72] nonnegative = [0.77, 0.75, 0.75] originalidf = [0.77, 0.75, 0.75] tfidf_cos = [0.73, 0.70, 0.71] tf_cos = [0.55, 0.51, 0.52] plt.barh([1], bm25[-1], 0.5) plt.barh([2], now1[-1], 0.5) plt.barh([3], nonnegative[-1], 0.5) plt.barh([4], originalidf[-1], 0.5) plt.barh([5], tfidf_cos[-1], 0.5) plt.barh([6], tf_cos[-1], 0.5) plt.text(bm25[-1] + 0.035, 1 - 0.1, bm25[-1], ha='center', va='bottom') plt.text(now1[-1] + 0.035, 2 - 0.1, now1[-1], ha='center', va='bottom') plt.text(nonnegative[-1] + 0.035, 3 - 0.1, nonnegative[-1], ha='center', va='bottom') plt.text(originalidf[-1] + 0.035, 4 - 0.1, originalidf[-1], ha='center', va='bottom') plt.text(tfidf_cos[-1] + 0.035, 5 - 0.1, tfidf_cos[-1], ha='center', va='bottom') plt.text(tf_cos[-1] + 0.035, 6 - 0.1, tf_cos[-1], ha='center', va='bottom') plt.xlim(0, 1) plt.yticks([1, 2, 3, 4, 5, 6], ['BM25', 'BM25\n(remove idf)', 'Max(BM25,0)', 'BM25\n(idf = log(N/ft))', 'Cosine diatance\n(Tfidf vectors)', 'Cosine diatance\n(Tf vectors)']) plt.xlabel('f1-score') plt.show() def get_f1_score(predictions, true_answers, average='macro'): TP = 0 FP = 0 FN = 0 precision = 0 recall = 0 f1 = 0 for i in range(len(predictions)): prediction = predictions[i] answer = true_answers[i] prediction_tokens = prediction.split() answer_tokens = answer.split() common = Counter(prediction_tokens) & Counter(answer_tokens) num_same = sum(common.values()) if average == 'micro': TP += num_same FP += len(prediction_tokens) - num_same FN += len(answer_tokens) - num_same if average == 'macro': TP = num_same FP = len(prediction_tokens) - num_same FN = len(answer_tokens) - num_same if num_same == 0: continue precision += 1.0 * TP / (TP + FP) recall += 1.0 * TP / (TP + FN) f1 += (2 * (1.0 * TP / (TP + FP)) * (1.0 * TP / (TP + FN))) / ( (1.0 * TP / (TP + FP)) + (1.0 * TP / (TP + FN))) if average == 'micro': precision = 1.0 * TP / (TP + FP) recall = 1.0 * TP / (TP + FN) f1 = (2 * precision * recall) / (precision + recall) if average == 'macro': precision /= len(predictions) recall /= len(predictions) f1 /= len(predictions) return precision, recall, f1 # Following functions are previously developed for different design of the system. # However, these methods are not adopted in the final version. # Including: relationship extraction, dependency parsing, feature processing for attention-based neural network, etc. def noun_chunk_extraction(text, nlp): chunks = [] doc = nlp(text) for chunk in doc.noun_chunks: chunks.append((chunk.text, chunk.root.text, chunk.root.dep_, chunk.root.head.text)) return chunks def get_root_verb(text, nlp): # chunks = [] doc = nlp(text) for token in doc: if token.dep_ == 'ROOT': return (token.text, token.dep_, token.head.pos_, [child for child in token.children]) return doc def relations_extraction(text, nlp, types): doc = nlp(text) # merge entities and noun chunks into one token spans = list(doc.ents) + list(doc.noun_chunks) for span in spans: span.merge() relations = [] for entity in filter(lambda w: w.ent_type_ in types, doc): if entity.dep_ in ('attr', 'dobj') or entity.dep_ in ('attr', 'iobj'): subject = [w for w in entity.head.lefts if w.dep_ == 'nsubj' or w.dep_ == 'nsubjpass'] if subject: subject = subject[0] relations.append((subject, entity.head, entity, 2)) elif entity.dep_ in ('attr', 'nsubj'): object = [w for w in entity.head.rights if w.dep_ == 'dobj' or w.dep_ == 'iobj'] if object: object = object[0] relations.append((entity, entity.head, object, 0)) elif entity.dep_ == 'pobj': # and money.head.dep_ == 'prep': verb = entity count = 0 while verb.pos != VERB: verb = verb.head count += 1 if count > 5: verb = entity.head.head break subject = [w for w in verb.lefts if w.dep_ == 'nsubj' or w.dep_ == 'nsubjpass'] if subject: subject = subject[0] object = [w for w in verb.rights if w.dep_ == 'dobj' or w.dep_ == 'iobj'] if object: object = object[0] relations.append((subject, verb, object, entity, 3)) elif entity.dep_ == 'compound': verb = entity count = 0 while verb.pos != VERB: verb = verb.head count += 1 if count > 5: verb = entity.head.head break subject = [w for w in verb.lefts if w.dep_ == 'nsubj' or w.dep_ == 'nsubjpass'] if subject: subject = subject[0] object = [w for w in verb.rights if w.dep_ == 'dobj' or w.dep_ == 'iobj'] if object: object = object[0] relations.append((subject, verb, object, entity, 3)) return relations def build_word2vec_and_pos2vec(doc_path='data/documents.json'): lemmatizer = WordNetLemmatizer() doc_set = get_dataset(doc_path) word_corpus = [] pos_corpus = [] for doc in doc_set: for para in doc['text']: for sent in sent_tokenize(para): tagged_sentence = pos_tag(word_tokenize(sent)) sent_words = [] sent_pos = [] for word, pos in tagged_sentence: wordnet_pos = get_wordnet_pos(pos) or wordnet.NOUN sent_words.append(lemmatizer.lemmatize(word.lower(), pos=wordnet_pos)) sent_pos.append(pos) word_corpus.append(sent_words) pos_corpus.append(sent_pos) word_model = Word2Vec(word_corpus, min_count=1) word_model.save('data/word2vec.pkl') pos_model = Word2Vec(pos_corpus, size=15) pos_model.save('data/pos2vec.pkl') return word_model, pos_model def create_metadata(doc_path='./data/documents.json', training_path='./data/training.json', develop_path='./data/devel.json'): doc_set = get_dataset(doc_path) i_para = 0 meta = {} para_lengths = {} for doc in doc_set: for para in doc['text']: para_lengths[i_para] = sum([len(word_tokenize(sent)) for sent in sent_tokenize(para)]) i_para += 1 meta['para_lengths'] = para_lengths dataset = get_dataset(training_path) + get_dataset(develop_path) i_ques = 0 question_lengths = {} answer_lengths = {} for question in dataset: question_lengths[i_ques] = len(word_tokenize(question['question'])) answer_lengths[i_ques] = len(word_tokenize(question['text'])) i_ques += 1 meta['question_lengths'] = question_lengths meta['answer_lengths'] = answer_lengths with open("./data/metadata.json", "w") as f: json.dump(meta, f) f.close() # Return the lemmatized tokens in text with their POS tags, but never remove stop words. def tokenize_and_pos(text): lemmatizer = WordNetLemmatizer() corpus = [] for sent in sent_tokenize(text): tagged_sentence = pos_tag(word_tokenize(sent)) for word, pos in tagged_sentence: wordnet_pos = get_wordnet_pos(pos) or wordnet.NOUN corpus.append((lemmatizer.lemmatize(word.lower(), pos=wordnet_pos), pos)) return corpus def preprocess_feature(word_model, pos_model, para, question, para_length=400, ques_length=50, ans_length=10): para = tokenize_and_pos(para) question = tokenize_and_pos(question) # Omit the context over limited length if len(para) > para_length: para = para[:para_length] if len(question) > ques_length: question = question[:ques_length] para_word = np.zeros((para_length, word_model.vector_size), dtype=np.float32) para_pos = np.zeros((para_length, pos_model.vector_size), dtype=np.float32) for i in range(len(para)): if para[i][0] in word_model.wv: para_word[i] = word_model.wv[para[i][0]] if para[i][1] in pos_model.wv: para_pos[i] = pos_model.wv[para[i][1]] ques_word = np.zeros((ques_length, word_model.vector_size), dtype=np.float32) ques_pos = np.zeros((ques_length, pos_model.vector_size), dtype=np.float32) for i in range(len(question)): if question[i][0] in word_model.wv: ques_word[i] = word_model.wv[question[i][0]] if question[i][1] in pos_model.wv: ques_pos[i] = pos_model.wv[question[i][1]] return para_word, para_pos, ques_word, ques_pos def preprocess_answer(para, answer): para_token = word_tokenize(para) ans_token = word_tokenize(answer) para_token = [w.lower() for w in para_token] ans_token = [w.lower() for w in ans_token] start = [i for i, v in enumerate(para_token) if v == ans_token[0]] for s in start: for e in range(0, len(ans_token)): if para_token[s + e] != ans_token[e]: break if e == len(ans_token) - 1: return s, s + e + 1 return None, None def find_raw_answer_position(para, answer): start = [i for i, v in enumerate(para) if v.lower() == answer[0].lower()] try: for s in start: for e in range(0, len(answer)): if para[s + e].lower() != answer[e].lower(): break if e == len(answer) - 1: return s, s + e + 1 return None, None except: return None, None def keywords_extraction(ques): keywords = [] lemmatizer = WordNetLemmatizer() stopWords = set(stopwords.words('english')) for word, pos in pos_tag(word_tokenize(ques)): if pos.startswith('V') or pos.startswith('J') or pos.startswith('R'): wordnet_pos = get_wordnet_pos(pos) or wordnet.NOUN preprocess_keyword = lemmatizer.lemmatize(word.lower(), pos=wordnet_pos) if preprocess_keyword not in stopWords: keywords.append(preprocess_keyword) return keywords <file_sep>/vector_space_model.py import utils import json import math from sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer from scipy.spatial.distance import cosine as cos_distance import numpy as np class VectorSpaceModel: def __init__(self,corpus, bm25_parameter=[1.5,0.75,0]): self.corpus = corpus self.tf = self.build_tf_model() self.build_vocabulary() self.build_inverted_index() self.tfidf = self.build_tfidf_model() self.bm25_parameter = bm25_parameter def build_vocabulary(self): self.vocabulary = self.count_vectorizer.vocabulary_ self.inverted_vocabulary = [] for term, _ in sorted(self.vocabulary.items(), key=lambda x: x[1]): self.inverted_vocabulary.append(term) return self.vocabulary def build_inverted_index(self): transpose_tf = self.tf.T self.inverted_index = [] for t in sorted(self.vocabulary.values(), key=lambda x: x): nonzero_doc = transpose_tf[t].nonzero() self.inverted_index.append([(d,transpose_tf[t][d])for d in nonzero_doc[0]]) def build_tf_model(self): self.count_vectorizer = CountVectorizer(analyzer=utils.preprocess) self.tf = self.count_vectorizer.fit_transform(self.corpus).toarray() return np.array(self.tf) def build_tfidf_model(self): self.tfidf_transformer = TfidfTransformer() self.tfidf = self.tfidf_transformer.fit_transform(self.tf).toarray() return np.array(self.tfidf) def get_tf_vector(self,doc): return self.count_vectorizer.transform(doc).toarray() def get_tfidf_vector(self,doc): return self.tfidf_transformer.transform(self.get_tf_vector(doc)).toarray() def get_top_k_doc(self, query, k=5, method='bm25'): doc_similarities={} if method == 'bm25': k1 = self.bm25_parameter[0] b = self.bm25_parameter[1] k3 = self.bm25_parameter[2] # Get tf vector of query query_vector = self.get_tf_vector([query])[0] if len(query_vector.nonzero()[0]) == 0: return [(0,0)]*k N = len(self.corpus) Lavg = np.mean([len(d) for d in self.corpus]) for term in query_vector.nonzero()[0]: fqt = query_vector[term] ft = np.count_nonzero(self.tf, axis=0)[term] # idf w1 = np.log(N/ft) # Prevent BM25 from being negative # Only calculate the BM25 for the document which contain query token for doc,fdt in self.inverted_index[term]: Ld = len(self.corpus[doc]) # tf in doc w2 = (k1 + 1) * fdt / (k1 * ((1 - b) + b * Ld / Lavg) + fdt) # tf in query w3 = (k3 + 1) * fqt / (k3 + fqt) w = w1 * w2 * w3 doc_similarities[doc] = doc_similarities.get(doc,0) + w elif method == 'tfidf': # Get tfidf vector of query query_vector = self.get_tfidf_vector([query])[0] if len(query_vector.nonzero()[0]) == 0: return [(0,0)]*k for term in query_vector.nonzero()[0]: # Only calculate the cosine distance for the document which contain query token for doc,_ in self.inverted_index[term]: if doc not in doc_similarities: doc_similarities[doc] = 1 - cos_distance(self.tfidf[doc], query_vector) elif method == 'tf': # Get tf vector of query query_vector = self.get_tf_vector([query])[0] if len(query_vector.nonzero()[0]) == 0: return [(0,0)]*k for term in query_vector.nonzero()[0]: # Only calculate the cosine distance for the document which contain query token for doc,_ in self.inverted_index[term]: if doc not in doc_similarities: doc_similarities[doc] = 1 - cos_distance(self.tf[doc], query_vector) rank = sorted(doc_similarities.items(), key=lambda x: x[1], reverse=True) return rank[:k] <file_sep>/question_classifier.py import tensorflow as tf import numpy as np class QuestionClassifier(object): def __init__( self, input_size, n_classes, vocabulary_size): self.question = tf.placeholder(tf.int32, [None, input_size]) self.label = tf.placeholder(tf.float32, [None, n_classes]) self.dropout_rate = tf.placeholder(tf.float32) # Embedding layer W = tf.Variable(tf.random_uniform([vocabulary_size, 128], -1.0, 1.0)) self.embedded_chars = tf.nn.embedding_lookup(W, self.question) self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1) # Convolution Layer: filter size 3 W1 = tf.Variable(tf.truncated_normal([3, 128, 1, 128], stddev=0.1)) b1 = tf.Variable(tf.constant(0.1, shape=[128])) conv1 = tf.nn.conv2d(self.embedded_chars_expanded, W1, strides=[1, 1, 1, 1],padding="VALID") pool1 = tf.nn.max_pool(tf.nn.relu(tf.nn.bias_add(conv1, b1)), ksize=[1, input_size - 3 + 1, 1, 1], strides=[1, 1, 1, 1],padding='VALID') # Convolution Layer: filter size 4 W2 = tf.Variable(tf.truncated_normal([4, 128, 1, 128], stddev=0.1)) b2 = tf.Variable(tf.constant(0.1, shape=[128])) conv2 = tf.nn.conv2d(self.embedded_chars_expanded, W2, strides=[1, 1, 1, 1], padding="VALID") pool2 = tf.nn.max_pool(tf.nn.relu(tf.nn.bias_add(conv2, b2)), ksize=[1, input_size - 4 + 1, 1, 1], strides=[1, 1, 1, 1], padding='VALID') # Convolution Layer: filter size 5 W3 = tf.Variable(tf.truncated_normal([5, 128, 1, 128], stddev=0.1)) b3 = tf.Variable(tf.constant(0.1, shape=[128])) conv3 = tf.nn.conv2d(self.embedded_chars_expanded, W3, strides=[1, 1, 1, 1], padding="VALID") pool3 = tf.nn.max_pool(tf.nn.relu(tf.nn.bias_add(conv3, b3)), ksize=[1, input_size - 5 + 1, 1, 1], strides=[1, 1, 1, 1], padding='VALID') # Combine all the output of all convolution layers self.flat_pool = tf.reshape(tf.concat([pool1, pool2, pool3], 3), [-1, 128 * 3]) self.dropout = tf.nn.dropout(self.flat_pool, self.dropout_rate) # Output Layer self.scores = tf.layers.dense(self.dropout, n_classes, activation=None, kernel_initializer=tf.contrib.layers.xavier_initializer(), bias_initializer= tf.constant_initializer(0.1)) self.predictions = tf.argmax(self.scores, 1) # Loss self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.scores, labels=self.label)) # Accuracy correct = tf.equal(self.predictions, tf.argmax(self.label, 1)) self.accuracy = tf.reduce_mean(tf.cast(correct, "float")) # Training optimizer = tf.train.AdamOptimizer(1e-3) self.train_op = optimizer.apply_gradients(optimizer.compute_gradients(self.loss))
ffcc0366b6e14d75f42fc3edc9dff165c82a579d
[ "Markdown", "Python" ]
6
Python
lotharJiang/Question-Answering-System
2692f5799af7c75c2cd3ee8ff3064d6ab23776b1
5d9d89d6d2c8544b649db7f351d13cc26d588415
refs/heads/master
<repo_name>dmbarrett/gatsby-starter-mdblog<file_sep>/src/pages/blog.js import React from "react" //import { css } from "@emotion/core" //import { rhythm } from "typography" import Layout from "../components/layout" export default () => { return ( <Layout> <h1>This is de blog mon.</h1> </Layout> ) } <file_sep>/src/components/preview.js import React from "react" import { StaticQuery, graphql } from "gatsby" import { css } from "@emotion/core" import { rhythm } from "typography" export default props => ( <StaticQuery query={graphql` query { allMarkdownRemark( limit: 2 sort: { fields: [frontmatter___date], order: DESC } ) { edges { node { id frontmatter { title date(formatString: "DD MMMM, YYYY") } excerpt } } } } `} render={data => ( <div> {console.log(data)} {data.allMarkdownRemark.edges.map(({ node }) => ( <div key={node.id}> <h3>{node.frontmatter.title}</h3> <p>{node.frontmatter.date}</p> <p>{node.excerpt}</p> </div> ))} </div> )} /> ) <file_sep>/src/pages/index.js import React from "react" import { Link, graphql } from "gatsby" import { rhythm } from "../utils/typography" import { css } from "@emotion/core" import HomeLayout from "../components/homeLayout" import Preview from "../components/preview" import Img from "gatsby-image" export default ({ data }) => { return ( <HomeLayout> <div css={css` background-color: black; color: white; height: 100vh; max-width: 50vw; `} > <div css={css` padding: ${rhythm(2)}; padding-top: ${rhythm(1.5)}; `} > <h1 css={css` color: inherit; margin-top: 0; `} > {data.site.siteMetadata.title} </h1> <h5 css={css` color: slategray; max-width: 400px; margin-top: ${rhythm(0.5)}; `} > {data.site.siteMetadata.description} </h5> </div> <h2 css={css` color: white; padding-left: ${rhythm(2)}; `} > What is markdown you say? </h2> <div css={css` display: flex; flex-direction: row; justify-content: space-around; padding: ${rhythm(2)}; padding-top: ${rhythm(0.5)}; `} > <div> <h5 css={css` color: slategray; padding-right: ${rhythm(2)}; margin-top: 0; `} > "Markdown is a text-to-HTML conversion tool for web writers. Markdown allows you to write using an easy-to-read, easy-to-write plain text format, then convert it to structurally valid XHTML or HTML." - <i><NAME></i> <br /> <div css={css` padding: ${rhythm(0.5)}; margin-top: ${rhythm(0.5)}; background-color: white; border-radius: 10px; display: inline-block; `} > <a href="https://daringfireball.net/projects/markdown/" target="_blank" css={css` text-shadow: none; `} > Learn more... </a> </div> </h5> </div> <div css={css` width: 200px; `} > <Img fixed={data.file.childImageSharp.fixed} /> </div> </div> <div css={css` display: flex; justify-content: center; `} > <h3 css={css` color: slategray; `} > 2019 -- <NAME> </h3> </div> </div> <div css={css` padding: ${rhythm(2)}; padding-top: ${rhythm(1.5)}; max-width: 50vw; `} > <Link to="/blog">Blog</Link> <div> <Preview /> </div> </div> </HomeLayout> ) } export const query = graphql` query { site { siteMetadata { title description } } file(relativePath: { eq: "mark.png" }) { childImageSharp { fixed(width: 200, height: 123) { ...GatsbyImageSharpFixed } } } allMarkdownRemark( limit: 1 sort: { fields: [frontmatter___date], order: DESC } ) { totalCount edges { node { id frontmatter { title date(formatString: "DD MMMM, YYYY") } excerpt } } } } ` <file_sep>/src/components/homeLayout.js import React from "react" import { css } from "@emotion/core" //import { rhythm } from "../utils/typography" export default ({ children }) => { return ( <div css={css` margin: 0; display: flex; flex-direction: row; justify-content: space-between; `} > {children} </div> ) }
0ba5657c4fa01cfc4020a34b650a7aaad12c8f00
[ "JavaScript" ]
4
JavaScript
dmbarrett/gatsby-starter-mdblog
208d5b3208ef2726a4cc3c18299c62e85e7e8900
9465eb65cabf4d6411317117feedce3705661afa
refs/heads/master
<file_sep>import { PermissionTable, PermissionList } from '../models'; export function createPermissionTableWithStatus( allow: boolean ): PermissionTable { return { read: allow, create: allow, delete: allow, update: allow, }; } export function createPermissionsList(allow: boolean): PermissionList { return { buildings: createPermissionTableWithStatus(allow), classes: createPermissionTableWithStatus(allow), categories: createPermissionTableWithStatus(allow), lecturer: createPermissionTableWithStatus(allow), permissions: createPermissionTableWithStatus(allow), payDuplicator: createPermissionTableWithStatus(allow), user: createPermissionTableWithStatus(allow), files: createPermissionTableWithStatus(allow), settings: createPermissionTableWithStatus(allow), semesters: createPermissionTableWithStatus(allow), courses: createPermissionTableWithStatus(allow), coupons: createPermissionTableWithStatus(allow), students: createPermissionTableWithStatus(allow), }; } <file_sep>import mongoose, { Schema, Document } from 'mongoose'; import { createHash } from 'crypto'; export interface IUser { name: string; lastName: string; email: string; role: string; password: string; } type IUserDOC = IUser & Document; export const UserSchema = new Schema({ name: { type: String, required: true }, lastName: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, role: { type: Schema.Types.ObjectId, required: true }, }); UserSchema.pre<IUserDOC>('save', function (next) { var user = this; // only hash the password if it has been modified (or is new) if (!user.isModified('password')) return next(null); const pass = createHash('sha256') .update(user.password as string) .digest('base64'); user.password = <PASSWORD>; next(null); }); export default mongoose.model<IUserDOC>('users', UserSchema); <file_sep>import { Router } from 'express'; import vatRouter from './vat'; const settingsRouter = Router(); settingsRouter.use('/vat', vatRouter) export default settingsRouter<file_sep>import { Document, model, Schema } from 'mongoose'; export interface IStudent { _id?: string; name: string; lastName: string; id: number; email: string; phone: number; advertising: boolean; } export type IStudentDOC = IStudent & Document; const StudentSchema = new Schema({ name: { type: String, required: true }, lastName: { type: String, required: true }, id: { type: Number, required: true, unique: true }, email: { type: String, required: true, unique: true }, phone: { type: String, required: true }, advertising: { type: Boolean, required: false, default: true }, }); export default model<IStudentDOC>('students', StudentSchema); <file_sep>import { isValidObjectId, Types } from 'mongoose'; function ByIds(data: string[]) { return { _id: { $in: data.map((dataLine) => Types.ObjectId(dataLine)), }, }; } function ById(id: string) { if (!isValidObjectId(id)) { throw new Error(`${id} is not a valid object id`); } const _id = Types.ObjectId(id); return { _id }; } const Queries = { ById, ByIds, }; export default Queries; <file_sep>import mongoose, { Schema, Document } from 'mongoose'; export interface IPayDuplicator extends Document { _id?: string; title: string; duplicate: number; // example: 1.2 - so it will be 120%, in lecturer obj we will have he's hourly salary - the duplicate will multiple it... vat: boolean; // to add or not to add the vat to the salary active: boolean; } export const PayDuplicatorSchema = new Schema({ title: { type: String, required: true, unique: true }, duplicate: { type: Number, required: true }, vat: { type: Boolean, required: true }, active: { type: Boolean, required: false, default: true }, }); export default mongoose.model<IPayDuplicator>('pays', PayDuplicatorSchema); <file_sep>import { Router, Response } from 'express'; import { PermissionsScope } from '../../models'; import allow from '../../helper/user-permission'; import { RequestExtend } from '../../auth'; import { isValidObjectId } from 'mongoose'; import { GetFileById } from '../../db/v1/models/files/controller'; import { ServerError } from '../../helper/http'; import path from 'path'; import { getPath } from '../../services/files'; const filesRouter = Router(); const scope: PermissionsScope = 'files'; const allowPath = allow(scope); filesRouter.get( '/:fileId', allowPath, async (req: RequestExtend, res: Response) => { const { fileId } = req.params; if (!isValidObjectId(fileId)) { return res.sendStatus(400); } return GetFileById(fileId) .then((fileData) => { res.attachment(fileData.name); res.download(path.join(getPath(fileData.secure), fileData.name)); }) .catch((errors) => ServerError(res, errors)); } ); export default filesRouter; <file_sep>import CategoriesModel, { ICategory } from './model'; export async function GetAllCategories( query: object = {} ): Promise<ICategory[]> { return CategoriesModel.find(query); } export async function GetSingleCategory(query: object) { return CategoriesModel.findOne(query); } export async function CreateCategory(classData: ICategory) { const newClass = new CategoriesModel(classData); return newClass.save().then((d) => d.toJSON()); } export async function DeleteCategory(id: string) { return CategoriesModel.findByIdAndDelete(id).then((_) => true); } export async function UpdateCategory(id: string, data: ICategory) { return CategoriesModel.findByIdAndUpdate( id, { $set: data }, { new: true, runValidators: true } ).exec(); } <file_sep>require('dotenv').config(); import express from 'express'; import authRouter from './auth'; import appRouter from './routing'; import mongoConnect from './db/v1'; import expressFileUpload from 'express-fileupload'; import path from 'path'; import cors from 'cors'; const app = express(); // Simple check if body contains well defined content app.use((req, res, next) => express.json()(req, res, (err) => (err ? res.sendStatus(400) : next())) ); app.use(cors()); // All files in this directory are open and not secure (Upload only public available files) app.use('/uploads', express.static(path.join(__dirname, '../uploads'))); app.use( expressFileUpload({ createParentPath: true, }) ); app.use(authRouter); app.use(appRouter); app.all('*', (_, res) => { res.status(404).json({ message: 'Nothing here', }); }); app.listen(process.env.PORT, () => { console.log(`Running at localhost:${process.env.PORT}`); }); mongoConnect(); <file_sep>import mongoose, { Schema, Document } from 'mongoose'; import { Validators } from '../../../validators'; import { Address } from '../../../../models'; import { AddressSchema } from '../../../schema'; import { INote } from '../notes/model'; import { IFileDetails } from '../files/model'; import { IPayDuplicator } from '../pay-duplicator/model'; export interface ILecturer { _id?: string; name: string; idNumber: string; email: string; phone: string; address: Address; hourlyRate: number; duplicator: string; //duplicator id active: boolean; details: string; //text editor avatar: string; description: string; experience: string; teaching: string; notes: string; files: string[]; internalNotes: string[]; } type ILecturerDOC = ILecturer & Document; export const ILecturerSchema = new Schema({ name: { type: String, required: true }, idNumber: { type: Number, required: true, unique: true }, email: { type: String, trim: true, unique: true, validate: Validators.email, }, phone: { type: String, required: true, unique: true }, address: { type: AddressSchema, required: false }, hourlyRate: { type: Number, required: true }, duplicator: { type: Schema.Types.ObjectId, required: true }, active: { type: Boolean, required: false, default: true }, details: { type: String, required: false }, avatar: { type: Schema.Types.ObjectId, required: false }, description: { type: String, required: false }, experience: { type: String, required: false }, teaching: { type: String, required: false }, notes: { type: String, required: false }, files: { type: [Schema.Types.ObjectId], required: false }, internalNotes: { type: [Schema.Types.ObjectId], required: false }, }); export interface Lecturer { _id?: string; name: string; idNumber: string; email: string; phone: string; address: Address; hourlyRate: number; duplicator: IPayDuplicator; //duplicator id active: boolean; details: string; //text editor avatar: IFileDetails; description: string; experience: string; teaching: string; notes: string; files: string[]; internalNotes: INote[]; } export default mongoose.model<ILecturerDOC>('lecturer', ILecturerSchema); <file_sep>import BuildingModel, { IBuilding } from './model'; export async function GetAllBuildings() { return BuildingModel.find({}); } export async function GetBuildingById(id: string) { return BuildingModel.findById(id).then((data) => data?.toObject()); } export async function CreateBuildingRecord(building: IBuilding) { const buildingRecord = new BuildingModel(building); return buildingRecord.save().then((role) => role.toObject()); } export async function FindAndUpdate(_id: string, building: IBuilding) { return BuildingModel.findOneAndUpdate({ _id }, building, { new: true, }).then((updated) => updated?.toObject()); } export async function DeleteBuildingRecord(id: string) { return BuildingModel.findByIdAndDelete(id).then((data) => !!data?.id); } <file_sep>import { Types } from 'mongoose'; import INoteSchemaModel, { INote } from './model'; export async function GetNotes(query: object = {}): Promise<INote[]> { return INoteSchemaModel.aggregate([ { $match: query, }, { $lookup: { from: 'users', localField: 'user', foreignField: '_id', as: 'user', }, }, { $unwind: { path: '$user', preserveNullAndEmptyArrays: true }, }, { $project: { related: 0, }, }, ]); } export async function GetNote(query: object = {}): Promise<INote> { return GetNotes(query).then((response) => { if (response.length) { return Promise.resolve(response[0]); } return Promise.reject({ errors: 'Not found' }); }); } export async function CreateNote(LecturerData: INote): Promise<INote> { const newClass = new INoteSchemaModel(LecturerData); return newClass.save().then((noteDate) => { return GetNote({ _id: Types.ObjectId(noteDate._id) }); }); } export async function DeleteNote(id: string): Promise<Boolean> { return INoteSchemaModel.findByIdAndDelete(id).then((d) => !!d); } export async function UpdateNote( id: string, data: INote ): Promise<INote | undefined> { return INoteSchemaModel.findByIdAndUpdate(id, data, { new: true, runValidators: true, }).then((data) => data?.toJSON()); } <file_sep>import mongoose from 'mongoose'; import populate from './population'; export default () => { const connect = () => { mongoose .connect( `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}/${process.env.DB_NAME}`, { dbName: process.env.DB_NAME, useUnifiedTopology: true, useNewUrlParser: true, useFindAndModify: false, } ) .then(() => { populate(); return console.info(`Successfully connected to ${process.env.DB_NAME}`); }) .catch((error) => { console.error('Error connecting to database: ', error); return process.exit(1); }); }; // Exec connection connect(); // In case of disconnection reconnect mongoose.connection.on('disconnected', connect); }; <file_sep>import { Router, Response } from 'express'; import { PermissionsScope } from '../../models'; import allow from '../../helper/user-permission'; import { RequestExtend } from '../../auth'; import { FindRoles, FindRole, RoleUpdateOne, } from '../../db/v1/models/permissions/controller'; import { isValidObjectId, Types } from 'mongoose'; const permissionsRouter = Router(); const scope: PermissionsScope = 'permissions'; const allowPath = allow(scope); permissionsRouter.get( '/', allowPath, async (_: RequestExtend, res: Response) => { return FindRoles() .then((result) => { return res.status(200).json(result); }) .catch((err) => { console.error(err); res.sendStatus(500); }); } ); permissionsRouter.get( '/:id', allowPath, async (req: RequestExtend, res: Response) => { if (!isValidObjectId(req.params.id)) { return res.sendStatus(400); } return FindRole({ _id: Types.ObjectId(req.params.id) }) .then((singlePermission) => { if (!singlePermission) { return res.sendStatus(404); } return res.status(200).json(singlePermission); }) .catch((err) => { console.error(err); res.sendStatus(500); }); } ); permissionsRouter.put( '/:id', allowPath, async (req: RequestExtend, res: Response) => { if (!isValidObjectId(req.params.id)) { return res.sendStatus(400); } return RoleUpdateOne(req.params.id, req.body) .then((result) => { return res.status(200).json(result); }) .catch((err) => { console.error(err); res.sendStatus(500); }); } ); export default permissionsRouter; <file_sep>import { isEqual } from 'lodash'; import { DefaultPermissionsSuperUser } from '../../../../settings/permissions'; import { CreateRole, FindRole, RoleUpdateOne, } from '../../models/permissions/controller'; import { IRole } from '../../models/permissions/model'; import { CreateUser, FindUser } from '../../models/user/controller'; function createAdminUser(role: IRole) { return FindUser({ name: 'admin' }).then((user) => { if (!user) { return CreateUser({ name: 'admin', lastName: 'admin', role: role._id as string, email: '<EMAIL>', password: '<PASSWORD>', }); } return Promise.reject('User admin was already populated'); }); } export async function populateAdmin() { try { let role = await FindRole({ name: 'admin' }); if (!role) { role = await CreateRole({ name: 'admin', permissions: DefaultPermissionsSuperUser, }); } else if (!isEqual(role.permissions, DefaultPermissionsSuperUser)) { console.log(`Role ${role._id} update with new permissions`); await RoleUpdateOne(role._id, { permissions: DefaultPermissionsSuperUser, }); } await createAdminUser(role); } catch (e) { console.error(e); } } <file_sep>import { Router, Response } from 'express'; import { RequestExtend } from '../../auth'; import allow from '../../helper/user-permission'; import { CreateUser, FindUserFull } from '../../db/v1/models/user/controller'; import { isValidObjectId } from 'mongoose'; const userRouter = Router(); const scope = 'user'; userRouter.get('/', (req: RequestExtend, res: Response) => { const { user } = req; res.status(200).json(user); }); userRouter.post( '/', allow(scope), async (req: RequestExtend, res: Response) => { return CreateUser(req.body) .then((user) => { return res.status(200).json({ user, }); }) .catch((err) => { console.error(err); return res.status(500).json(err.errors); }); } ); userRouter.get( '/:id', allow(scope), async (req: RequestExtend, res: Response) => { if (!isValidObjectId(req.params.id)) { return res.sendStatus(400); } return FindUserFull({ _id: req.params.id, }) .then((user) => { if (!user) { return res.sendStatus(404); } return res.status(200).json(user); }) .catch((err) => { console.error(err.errors); return res.sendStatus(500); }); } ); export default userRouter; <file_sep>import { populateAdmin } from './controllers/admin'; import { populateAppSettings } from './controllers/appSettings'; export default async function populate() { await populateAdmin().catch((error) => console.error(error)); await populateAppSettings().catch((error) => console.error(error)); } <file_sep>import { createPermissionsList } from './helper'; export const DefaultPermissions = createPermissionsList(false); export const DefaultPermissionsSuperUser = createPermissionsList(true); <file_sep>import mongoose, { Document, Schema } from 'mongoose'; export interface IClassRoom { building: string; name: string; minStudents: number; maxStudents: number; } export type IClassRoomDOC = IClassRoom & Document; export const ClassesSchema = new Schema({ building: { type: Schema.Types.ObjectId, required: true }, name: { type: String, required: true, unique: true }, minStudents: { type: Number, required: false, default: 1 }, maxStudents: { type: Number, required: true }, }); export default mongoose.model<IClassRoomDOC>('Classes', ClassesSchema); <file_sep>import CouponModel, { ICoupon } from './model'; export function GetAllCoupons(): Promise<ICoupon[]> { return CouponModel.find({}).then((data) => data); } export function GetSingleCoupon(id: string): Promise<ICoupon | undefined> { return CouponModel.findById(id).then((data) => data || undefined); } export function DeleteSingleCoupon(id: string): Promise<boolean> { return CouponModel.findByIdAndDelete(id).then((data) => !!data); } export function CreateSingleCoupon(data: ICoupon): Promise<ICoupon> { const newCoupons = new CouponModel(data); return newCoupons.save().then((data) => data.toJSON()); } export function UpdateSingleCoupon( id: string, data: ICoupon ): Promise<ICoupon | undefined> { return CouponModel.findByIdAndUpdate(id, { $set: data }, { new: true }).then( (data) => data || undefined ); } <file_sep>import mongoose, { Schema, Document } from 'mongoose'; export interface TitlesForWebsite { title?: string; target?: string; requirements?: string; progress?: string; marketing?: string; meetingsCount?: string; meetingLength?: string; } export interface ICourse { _id?: string; title: string; category: string; target: string; requirements: string; progress: string; marketing: string; meetingsCount: string; meetingLength: string; minStudents: number; maxStudents: number; active: boolean; assignToClassComments: string; schedulingComments: string; extTitles: TitlesForWebsite; coupons: string; } type ICourseDOC = ICourse & Document; export const TitlesForWebsite = new Schema( { title: { type: String, required: false, default: '' }, target: { type: String, required: false, default: '' }, requirements: { type: String, required: false, default: '' }, progress: { type: String, required: false, default: '' }, meetingsCount: { type: String, required: false, default: '' }, meetingLength: { type: String, required: false, default: '' }, }, { _id: false, } ); export const CourseSchema = new Schema({ title: { type: String, required: true }, category: { type: Schema.Types.ObjectId, required: false }, active: { type: Boolean, required: false, default: true }, target: { type: String, required: false, default: '' }, requirements: { type: String, required: false, default: '' }, progress: { type: String, required: false, default: '' }, marketing: { type: String, required: false, default: '' }, meetingsCount: { type: Number, required: false, default: 0 }, meetingLength: { type: Number, required: false, default: 0 }, minStudents: { type: Number, required: false, default: 1, min: 1 }, maxStudents: { type: Number, required: false, default: 1, min: 1 }, extTitles: { type: TitlesForWebsite, required: false, default: {} }, assignToClassComments: { type: String, required: false, default: '' }, schedulingComments: { type: String, required: false, default: '' }, coupon: { type: Schema.Types.ObjectId, required: false }, assignedLecturers: { type: [Schema.Types.ObjectId], required: false }, files: { type: [Schema.Types.ObjectId], required: false }, }); export default mongoose.model<ICourseDOC>('courses', CourseSchema); <file_sep>import moment from 'moment'; interface TimeRange { from: string; to: string; } export function CreateDateRangeAndCheck( from: string, to: string, daysLimiter: string[] = [] ): { error?: string; result?: TimeRange[] } { const fromDate = moment(from); const toDate = moment(to); const daysLimiterNumbers = daysLimiter.map(Number); const limiterIncludes = (day: number) => { return daysLimiterNumbers.length === 0 || daysLimiterNumbers.includes(day); }; if (!fromDate.isValid()) { return { error: `From date "${from}" is not a valid date`, }; } if (!toDate.isValid()) { return { error: `To date "${to}" is not a valid date`, }; } if (fromDate.isAfter(toDate)) { return { error: '"From" date must be before "To" date', }; } if (toDate.diff(fromDate, 'minutes') < 30) { return { error: 'Booking for less than 30 min is prohibited', }; } const range = toDate.diff(fromDate, 'day'); const rangeMin = toDate .clone() .add(-Math.abs(range), 'days') .diff(fromDate, 'minutes'); const singularDefaultResult: TimeRange[] = []; if (range === 0 && limiterIncludes(fromDate.day())) { singularDefaultResult.push({ from: fromDate.toISOString(), to: toDate.toISOString(), }); return { result: singularDefaultResult, }; } else if (range > 0 && limiterIncludes(fromDate.day())) { singularDefaultResult.push({ from: fromDate.toISOString(), to: toDate.clone().add(-Math.abs(range), 'days').toISOString(), }); } const futureResults = new Array(range) .fill(0) .map((_, index) => index + 1) .map((incrementor, _, arr) => { const currentDate = fromDate.clone().add(incrementor, 'days'); if ( daysLimiterNumbers.length > 0 && !limiterIncludes(currentDate.day()) ) { return undefined; } return { from: currentDate.toISOString(), to: incrementor === arr.length ? toDate.toISOString() : currentDate.clone().add(rangeMin, 'minutes').toISOString(), }; }); if (futureResults.length === 0) { return { error: 'After calculation there are no availability to create, please double check the input dates and days limiter', }; } return { result: singularDefaultResult.concat( futureResults.filter(Boolean) as TimeRange[] ), }; } <file_sep>import { Schema } from 'mongoose'; export const AddressSchema = new Schema( { address: { type: String, required: false }, zip: { type: String, required: false }, city: { type: String, required: false }, region: { type: String, required: false }, country: { type: String, required: false }, houseNumber: { type: Number, required: false }, entry: { type: String, required: false }, floor: { type: Number, required: false }, flatNumber: { type: Number, required: false }, }, { _id: false, } ); <file_sep>import { Role } from './permissions'; export interface User { _id: string; fullName: string; name: string; lastName: string; email: string; role: Role; password?: string; } <file_sep>const mongoErrors = require('mongo-error-handler'); import { Router, Response } from 'express'; import { isValidObjectId } from 'mongoose'; import { UploadedFile } from 'express-fileupload'; import { RequestExtend } from '../../auth'; import allow from '../../helper/user-permission'; import { GetMultipleCourses, GetSingleCourse, UpdateCourse, DeleteSingleCourse, CreateCourse, PushCourseFiles, PullCourseFiles, } from '../../db/v1/models/courses/controller'; import { BadRequest, NotFound, ServerError, SuccessfulResponse, } from '../../helper/http'; import Queries from '../../db/queries'; import { Delete, Upload } from '../../db/v1/models/files/controller'; const coursesRouter = Router(); const scope = 'courses'; coursesRouter.get( '/', allow(scope), async (_: RequestExtend, res: Response) => { return GetMultipleCourses() .then((data) => { return SuccessfulResponse(res, data); }) .catch((error) => ServerError(res, mongoErrors(error))); } ); coursesRouter.post( '/', allow(scope), async (req: RequestExtend, res: Response) => { return CreateCourse(req.body) .then((data) => { return SuccessfulResponse(res, data); }) .catch((error) => ServerError(res, mongoErrors(error))); } ); coursesRouter.get( '/:courseId', allow(scope), async (req: RequestExtend, res: Response) => { const { courseId } = req.params; if (!isValidObjectId(courseId)) { return BadRequest(res); } return GetSingleCourse(Queries.ById(courseId)) .then((data) => { if (!data) { return NotFound(res); } return SuccessfulResponse(res, data); }) .catch((error) => ServerError(res, mongoErrors(error))); } ); coursesRouter.put( '/:courseId', allow(scope), async (req: RequestExtend, res: Response) => { const { courseId } = req.params; if (!isValidObjectId(courseId)) { return BadRequest(res); } return UpdateCourse(courseId, req.body) .then((data) => { if (!data) { return NotFound(res); } return SuccessfulResponse(res, data); }) .catch((error) => ServerError(res, mongoErrors(error))); } ); coursesRouter.delete( '/:courseId', allow(scope), async (req: RequestExtend, res: Response) => { const { courseId } = req.params; if (!isValidObjectId(courseId)) { return BadRequest(res); } return DeleteSingleCourse(Queries.ById(courseId)) .then((deleted) => { return SuccessfulResponse(res, { deleted }); }) .catch((error) => ServerError(res, mongoErrors(error))); } ); coursesRouter.post( '/:courseId/file', allow(scope), allow('files'), (req: RequestExtend, res: Response) => { const { courseId } = req.params; if (!isValidObjectId(courseId)) { return BadRequest(res, 'Course ID is incorrect'); } const fileToUpload = req.files?.file as UploadedFile; if (!fileToUpload) { return BadRequest(res, 'No file was provided'); } return GetSingleCourse(Queries.ById(courseId)) .then(() => Upload(fileToUpload, true)) .then((fileUploaded) => PushCourseFiles(courseId, fileUploaded._id)) .then((lecturer) => SuccessfulResponse(res, lecturer || {})) .catch((errors) => ServerError(res, mongoErrors(errors))); } ); coursesRouter.delete( '/:courseId/file/:fileId', allow(scope), allow('files'), (req: RequestExtend, res: Response) => { const { courseId, fileId } = req.params; if (!isValidObjectId(courseId)) { return BadRequest(res, 'Lecturer ID is incorrect'); } if (!isValidObjectId(fileId)) { return BadRequest(res, 'File ID is incorrect'); } return GetSingleCourse(Queries.ById(courseId)) .then(() => Delete(Queries.ById(fileId), true)) .then(() => PullCourseFiles(courseId, fileId)) .then((course) => SuccessfulResponse(res, course || {})) .catch((errors) => ServerError(res, errors)); } ); export default coursesRouter; <file_sep>import SettingsDefaults from '../../../../settings/appSettings'; import { createSettingMany, findSettings, } from '../../models/settings/controller'; export async function populateAppSettings(): Promise<void> { const settingsList = Object.values(SettingsDefaults); const settingNameList = settingsList.map(({ name }) => name); const queryResults = await findSettings({ name: { $in: settingNameList } }); // If no setting were found we populate them all if (queryResults.length === 0) { console.log( `Populated ${settingsList.length} new settings "${settingsList .map(({ name }) => name) .join()}"` ); return createSettingMany(settingsList).then(() => void 0); } const needToBePopulated = settingsList.filter( ({ name: needToBePopulatedName }) => queryResults.every(({ name }) => name !== needToBePopulatedName) ); // If some setting were found we filter out the existing and populate the rest if (needToBePopulated.length > 0) { console.log( `Populated ${ needToBePopulated.length } new settings "${needToBePopulated.map(({ name }) => name).join()}"` ); return createSettingMany(needToBePopulated).then(() => void 0); } console.log(`No settings were populated`); return Promise.resolve(); } <file_sep>const mongoErrors = require('mongo-error-handler'); import { Router, Response } from 'express'; import { isValidObjectId } from 'mongoose'; import { RequestExtend } from '../../auth'; import allow, { loggedIn } from '../../helper/user-permission'; import Queries from '../../db/queries'; import { BadRequest, SuccessfulResponse, ServerError, NotFound, SuccessOrNotFound, } from '../../helper/http'; import { CreateNote, DeleteNote } from '../../db/v1/models/notes/controller'; import { CreateSingleStudent, DeleteSingleStudent, GetAllStudents, GetSingleStudent, GetStudentNotes, UpdateSingleStudent, } from '../../db/v1/models/students/controller'; const studentRouter = Router(); const scope = 'students'; studentRouter.get( '/', allow(scope), async (_: RequestExtend, res: Response) => { return GetAllStudents() .then((data) => SuccessfulResponse(res, data)) .catch((error) => { return ServerError(res, mongoErrors(error)); }); } ); studentRouter.get( '/:studentId', allow(scope), async (req: RequestExtend, res: Response) => { const { studentId } = req.params; if (!isValidObjectId(studentId)) { return BadRequest(res); } return GetSingleStudent(Queries.ById(studentId)) .then((data) => { if (!data) { return NotFound(res); } return SuccessfulResponse(res, data); }) .catch((error) => { return ServerError(res, mongoErrors(error)); }); } ); studentRouter.post( '/', allow(scope), async (req: RequestExtend, res: Response) => { return CreateSingleStudent(req.body) .then((data) => { return SuccessfulResponse(res, data); }) .catch((error) => { return ServerError(res, mongoErrors(error)); }); } ); studentRouter.put( '/:studentId', allow(scope), (req: RequestExtend, res: Response) => { const { studentId } = req.params; if (!isValidObjectId(studentId)) { return BadRequest(res); } return UpdateSingleStudent(studentId, req.body) .then((data) => { return SuccessOrNotFound(res, data); }) .catch((error) => { return ServerError(res, mongoErrors(error)); }); } ); studentRouter.delete( '/:studentId', allow(scope), (req: RequestExtend, res: Response) => { const { studentId } = req.params; if (!isValidObjectId(studentId)) { return BadRequest(res); } return DeleteSingleStudent(studentId) .then((deleted) => { return SuccessfulResponse(res, { deleted }); }) .catch((error) => { return ServerError(res, mongoErrors(error)); }); } ); studentRouter.get( '/:studentId/notes', loggedIn, (req: RequestExtend, res: Response) => { const { studentId } = req.params; if (!isValidObjectId(studentId)) { return BadRequest(res); } return GetStudentNotes(studentId) .then((notes) => SuccessfulResponse(res, notes)) .catch((error) => { return ServerError(res, mongoErrors(error)); }); } ); studentRouter.post( '/:studentId/notes', loggedIn, (req: RequestExtend, res: Response) => { const { studentId } = req.params; if (!isValidObjectId(studentId)) { return BadRequest(res); } const { user } = req; return CreateNote({ user: user?._id as string, created: new Date().toUTCString(), text: req.body.text, related: studentId, }) .then((newNote) => SuccessfulResponse(res, newNote)) .catch((error) => { return ServerError(res, mongoErrors(error)); }); } ); studentRouter.delete( '/:studentId/notes/:noteId', loggedIn, (req: RequestExtend, res: Response) => { const { studentId, noteId } = req.params; if (!isValidObjectId(studentId) || !isValidObjectId(noteId)) { return BadRequest(res); } return DeleteNote(noteId) .then((deleted) => SuccessfulResponse(res, { deleted })) .catch((error) => { return ServerError(res, mongoErrors(error)); }); } ); export default studentRouter; <file_sep>import { Response, NextFunction } from 'express'; import { RequestExtend } from '../auth'; import { PermissionOptions, PermissionsScope, User } from '../models'; function hasPermission( user: User, scope: PermissionsScope, permission: PermissionOptions ): boolean { return ( user?.role.permissions && user?.role.permissions[scope] && user?.role.permissions[scope][permission] ); } function methodMapper(method: string): PermissionOptions | undefined { switch (method.toLowerCase()) { case 'get': return 'read'; case 'post': return 'create'; case 'delete': return 'delete'; case 'put': return 'update'; default: return undefined; } } export function loggedIn( req: RequestExtend, res: Response, next: NextFunction ) { const { user } = req; if (!user) { return res.status(401).json({ message: `Action is not allowed`, }); } return next(); } export default function allow(scope: PermissionsScope) { return (req: RequestExtend, res: Response, next: NextFunction) => { const method = req.method; const { user } = req; if (!user) { return res.status(401).json({ message: `Action is not allowed`, }); } const permissionAction = methodMapper(method); if (permissionAction === undefined) { return res.sendStatus(405); } if (hasPermission(user, scope, permissionAction) === false) { return res.status(403).json({ message: `Action ${permissionAction} on ${scope} is not allowed`, }); } return next(); }; } <file_sep>import Queries from '../../../queries'; import { INote } from '../notes/model'; import LecturerSchemaModel, { ILecturer, Lecturer } from './model'; /** * @export * @param {object} [query={}] * @return {*} {Promise<Lecturer[]>} */ export async function GetAllLecturers(query: object = {}): Promise<Lecturer[]> { return LecturerSchemaModel.aggregate([ { $match: query, }, { $lookup: { from: 'notes', let: { internalNotes: '$internalNotes' }, pipeline: [ { $match: { $expr: { $in: ['$_id', '$$internalNotes'], }, }, }, { $lookup: { from: 'users', localField: 'user', foreignField: '_id', as: 'user', }, }, { $unwind: '$user', }, ], as: 'internalNotes', }, }, { $lookup: { from: 'files', localField: 'avatar', foreignField: '_id', as: 'avatar', }, }, { $unwind: { path: '$avatar', preserveNullAndEmptyArrays: true, }, }, { $lookup: { from: 'files', localField: 'files', foreignField: '_id', as: 'files', }, }, { $lookup: { from: 'pays', localField: 'duplicator', foreignField: '_id', as: 'duplicator', }, }, { $unwind: { path: '$duplicator', preserveNullAndEmptyArrays: true, }, }, { $project: { 'internalNotes.user.password': 0, 'internalNotes.user.role': 0, 'internalNotes.user.__v': 0, 'internalNotes.user.email': 0, 'files.secure': 0, 'files.__v': 0, 'internalNotes.__v': 0, 'avatar.__v': 0, __v: 0, }, }, ]).exec(); } /** * @export * @param {object} [query={}] * @return {*} {Promise<Lecturer>} */ export async function GetSingleLecturer(query: object = {}): Promise<Lecturer> { return GetAllLecturers(query).then((data) => { if (data.length === 0) { return Promise.reject({ errors: 'Lecturer not found' }); } return data[0]; }); } /** * @export * @param {Lecturer} LecturerData * @return {*} {Promise<Lecturer>} */ export async function CreateLecturer( LecturerData: ILecturer ): Promise<ILecturer> { const newClass = new LecturerSchemaModel(LecturerData); return newClass.save().then((d) => d.toJSON()); } /** * @export * @param {string} id * @return {*} {Promise<Boolean>} */ export async function DeleteLecturer(id: string): Promise<Boolean> { return LecturerSchemaModel.findByIdAndDelete(id).then((_) => true); } /** * @export * @param {string} id * @param {Partial<Lecturer>} data * @return {*} {Promise<Lecturer>} */ export async function UpdateLecturer( id: string, data: Partial<ILecturer> ): Promise<Lecturer> { // remove fields that should not be updated with general update delete data.avatar; delete data.internalNotes; return LecturerSchemaModel.findByIdAndUpdate( id, { $set: data, }, { new: true, runValidators: true, } ).then((data) => GetSingleLecturer({ _id: data?._id })); } /** * @export * @param {string} id * @param {Partial<Lecturer>} data * @return {*} {Promise<Lecturer>} */ export async function UpdateLecturerAvatar( id: string, avatarObjectId: string ): Promise<Lecturer> { return LecturerSchemaModel.findByIdAndUpdate( id, { $set: { avatar: avatarObjectId }, }, { new: true, runValidators: true, } ).then((data) => GetSingleLecturer({ _id: data?._id })); } /** * @export * @param {string} lecturerId * @param {string} noteId * @return {*} */ export async function AddNote(lecturerId: string, noteId: string) { return LecturerSchemaModel.findByIdAndUpdate(lecturerId, { $push: { internalNotes: noteId }, }); } /** * @export * @param {string} lecturerId * @param {string} noteId * @return {*} */ export async function RemoveNote(lecturerId: string, noteId: string) { return LecturerSchemaModel.findByIdAndUpdate(lecturerId, { $pull: { internalNotes: noteId }, }); } export async function GetNotesByLecturerId( lecturerId: string ): Promise<INote[]> { return GetSingleLecturer(Queries.ById(lecturerId)).then( ({ internalNotes }) => internalNotes || [] ) as Promise<INote[]>; } export async function PushLecturerFiles(lecturerId: string, fileId: string) { return LecturerSchemaModel.findByIdAndUpdate( lecturerId, { $push: { files: fileId }, }, { new: true } ).then((lecturer) => GetSingleLecturer(Queries.ById(lecturer?._id))); } export async function PullLecturerFiles(lecturerId: string, fileId: string) { return LecturerSchemaModel.findByIdAndUpdate( lecturerId, { $pull: { files: fileId }, }, { new: true } ).then((lecturer) => GetSingleLecturer(Queries.ById(lecturer?._id))); } <file_sep>import Queries from '../../../queries'; import SettingsModel, { ISetting } from './model'; export function createSetting(settingData: ISetting) { const newDoc = new SettingsModel(settingData); return newDoc.save(); } export function createSettingMany(settingsDataList: ISetting[]) { return SettingsModel.insertMany(settingsDataList); } export function deleteSettingById(settingId: string) { return SettingsModel.findOneAndDelete(Queries.ById(settingId)); } export function findSettings(query: object) { return SettingsModel.find(query); } export function findSingleSettings(query: object) { return SettingsModel.findOne(query); } export function updateSetting(settingId: string, data: ISetting) { return SettingsModel.findOneAndUpdate( Queries.ById(settingId), { $set: data, }, { new: true, runValidators: true, } ); } <file_sep>import UserModel, { IUser } from './model'; import { User } from '../../../../models'; export async function FindUser(queryObject: Partial<IUser>) { return UserModel.findOne(queryObject).select('-password'); } export async function FindUserFull(queryObject: Partial<User>) { return UserModel.aggregate<User>([ { $match: queryObject, }, { $lookup: { from: 'roles', localField: 'role', foreignField: '_id', as: 'role', }, }, { $unwind: '$role', }, { $project: { password: 0, }, }, { $limit: 1, }, ]).then((singleUser) => singleUser[0]); } export async function CreateUser(user: IUser) { const newUser = new UserModel(user); return newUser.save(); } export async function UpdateUser(id: string, user: IUser) { return UserModel.findByIdAndUpdate( id, { $set: user }, { runValidators: true, new: true, } ); } <file_sep>import { Router } from 'express'; import { authenticateToken } from './auth'; import userRouter from './api/user'; import permissionsRouter from './api/permissions'; import buildingsRouter from './api/buildings'; import classesRouter from './api/classes'; import categoriesRouter from './api/categories'; import payDuplicatorRouter from './api/pay-duplicator'; import filesRouter from './api/files'; import lecturerRouter from './api/lecturers'; import settingsRouter from './api/settings'; import SemesterRouter from './api/semester'; import coursesRouter from './api/courses'; import couponsRouter from './api/coupons'; import studentsRouter from './api/students'; const appRouter = Router(); appRouter.use(authenticateToken); appRouter.use('/user', userRouter); appRouter.use('/permissions', permissionsRouter); appRouter.use('/buildings', buildingsRouter); appRouter.use('/classes', classesRouter); appRouter.use('/categories', categoriesRouter); appRouter.use('/pay-duplicator', payDuplicatorRouter); appRouter.use('/lecturer', lecturerRouter); appRouter.use('/files', filesRouter); appRouter.use('/settings', settingsRouter); appRouter.use('/semesters', SemesterRouter); appRouter.use('/courses', coursesRouter); appRouter.use('/coupons', couponsRouter); appRouter.use('/students', studentsRouter); export default appRouter; <file_sep>import { Router, Response } from 'express'; import { RequestExtend } from '../../auth'; import allow from '../../helper/user-permission'; import { isValidObjectId } from 'mongoose'; import { BadRequest, SuccessfulResponse, ServerError, NotFound, } from '../../helper/http'; import { GetAllPayDuplicators, GetSinglePayDuplicator, CreatePayDuplicator, UpdatePayDuplicator, DeletePayDuplicator, } from '../../db/v1/models/pay-duplicator/controller'; const payDuplicatorRouter = Router(); const scope = 'payDuplicator'; payDuplicatorRouter.get( '/', allow(scope), (_: RequestExtend, res: Response) => { return GetAllPayDuplicators() .then((data) => { return SuccessfulResponse(res, data); }) .catch((err) => { console.error(err.errors); return ServerError(res); }); } ); payDuplicatorRouter.get( '/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return GetSinglePayDuplicator({ _id: id }) .then((data) => { if (!data) { return NotFound(res); } return SuccessfulResponse(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); payDuplicatorRouter.post( '/', allow(scope), async (req: RequestExtend, res: Response) => { return CreatePayDuplicator(req.body) .then((data) => { return SuccessfulResponse(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); payDuplicatorRouter.put( '/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return UpdatePayDuplicator(id, req.body) .then((data) => { if (!data) { return NotFound(res); } return SuccessfulResponse(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); payDuplicatorRouter.delete( '/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return DeletePayDuplicator(id) .then((deleted) => { return SuccessfulResponse(res, { deleted }); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); export default payDuplicatorRouter; <file_sep>import { Document, model, Schema } from 'mongoose'; export interface ISetting { name: string; description?: string; value?: string; } type ISettingDOC = ISetting & Document; const SettingSchema = new Schema({ name: { type: String, required: true }, value: { type: String, required: false, default: '' }, description: { type: String, required: false, default: '' }, }); export default model<ISettingDOC>('settings', SettingSchema); <file_sep>import { Response } from 'express'; export function SuccessfulResponse<T extends object>( res: Response, data: T | string ): Response { return res .status(200) .json(typeof data === 'string' ? { message: data } : data); } export function BadRequest(res: Response, message: any = ''): Response { return res.status(400).json({ error: message || "Your request can't be processed, please check the request data", }); } export function NotFound(res: Response, message: any = ''): Response { return res.status(404).json({ error: message || 'Not found', }); } export function ServerError(res: Response, message: any = ''): Response { return res.status(500).json({ error: message || 'Some server error occurred', }); } export function SuccessOrNotFound( res: Response, data: any, message: any = '' ): Response { if (!data) { return NotFound(res, message); } return SuccessfulResponse(res, data); } <file_sep>import { Router, Response } from 'express'; import { RequestExtend } from '../../auth'; import allow from '../../helper/user-permission'; import { isValidObjectId } from 'mongoose'; import { BadRequest, SuccessfulResponse, ServerError, SuccessOrNotFound, } from '../../helper/http'; import { GetAllBuildings, GetBuildingById, CreateBuildingRecord, DeleteBuildingRecord, FindAndUpdate, } from '../../db/v1/models/buildings/controller'; const buildingsRouter = Router(); const scope = 'buildings'; buildingsRouter.get('/', allow(scope), (req: RequestExtend, res: Response) => { if (!isValidObjectId(req.params.id)) { return BadRequest(res); } return GetAllBuildings() .then((data) => { return SuccessfulResponse(res, data); }) .catch((err) => { console.error(err.errors); return ServerError(res); }); }); buildingsRouter.get( '/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return GetBuildingById(id) .then((data) => { return SuccessOrNotFound(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); buildingsRouter.post('/', allow(scope), (req: RequestExtend, res: Response) => { return CreateBuildingRecord(req.body) .then((data) => { return SuccessfulResponse(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); }); buildingsRouter.put( '/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return FindAndUpdate(id, req.body) .then((data) => { return SuccessOrNotFound(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); buildingsRouter.delete( '/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return DeleteBuildingRecord(id) .then((deleted) => { return SuccessfulResponse(res, { deleted }); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); export default buildingsRouter; <file_sep>import PayDuplicatorSchemaModel, { IPayDuplicator } from './model'; export async function GetAllPayDuplicators( query: object = {} ): Promise<IPayDuplicator[]> { return PayDuplicatorSchemaModel.find(query); } export async function GetSinglePayDuplicator(query: object = {}) { return PayDuplicatorSchemaModel.findOne(query); } export async function CreatePayDuplicator(payDuplicatorData: IPayDuplicator) { const newClass = new PayDuplicatorSchemaModel(payDuplicatorData); return newClass.save().then((d) => d.toJSON()); } export async function DeletePayDuplicator(id: string) { return PayDuplicatorSchemaModel.findByIdAndDelete(id).then((_) => true); } export async function UpdatePayDuplicator(id: string, data: IPayDuplicator) { return PayDuplicatorSchemaModel.findByIdAndUpdate( id, { $set: data }, { new: true, runValidators: true, } ); } <file_sep>import { Response, Router } from 'express'; import { RequestExtend } from '../../auth'; import { findSingleSettings, updateSetting, } from '../../db/v1/models/settings/controller'; import { NotFound, ServerError, SuccessfulResponse } from '../../helper/http'; import allow from '../../helper/user-permission'; import { PermissionsScope } from '../../models'; import settings from '../../settings/appSettings'; const vatRouter = Router(); const scope: PermissionsScope = 'settings'; const allowPath = allow(scope); vatRouter.get('/', allowPath, async (_: RequestExtend, res: Response) => { return findSingleSettings({ name: settings.VAT.name }) .then((vatValue) => { if (!vatValue) { return NotFound(res); } return SuccessfulResponse(res, vatValue); }) .catch((err) => ServerError(res, err)); }); vatRouter.post('/', allowPath, async (req: RequestExtend, res: Response) => { const { value } = req.body; return findSingleSettings({ name: settings.VAT.name }) .then((vatValue) => { if (!vatValue) { return NotFound(res); } return updateSetting(vatValue._id, { name: 'VAT', value }).then( (updatedValue) => { if (updatedValue) { return SuccessfulResponse(res, updatedValue); } return Promise.reject({ errors: 'Entry could not be updated' }); } ); }) .catch(({ errors }) => ServerError(res, errors)); }); export default vatRouter; <file_sep>export type PermissionOptions = 'read' | 'update' | 'delete' | 'create'; export type PermissionsScope = | 'user' | 'permissions' | 'buildings' | 'classes' | 'categories' | 'payDuplicator' | 'lecturer' | 'files' | 'settings' | 'semesters' | 'courses' | 'coupons' | 'students'; export type PermissionTable = Record<PermissionOptions, boolean>; export type PermissionList = Record<PermissionsScope, PermissionTable>; export interface Role { _id: string; name: string; permissions: PermissionList; } <file_sep>import { Response, Router } from 'express'; import { isValidObjectId } from 'mongoose'; import { RequestExtend } from '../../auth'; import Queries from '../../db/queries'; import { CreateSemester, DeleteSemester, GetAllSemesters, GetSemester, UpdateSemester, } from '../../db/v1/models/semester/controller'; import { BadRequest, ServerError, SuccessfulResponse, SuccessOrNotFound, } from '../../helper/http'; import allow from '../../helper/user-permission'; const scope = 'semesters'; const SemesterRouter = Router(); SemesterRouter.use(allow(scope)); SemesterRouter.get('/', (_: RequestExtend, res: Response) => { return GetAllSemesters() .then((data) => SuccessfulResponse(res, data)) .catch(({ errors }) => ServerError(res, errors)); }); SemesterRouter.get('/:id', (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return GetSemester(Queries.ById(id)) .then((data) => SuccessOrNotFound(res, data)) .catch(({ errors }) => ServerError(res, errors)); }); SemesterRouter.post('/', (req: RequestExtend, res: Response) => { const semesterData = req.body; return CreateSemester(semesterData) .then((data) => SuccessfulResponse(res, data)) .catch(({ errors }) => ServerError(res, errors)); }); SemesterRouter.put('/:id', (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } const semesterData = req.body; return UpdateSemester(id, semesterData) .then((data) => SuccessOrNotFound(res, data)) .catch(({ errors }) => ServerError(res, errors)); }); SemesterRouter.delete('/:id', (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return DeleteSemester(id) .then((deleted) => SuccessfulResponse(res, { deleted })) .catch(({ errors }) => ServerError(res, errors)); }); export default SemesterRouter; <file_sep>import mongoose, { Schema, Document } from 'mongoose'; export interface IBuilding { name: string; active: boolean; } export type IBuildingDOC = IBuilding & Document; export const BuildingSchema = new Schema({ name: { type: String, required: true, unique: true }, active: { type: Boolean, required: true }, }); export default mongoose.model<IBuildingDOC>('Buildings', BuildingSchema); <file_sep>import { Router, Response } from 'express'; import { RequestExtend } from '../../auth'; import allow, { loggedIn } from '../../helper/user-permission'; import { isValidObjectId } from 'mongoose'; import { BadRequest, SuccessfulResponse, ServerError, NotFound, } from '../../helper/http'; import { GetAllLecturers, GetSingleLecturer, CreateLecturer, UpdateLecturer, DeleteLecturer, AddNote, RemoveNote, UpdateLecturerAvatar, GetNotesByLecturerId, PushLecturerFiles, PullLecturerFiles, } from '../../db/v1/models/lecturer/controller'; import { CreateNote, DeleteNote } from '../../db/v1/models/notes/controller'; import Queries from '../../db/queries'; import { Delete, Upload } from '../../db/v1/models/files/controller'; import { UploadedFile } from 'express-fileupload'; const lecturerRouter = Router(); const scope = 'lecturer'; lecturerRouter.get( '/', allow(scope), async (_: RequestExtend, res: Response) => { return GetAllLecturers() .then((data) => SuccessfulResponse(res, data)) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); lecturerRouter.get( '/:lectureId', allow(scope), async (req: RequestExtend, res: Response) => { const { lectureId } = req.params; if (!isValidObjectId(lectureId)) { return BadRequest(res); } return GetSingleLecturer(Queries.ById(lectureId)) .then((data) => { if (!data) { return NotFound(res); } return SuccessfulResponse(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); lecturerRouter.post( '/', allow(scope), async (req: RequestExtend, res: Response) => { return CreateLecturer(req.body) .then((data) => { return SuccessfulResponse(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); lecturerRouter.put( '/:lectureId', allow(scope), (req: RequestExtend, res: Response) => { const { lectureId } = req.params; if (!isValidObjectId(lectureId)) { return BadRequest(res); } return UpdateLecturer(lectureId, req.body) .then((data) => { if (!data) { return NotFound(res); } return SuccessfulResponse(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); lecturerRouter.delete( '/:lectureId', allow(scope), (req: RequestExtend, res: Response) => { const { lectureId } = req.params; if (!isValidObjectId(lectureId)) { return BadRequest(res); } return DeleteLecturer(lectureId) .then((deleted) => { return SuccessfulResponse(res, { deleted }); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); lecturerRouter.get( '/:lecturerId/notes', loggedIn, (req: RequestExtend, res: Response) => { const { lecturerId } = req.params; if (!isValidObjectId(lecturerId)) { return BadRequest(res); } return GetNotesByLecturerId(lecturerId) .then((notes) => SuccessfulResponse(res, notes)) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); lecturerRouter.post( '/:lecturerId/notes', loggedIn, (req: RequestExtend, res: Response) => { const { lecturerId } = req.params; if (!isValidObjectId(lecturerId)) { return BadRequest(res); } const { user } = req; return CreateNote({ user: user?._id as string, created: new Date().toUTCString(), text: req.body.text, related: lecturerId, }) .then((newNote) => { return AddNote(lecturerId, newNote._id as string).then(() => Promise.resolve(newNote) ); }) .then((newNote) => SuccessfulResponse(res, newNote)) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); lecturerRouter.delete( '/:lecturerId/notes/:noteId', loggedIn, (req: RequestExtend, res: Response) => { const { lecturerId, noteId } = req.params; if (!isValidObjectId(lecturerId) || !isValidObjectId(noteId)) { return BadRequest(res); } return DeleteNote(noteId) .then(() => RemoveNote(lecturerId, noteId)) .then(() => SuccessfulResponse(res, { deleted: true })) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); lecturerRouter.post( '/:lecturerId/avatar', allow(scope), (req: RequestExtend, res: Response) => { const { lecturerId } = req.params; if (!isValidObjectId(lecturerId)) { return BadRequest(res, 'Lecturer ID is incorrect'); } const fileToUpload = req.files?.file as UploadedFile; if (!fileToUpload) { return BadRequest(res, 'No file was provided'); } return GetSingleLecturer(Queries.ById(lecturerId)) .then((lecturer) => { if (!lecturer.avatar?._id) { return Promise.resolve(); } return Delete(Queries.ById(lecturer.avatar._id), false); }) .then(() => Upload(fileToUpload, false)) .then((fileUploaded) => UpdateLecturerAvatar(lecturerId, fileUploaded._id) ) .then((lecturer) => SuccessfulResponse(res, lecturer)) .catch((errors) => ServerError(res, errors)); } ); lecturerRouter.post( '/:lecturerId/file', allow(scope), allow('files'), (req: RequestExtend, res: Response) => { const { lecturerId } = req.params; if (!isValidObjectId(lecturerId)) { return BadRequest(res, 'Lecturer ID is incorrect'); } const fileToUpload = req.files?.file as UploadedFile; if (!fileToUpload) { return BadRequest(res, 'No file was provided'); } return GetSingleLecturer(Queries.ById(lecturerId)) .then(() => Upload(fileToUpload, true)) .then((fileUploaded) => PushLecturerFiles(lecturerId, fileUploaded._id)) .then((lecturer) => SuccessfulResponse(res, lecturer || {})) .catch((errors) => ServerError(res, errors)); } ); lecturerRouter.delete( '/:lecturerId/file/:fileId', allow(scope), allow('files'), (req: RequestExtend, res: Response) => { const { lecturerId, fileId } = req.params; if (!isValidObjectId(lecturerId)) { return BadRequest(res, 'Lecturer ID is incorrect'); } if (!isValidObjectId(fileId)) { return BadRequest(res, 'File ID is incorrect'); } return GetSingleLecturer(Queries.ById(lecturerId)) .then(() => Delete(Queries.ById(fileId), true)) .then(() => PullLecturerFiles(lecturerId, fileId)) .then((lecturer) => SuccessfulResponse(res, lecturer || {})) .catch((errors) => ServerError(res, errors)); } ); export default lecturerRouter; <file_sep>import { Router, Response } from 'express'; import { RequestExtend } from '../../auth'; import allow from '../../helper/user-permission'; import { isValidObjectId } from 'mongoose'; import { BadRequest, SuccessfulResponse, ServerError, NotFound, } from '../../helper/http'; import { GetAllCategories, GetSingleCategory, CreateCategory, UpdateCategory, DeleteCategory, } from '../../db/v1/models/categories/controller'; const categoriesRouter = Router(); const scope = 'categories'; categoriesRouter.get('/', allow(scope), (req: RequestExtend, res: Response) => { if (!isValidObjectId(req.params.id)) { return BadRequest(res); } return GetAllCategories() .then((data) => { return SuccessfulResponse(res, data); }) .catch((err) => { console.error(err.errors); return ServerError(res); }); }); categoriesRouter.get( '/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return GetSingleCategory({ _id: id }) .then((data) => { if (!data) { return NotFound(res); } return SuccessfulResponse(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); categoriesRouter.post( '/', allow(scope), async (req: RequestExtend, res: Response) => { return CreateCategory(req.body) .then((data) => { return SuccessfulResponse(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); categoriesRouter.put( '/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return UpdateCategory(id, req.body) .then((data) => { if (!data) { return NotFound(res); } return SuccessfulResponse(res, data); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); categoriesRouter.delete( '/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return DeleteCategory(id) .then((deleted) => { return SuccessfulResponse(res, { deleted }); }) .catch(({ errors }) => { console.error(errors); return ServerError(res, errors); }); } ); export default categoriesRouter; <file_sep>import { isValidObjectId } from 'mongoose'; import Queries from '../../../queries'; import ClassesModel, { IClassRoom } from './model'; export async function GetAllClassRooms( query: object = {} ): Promise<IClassRoom[]> { return ClassesModel.aggregate<IClassRoom>([ { $match: query, }, { $lookup: { from: 'buildings', localField: 'building', foreignField: '_id', as: 'building', }, }, { $unwind: { path: '$building', preserveNullAndEmptyArrays: true }, }, { $lookup: { from: 'classavailabilities', localField: '_id', foreignField: 'classId', as: 'availability', }, }, { $project: { 'availability.classId': 0, 'availability.__v': 0, 'building.__v': 0, __v: 0, }, }, ]).exec(); } export async function GetSingleClassRoom(query: object) { return GetAllClassRooms(query).then((data) => { if (data.length > 0) { return data[0]; } return undefined; }); } export async function CreateClass(classData: IClassRoom) { const newClass = new ClassesModel(classData); return newClass.save().then((d) => d.toJSON()); } export async function DeleteClass(id: string) { return ClassesModel.findByIdAndDelete(id).then((_) => true); } export async function UpdateClass(id: string, data: IClassRoom) { if (!isValidObjectId(id)) { return Promise.reject('Not valid class ID'); } return ClassesModel.findByIdAndUpdate( id, { $set: data }, { new: true, runValidators: true } ) .exec() .then(() => GetSingleClassRoom(Queries.ById(id))); } <file_sep>import { Types } from 'mongoose'; import { GetNotes } from '../notes/controller'; import { INote } from '../notes/model'; import StudentModel, { IStudent } from './model'; export function GetAllStudents(query = {}): Promise<IStudent[]> { return StudentModel.aggregate([ { $match: query, }, { $lookup: { from: 'notes', let: { id: '$_id' }, pipeline: [ { $match: { $expr: { $eq: ['$related', '$$id'], }, }, }, { $lookup: { from: 'users', localField: 'user', foreignField: '_id', as: 'user', }, }, { $unwind: '$user', }, ], as: 'notes', }, }, { $project: { 'notes.related': 0, '*.__v': 0, }, }, ]).exec(); } export function GetSingleStudent(query = {}): Promise<IStudent | undefined> { return GetAllStudents(query).then((data) => { if (data.length === 0) { return Promise.reject({ errors: 'Student not found' }); } return data[0]; }); } export function DeleteSingleStudent(id: string): Promise<boolean> { return StudentModel.findByIdAndDelete(id).then((data) => !!data); } export function CreateSingleStudent(data: IStudent): Promise<IStudent> { const newStudents = new StudentModel(data); return newStudents.save(); } export function GetStudentNotes(studentId: string): Promise<INote[]> { return GetNotes({ related: Types.ObjectId(studentId) }); } export function UpdateSingleStudent( id: string, data: IStudent ): Promise<IStudent | undefined> { return StudentModel.findByIdAndUpdate(id, { $set: data }, { new: true }).then( (data) => data || undefined ); } <file_sep>import RoleModel, { IRole } from './model'; export async function CreateRole(role: IRole) { const roleModel = new RoleModel(role); return roleModel.save().then((role) => role.toObject()); } export async function FindRole(query = {}) { return RoleModel.findOne(query).then((role) => role?.toObject()); } export async function FindRoles(query: Partial<IRole> = {}) { return RoleModel.find(query); } export async function RoleUpdateOne(_id: string, doc: Partial<IRole>) { return RoleModel.findByIdAndUpdate( _id, { $set: doc, }, { new: true, } ); } <file_sep>import mongoose, { Schema, Document } from 'mongoose'; import moment from 'moment'; export interface IClassAvailability { _id?: string; classId: string; from: string; to: string; } export type IClassAvailabilityDOC = IClassAvailability & Document; export const ClassAvailabilitySchema = new Schema({ classId: { type: Schema.Types.ObjectId, required: true }, from: { type: Date, required: false, default: moment().utc().toDate(), min: Number(moment().utc().toNow()), }, to: { type: Date, required: true }, }); export default mongoose.model<IClassAvailabilityDOC>( 'ClassAvailability', ClassAvailabilitySchema ); <file_sep>import mongoose, { Schema, Document } from 'mongoose'; interface Option { value: string; title: string; } interface Session { count: Option; length: Option; } interface CourseDefaults { preliminaryKnowledge: Option; goals: Option; promotion: Option; marketing: string; session: Session; minStudents: number; maxStudents: number; price: number; studentPrice: number; } export interface ICategory { _id?: string; title: string; active: boolean; courseDefaults: CourseDefaults; } export type ICategoryDOC = ICategory & Document; const OptionSchema = new Schema({ value: { type: String, required: false }, title: { type: String, required: false }, }); const SessionSchema = new Schema({ count: { type: OptionSchema, required: false }, length: { type: OptionSchema, required: false }, }); const CourseDefaultsSchema = new Schema({ preliminaryKnowledge: { type: OptionSchema, required: false }, goals: { type: OptionSchema, required: false }, promotion: { type: OptionSchema, required: false }, marketing: { type: String, required: false, default: '' }, session: { type: SessionSchema, required: false }, minStudents: { type: Number, required: false, default: 0 }, maxStudents: { type: Number, required: false, default: 0 }, price: { type: Number, required: false, default: 0 }, studentPrice: { type: Number, required: false, default: 0 }, }); export const CategorySchema = new Schema({ title: { type: String, required: true }, active: { type: Boolean, required: false, default: true }, courseDefaults: { type: CourseDefaultsSchema, required: false }, }); export default mongoose.model<ICategoryDOC>('categories', CategorySchema); <file_sep>export function email(value: string) { return /^(([^<>()\[\]\\.,;:\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,}))$/.test( value ); } export const Validators = { email, }; <file_sep>import { ISetting } from '../db/v1/models/settings/model'; const VAT: ISetting = { name: 'VAT', description: 'Value-added tax', value: '', }; const settings = { VAT, }; export default settings; <file_sep>import mongoose, { Document, Schema } from 'mongoose'; export interface ISemester { _id?: string; name: string; startDate: string; endDate: string; active: boolean; } type ISemesterDoc = ISemester & Document; const SemesterSchema = new Schema({ name: { type: String, required: true }, startDate: { type: Date, required: true }, endDate: { type: Date, required: true }, active: { type: Boolean, required: false, default: true }, }); export default mongoose.model<ISemesterDoc>('semesters', SemesterSchema); <file_sep>import { UploadedFile } from 'express-fileupload'; import FileModelSchema, { IFileDetails } from './model'; import { deleteFile, moveFile } from '../../../../services/files'; import Queries from '../../../queries'; export async function Upload(file: UploadedFile, secure: boolean) { return moveFile(file, secure) .then((fileData) => { const fileSchema = new FileModelSchema(fileData); return fileSchema.save(); }) .then((doc) => doc.toJSON()) .catch((err) => { console.error(`${__filename}: ${err}`); throw new Error(err); }); } export async function Delete(query: object = {}, secure: boolean) { return FileModelSchema.findOneAndDelete(query) .then((doc) => deleteFile(doc?.name, secure)) .catch((err) => { console.error(`${__filename}: ${err}`); throw new Error(err); }); } export function GetFileList(query: object = {}) { return FileModelSchema.find(query); } export function GetFileById(fileId: string): Promise<IFileDetails> { return FileModelSchema.findOne(Queries.ById(fileId)).then((fileData) => { if (!fileData) { return Promise.reject({ errors: 'File was not found' }); } return fileData.toJSON(); }) as Promise<IFileDetails>; } <file_sep>import path from 'path'; import { existsSync, unlink } from 'fs'; import { UploadedFile } from 'express-fileupload'; import { IFileDetails } from '../db/v1/models/files/model'; export function getPath(secure: boolean = false) { const securePath = 'files'; const publicPath = 'uploads'; return secure ? securePath : publicPath; } export function moveFile( file: UploadedFile, secure: boolean = false ): Promise<IFileDetails> { const time = Date.now(); const { size, mimetype, name } = file; const finalName = `${time}_${name}`; return file.mv(`${getPath(secure)}/${finalName}`).then(() => ({ size, mimetype, name: finalName, secure, created: new Date(time).toUTCString(), })); } export function deleteFile( fileName: string = '', secure: boolean = false ): Promise<void> { const filePathFinal = path.join(getPath(secure), fileName); if (!existsSync(filePathFinal)) { console.error( `Tried to delete file at "${filePathFinal}", file was not found`, 'breaking operation none blocking fail' ); return Promise.resolve(); } return new Promise((res, rej) => unlink(filePathFinal, (err) => { if (err) { rej(err); } return res(); }) ); } <file_sep>import { Router, Request, Response, NextFunction } from 'express'; import { sign, verify } from 'jsonwebtoken'; import { createHash } from 'crypto'; import { User } from '../models'; import { FindUserFull } from '../db/v1/models/user/controller'; export type RequestExtend<T = any> = Request & { user?: User; body?: T; }; const authRouter = Router(); authRouter.post('/login', async (req, res) => { const { email, password } = req.body; if (!email || !password) { return res.status(400).json({ message: 'both email and password are required', }); } const pass = createHash('sha256') .update(password as string) .digest('base64'); return FindUserFull({ email, password: <PASSWORD>, }) .then((user) => { if (!user) { return res.sendStatus(404); } return res.status(200).json({ expiresIn: 3600, token: sign(user, process.env.ACCESS_TOKEN_SECRET as string, { expiresIn: '1h', }), }); }) .catch((err) => { console.error(err); return res.sendStatus(500); }); }); export function authenticateToken( req: RequestExtend, res: Response, next: NextFunction ) { const authHeader = req.headers.authorization; const token = authHeader && authHeader.split(' ')[1]; if (!token) { return res.sendStatus(401); } return verify( token, process.env.ACCESS_TOKEN_SECRET as string, (err, user) => { if (err) { return res.sendStatus(403); } req.user = user as User; return next(); } ); } export default authRouter; <file_sep>import Queries from '../../../queries'; import CourseModel, { ICourse } from './model'; export async function GetMultipleCourses( query: object = {}, limit: number = 999 ): Promise<ICourse[]> { if (limit) { } return CourseModel.aggregate<ICourse[]>([ { $match: query, }, { $lookup: { from: 'files', localField: 'files', foreignField: '_id', as: 'files', }, }, { $limit: limit }, ]).exec(); } export async function CreateCourse(data: ICourse): Promise<ICourse> { const newCourse = new CourseModel(data); return newCourse.save(); } export async function GetSingleCourse(query: object) { return GetMultipleCourses(query, 1).then((data) => { if (data.length == 0) { return Promise.reject('Course was not found'); } return data[0]; }); } export async function DeleteSingleCourse(query: object) { return CourseModel.findOneAndDelete(query).then(() => true); } export async function UpdateCourse(id: string, data: ICourse) { return CourseModel.findByIdAndUpdate( id, { $set: data }, { new: true, runValidators: true } ); } export async function PushCourseFiles(id: string, fileId: string) { return CourseModel.findByIdAndUpdate( id, { $push: { files: fileId }, }, { new: true } ).then((course) => GetSingleCourse(Queries.ById(course?._id))); } export async function PullCourseFiles(id: string, fileId: string) { return CourseModel.findByIdAndUpdate( id, { $pull: { files: fileId }, }, { new: true } ).then((course) => GetSingleCourse(Queries.ById(course?._id))); } <file_sep>import { CreateDateRangeAndCheck } from './helper'; import moment from 'moment'; describe('check helper file for availability', () => { test('should return range CreateDateRangeAndCheck', () => { const dateFrom = moment('2020-09-25T17:30:00.000Z'); const dateTo = dateFrom.clone().add(5, 'days').add(2, 'hours'); const dateFromISO = dateFrom.toISOString(); const dateToISO = dateTo.toISOString(); const { result, error } = CreateDateRangeAndCheck(dateFromISO, dateToISO); const [firstDate, ...dates] = result || []; expect(error).toBeUndefined(); expect(result?.length).toBe(6); expect(firstDate?.from).toBe(dateFromISO); expect(firstDate?.to).toBe(dateFrom.clone().add(2, 'hours').toISOString()); expect(dates.pop()?.to).toBe(dateTo.toISOString()); }); test('should skip 2nd day of the week CreateDateRangeAndCheck', () => { const dateFrom = moment('2020-09-25T17:30:00.000Z'); const dateTo = dateFrom.clone().add(5, 'days').add(2, 'hours'); const { result, error } = CreateDateRangeAndCheck( dateFrom.toISOString(), dateTo.toISOString(), ['1'] ); expect(error).toBeUndefined(); expect(result?.length).toBe(1); }); test('should fail on 1st date', () => { const dateFrom = 'asdasd'; const dateTo = moment().add(5, 'days').add(2, 'hours'); const { error, result } = CreateDateRangeAndCheck( dateFrom, dateTo.toISOString(), ['1'] ); expect(result).toBeUndefined(); expect(error).toBeDefined(); expect(error).toBe(`From date "${dateFrom}" is not a valid date`); }); test('should fail on 2nd date', () => { const dateFrom = moment().toISOString(); const dateTo = 'asdasd'; const { error } = CreateDateRangeAndCheck(dateFrom, dateTo, ['1']); expect(error).toBeDefined(); expect(error).toBe(`To date "${dateTo}" is not a valid date`); }); test('should fail on date to is earlier than from', () => { const dateFrom = moment().add(5, 'days').add(2, 'hours').toISOString(); const dateTo = moment().toISOString(); const { error } = CreateDateRangeAndCheck(dateFrom, dateTo); expect(error).toBeDefined(); expect(error).toBe('"From" date must be before "To" date'); }); test('should fail on 2nd date', () => { const dateFrom = moment().toISOString(); const dateTo = moment().add(2, 'minutes').toISOString(); const { error } = CreateDateRangeAndCheck(dateFrom, dateTo); expect(error).toBeDefined(); expect(error).toBe('Booking for less than 30 min is prohibited'); }); test('should return only the one range day', () => { const dateFrom = moment().toISOString(); const dateTo = moment().add(45, 'minutes').toISOString(); const { result = [], error } = CreateDateRangeAndCheck(dateFrom, dateTo); expect(error).toBeUndefined(); expect(result?.length).toBe(1); expect(result[0].from).toBe(dateFrom); expect(result[0].to).toBe(dateTo); }); test('should fail to return range as limiter is set to allow a different day of the week', () => { const dateFrom = moment('2020-09-25T17:30:00.000Z'); const dateTo = dateFrom.clone().add(45, 'minutes').toISOString(); const { result, error } = CreateDateRangeAndCheck( dateFrom.toISOString(), dateTo, ['4'] ); expect(result).toBeUndefined(); expect(error).toBe( 'After calculation there are no availability to create, please double check the input dates and days limiter' ); }); }); <file_sep>import mongoose, { Schema, Document } from 'mongoose'; export interface INote { _id?: string; user: string; //must be aggregated with actual user, created?: string; text: string; related: string; } type INoteDOC = INote & Document; export const INoteSchema = new Schema({ user: { type: Schema.Types.ObjectId, required: true }, created: { type: Date, required: true, default: new Date() }, text: { type: String, required: true, default: '' }, related: { type: Schema.Types.ObjectId, required: true }, }); export default mongoose.model<INoteDOC>('notes', INoteSchema); <file_sep>const mongoError = require('mongo-error-handler'); import { Router, Response } from 'express'; import { isValidObjectId } from 'mongoose'; import { RequestExtend } from '../../auth'; import allow from '../../helper/user-permission'; import { BadRequest, SuccessfulResponse, ServerError, SuccessOrNotFound, } from '../../helper/http'; import { CreateSingleCoupon, DeleteSingleCoupon, GetAllCoupons, GetSingleCoupon, UpdateSingleCoupon, } from '../../db/v1/models/coupons/controller'; const couponsRouter = Router(); const scope = 'coupons'; couponsRouter.get('/', allow(scope), (_: RequestExtend, res: Response) => { return GetAllCoupons() .then((data) => { return SuccessfulResponse(res, data); }) .catch((err) => { console.log(err); return ServerError(res, mongoError(err)); }); }); couponsRouter.get('/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return GetSingleCoupon(id) .then((data) => SuccessOrNotFound(res, data)) .catch((err) => { console.log(err); return ServerError(res, mongoError(err)); }); }); couponsRouter.post('/', allow(scope), (req: RequestExtend, res: Response) => { return CreateSingleCoupon(req.body) .then((data) => { return SuccessfulResponse(res, data); }) .catch((err) => { console.log(err); return ServerError(res, mongoError(err)); }); }); couponsRouter.put('/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return UpdateSingleCoupon(id, req.body) .then((data) => { return SuccessOrNotFound(res, data); }) .catch((err) => { console.log(err); return ServerError(res, mongoError(err)); }); }); couponsRouter.delete( '/:id', allow(scope), (req: RequestExtend, res: Response) => { const { id } = req.params; if (!isValidObjectId(id)) { return BadRequest(res); } return DeleteSingleCoupon(id) .then((deleted) => { return SuccessOrNotFound(res, { deleted }); }) .catch((err) => { console.log(err); return ServerError(res, mongoError(err)); }); } ); export default couponsRouter; <file_sep>import { Router, Response } from 'express'; import { RequestExtend } from '../../auth'; import allow from '../../helper/user-permission'; import { isValidObjectId } from 'mongoose'; import { ServerError, SuccessfulResponse, BadRequest, NotFound, } from '../../helper/http'; import { CreateClass, GetAllClassRooms, DeleteClass, UpdateClass, GetSingleClassRoom, } from '../../db/v1/models/classes/controller'; import { Create, GetAllClassAvailability, UpdateAvailability, FindOneClassAvailability, DeleteAvailability, } from '../../db/v1/models/classes/availability/controller'; import Queries from '../../db/queries'; const classesRouter = Router(); const scope = 'classes'; // Get all class rooms classesRouter.get( '/', allow(scope), async (_: RequestExtend, res: Response) => { return GetAllClassRooms() .then((data) => { return SuccessfulResponse(res, data); }) .catch((error) => ServerError(res, error)); } ); // Get single class rooms classesRouter.get( '/:classId', allow(scope), async (req: RequestExtend, res: Response) => { const { classId } = req.params; if (!isValidObjectId(classId)) { return BadRequest(res); } return GetSingleClassRoom(Queries.ById(classId)) .then((data) => { if (!data) { return NotFound(res); } return SuccessfulResponse(res, data); }) .catch((error) => ServerError(res, error)); } ); // Create a class rooms classesRouter.post('/', allow(scope), (req: RequestExtend, res: Response) => { const { classId } = req.params; if (!isValidObjectId(classId)) { return BadRequest(res); } return CreateClass(req.body) .then(({ _id }) => GetSingleClassRoom({ _id })) .then((classRoom) => { if (!classRoom) { return ServerError( res, 'Trying to retrieve class room after creation failed' ); } return SuccessfulResponse(res, classRoom); }) .catch(({ errors }) => ServerError(res, errors)); }); // Delete a class rooms classesRouter.delete( '/:classId', allow(scope), (req: RequestExtend, res: Response) => { const { classId } = req.params; if (!isValidObjectId(classId)) { return BadRequest(res); } return DeleteClass(classId) .then((deleted) => { SuccessfulResponse(res, { deleted }); }) .catch(({ error }) => ServerError(res, error)); } ); // Update a class rooms classesRouter.put( '/:classId', allow(scope), (req: RequestExtend, res: Response) => { const { classId } = req.params; if (!isValidObjectId(classId)) { return BadRequest(res); } return UpdateClass(classId, req.body) .then((updatedData) => { if (!updatedData) { return ServerError( res, `No class was found with the id ${classId} or failed to update` ); } return SuccessfulResponse(res, updatedData); }) .catch(({ error }) => ServerError(res, error)); } ); // Create availability for a class rooms classesRouter.post( '/:classId/availability', allow(scope), (req: RequestExtend, res: Response) => { const { classId } = req.params; if (!isValidObjectId(classId)) { return BadRequest(res); } return Create(classId, req.body) .then((d) => { SuccessfulResponse(res, d); }) .catch(({ errors }) => ServerError(res, errors)); } ); // Get availability for a class rooms classesRouter.get( '/:classId/availability', allow(scope), (req: RequestExtend, res: Response) => { const { classId } = req.params; if (!isValidObjectId(classId)) { return BadRequest(res); } return GetAllClassAvailability(classId) .then((d) => { SuccessfulResponse(res, d); }) .catch(({ errors }) => ServerError(res, errors)); } ); // Get a specific availability for a class rooms classesRouter.get( '/availability/:availabilityId', allow(scope), (req: RequestExtend, res: Response) => { const { availabilityId } = req.params; if (!isValidObjectId(availabilityId)) { return BadRequest(res); } return FindOneClassAvailability(availabilityId) .then((data) => { if (!data) { return NotFound( res, `No availability was found with the id ${availabilityId} or failed to update` ); } return SuccessfulResponse(res, data); }) .catch(({ errors }) => ServerError(res, errors)); } ); // Update a specific availability for a class rooms classesRouter.put( '/availability/:availabilityId', allow(scope), (req: RequestExtend, res: Response) => { const { availabilityId } = req.params; if (!isValidObjectId(availabilityId)) { return BadRequest(res); } return UpdateAvailability(availabilityId, req.body) .then((data) => { if (!data) { return NotFound( res, `No availability was found with the id ${availabilityId} or failed to update` ); } return SuccessfulResponse(res, data); }) .catch(({ errors }) => ServerError(res, errors)); } ); // Update a specific availability for a class rooms classesRouter.delete( '/availability/:availabilityId', allow(scope), (req: RequestExtend, res: Response) => { const { availabilityId } = req.params; if (!isValidObjectId(availabilityId)) { return BadRequest(res); } return DeleteAvailability(availabilityId) .then((deleted) => { return SuccessfulResponse(res, { deleted }); }) .catch(({ errors }) => ServerError(res, errors)); } ); export default classesRouter; <file_sep>export interface Address { address: string; zip: string; city: string; region: string; country: string; houseNumber: string; entry: string; floor: number; flatNumber: number; } <file_sep>import ClassAvailabilityModel, { IClassAvailability } from './model'; import { CreateDateRangeAndCheck } from './helper'; export async function GetAllClassAvailability( classId: string ): Promise<IClassAvailability[]> { return ClassAvailabilityModel.find({ classId }) .select({ classId: 0, }) .lean(); } export async function FindOneClassAvailability( _id: string ): Promise<IClassAvailability | null> { return ClassAvailabilityModel.findOne({ _id }).lean(); } export async function Create( classId: string, { from, to, limiter = [] }: { from: string; to: string; limiter: string[] } ) { const { error, result = [] } = CreateDateRangeAndCheck(from, to, limiter); if (error) { return Promise.reject({ errors: error }); } return ClassAvailabilityModel.insertMany( result.map((singleAvailability) => ({ ...singleAvailability, classId, })) ); } export async function DeleteAvailability(id: string): Promise<boolean> { return ClassAvailabilityModel.findByIdAndDelete(id).then(() => true); } export async function UpdateAvailability( id: string, data: IClassAvailability ): Promise<IClassAvailability | undefined> { return ClassAvailabilityModel.findByIdAndUpdate( id, { $set: data }, { new: true, runValidators: true } ).then((data) => data?.toJSON()); } <file_sep>import mongoose, { Schema, Document } from 'mongoose'; export interface IFileDetails { _id?: string; name: string; size: number; mimetype: string; secure: boolean; created: string; } type FileDetailsDOC = IFileDetails & Document; const FileSchema = new Schema({ name: { type: String, required: true }, size: { type: Number, required: true }, mimetype: { type: String, required: true }, secure: { type: Boolean, required: false, default: false }, created: { type: Date, required: false, default: new Date() }, }); export default mongoose.model<FileDetailsDOC>('files', FileSchema); <file_sep>import { Document, model, Schema } from 'mongoose'; export interface ICoupon { title: string; code: string; isPercent: boolean; discount: number; active: boolean; effectiveFrom: Date; effectiveTo: Date; } export type ICouponDOC = ICoupon & Document; const CouponSchema = new Schema({ title: { type: String, required: true }, code: { type: String, required: true, unique: true }, isPercent: { type: Boolean, required: true }, discount: { type: Number, required: true }, active: { type: Boolean, required: true }, effectiveFrom: { type: Date, required: false }, effectiveTo: { type: Date, required: false }, }); export default model<ICouponDOC>('coupons', CouponSchema); <file_sep>import SemesterModel, { ISemester } from './model'; export async function CreateSemester(data: ISemester) { const newSemester = new SemesterModel(data); return newSemester.save(); } export async function GetSemester( query: object ): Promise<ISemester | undefined> { return SemesterModel.findOne(query).then((json) => json?.toJSON()); } export async function GetAllSemesters(): Promise<ISemester[]> { return SemesterModel.find({}); } export async function UpdateSemester( id: string, data: ISemester ): Promise<ISemester | undefined> { return SemesterModel.findByIdAndUpdate( id, { $set: data }, { new: true } ).then((json) => json?.toJSON()); } export async function DeleteSemester(id: string): Promise<boolean> { return SemesterModel.findByIdAndDelete(id).then(() => true); }
05dfec6f197502365f3cabc7dfe4fa84637df39a
[ "TypeScript" ]
64
TypeScript
alexander-shch/xtra-server
74f072b7403ba5546f4be17a28fb117a08d57468
ede8d64c62d281edb2321e9b258a2d37d4dd4f76
refs/heads/main
<file_sep>import styles from '../styles/Header.module.css'; export const Header = () => { return ( <header className={styles.header}> <strong className={styles.strong}>Torre</strong> </header> ) }<file_sep>This is a [Next.js](https://nextjs.org/) project To run the development server use: ```bash npm run dev # or yarn dev ``` You can also check the figma [sketch here](https://www.figma.com/file/1gGUaWd8oyrZKoj4qIptlG/Index) And the endpoints in the [postman collection here](https://www.getpostman.com/collections/1126ada0c9dc9531f4a4) The project isn't finished so there is no deploy.
6fc57c1d28d19abfe42be00637da8760e00fe25d
[ "JavaScript", "Markdown" ]
2
JavaScript
Alberthor47/TechnicalTets
72dd813109026c23638f6d49065e2551c741c029
8734585245392d70051ce94c244b031b683aaefc
refs/heads/master
<repo_name>captjvmoore/noob-_-brother<file_sep>/main.js // SLIDESHOW var slideIndex = 0; carousel(); function carousel() { var i; var x = document.getElementsByClassName("mySlides"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } slideIndex++; if (slideIndex > x.length) {slideIndex = 1} x[slideIndex-1].style.display = "block"; setTimeout(carousel, 4000); } var $slider = document.getElementById('slider'); var $toggle = document.getElementById('toggle'); $toggle.addEventListener('click', function() { var isOpen = $slider.classList.contains('slide-in'); $slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in'); }); // Menu function openNav() { document.getElementById("myNav").style.width = "100%"; } function closeNav() { document.getElementById("myNav").style.width = "0%"; } function myFunction(x) { x.classList.toggle("change"); }
f4f17193077096df5835ae1287e6af29f2a12cdf
[ "JavaScript" ]
1
JavaScript
captjvmoore/noob-_-brother
68d5fd067a8004035f9383297676a4f96c9d136e
3fc17147f796288a9afb0cdff0750192bb171ff1
refs/heads/master
<file_sep>var nophp_server = "https://nophp-server.herokuapp.com/server.php"; // change this to your own nophp server function nophp(code, server) { var xhttp = new XMLHttpRequest(); xhttp.open("POST", nophp_server, true); xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhttp.onload = function() { // start json parsing and processing var obj = JSON.parse(this.response); console.log("tmpfile: " + obj.file); var filelink = obj.file; var newrequest = new XMLHttpRequest(); newrequest.open("GET", filelink, true); newrequest.onload = function() { // start json parsing and processing document.getElementById("nophp").innerHTML = this.responseText; } newrequest.send(); } var data = "code=" + code; xhttp.send(data); } <file_sep># noPHP Run php remotely from javascript. PHP is awesome, but for PHP you need a webserver which is expensive and still your webserver needs to support php. But what if we could run php clientside for free? noPHP does just that, noPHP is a JavaScript plugin which talks to a public(or private) noPHP server and returns the output. This does not only enable everyone(even without a php server) to run PHP but it also allows you to run PHP semi-clientside, so you can run php without reloading the page. # Usage client To use noPHP you'll have to add the code below to your document. ```<script src="https://nophp-server.herokuapp.com/client.js"></script><div id="nophp"></div>``` You can use a different noPHP server by ,changing the serverlink. Now to run php you'll have to add the code below to your html document. ```<script>nophp("<?php your php code ?>");</script>``` # Setup server To setup your own noPHP server follow the steps below: 1. Clone this repository to your computer(```git clone https://github.com/Bluppie05/nophp.git```) 2. Upload / move the downloaded folder to your php webserver 3. In client.js, change the nophp_server variable to the url of your own server.php file 4. In server.php, you can configure the server to your likings under server settings, so for example blacklist a function 4. Add ```<script src="https://yourserver.com/path/to/client.js"></script><div id="nophp"></div>``` to your html file to use your new noPHP server # Changelog - v0.0.1: Added CORS bypassing - v0.0.2: Added command blacklist WARNING: Use server versions before v0.1 at your own risk, these are alpha versions and are at high risk of hack attacks and could destroy your host server. Server versions after v0.1 are beta versions and are much safer to use. # Public noPHP server list - https://nophp-server.herokuapp.com/client.js (default) (reliable) (up2date) - https://nophp-server.000webhostapp.com/client.js (fast) (up2date) To get your public noPHP server in the list, make an issue with the "serverlist request" label where you place the link of your server's client.js file and some info. <file_sep><html> <h1 id="nophp">noPHP</h1> <p>Run php inside javascript.</p> <p>PHP is awesome, but for PHP you need a webserver which is expensive and still your webserver needs to support php. But what if we could run php clientside for free? noPHP does just that, noPHP is a JavaScript plugin which talks to a public(or private) noPHP server and returns the output. This does not only enable everyone(even without a php server) to run PHP but it also allows you to run PHP semi-clientside, so you can run php without reloading the page.</p> <h1 id="usageclient">Usage client</h1> <p>To use noPHP you'll have to add the code below to your document.</p> <pre><code class="<script src="https://nophp-server.herokuapp.com/client.js"></script><div id="nophp"></div>``` language-<script src="https://nophp-server.herokuapp.com/client.js"></script><div id="nophp"></div>```">You can use a different noPHP server by ,changing the serverlink. Now to run php you'll have to add the code below to your html document. </code></pre> <script>nophp("<?php your php code ?>");</script> <p>```</p> <h1 id="setupserver">Setup server</h1> <p>To setup your own noPHP server follow the steps below:</p> <ol> <li>Clone this repository to your computer(<code>git clone https://github.com/Bluppie05/nophp.git</code>)</li> <li>Upload / move the downloaded folder to your php webserver</li> <li>In client.js, change the nophp_server variable to the url of your own server.php file</li> <li>In server.php, you can configure the server to your likings under server settings, so for example blacklist a function</li> <li>Add <code>&lt;script src="https://yourserver.com/path/to/client.js"&gt;&lt;/script&gt;&lt;div id="nophp"&gt;&lt;/div&gt;</code> to your html file to use your new noPHP server</li> </ol> <h1 id="publicnophpserverlist">Public noPHP server list</h1> <ul> <li>https://nophp-server.herokuapp.com/client.js (default) (reliable) (up2date)</li> <li>https://nophp-server.000webhostapp.com/client.js (fast) (up2date)</li> </ul> <p>To get your public noPHP server in the list, make an issue with the "serverlist request" label where you place the link of your server's client.js file and some info.</p> </html> <file_sep><?php header('Access-Control-Allow-Origin: *'); // allow requests from foregein clients // server settings $deletion = False; $block_prevention = True; // set this to true if your webserver has CORS disabled by default, set this to false if your webserver has CORS enabled by default or if you can change the CORS settings on your webserver to prevent buggs $blacklist = array("file_put_contents"); // Add commands to this list to blacklist them on your server, they won't work if(isset($_POST["code"])) { $code = $_POST["code"]; $host = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; // grab current url $host = explode("server.php", $host); // explode at filename $host = $host[0]; // grab the current folder $host = str_replace("http", "https", $host); // replace http with https so requests can safely get through $ip = $_SERVER['REMOTE_ADDR']; // get userip $date = date("Y_m_d"); // get date $filename = $ip."-".$date.".php"; // generate filename $filelink = $host."tmp/".$filename; // generates the filelink if($block_prevention) { $code = str_replace("<?php", "<?php header('Access-Control-Allow-Origin: *'); ", $code); // enables access from different locations to prevent request blocking } $loopnum = 0; // defines the used variable for the loop $blackcount = count($blacklist); // counts how many items are on the blacklist $blackerror = False; // sets the error detector while($loopnum < $blackcount) { if(strpos($code, $blacklist[$loopnum]) !== false) { file_put_contents("tmp/$filename", "Error: Used blacklisted component by the server"); // write an error to the temporary file $blackerror = True; // sets error to true } $loopnum = $loopnum + 1; // updating loop } if(!$blackerror) { file_put_contents("tmp/$filename", $code); // make the temporary php file } // json output start header('Content-Type: application/json'); // setting json header $myObj->file = $filelink; // adding file to json $myJSON = json_encode($myObj); // generating json print_r($myJSON); // outputting json // json output end } ?>
9be7f585506518d2997473163550c32359d45df5
[ "JavaScript", "PHP", "Markdown" ]
4
JavaScript
Bluppie05/nophp
a8c57771df6d3c030ef49d92c65664a3925302aa
8cbd2205b2837d5e8ca6dff9be50a643485c8a1d
refs/heads/master
<file_sep>import paho.mqtt.client as mqtt import json def on_connect(client, user, data, flags, rc): print("Connected with result code" + str(rc)) client.subscribe("chat") client.publish("chat", json.dumps({"user": user, "say": "Hello, anyone!"})) <file_sep>flag_i = 0 flag_i_group = 0 flag_i_it = 0 flag_i_it_to_all = 0 flag_i_group_to_all = 0 flag_set_it = 0 flag_set_group = 0<file_sep>#!usr/bin/ven python # -*- coding:utf-8 -*- import itchat from itchat.content import * import global_list itchat.auto_login(hotReload=True) sfs = itchat.search_friends() my = sfs @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING, PICTURE, RECORDING, ATTACHMENT, VIDEO]) def text_reply(msg): if msg['FromUserName'] == my['UserName']: if msg['Text'] == u'开启群聊': global_list.flag_i_group = 1 global_list.flag_i = 1 elif msg['Text'] == u'关闭群聊': global_list.flag_i_group = 0 global_list.flag_i = 1 elif msg['Text'] == u'开启私聊': global_list.flag_i_it = 1 global_list.flag_i = 1 elif msg['Text'] == u'关闭私聊': global_list.flag_i_it = 0 global_list.flag_i = 1 elif msg['Text'] == u'好友群发': global_list.flag_i_it_to_all = 1 global_list.flag_set_it = 1 elif msg['Text'] == u'群友群发': global_list.flag_i_group_to_all = 1 global_list.flag_set_group = 1 elif msg['Text'] == u'关闭群发': global_list.flag_i_it_to_all = 0 global_list.flag_i_group_to_all = 0 elif msg['Text'] == u'帮助': itchat.send(u'开启群聊:关闭群聊:开启私聊:开启私聊:好友群发:群友群发:复位(关闭所有功能)', msg['FromUserName']) elif msg['Text'] == u'复位': global_list.flag_i = 0 global_list.flag_i_it_to_all = 0 global_list.flag_i_group_to_all = 0 itchat.send('%s, %s' % (u'感谢使用', u'复位成功'), msg['FromUserName']) if global_list.flag_i_it_to_all == 1 and global_list.flag_set_it != 1: print u'好友群发' myt = itchat.get_friends(update=True) for myi in range(len(myt)): itchat.send('%s(%s), %s' % (myt[myi].get('NickName'), myt[myi].get('RemarkName'), msg['Text']), myt[myi].get('UserName')) if global_list.flag_i_group_to_all == 1 and global_list.flag_set_group != 1: print u'群友群发' chatrooms = itchat.get_chatrooms(update=True) for cr in range(len(chatrooms)): print cr, 'saiun', chatrooms[cr]['NickName'].encode("utf-8"), chatrooms[cr]['UserName'].encode("utf-8") itchat.send(u'@%s\u2005的群友们: %s' % (chatrooms[cr]['NickName'], msg['Text']), chatrooms[cr]['UserName']) global_list.flag_set_it = 0 # 防止第一次开启命令被群发出去 global_list.flag_set_group = 0 # 防止第一次开启命令被群发出去 rn = itchat.search_friends(userName=msg['FromUserName']).get('RemarkName') nn = itchat.search_friends(userName=msg['FromUserName']).get('NickName') if global_list.flag_i_it == 1 and global_list.flag_i == 1: if msg['Type'] in [PICTURE, RECORDING, ATTACHMENT, VIDEO]: msg['Text'](msg['FileName']) return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName']) else: itchat.send('%s(%s), %s' % (nn, rn, msg['Text']), msg['FromUserName']) @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING, PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat=True) def text_reply(msg): if global_list.flag_i_group == 1 and global_list.flag_i == 1: if msg['Type'] in [PICTURE, RECORDING, ATTACHMENT, VIDEO]: msg['Text'](msg['FileName']) return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName']) else: itchat.send(u'%s, %s' % (msg['ActualNickName'], msg['Content']), msg['FromUserName']) itchat.run()
caca9d12d8ba567dd7174f8f4b93b68a4fdd8989
[ "Python" ]
3
Python
ASaiun/wx_qq
3dd1f4f6f515e909ad753bd09a2217604e078379
edcc95ec08887bfa6ac2ed6597f5d07ba304650d
refs/heads/master
<repo_name>isaachaberman/DeepGoogol<file_sep>/hpc/eval/q_b21_t101010_eval.sbatch #!/bin/bash #SBATCH --job-name=qb21t101010 #SBATCH --nodes=1 #SBATCH --cpus-per-task=2 #SBATCH --mem=12GB #SBATCH --time=24:00:00 #SBATCH --output=slurm_q_b21_t101010_%j.out #Run.A PYTHONPATH=$PYTHONPATH:. python agent_eval.py \ --agent q_learn \ --agent_path agent_values/q_b21_t101010.pkl \ --lo 1 \ --hi 100 \ --n_idx 50 \ --n_games 50000 \ --n_print 5000 \ --delay 0 \<file_sep>/plot_utils.py import matplotlib.pyplot as plt def setDefault(figsize=(20, 10)): plt.style.use(['dark_background', 'bmh']) plt.rc('axes', facecolor='k') plt.rc('figure', facecolor='k') plt.rc('figure', figsize=figsize) def plotQValues(agent, value, n_states): keys = ["{}_{}".format(s, value) for s in range(n_states)] stops, swaps = [], [] for i, key in enumerate(keys): if (agent.Q[key][0] == 0) & (agent.Q[key][1] == 0): continue else: stops.append((i, agent.Q[key][0])) swaps.append((i, agent.Q[key][1])) plt.xlim(0, n_states+1) plt.scatter(*zip(*stops), cmap=plt.cm.Spectral, label="Stops") plt.scatter(*zip(*swaps), cmap=plt.cm.Spectral, label="Swaps") plt.ylabel("Q-value") plt.xlabel("State") plt.title("Q-value vs. State") plt.legend() plt.show()<file_sep>/writing/notes.txt Papers - Searching for the Next Best Mate (Todd) - Should I Stay or Should I Go? How the Human Brain Manages the Trade-off Between Exploitation and Exploration: (Cohen, McClure, Yu) - Don't Stop Til You Get Enough: Adaptive Information Sampling in a Visuomotor Estimation Task (Guerickis, Maloney, Juni) - The Value of Approaching Bad Things (Rich, Gureckis) - Information Sampling Behavior with Explicit Sampling Costs (Gureckis, Maloney, Juni) Game Parameters - Number of cards - Distribution of values - Range of values - Sampling with/out replacement - Search cost Overall Ideas - Transfer learning: Choose a subset of games, train agents on the training games and evaluate on unseen games - Apply search cost for better human comparison - "How far off are we if we stop at X%" - Are there flat maximas? Updated Suggestions (5/2) - After tuning, do transfer learning - Currently transfering less stringent -> more. Reverse it? - For human trials, use empirical evidence, not self-reporting - Where to agents tend to stop? How about humans? Are they undersampling to save on cognitive resources, as mentioned in <NAME>'s paper? Agents - Q-learning - SARSA - Deep Q-learning - Monte Carlo ======================================================================================= Transfer Learning Test Cases Default: 50 cards, range [1, 1000], uniform distribution, no replacement, search cost 0 Altering Number of Cards - Default -> 5 cards, range [1, 1000], uniform distribution, no replacement, search cost 0 - Default -> 51 cards, range [1, 1000], uniform distribution, no replacement, search cost 0 - Default -> 500 cards, range [1, 1000], uniform distribution, no replacement, search cost 0 Altering Range - Default -> 50 cards, range [1, 100], uniform distribution, no replacement, search cost 0 - Default -> 50 cards, range [1, 1001], uniform distribution, no replacement, search cost 0 - Default -> 50 cards, range [1, 10000], uniform distribution, no replacement, search cost 0 Altering Replacement - Default -> 50 cards, range [1, 1000], uniform distribution, with replacement, search cost 0 Altering Search Cost - Default -> 50 cards, range [1, 1000], uniform distribution, no replacement, search cost 1 Altering Distribution <file_sep>/hpc/train/mc_train.sbatch #!/bin/bash #SBATCH --job-name=mc_train #SBATCH --nodes=1 #SBATCH --cpus-per-task=2 #SBATCH --mem=12GB #SBATCH --time=24:00:00 #SBATCH --output=slurm_mc_train_%j.out #Run.A PYTHONPATH=$PYTHONPATH:. python mc_train.py \ --gamma 0.9 \ --epsilon 0.1 \ --eps_decay .00001 \ --s_cost 0 \ --q_key_fn bin \ --q_key_params 2_3 \ --v_fn vIdx \ --lo 1 \ --hi 1000 \ --n_idx 50 \ --replace False \ --reward_fn topN \ --reward 10_10_10 \ --n_episodes 100000 \ --n_print 10000 \ --delay 0 \ --curr_epoch 10000 \ --curr_params 0_0_1_minus \ --lo_eval 1 \ --hi_eval 1000 \ --n_idx_eval 50 \ --replace_eval False \ --reward_fn_eval scalar \ --reward_eval 1_1 \ --n_games_eval 10000 \ --n_print_eval 1000 \ --delay_eval 0 \ --file_path agents/mc_train.pkl <file_sep>/hpc/train/dq_train.sbatch #!/bin/bash #SBATCH --job-name=dqa_train #SBATCH --nodes=1 #SBATCH --gres=gpu:1 #SBATCH --cpus-per-task=4 #SBATCH --mem=96000 #SBATCH --time=2:00:00 #SBATCH --output=slurm_dqa_train_%j.out #Run.A PYTHONPATH=$PYTHONPATH:. python dqa_train.py \ --device cuda \ --net basic \ --net_params 2_128_0.0 \ --batch_size 256 \ --target_update 100 \ --optimizer rmsprop \ --loss huber \ --mem_size 1000 \ --p_to_s stateMax \ --gamma 0.9 \ --epsilon 0.1 \ --eps_decay .00001 \ --s_cost 0 \ --v_fn vIdx \ --lo 1 \ --hi 100000 \ --n_idx 50 \ --replace False \ --reward_fn topN \ --reward 10_10_11 \ --n_games 100000 \ --n_print 10000 \ --delay 0 \ --curr_epoch 10000 \ --curr_params 0_0_1_minus \ --lo_eval 1 \ --hi_eval 100000 \ --n_idx_eval 50 \ --replace_eval False \ --reward_fn_eval scalar \ --reward_eval 1_1 \ --n_games_eval 10000 \ --n_print_eval 1000 \ --delay_eval 0 \ --file_path agents/dqa_train_5 <file_sep>/README.md # DeepGoogol Final Project for Computational Cognitive Modeling (NYU PSYCH-GA 3405.002 / DS-GS 3001.005) Results: https://docs.google.com/spreadsheets/d/1pS1UTBt8W-3IH4qjOUHC0U4UOJvPaNY_J0-i7nCuKaY/edit?usp=sharing Report: https://www.overleaf.com/2521124919cxdbbnrkkwfn
a9a93f0a2dafc592bd3f3efa69670cfd0bcb0b95
[ "Markdown", "Python", "Text", "Shell" ]
6
Shell
isaachaberman/DeepGoogol
dda5744e0d9f09f45d043ae5f41e986b71e87be0
8de86a4d406e3e1d2fc6e5bfcb67155ddc7d6cbf
refs/heads/master
<repo_name>MosheBlumbergX/JenksTest<file_sep>/source.py import urllib2 import os username = 'testss' server = '@<IP>:' pathtop = '/auto/artifacts/' dir = os.listdir(pathtop) def versionname(): print "printing all paths of NimOS" for directory in dir: if directory.startswith('package-dev_rel'): print directory pathinput = raw_input("Waiting infput:") global path path = "/auto/artifacts/" + pathinput + "/latest-successful" def packagenumber(): for file in os.listdir(path): if file.endswith("-opt.manifest"): firstcut = file.replace('xx-', '') global package_name package_name = firstcut.replace('-opt.manifest', '') print package_name def copyfile(): update = 'scp ' + path + '/*-opt.update ' + username + server + '/var/www/html/software_updates/' os.system(update) manifest = 'scp ' + path + '/xx*-opt.manifest ' + username + server + '/tftpboot/boot/manifest-' + package_name os.system(manifest) initrd = 'scp ' + path + '/usb_install-opt/initrd.img ' + username + server + '/tftpboot/boot/initrd.img-' + package_name os.system(initrd) vmlinuz = 'scp ' + path + '/usb_install-opt/vmlinuz*-opt ' + username + server + '/tftpboot/boot/vmlinuz-' + package_name os.system(vmlinuz) #print update #print manifest #print initrd #print vmlinuz if __name__ == "__main__": versionname() packagenumber() copyfile()<file_sep>/README.md # JenksTest # second line
9fd793aaa72716c2c89a05eb4b077a49b25a57a1
[ "Markdown", "Python" ]
2
Python
MosheBlumbergX/JenksTest
a699ecb700309705f32873d5da8adebc064fba07
a2495af0363c6bda122ec6b1222a6bc2a38b2023
refs/heads/master
<file_sep>#include "stm32f10x.h" static void NVIC_Config(void){ NVIC_InitTypeDef NVIC_Struct; NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); NVIC_Struct.NVIC_IRQChannel = TIM1_CC_IRQn; NVIC_Struct.NVIC_IRQChannelPreemptionPriority = 1; NVIC_Struct.NVIC_IRQChannelSubPriority = 1; NVIC_Struct.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_Struct); } void TIM1_CH1_Config(void){ NVIC_Config(); // GPIO_InitTypeDef GPIO_PA8_Struct; // RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); // GPIO_PA8_Struct.GPIO_Pin = GPIO_Pin_8; // GPIO_PA8_Struct.GPIO_Mode = GPIO_Mode_IN_FLOATING; // GPIO_PA8_Struct.GPIO_Speed = GPIO_Speed_50MHz; // GPIO_Init(GPIOA,&GPIO_PA8_Struct); TIM_TimeBaseInitTypeDef TIM1_CH1_Struct; RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE); TIM1_CH1_Struct.TIM_Period = 0XFFFF-1; TIM1_CH1_Struct.TIM_Prescaler = 71; TIM1_CH1_Struct.TIM_ClockDivision = TIM_CKD_DIV1; TIM1_CH1_Struct.TIM_CounterMode = TIM_CounterMode_Up; TIM1_CH1_Struct.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM1,&TIM1_CH1_Struct); TIM_ICInitTypeDef TIM1_CH1_IC_Struct; TIM1_CH1_IC_Struct.TIM_Channel = TIM_Channel_1; TIM1_CH1_IC_Struct.TIM_ICPolarity = TIM_ICPolarity_Rising; TIM1_CH1_IC_Struct.TIM_ICSelection = TIM_ICSelection_DirectTI; TIM1_CH1_IC_Struct.TIM_ICPrescaler = TIM_ICPSC_DIV1; TIM1_CH1_IC_Struct.TIM_ICFilter = 0; TIM_PWMIConfig(TIM1,&TIM1_CH1_IC_Struct); TIM_SelectInputTrigger(TIM1,TIM_TS_TI1FP1); TIM_SelectSlaveMode(TIM1,TIM_SlaveMode_Reset); TIM_SelectMasterSlaveMode(TIM1,TIM_MasterSlaveMode_Enable); TIM_ITConfig(TIM1,TIM_IT_CC1,ENABLE); TIM_ClearITPendingBit(TIM1,TIM_IT_CC1); TIM_Cmd(TIM1,ENABLE); } <file_sep>#include <stdio.h> #include "stm32f10x.h" #include "usart.h" #include "tim1_ch1.h" #include "tim2_ch4.h" unsigned int Time = 0; void delay(unsigned int t){ while(t--); } int main(void){ TIM_CH4_Config(); TIM1_CH1_Config(); USART_1_Config(); printf("\rbull shit\n"); while(1){ TIM2->CCR4 = Time; if(++Time == 1000){Time = 0;} delay(0X1FFFF); } } <file_sep>#ifndef _TIM1_CH1_H_ #define _TIM1_CH1_H_ void TIM1_CH1_Config(void); #endif <file_sep>#ifndef _TIM2_CH4_H_ #define _TIM2_CH4_H_ void TIM_CH4_Config(void); #endif <file_sep># STM32-TIM-DetectPWM 后期补充目前水平不够 ```C GPIO_InitTypeDef GPIO_PA3_Struct; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); GPIO_PA3_Struct.GPIO_Pin = GPIO_Pin_3; GPIO_PA3_Struct.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_PA3_Struct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA,&GPIO_PA3_Struct); TIM_TimeBaseInitTypeDef TIM2_CH4_Struct; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); TIM2_CH4_Struct.TIM_Period = 999; TIM2_CH4_Struct.TIM_Prescaler = 71; TIM2_CH4_Struct.TIM_ClockDivision = TIM_CKD_DIV1; TIM2_CH4_Struct.TIM_CounterMode = TIM_CounterMode_Up; TIM2_CH4_Struct.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM2,&TIM2_CH4_Struct); TIM_OCInitTypeDef TIM2_CH4_OC_Struct; TIM2_CH4_OC_Struct.TIM_OCMode = TIM_OCMode_PWM1; TIM2_CH4_OC_Struct.TIM_OutputState = TIM_OutputState_Enable; TIM2_CH4_OC_Struct.TIM_Pulse = 800; TIM2_CH4_OC_Struct.TIM_OCPolarity = TIM_OCPolarity_High; TIM2_CH4_OC_Struct.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OC4Init(TIM2,&TIM2_CH4_OC_Struct); TIM_OC4PreloadConfig(TIM2,TIM_OCPreload_Enable); TIM_Cmd(TIM2,ENABLE); TIM_CtrlPWMOutputs(TIM2,ENABLE); ``` ```C #include "stm32f10x.h" static void NVIC_Config(void){ NVIC_InitTypeDef NVIC_Struct; NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); NVIC_Struct.NVIC_IRQChannel = TIM1_CC_IRQn; NVIC_Struct.NVIC_IRQChannelPreemptionPriority = 1; NVIC_Struct.NVIC_IRQChannelSubPriority = 1; NVIC_Struct.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_Struct); } void TIM1_CH1_Config(void){ NVIC_Config(); // GPIO_InitTypeDef GPIO_PA8_Struct; // RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); // GPIO_PA8_Struct.GPIO_Pin = GPIO_Pin_8; // GPIO_PA8_Struct.GPIO_Mode = GPIO_Mode_IN_FLOATING; // GPIO_PA8_Struct.GPIO_Speed = GPIO_Speed_50MHz; // GPIO_Init(GPIOA,&GPIO_PA8_Struct); TIM_TimeBaseInitTypeDef TIM1_CH1_Struct; RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE); TIM1_CH1_Struct.TIM_Period = 0XFFFF-1; TIM1_CH1_Struct.TIM_Prescaler = 71; TIM1_CH1_Struct.TIM_ClockDivision = TIM_CKD_DIV1; TIM1_CH1_Struct.TIM_CounterMode = TIM_CounterMode_Up; TIM1_CH1_Struct.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM1,&TIM1_CH1_Struct); TIM_ICInitTypeDef TIM1_CH1_IC_Struct; TIM1_CH1_IC_Struct.TIM_Channel = TIM_Channel_1; TIM1_CH1_IC_Struct.TIM_ICPolarity = TIM_ICPolarity_Rising; TIM1_CH1_IC_Struct.TIM_ICSelection = TIM_ICSelection_DirectTI; TIM1_CH1_IC_Struct.TIM_ICPrescaler = TIM_ICPSC_DIV1; TIM1_CH1_IC_Struct.TIM_ICFilter = 0; TIM_PWMIConfig(TIM1,&TIM1_CH1_IC_Struct); TIM_SelectInputTrigger(TIM1,TIM_TS_TI1FP1); TIM_SelectSlaveMode(TIM1,TIM_SlaveMode_Reset); TIM_SelectMasterSlaveMode(TIM1,TIM_MasterSlaveMode_Enable); TIM_ITConfig(TIM1,TIM_IT_CC1,ENABLE); TIM_ClearITPendingBit(TIM1,TIM_IT_CC1); TIM_Cmd(TIM1,ENABLE); } ``` <file_sep>#include <stdio.h> #include "stm32f10x.h" void USART_1_Config(void){ USART_InitTypeDef USART_1_Sturct; GPIO_InitTypeDef USART_1_GPIO_Sturct; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); USART_1_GPIO_Sturct.GPIO_Pin = GPIO_Pin_9; USART_1_GPIO_Sturct.GPIO_Mode = GPIO_Mode_AF_PP; USART_1_GPIO_Sturct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA,&USART_1_GPIO_Sturct); USART_1_GPIO_Sturct.GPIO_Pin = GPIO_Pin_10; USART_1_GPIO_Sturct.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA,&USART_1_GPIO_Sturct); RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE); USART_1_Sturct.USART_BaudRate = 115200; USART_1_Sturct.USART_WordLength = USART_WordLength_8b; USART_1_Sturct.USART_StopBits = USART_StopBits_1; USART_1_Sturct.USART_Parity = USART_Parity_No; USART_1_Sturct.USART_Mode = USART_Mode_Rx|USART_Mode_Tx; USART_1_Sturct.USART_HardwareFlowControl = 0; USART_Init(USART1,&USART_1_Sturct); USART_Cmd(USART1,ENABLE); } void Sendbit(USART_TypeDef* USARTx,unsigned char data){ USART_SendData(USARTx,data); while(USART_GetFlagStatus(USARTx,USART_FLAG_TXE) == RESET); } void SendString(USART_TypeDef* USARTx,unsigned char* data){ do{ USART_SendData(USARTx,*data); }while(*(++data) != '\0'); while(USART_GetFlagStatus(USARTx,USART_FLAG_TC) == RESET); } int fputc(int c, FILE * s){ USART_SendData(USART1,(unsigned char)c); while(USART_GetFlagStatus(USART1,USART_FLAG_TC) == RESET); return c; } <file_sep>#include "stm32f10x.h" void TIM_CH4_Config(void){ // GPIO_InitTypeDef GPIO_PA3_Struct; // // RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); // GPIO_PA3_Struct.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_5; // GPIO_PA3_Struct.GPIO_Mode = GPIO_Mode_AF_PP; // GPIO_PA3_Struct.GPIO_Speed = GPIO_Speed_50MHz; // GPIO_Init(GPIOB,&GPIO_PA3_Struct); // // TIM_TimeBaseInitTypeDef TIM2_CH4_Struct; // RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); // TIM2_CH4_Struct.TIM_Period = 999; // TIM2_CH4_Struct.TIM_Prescaler = 71; // TIM2_CH4_Struct.TIM_ClockDivision = TIM_CKD_DIV1; // TIM2_CH4_Struct.TIM_CounterMode = TIM_CounterMode_Up; // TIM2_CH4_Struct.TIM_RepetitionCounter = 0; // TIM_TimeBaseInit(TIM3,&TIM2_CH4_Struct); // // TIM_OCInitTypeDef TIM2_CH4_OC_Struct; // TIM2_CH4_OC_Struct.TIM_OCMode = TIM_OCMode_PWM1; // TIM2_CH4_OC_Struct.TIM_OutputState = TIM_OutputState_Enable; // TIM2_CH4_OC_Struct.TIM_Pulse = 1; // TIM2_CH4_OC_Struct.TIM_OCPolarity = TIM_OCPolarity_High; // TIM2_CH4_OC_Struct.TIM_OCIdleState = TIM_OCIdleState_Set; // // TIM_OC2Init(TIM3,&TIM2_CH4_OC_Struct); // TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable); // // TIM_OC3Init(TIM3,&TIM2_CH4_OC_Struct); // TIM_OC3PreloadConfig(TIM3,TIM_OCPreload_Enable); // // TIM_OC4Init(TIM3,&TIM2_CH4_OC_Struct); // TIM_OC4PreloadConfig(TIM3,TIM_OCPreload_Enable); // GPIO_InitTypeDef GPIO_PA3_Struct; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); GPIO_PA3_Struct.GPIO_Pin = GPIO_Pin_3; GPIO_PA3_Struct.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_PA3_Struct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA,&GPIO_PA3_Struct); TIM_TimeBaseInitTypeDef TIM2_CH4_Struct; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); TIM2_CH4_Struct.TIM_Period = 999; TIM2_CH4_Struct.TIM_Prescaler = 71; TIM2_CH4_Struct.TIM_ClockDivision = TIM_CKD_DIV1; TIM2_CH4_Struct.TIM_CounterMode = TIM_CounterMode_Up; TIM2_CH4_Struct.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM2,&TIM2_CH4_Struct); TIM_OCInitTypeDef TIM2_CH4_OC_Struct; TIM2_CH4_OC_Struct.TIM_OCMode = TIM_OCMode_PWM1; TIM2_CH4_OC_Struct.TIM_OutputState = TIM_OutputState_Enable; TIM2_CH4_OC_Struct.TIM_Pulse = 800; TIM2_CH4_OC_Struct.TIM_OCPolarity = TIM_OCPolarity_High; TIM2_CH4_OC_Struct.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OC4Init(TIM2,&TIM2_CH4_OC_Struct); TIM_OC4PreloadConfig(TIM2,TIM_OCPreload_Enable); TIM_Cmd(TIM2,ENABLE); TIM_CtrlPWMOutputs(TIM2,ENABLE); }
2c56b2e44e6054d4c5efe7daa9407b08962cb22b
[ "Markdown", "C" ]
7
C
Sean-Huan/STM32-TIM-DetectPWM
bbffb9da69137817b97f8348ce9dafb5911de0ae
0ad3012cc9fdbf311ab249f5444843dee96b869a
refs/heads/main
<repo_name>z0mi3ie/nightnick<file_sep>/src/components/NightNickContainer.js import React from "react" import LinksList from "./LinksList" import Header from "./Header" import bubble1 from "../images/tiger_bubble_1.png" class NightNickContainer extends React.Component { state = { links: [ { id: 1, title: "visit my shop!", link: "http://www.etsy.com/shop/nightnick", image: "", priority: 1, }, { id: 2, title: "request for custom pet kitty", link: "https://www.etsy.com/listing/994750181/custom-pet-cat-figurine-customizable?ref=shop_home_feat_1&ltclid=", image: "", priority: 0, }, { id: 3, title: "custom pocket pal woodland critter", link: "https://www.etsy.com/listing/1012764435/customize-your-own-pocket-pal-woodland?ref=shop_home_active_8&ltclid=", image: "", priority: 0, }, { id: 4, title: "instagram", link: "https://www.instagram.com/nightnick_?ltclid=", image: "", priority: 0, }, { id: 5, title: "tiktok", link: "https://vm.tiktok.com/ZMJwQaJDB/?ltclid=", image: "", priority: 0, }, { id: 6, title: "amazon wish list", link: "https://www.amazon.com/hz/wishlist/ls/2U9SCZUP9UTYI?ref_=wl_share&ltclid=", image: "", priority: 0, }, ] } render() { return ( <div className="container"> <div className="inner"> <Header /> <LinksList links={this.state.links} /> </div> <div id="background-wrap"> <div className="bubble x1"><img className="" src={bubble1} alt="float tiger" /></div> <div className="bubble x2"><img className="" src={bubble1} alt="float tiger" /></div> <div className="bubble x3"><img className="" src={bubble1} alt="float tiger" /></div> <div className="bubble x4"><img className="" src={bubble1} alt="float tiger" /></div> <div className="bubble x5"><img className="" src={bubble1} alt="float tiger" /></div> <div className="bubble x6"><img className="" src={bubble1} alt="float tiger" /></div> <div className="bubble x7"><img className="" src={bubble1} alt="float tiger" /></div> <div className="bubble x8"><img className="" src={bubble1} alt="float tiger" /></div> <div className="bubble x9"><img className="" src={bubble1} alt="float tiger" /></div> <div className="bubble x10"><img className="" src={bubble1} alt="float tiger" /></div> </div> </div> ) } } export default NightNickContainer<file_sep>/src/components/Header.js import React from "react" import logo from "../images/tiger_logo.jpg" import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { fab } from '@fortawesome/free-brands-svg-icons' import { library } from '@fortawesome/fontawesome-svg-core' library.add(fab) const Header = () => { return ( <header> <div> <img className="animate__animated animate__bounce logoimg" src={logo} alt="tiger figure" /> </div> <div> <h1 className="logotext">nightnick</h1> </div> <div> <h2 className="medialinks"> <a className="iconlink" href="http://www.etsy.com/shop/nightnick"><FontAwesomeIcon className="fa-fw" icon={['fab', 'etsy']} /></a> <a className="iconlink" href="https://www.instagram.com/nightnick_?ltclid="><FontAwesomeIcon className="fa-fw" icon={['fab', 'instagram']} /></a> <a className="iconlink" href="https://vm.tiktok.com/ZMJwQaJDB/?ltclid="><FontAwesomeIcon className="fa-fw" icon={['fab', 'tiktok']} /></a> </h2> </div> </header> ) } export default Header<file_sep>/src/components/LinksItem.js import React from "react" class LinksItem extends React.Component { render() { if (this.props.link.priority === 1) { console.log("WE HAVE PRIORITY ONE for " + this.props.link.link) return ( <li><a className="linklistitem-high animate__animated animate__swing" href={this.props.link.link}>{this.props.link.title}</a></li> ) } return ( <li><a className="linklistitem" href={this.props.link.link}>{this.props.link.title}</a></li> ) } } export default LinksItem<file_sep>/src/index.js import React from "react" import ReactDOM from "react-dom" import "animate.css" // Component import NightNickContainer from "./components/NightNickContainer" // Stylesheet import "./styles/App.css" ReactDOM.render( <React.StrictMode> <NightNickContainer /> </React.StrictMode>, document.getElementById("root") )
2e6eb9a7ad2285e16b581cdd31c2fbe05af3b7a8
[ "JavaScript" ]
4
JavaScript
z0mi3ie/nightnick
c99c4ffc764caf8bab9ab5ff5bc815ce687cb593
0ce1b90366997549dc0331aad79bfc5f9485491e
refs/heads/master
<file_sep>class CommentsController < ApplicationController before_action :require_user, only: [:new, :create, :edit, :update] # or except: [:index, :show] def create @post = Post.find(params[:post_id]) @comment = Comment.new(comment_params) @comment.post = @post @comment.user = current_user if @comment.save flash[:notice] = 'You added a comment' redirect_to post_path(@post) else render 'posts/show' end end private def comment_params #only allow the description parameter params.require(:comment).permit(:description) end end<file_sep>mypostit ======== Tealeaf Postit App <file_sep>class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception # allows methods to be available to items other than just controllers helper_method :current_user, :logged_in? #QUESTION - What is the difference having these here or in application_helper? def current_user # if there's authenticated user, return the user object #checks if this instance variable exists, if not, makes the db call...called Memoization @current_user ||= User.find(session[:user_id]) if session[:user_id] end def logged_in? # !! turns anything into a boolean !!current_user end def require_user if !logged_in? flash[:error] = "Must be logged in." redirect_to root_path end end end <file_sep>class RemoveCommentsColumn < ActiveRecord::Migration def change remove_column :comments, :comments end end <file_sep>class PostsController < ApplicationController before_action :set_post, only: [:show, :edit, :update] before_action :require_user, only: [:new, :create, :edit, :update] # or except: [:index, :show] def index @posts = Post.all end def show #@post = Post.find(params[:id]) - replaced with the before_action #required to link comments to a post @comment = Comment.new end def new @post = Post.new end def create @post = Post.new(post_params) @post.user = current_user if @post.save flash[:notice] = 'You created a post' redirect_to root_path else render :new end end def edit #@post = Post.find(params[:id]) - replaced with the before_action end def update #@post = Post.find(params[:id]) - replaced with the before_action # example @post.title = params[:post][:title] if @post.update(post_params) flash[:notice] = 'You updated a post' redirect_to post_path(@post) else render :edit end end def set_post @post = Post.find(params[:id]) end def post_params #params.require(:post).permit! - permits everything or be more specific like below params.require(:post).permit(:title, :url, :description, category_ids: []) end end <file_sep>class Post < ActiveRecord::Base BADWORDS = ['cheese', 'poof'] belongs_to :user has_many :comments has_many :post_categories has_many :categories, through: :post_categories validates :title, presence: true, length: {minimum: 5} validate :bad_words def bad_words #binding.pry title.split(' ').each do |word| if BADWORDS.include?(word) errors.add(:base, "Can't contain bad words") break end end end end<file_sep>class CategoriesController < ApplicationController before_action :require_user, only: [:new, :create, :edit, :update] # or except: [:index, :show] def new @category = Category.new end def create @category = Category.new(params.require(:category).permit(:name)) if @category.save flash[:notice] = "You created a category" redirect_to root_path else render :new end end def show end end<file_sep>module ApplicationHelper def fix_url(url) url.starts_with?("http") ? url : "http://#{url}" end def formated_date(dt) dt.strftime("%m/%d/%Y %1:%M%P %Z") #01/01/2013 9:05pm end end
4befb6ea6994beb80bab71ad027373dbb12304c8
[ "Markdown", "Ruby" ]
8
Ruby
jasonrobinett/mypostit
1389c6845e38ea7919ba96882c3e3aeb4a663c9d
9ec7209d5d5921d38411b32097b987813b641b60
refs/heads/master
<file_sep>const express = require('express'); const app = express(); const notebooks = require('./routes/notebooks'); const home = require('./routes/home'); const mongoose = require('mongoose'); app.use(express.json()); app.use('/api/notebooks', notebooks); app.use('/', home); mongoose.connect('mongodb://localhost/notebooks', {useNewUrlParser: true}) .then(() => console.log("Connected to MongoDB...")) .catch(err => console.error("Could not connect to MongoDB...", err)); // Schema will soon appear const port = process.env.PORT || 3000; app.listen(port, () => console.log(`Listening on port ${port} ...`));<file_sep>const express = require('express'); const router = express.Router(); const notebooks = [ {id: 1, name: "Lenovo Ideapad 700"}, {id: 2, name: "Thinkpad X220"} ] router.get('/', (req, res) => { res.send(notebooks); }); router.get('/:id', (req, res) => { const notebook = notebooks.find(n => n.id === parseInt(req.params.id)); if(!notebook) return res.status(404).send("The notebook with given ID was not found"); res.send(notebook); }); module.exports = router;
63d55780915a92dc6d36d5c8418a1137a9dec2d8
[ "JavaScript" ]
2
JavaScript
chlodnywiatr/TAUtology
d3af1a8387a465222b6b47b2bde19aff0ff6d978
8128b6d9f6bd263975391f921e9836d54a183ab9
refs/heads/master
<file_sep>#!/bin/bash -x echo "Enter Number" read num for (( i=2; i<=num/2; i++ )) do if [ $((num%i)) -eq 0 ] then echo "$num is not a prime number" fi echo "$num is a prime number" done <file_sep>#!/bin/bash -x for files in 'access.log.1 ls -l /etc/passwd echo "access.log.1" <file_sep>#!/bin/bash -x isPresent=100 randomCheck=$((RANDOM%5+100)); if [ $isPresent -eq $randomCheck ]; then min else max="$ispresent"; fi <file_sep>#!/bin/bash -x read -p " Enter Date" read -p "Enter Month" if (( ($Month <= 6 && $date <= 20) && (($Month >= 3 && $date <= 20)) )) then echo $Month $date "True"; else echo "False"; fi <file_sep>#!/bin/bash -x ft=feet 1ft=12 echo "$(42/12)" <file_sep>#!/bin/bash -x echo 'Enter the width of the rectangle' read W echo 'Enter the length of the rectangle' read L echo "The area of the rectangle is $((W * L))" METERS= echo $"["$((W * L))" * 0.3048]" echo 'METERS' <file_sep>#!/bin/bash -x isPresent=100 randomCheck=$((RANDOM%5+100)); if [ $isPresent -eq $randomCheck ]; then min="$isPresent"; else max="$ispresent"; fi <file_sep>#!/bin/bash -x for files in current directory echo "folder exist in current directory" if [ -d $foldername ] then rm -R $foldername else echo "folder already exists"; fi done <file_sep>#!/bin/bash -x ispresent=2021 randonCheck=$((RANDOM%4 RANDOM%100 RANDOM%400)); if [ $ispresent -eq $randomCheck ]; then echo "leap year"; else "not leap year"; fi <file_sep>#!/bin/bash -x DAYOFWEEK=$(date+ "%a") echo DAYOFWEEK if [ "$DAYOFWEEK"==="7"]; then echo YES else echo NO fi <file_sep>#!/bin/bash -x isPresent=1; randomCheck=$((RANDOM%7)); if [ $isPresent -eq $randomCheck ]; fi <file_sep>#!/bin/bash -x declare -A number number=$(( ( RANDOM % 5 + 1 ) )) number=$(( RANDOM%6 )) <file_sep>#!/bin/bash -x echo $(( RANDOM %5 + 10 )) sum=$(( RANDOM %5 + 10 )) avg=$(( sum/5 )) <file_sep>#!/bin/bash -x declare -a indexed_array read -p "enter element of an array:" value indexed_array[0]="$value" echo ${indexed_array[0]} <file_sep>#!/bin/bash -x count=1 while [ n>0 && (n & (n-1)) ==0 ] do <file_sep> #!/bin/bash -x read -p "Enter a number" if [ "$character" = "1" ]; echo "one" fi
7d8c575f4e48f0b55844ecbaf138504ec35459f5
[ "Shell" ]
16
Shell
sami687/Terminalcommands
9fcf904192b6306b11ac33d9c78839bb98a0c010
9df089b2c0ff41e58179faffe3475cfb48219e16
refs/heads/master
<repo_name>Build-Week-Spotify-Song-Suggester-5/Data-Science<file_sep>/app/app.py # imported libraries from flask import Flask, jsonify import sqlite3 import pandas as pd from flask_sqlalchemy import SQLAlchemy from sqlalchemy import create_engine import numpy as np from sklearn import preprocessing # for category encoder from sklearn.neighbors import NearestNeighbors from sklearn.model_selection import train_test_split from typing import List, Tuple DB = SQLAlchemy() #Tell SQLAlchemy what the table name is and if there's any table-specific arguments it should know about class Songs(DB.Model): __tablename__ = "Songs" id = DB.Column(DB.BigInteger, primary_key=True) genre = DB.Column(DB.String(50)) artist_name = DB.Column(DB.String(50)) track_name = DB.Column(DB.String(100)) track_id = DB.Column(DB.String(50)) popularity = DB.Column(DB.Integer) acousticness = DB.Column(DB.Float) danceability = DB.Column(DB.Float) duration_ms = DB.Column(DB.Integer) energy = DB.Column(DB.Float) instrumentalness = DB.Column(DB.Float) key = DB.Column(DB.Integer) liveness = DB.Column(DB.Float) loudness = DB.Column(DB.Float) mode = DB.Column(DB.Integer) speechiness = DB.Column(DB.Float) tempo = DB.Column(DB.Float) time_signature = DB.Column(DB.Integer) valence = DB.Column(DB.Float) def __repr__(self): return '<Song {}>'.format(self.track_name) ''' This calls to the __init__ function to initialize the flask app. Upon instantiation, the app populates the database and runs the nearest neighbors Machine Learning model. ''' def create_app(): app = Flask(__name__) # Makes the database persist on Heroku app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://Spotify_Songs.db" # Connects and populates the database with the given structure of class Songs engine = create_engine('sqlite:///Spotify_Songs.db') Songs.metadata.create_all(engine) file_name = 'https://raw.githubusercontent.com/msnyd/spotify_song_suggestor/master/app/most_popular_spotify_songs.csv' df = pd.read_csv(file_name) db = df.to_sql(con=engine, index_label='id', name=Songs.__tablename__, if_exists='replace') ''' This pre_process function takes in a pandas dataframe and runs it through encoding code to standardize certain features, it also onehotencodes the dataframe to make it all numeric. ''' def pre_process(df): time_sig_encoding = {'0/4': 0, '1/4': 1, '3/4': 3, '4/4': 4, '5/4': 5} key_encoding = {'A': 0, 'A#': 1, 'B': 2, 'C': 3, 'C#': 4, 'D': 5, 'D#': 6, 'E': 7, 'F': 8, 'F#': 9, 'G': 10, 'G#': 11} mode_encoding = {'Major': 0, 'Minor': 1} df['key'] = df['key'].map(key_encoding) df['time_signature'] = df['time_signature'].map(time_sig_encoding) df['mode'] = df['mode'].map(mode_encoding) # helper function to one hot encode genre def encode_and_bind(original_dataframe, feature_to_encode): dummies = pd.get_dummies(original_dataframe[[feature_to_encode]]) res = pd.concat([original_dataframe, dummies], axis=1) return(res) df = encode_and_bind(df, 'genre') return df ''' This will run the nearest neighbors model when we instantiate the app. ''' processed_df = pre_process(df) neigh = NearestNeighbors(n_neighbors=11) features = list(processed_df.columns[4:]) X = processed_df[features].values neigh.fit(X) ''' Takes in a dataframe, a feature set array and a song ID and returns a list of tuples of Artist Name and Track Name ''' def closest_ten(df: pd.DataFrame, X_array: np.ndarray, song_id: int) -> List[Tuple]: song = df.iloc[song_id] X_song = X[song_id] _, neighbors = neigh.kneighbors(np.array([X_song])) return neighbors[0][1:] # accepts the cursor and the row as a tuple and returns a dictionary result and you can object column by name def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d # Landing Page @app.route('/') def hello_world(): return "Welcome to our Spotify Song Suggester API!" ''' Main API route that takes in a Track ID sent from the user and pairs it with a unique track_id from the database and returns the closest songs from our Machine Learning model. ''' @app.route('/track/<track_id>', methods=['GET']) def track(track_id): track_id = int(track_id) conn = sqlite3.connect('Spotify_Songs.db') conn.row_factory = dict_factory curs = conn.cursor() songlist = [] song_recs = closest_ten(df, X, track_id) for idx in song_recs: song = curs.execute( f'SELECT DISTINCT * FROM Songs WHERE id=={idx};').fetchone() songlist.append(song) return jsonify(songlist) return app<file_sep>/README.md # Data-Science #### General Guide - [Lambda School Project Explanation, Guidelines, and Team Roles](https://airtable.com/shrtA1m4LFJAnjvqS/tblI02wuarVEYWVSv/viw2L09271lKsRt5x/recsd9pTmzGNlk2re?blocks=hide) - [Song Suggester Architecture](https://www.notion.so/Spotify-Song-Suggester-0fd8e64d69c54e03a7884eec81885dbc) - [Team Github](https://trello.com/c/i2p8e44L/5-ml-engineers) - [A Guide to what other roles within our team are doing](https://www.notion.so/Working-Effectively-Across-Tracks-7be8d0eb25a14418b1e2a93ddde1d561) #### Machine Learning Engineer Links - [Kaggle Set](https://www.kaggle.com/tomigelo/spotify-audio-features) - [Data Science Rubric](https://www.notion.so/Data-Science-Unit-4-814c17e421334cd8b3d2867d1d49f541) ### Project Details #### *Background* > Create an algorithm to recommend songs based on user input songs. In production, Spotify uses a mixture of Deep Learning, Collaborative Filtering, persistent user 'taste profiles', frequent itemset mining, and some sort of neighbors algorithm based on taste profiles, time listened, etc. Competitor Pandora has hired musiciologists to work on their 'music genome project' which is probably more of a feature engineering thing using domain experts. #### *We chose this model because:* We ended up using only Nearest Neighbors. Couldn't find a data set to do CF on. Feature engineering included scraping genres, predicting languages of the track_names, and sentiment analysis of the track names. While we found several research papers on using Neural Networks, LSTMs on Nearest Neighbors, we were unable to find source code or pre-trained models or create one in the time alotted. Research into siamese network matching algorithms looks more promising as they train much faster but we were also unable to create or find a ready to use model in the time alotted. Also Siamese networks scale much better than Nearest Neighbors as the dataset increases in size. Read more [here: K-Nearest Neighbors](https://towardsdatascience.com/machine-learning-basics-with-the-k-nearest-neighbors-algorithm-6a6e71d01761) & [here: K-Nearest Neighbors Documentation](https://scikit-learn.org/stable/modules/neighbors.html) #### *Our Goal:* > **Pitch**: Build an app to enable users to browse and visualize audio features of over 116k spotify songs. MVP: User can search for a specific song and see its audio features displayed in a visually appealing way. The app also identifies songs with similar audio features. DS: 1. Build a model to recommend songs based on similarity to user input (I like song x, here are n songs like it based on these similar features) 2. Create visualizations using song data to highlight similarities and differences between recommendations. #### Further Reading & Resources: https://developer.spotify.com/documentation/web-api/reference/tracks/get-audio-features/ https://www.reddit.com/r/MachineLearning/comments/2f8jff/using_neural_networks_for_nearest_neighbor/ https://towardsdatascience.com/how-to-build-a-simple-song-recommender-296fcbc8c85 https://medium.com/hulu-tech-blog/applying-deep-learning-to-collaborative-filtering-how-hulu-builds-its-industry-leading-3b10a4ed7470 https://arxiv.org/pdf/1605.09477.pdf https://medium.com/@b.terryjack/nlp-pre-trained-sentiment-analysis-1eb52a9d742c https://arxiv.org/pdf/1810.12575.pdf https://blogs.cornell.edu/info4220/2016/03/18/spotify-recommendation-matching-algorithm/ http://www.mmds.org/ Future Teams are welcome to build upon our data set which includes genres, predicted track languages here: https://raw.githubusercontent.com/Build-Week-Spotify-Song-Suggester-5/Data-Science/master/spotify_unique_track_id_lang.csv The script to predict sentiment is still running and will be done soon(TM) but maybe your machines are faster and you can run it here: https://github.com/Build-Week-Spotify-Song-Suggester-5/Data-Science/blob/master/Sentiment_Feature_Script.ipynb Note that it only runs sentiment analysis on the top 75000 songs by popularity because of database size constraints for Flask.
0bdcf0e5c5b678b4fb8f78c929b8a0b17c3da5e7
[ "Markdown", "Python" ]
2
Python
Build-Week-Spotify-Song-Suggester-5/Data-Science
45403f2fafafdfcb0d2cc3de26d6583d76db5195
3a8d29423f970cc8beb92ba5fd662ea96e8dde65
refs/heads/master
<file_sep>var JSUTILS = {} function trace(val) { console.log(val); }<file_sep>/** * ShaderLoader.js v1.0 * An asynchronous shader loader for WebGL using AJAX with jQuery. * * Copyright (c) 2013 - 2014 <NAME> / http://andre-cruz.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Dependencies: jQuery * Documentation: https://github.com/codecruzer/webgl-shader-loader-js */ var SHADER_LOADER = SHADER_LOADER || {}; /** * Loads all shaders from an external file that are included in the * DOM as script elements. See comments in ShaderLoader.js for documentation. * * @param {Function} Callback invoked when all shaders have loaded with signature * function (data) {} */ SHADER_LOADER.load = function (onShadersLoaded) { /** * Checks if there are any shaders still pending to load. * If there are none remaining, then invoke the onShadersLoaded * callback. * */ var checkForRemaining = function () { if (unloadedRemaining <= 0 && onShadersLoaded) { onShadersLoaded(loadedShaders); } } /** * Loads an external shader file asynchronously using AJAX * * @param {Object} The shader script tag from the DOM * @param {String} The type of shader [vertex|fragment] */ var loadShaderFile = function (shaderElement, type) { /** * Processes a shader that comes back from * the AJAX and stores it in the Shaders * Object for later on * * @param {Object} The jQuery XHR object * @param {String} The response text, e.g. success, error */ var onComplete = function onComplete(jqXHR, textStatus) { --unloadedRemaining; if (!loadedShaders[name]) { loadedShaders[name] = { vertex: "", fragment: "" }; } loadedShaders[name][type] = jqXHR.responseText; checkForRemaining(); } var element = $(shaderElement); var url = element.data("src"); var name = element.data("name"); $.ajax( { url: url, dataType: "text", context: { name: name, type: type }, complete: onComplete } ); } /************************ * Load the shaders here * ************************/ var loadedShaders = {}; // Get all of the shaders from the DOM var vertexShaders = $('script[type="x-shader/x-vertex"]'); var fragmentShaders = $('script[type="x-shader/x-fragment"]'); var unloadedRemaining = vertexShaders.length + fragmentShaders.length; // Load vertex shaders var shader; var i, shaderCount; for (i = 0, shaderCount = vertexShaders.length; i < shaderCount; ++i) { shader = vertexShaders[i]; loadShaderFile(shader, "vertex"); } // Load fragment shaders for (i = 0, shaderCount = fragmentShaders.length; i < shaderCount; ++i) { shader = fragmentShaders[i]; loadShaderFile(shader, "fragment"); } // Check if we're still waiting for any shaders to load, in case they already // finished or if there were none. checkForRemaining(); }<file_sep>uniform float elapsedTime; uniform float depth; const float F_VELOCITY = 100.0; const float F_MIN_SIZE = 5.0; const float F_MAX_SIZE = 25.0; void main() { vec4 pos = vec4(position, 1.0); pos.z += mod(F_VELOCITY * elapsedTime, depth); vec4 mvPosition = modelViewMatrix * pos; gl_PointSize = mix(F_MAX_SIZE, F_MIN_SIZE, depth / pos.z); gl_Position = projectionMatrix * mvPosition; }
3f8513bf60ffc4a7fcb4bd745099d7bc8b9ed42d
[ "JavaScript" ]
3
JavaScript
codecruzer/webgl-starfield
1380c94c55c8a3ae7057ca07c3d16552843d531b
b914dfad81ece9b215fc69155ce2bb3b6f767275
refs/heads/master
<file_sep>import "tachyons/css/tachyons.min.css"; import React, { Component } from "react"; import { Modal } from "basic-react-component-library"; import JiraForm from "./jiraForm.js"; class App extends Component { constructor(props) { super(props); this.state = { modalHidden: false }; //TODO: in production change this to true this.toggleModalHide = this.toggleModalHide.bind(this); this.renderToolbar = this.renderToolbar.bind(this); } closeModal() { !this.state.modalHidden && this.toggleModalHide(); } toggleModalHide() { this.setState(prevState => ({ modalHidden: !prevState.modalHidden })); } renderToolbar() { return ( <a href="#" onClick={this.toggleModalHide}> Click me </a> ); } render() { let { modalHidden } = this.state; return ( <div className=""> {!modalHidden && ( <Modal handleClose={this.toggleModalHide}> <h1 className="tracked b ttu f2 lh-title tc">Fast File</h1> <hr /> <JiraForm /> </Modal> )} {this.renderToolbar()} </div> ); } } export default App; <file_sep>import React from "react"; import{ CloseIcon, TagItem } from "basic-react-component-library"; const ReferenceItem = ({ value, onClick, toRemove, ...props }) => ( <TagItem additionalContainerClasses={["ma1", "blue"]} additionalValueClasses={["dib underline-hover"]} name={value} value={value} onClick={onClick} {...props} > <CloseIcon additionalContainerClasses={["dim"]} color="gray" size="small" onClick={toRemove} /> </TagItem> ); export default ReferenceItem;
e81d37f6fc33ef57235f916fedb81800ef2cd926
[ "JavaScript" ]
2
JavaScript
mistahchris/ffv2
418620075138a9e405c74e833f0cee3e7bfac309
d82bffa6a36f20542b1fa100e14e52b4304616e5
refs/heads/main
<file_sep>package com.alves.project.entities; public class Cliente { private String nome_cliente; private Telefone telefone; private Conta conta; public void setNome(String nome_cliente) { this.nome_cliente = nome_cliente; } public String getNome() { return this.nome_cliente; } public void setLinha(Telefone telefone) { this.telefone = telefone; } public Telefone getTelefone() { return this.telefone; } public void setConta(Conta conta) { this.conta = conta; } public Conta getConta() { return this.conta; } } <file_sep>package com.alves.project.entities; public class Telefone { private String numero_linha; private int saldo; public void setNumeroLinha(String numero_linha) { this.numero_linha = numero_linha; } public String getNumeroLinha() { return this.numero_linha; } public void setSaldo(int saldo) { this.saldo = saldo; } public int getSaldo() { return this.saldo; } }
2c24f60a7eefbf2c1e46559f79405fe4a5addca3
[ "Java" ]
2
Java
GustAlves/QAEnginnerTestPl_Teste1
c84c28ce22751463c09094279767fbc4ffb06242
cef474f7fed5093a796a550000fc07a4aa48b7a8
refs/heads/main
<repo_name>Poppy850/lab9_web<file_sep>/README.md # lab9_web Nama : <NAME> Kelas : TI.19.C1 NIM : 311910687![1](https://user-images.githubusercontent.com/85287196/121448340-4f4bd780-c94c-11eb-839b-ac4b27177c5d.png) Pratikum 9 & 10 Tampilan Halaman Home ![1](https://user-images.githubusercontent.com/85287196/121448462-8cb06500-c94c-11eb-8be6-2d8ae2bc4f15.png) Tampilan About ![2](https://user-images.githubusercontent.com/85287196/121448527-b5d0f580-c94c-11eb-8acc-2def66a65576.png) Pertanyaan Tugas Implementasikan konsep modularisasi pada kode program praktikum 8 tentang database, sehingga setiap halamannya memiliki template tampilan yang sama. Tampilan Data Barang ![data](https://user-images.githubusercontent.com/85287196/121757530-ba271b00-cad2-11eb-82a8-97d9587addc3.png) Tampilan Tambah Barang ![peranyaan tugas 1](https://user-images.githubusercontent.com/85287196/121757453-6ae0ea80-cad2-11eb-8725-03cc4d028a15.png) Tampilan Ubah Barang ![ubah](https://user-images.githubusercontent.com/85287196/121757613-fbb7c600-cad2-11eb-9c0f-f1158b734982.png) ![hapus barang](https://user-images.githubusercontent.com/85287196/121446264-f8440380-c947-11eb-9431-29efa40db58e.png) <file_sep>/kontak.php <?php require('header.php'); ?> <div class="content"> <h2>Ini Halaman Kontak</h2> <p>Tampilan ini adalah bagian content dari halaman.</p> </div> <footer> <p>&copy; 2021, Informatika, Universitas Pelita Bangsa</p> </footer>
207224007227988602df3cd53691e78163fd209c
[ "Markdown", "PHP" ]
2
Markdown
Poppy850/lab9_web
de34ea3071970f1b3be91b4f6ffbcedbd65b67c6
308673d8c7e7701dd9616fe77014f78f9e91880d
refs/heads/master
<file_sep>#didnt know where to go from here. class Regex def initialize (domainname) @domain = domainname @regex = regex @num = num h = Hash.new end def parse_line(logline) @m["sent"] = 0 @m["recieved"] = 0 @m["discarded"] = 0 @m["seen"] = 0 end if @domain = "" @num = @num - 1 puts @num if line = /(<[-\w.+=_]+@[-\w]+(\.[-\w]+)+@#{domainname}>)/ puts $4 @f = $3 @fd = $4 puts "this is #{@f}" puts $7 @t= $6 @td= $7 puts "this os #{@t}" puts @domain puts @domain == $4 puts @domain == $7 puts $10 if line == "discard" puts "DISCARD" if @fd == @domain puts "domain match" if @h[$3]==nil @b=Hash.new @b["sent"]=0 end end results() end <file_sep>class ListFree attr_accessor :column, :larray, :ip, :iparray, :ipint def initialize(column) @column=column @larray @ip @iparray=[] @ipint=[] end def parse_line(line) @string_array = line.split(" ") iparray.push(@string_array[column-1]) end def free(&b) iparray.sort_by! {|ip| ip.split('.').map{ |octet| octet.to_i} } ipA = [] ipB = [] iparray.each{|x| ipA.push(x.split('.'))} ipA.sort_by! {|ip| ip.map{ |octet| octet.to_i} } i=0 ipA.each{ ipA[i][3]=ipA[i][3].to_i i+=1} i=0 ipA.each{ if ipA[i+1]!=nil if ipA[i][3]+1 != ipA[i+1][3]and ipA[i][3]!=ipA[i+1][3] ipA[i][3]=ipA[i][3]+1 x=ipA[i].join('.') if ipA[i][3]+1!=ipA[i+1][3] ipA[i][3]=ipA[i+1][3]-1 y=ipA[i].join('.') else y=nil end yield(x,y) end end i+=1} end end<file_sep>class IsFibo attr_accessor :fibs def initialize @fibs =[1,1] end def binary_search(x, from=0, to=nil) if to==nil [email protected] end mid=(from +to)/2 if from<mid if x>@fibs[mid] binary_search(x,mid,to) elsif x<@fibs[mid] binary_search(x,from,mid) else return true end else if x==@fibs[mid] return true else return false end end end def isfibo?(x) if x>@fibs[-1] while x>@fibs[-1] do @fibs.push @fibs[-2]+@fibs[-1] end if @fibs[-1]==x return true end else if @fibs[-1]==x return true else binary_search(x) end end end end <file_sep>class ListFree def initialize(column) @column = column - 1 @IPs = [] end def parse_line(line) @string_array = line.split(" ") @IPs.push(@string_array[@column]) end def free(&b) @IPs.sort! i = 1 b.each {|j| if } end end a = ListFree.new(3) a.parse_line("stuff morestuf 10.10.10.42 stuff") a.parse_line("stuff morestuff 10.10.10.10 maybemorestuff") a.parse_line("stuff222 morestuf22 10.10.10.44") a.parse_line("stuff2 morestuf2 10.10.10.11 maybe more stuff") a.parse_line("stuff morestuf 10.10.10.46 stuff") a.parse_line("stuff morestuf 10.10.10.22 stuff") <file_sep>class Customers include Comparable attr_accessor :firstname, :lastname def initialize firstname,lastname @firstname = firstname @lastname = lastname end def <=> other if other.lastname.downcase > self.lastname.downcase -1 elsif other.lastname.downcase < self.lastname.downcase 1 else 0 if other.firstname.downcase > self.firstname.downcase -1 elsif other.firstname.downcase < self.firstname.downcase 1 else 0 end end end def to_s "#{firstname}\t#{lastname}" end end<file_sep>#!/usr/local/bin/ruby -w def roman_id { 1000 => "M", 900 => "CM", 500 => "D", 400 => "CD", 100 => "C", 90 => "XC", 50 => "L", 40 => "XL", 10 => "X", 9 => "IX", 5 => "V", 4 => "IV", 1 => "I" } end class Integer def to_roman(number = self, result = "") return result if number == 0 roman_id.keys.each do |divisor| quotient, modulus = number.divmod(divisor) result << roman_id[divisor] * quotient return to_roman(modulus, result) if quotient > 0 end end end class String def roman_id { 1000 => "M", 900 => "CM", 500 => "D", 400 => "CD", 100 => "C", 90 => "XC", 50 => "L", 40 => "XL", 10 => "X", 9 => "IX", 5 => "V", 4 => "IV", 1 => "I" } end def to_arabic(str = self, result = 0) return result if str.empty? roman_id.values.each do |roman| if str.start_with?(roman) result += roman_id.invert[roman] str = str.slice(roman.length, str.length) return to_arabic(str, result) end end end end class Roman def initialize (mynum) @mynum = mynum end def to_s(number = @mynum, result = "") return @mynum if @mynum.is_a?(String) roman_id.keys.each do |divisor| quotient, modulus = number.divmod(divisor) result << roman_id[divisor] * quotient return to_s(modulus, result) if quotient > 0 end end def to_i(str = @mynum, result = 0) #return str if str.is_a?(String) return result if str.empty? roman_id.values.each do |roman| if str.start_with?(roman) result += roman_id.invert[roman] str = str.slice(roman.length, str.length) return to_i(str, result) end end end def *(s) y = self.to_i * s.to_i return y end end <file_sep>#couldnt figure out the syntax for preserving the addresses in parse line class EmailWatcher @regex @domainname def initialize(domainname) @domainname = domainname end def parse_line(logline) if @domainname = "" @regex = /(<[-\w.+=_]+@[-\w]+(\.[-\w]+)+@#{domainname}>)/ else @regex = /(<[-\w.+=_]+@[-\w]+(\.[-\w]+)+>)/ a = [] a = logline.scan (@regex).flatten a.each ( |x| x.slice!(0), x.slice(x.size - 1)) if !a.empty?; yield a end end end <file_sep># Ruby All of Ruby's main programming principles using lists, classes, arrays, regular expressions, attribute accessors, fibinacci sequence using binary search and parsing
0d71816593ff701698de4e60643bfba8243224dc
[ "Markdown", "Ruby" ]
8
Ruby
rOmAn2193/Ruby
880e77615e1d5a2cebb8791c7fde8b1eaa7939cd
83b3066ed63e79fe1372c76a3a83b9ac2b6d11c4